]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/index-pack.c
object-store.h: move struct object_info from cache.h
[thirdparty/git.git] / builtin / index-pack.c
1 #include "builtin.h"
2 #include "alloc.h"
3 #include "config.h"
4 #include "delta.h"
5 #include "hex.h"
6 #include "pack.h"
7 #include "csum-file.h"
8 #include "blob.h"
9 #include "commit.h"
10 #include "tag.h"
11 #include "tree.h"
12 #include "progress.h"
13 #include "fsck.h"
14 #include "exec-cmd.h"
15 #include "streaming.h"
16 #include "thread-utils.h"
17 #include "packfile.h"
18 #include "object-store.h"
19 #include "promisor-remote.h"
20
21 static const char index_pack_usage[] =
22 "git index-pack [-v] [-o <index-file>] [--keep | --keep=<msg>] [--[no-]rev-index] [--verify] [--strict] (<pack-file> | --stdin [--fix-thin] [<pack-file>])";
23
24 struct object_entry {
25 struct pack_idx_entry idx;
26 unsigned long size;
27 unsigned char hdr_size;
28 signed char type;
29 signed char real_type;
30 };
31
32 struct object_stat {
33 unsigned delta_depth;
34 int base_object_no;
35 };
36
37 struct base_data {
38 /* Initialized by make_base(). */
39 struct base_data *base;
40 struct object_entry *obj;
41 int ref_first, ref_last;
42 int ofs_first, ofs_last;
43 /*
44 * Threads should increment retain_data if they are about to call
45 * patch_delta() using this struct's data as a base, and decrement this
46 * when they are done. While retain_data is nonzero, this struct's data
47 * will not be freed even if the delta base cache limit is exceeded.
48 */
49 int retain_data;
50 /*
51 * The number of direct children that have not been fully processed
52 * (entered work_head, entered done_head, left done_head). When this
53 * number reaches zero, this struct base_data can be freed.
54 */
55 int children_remaining;
56
57 /* Not initialized by make_base(). */
58 struct list_head list;
59 void *data;
60 unsigned long size;
61 };
62
63 /*
64 * Stack of struct base_data that have unprocessed children.
65 * threaded_second_pass() uses this as a source of work (the other being the
66 * objects array).
67 *
68 * Guarded by work_mutex.
69 */
70 static LIST_HEAD(work_head);
71
72 /*
73 * Stack of struct base_data that have children, all of whom have been
74 * processed or are being processed, and at least one child is being processed.
75 * These struct base_data must be kept around until the last child is
76 * processed.
77 *
78 * Guarded by work_mutex.
79 */
80 static LIST_HEAD(done_head);
81
82 /*
83 * All threads share one delta base cache.
84 *
85 * base_cache_used is guarded by work_mutex, and base_cache_limit is read-only
86 * in a thread.
87 */
88 static size_t base_cache_used;
89 static size_t base_cache_limit;
90
91 struct thread_local {
92 pthread_t thread;
93 int pack_fd;
94 };
95
96 /* Remember to update object flag allocation in object.h */
97 #define FLAG_LINK (1u<<20)
98 #define FLAG_CHECKED (1u<<21)
99
100 struct ofs_delta_entry {
101 off_t offset;
102 int obj_no;
103 };
104
105 struct ref_delta_entry {
106 struct object_id oid;
107 int obj_no;
108 };
109
110 static struct object_entry *objects;
111 static struct object_stat *obj_stat;
112 static struct ofs_delta_entry *ofs_deltas;
113 static struct ref_delta_entry *ref_deltas;
114 static struct thread_local nothread_data;
115 static int nr_objects;
116 static int nr_ofs_deltas;
117 static int nr_ref_deltas;
118 static int ref_deltas_alloc;
119 static int nr_resolved_deltas;
120 static int nr_threads;
121
122 static int from_stdin;
123 static int strict;
124 static int do_fsck_object;
125 static struct fsck_options fsck_options = FSCK_OPTIONS_MISSING_GITMODULES;
126 static int verbose;
127 static const char *progress_title;
128 static int show_resolving_progress;
129 static int show_stat;
130 static int check_self_contained_and_connected;
131
132 static struct progress *progress;
133
134 /* We always read in 4kB chunks. */
135 static unsigned char input_buffer[4096];
136 static unsigned int input_offset, input_len;
137 static off_t consumed_bytes;
138 static off_t max_input_size;
139 static unsigned deepest_delta;
140 static git_hash_ctx input_ctx;
141 static uint32_t input_crc32;
142 static int input_fd, output_fd;
143 static const char *curr_pack;
144
145 static struct thread_local *thread_data;
146 static int nr_dispatched;
147 static int threads_active;
148
149 static pthread_mutex_t read_mutex;
150 #define read_lock() lock_mutex(&read_mutex)
151 #define read_unlock() unlock_mutex(&read_mutex)
152
153 static pthread_mutex_t counter_mutex;
154 #define counter_lock() lock_mutex(&counter_mutex)
155 #define counter_unlock() unlock_mutex(&counter_mutex)
156
157 static pthread_mutex_t work_mutex;
158 #define work_lock() lock_mutex(&work_mutex)
159 #define work_unlock() unlock_mutex(&work_mutex)
160
161 static pthread_mutex_t deepest_delta_mutex;
162 #define deepest_delta_lock() lock_mutex(&deepest_delta_mutex)
163 #define deepest_delta_unlock() unlock_mutex(&deepest_delta_mutex)
164
165 static pthread_key_t key;
166
167 static inline void lock_mutex(pthread_mutex_t *mutex)
168 {
169 if (threads_active)
170 pthread_mutex_lock(mutex);
171 }
172
173 static inline void unlock_mutex(pthread_mutex_t *mutex)
174 {
175 if (threads_active)
176 pthread_mutex_unlock(mutex);
177 }
178
179 /*
180 * Mutex and conditional variable can't be statically-initialized on Windows.
181 */
182 static void init_thread(void)
183 {
184 int i;
185 init_recursive_mutex(&read_mutex);
186 pthread_mutex_init(&counter_mutex, NULL);
187 pthread_mutex_init(&work_mutex, NULL);
188 if (show_stat)
189 pthread_mutex_init(&deepest_delta_mutex, NULL);
190 pthread_key_create(&key, NULL);
191 CALLOC_ARRAY(thread_data, nr_threads);
192 for (i = 0; i < nr_threads; i++) {
193 thread_data[i].pack_fd = xopen(curr_pack, O_RDONLY);
194 }
195
196 threads_active = 1;
197 }
198
199 static void cleanup_thread(void)
200 {
201 int i;
202 if (!threads_active)
203 return;
204 threads_active = 0;
205 pthread_mutex_destroy(&read_mutex);
206 pthread_mutex_destroy(&counter_mutex);
207 pthread_mutex_destroy(&work_mutex);
208 if (show_stat)
209 pthread_mutex_destroy(&deepest_delta_mutex);
210 for (i = 0; i < nr_threads; i++)
211 close(thread_data[i].pack_fd);
212 pthread_key_delete(key);
213 free(thread_data);
214 }
215
216 static int mark_link(struct object *obj, enum object_type type,
217 void *data, struct fsck_options *options)
218 {
219 if (!obj)
220 return -1;
221
222 if (type != OBJ_ANY && obj->type != type)
223 die(_("object type mismatch at %s"), oid_to_hex(&obj->oid));
224
225 obj->flags |= FLAG_LINK;
226 return 0;
227 }
228
229 /* The content of each linked object must have been checked
230 or it must be already present in the object database */
231 static unsigned check_object(struct object *obj)
232 {
233 if (!obj)
234 return 0;
235
236 if (!(obj->flags & FLAG_LINK))
237 return 0;
238
239 if (!(obj->flags & FLAG_CHECKED)) {
240 unsigned long size;
241 int type = oid_object_info(the_repository, &obj->oid, &size);
242 if (type <= 0)
243 die(_("did not receive expected object %s"),
244 oid_to_hex(&obj->oid));
245 if (type != obj->type)
246 die(_("object %s: expected type %s, found %s"),
247 oid_to_hex(&obj->oid),
248 type_name(obj->type), type_name(type));
249 obj->flags |= FLAG_CHECKED;
250 return 1;
251 }
252
253 return 0;
254 }
255
256 static unsigned check_objects(void)
257 {
258 unsigned i, max, foreign_nr = 0;
259
260 max = get_max_object_index();
261
262 if (verbose)
263 progress = start_delayed_progress(_("Checking objects"), max);
264
265 for (i = 0; i < max; i++) {
266 foreign_nr += check_object(get_indexed_object(i));
267 display_progress(progress, i + 1);
268 }
269
270 stop_progress(&progress);
271 return foreign_nr;
272 }
273
274
275 /* Discard current buffer used content. */
276 static void flush(void)
277 {
278 if (input_offset) {
279 if (output_fd >= 0)
280 write_or_die(output_fd, input_buffer, input_offset);
281 the_hash_algo->update_fn(&input_ctx, input_buffer, input_offset);
282 memmove(input_buffer, input_buffer + input_offset, input_len);
283 input_offset = 0;
284 }
285 }
286
287 /*
288 * Make sure at least "min" bytes are available in the buffer, and
289 * return the pointer to the buffer.
290 */
291 static void *fill(int min)
292 {
293 if (min <= input_len)
294 return input_buffer + input_offset;
295 if (min > sizeof(input_buffer))
296 die(Q_("cannot fill %d byte",
297 "cannot fill %d bytes",
298 min),
299 min);
300 flush();
301 do {
302 ssize_t ret = xread(input_fd, input_buffer + input_len,
303 sizeof(input_buffer) - input_len);
304 if (ret <= 0) {
305 if (!ret)
306 die(_("early EOF"));
307 die_errno(_("read error on input"));
308 }
309 input_len += ret;
310 if (from_stdin)
311 display_throughput(progress, consumed_bytes + input_len);
312 } while (input_len < min);
313 return input_buffer;
314 }
315
316 static void use(int bytes)
317 {
318 if (bytes > input_len)
319 die(_("used more bytes than were available"));
320 input_crc32 = crc32(input_crc32, input_buffer + input_offset, bytes);
321 input_len -= bytes;
322 input_offset += bytes;
323
324 /* make sure off_t is sufficiently large not to wrap */
325 if (signed_add_overflows(consumed_bytes, bytes))
326 die(_("pack too large for current definition of off_t"));
327 consumed_bytes += bytes;
328 if (max_input_size && consumed_bytes > max_input_size) {
329 struct strbuf size_limit = STRBUF_INIT;
330 strbuf_humanise_bytes(&size_limit, max_input_size);
331 die(_("pack exceeds maximum allowed size (%s)"),
332 size_limit.buf);
333 }
334 }
335
336 static const char *open_pack_file(const char *pack_name)
337 {
338 if (from_stdin) {
339 input_fd = 0;
340 if (!pack_name) {
341 struct strbuf tmp_file = STRBUF_INIT;
342 output_fd = odb_mkstemp(&tmp_file,
343 "pack/tmp_pack_XXXXXX");
344 pack_name = strbuf_detach(&tmp_file, NULL);
345 } else {
346 output_fd = xopen(pack_name, O_CREAT|O_EXCL|O_RDWR, 0600);
347 }
348 nothread_data.pack_fd = output_fd;
349 } else {
350 input_fd = xopen(pack_name, O_RDONLY);
351 output_fd = -1;
352 nothread_data.pack_fd = input_fd;
353 }
354 the_hash_algo->init_fn(&input_ctx);
355 return pack_name;
356 }
357
358 static void parse_pack_header(void)
359 {
360 struct pack_header *hdr = fill(sizeof(struct pack_header));
361
362 /* Header consistency check */
363 if (hdr->hdr_signature != htonl(PACK_SIGNATURE))
364 die(_("pack signature mismatch"));
365 if (!pack_version_ok(hdr->hdr_version))
366 die(_("pack version %"PRIu32" unsupported"),
367 ntohl(hdr->hdr_version));
368
369 nr_objects = ntohl(hdr->hdr_entries);
370 use(sizeof(struct pack_header));
371 }
372
373 __attribute__((format (printf, 2, 3)))
374 static NORETURN void bad_object(off_t offset, const char *format, ...)
375 {
376 va_list params;
377 char buf[1024];
378
379 va_start(params, format);
380 vsnprintf(buf, sizeof(buf), format, params);
381 va_end(params);
382 die(_("pack has bad object at offset %"PRIuMAX": %s"),
383 (uintmax_t)offset, buf);
384 }
385
386 static inline struct thread_local *get_thread_data(void)
387 {
388 if (HAVE_THREADS) {
389 if (threads_active)
390 return pthread_getspecific(key);
391 assert(!threads_active &&
392 "This should only be reached when all threads are gone");
393 }
394 return &nothread_data;
395 }
396
397 static void set_thread_data(struct thread_local *data)
398 {
399 if (threads_active)
400 pthread_setspecific(key, data);
401 }
402
403 static void free_base_data(struct base_data *c)
404 {
405 if (c->data) {
406 FREE_AND_NULL(c->data);
407 base_cache_used -= c->size;
408 }
409 }
410
411 static void prune_base_data(struct base_data *retain)
412 {
413 struct list_head *pos;
414
415 if (base_cache_used <= base_cache_limit)
416 return;
417
418 list_for_each_prev(pos, &done_head) {
419 struct base_data *b = list_entry(pos, struct base_data, list);
420 if (b->retain_data || b == retain)
421 continue;
422 if (b->data) {
423 free_base_data(b);
424 if (base_cache_used <= base_cache_limit)
425 return;
426 }
427 }
428
429 list_for_each_prev(pos, &work_head) {
430 struct base_data *b = list_entry(pos, struct base_data, list);
431 if (b->retain_data || b == retain)
432 continue;
433 if (b->data) {
434 free_base_data(b);
435 if (base_cache_used <= base_cache_limit)
436 return;
437 }
438 }
439 }
440
441 static int is_delta_type(enum object_type type)
442 {
443 return (type == OBJ_REF_DELTA || type == OBJ_OFS_DELTA);
444 }
445
446 static void *unpack_entry_data(off_t offset, unsigned long size,
447 enum object_type type, struct object_id *oid)
448 {
449 static char fixed_buf[8192];
450 int status;
451 git_zstream stream;
452 void *buf;
453 git_hash_ctx c;
454 char hdr[32];
455 int hdrlen;
456
457 if (!is_delta_type(type)) {
458 hdrlen = format_object_header(hdr, sizeof(hdr), type, size);
459 the_hash_algo->init_fn(&c);
460 the_hash_algo->update_fn(&c, hdr, hdrlen);
461 } else
462 oid = NULL;
463 if (type == OBJ_BLOB && size > big_file_threshold)
464 buf = fixed_buf;
465 else
466 buf = xmallocz(size);
467
468 memset(&stream, 0, sizeof(stream));
469 git_inflate_init(&stream);
470 stream.next_out = buf;
471 stream.avail_out = buf == fixed_buf ? sizeof(fixed_buf) : size;
472
473 do {
474 unsigned char *last_out = stream.next_out;
475 stream.next_in = fill(1);
476 stream.avail_in = input_len;
477 status = git_inflate(&stream, 0);
478 use(input_len - stream.avail_in);
479 if (oid)
480 the_hash_algo->update_fn(&c, last_out, stream.next_out - last_out);
481 if (buf == fixed_buf) {
482 stream.next_out = buf;
483 stream.avail_out = sizeof(fixed_buf);
484 }
485 } while (status == Z_OK);
486 if (stream.total_out != size || status != Z_STREAM_END)
487 bad_object(offset, _("inflate returned %d"), status);
488 git_inflate_end(&stream);
489 if (oid)
490 the_hash_algo->final_oid_fn(oid, &c);
491 return buf == fixed_buf ? NULL : buf;
492 }
493
494 static void *unpack_raw_entry(struct object_entry *obj,
495 off_t *ofs_offset,
496 struct object_id *ref_oid,
497 struct object_id *oid)
498 {
499 unsigned char *p;
500 unsigned long size, c;
501 off_t base_offset;
502 unsigned shift;
503 void *data;
504
505 obj->idx.offset = consumed_bytes;
506 input_crc32 = crc32(0, NULL, 0);
507
508 p = fill(1);
509 c = *p;
510 use(1);
511 obj->type = (c >> 4) & 7;
512 size = (c & 15);
513 shift = 4;
514 while (c & 0x80) {
515 p = fill(1);
516 c = *p;
517 use(1);
518 size += (c & 0x7f) << shift;
519 shift += 7;
520 }
521 obj->size = size;
522
523 switch (obj->type) {
524 case OBJ_REF_DELTA:
525 oidread(ref_oid, fill(the_hash_algo->rawsz));
526 use(the_hash_algo->rawsz);
527 break;
528 case OBJ_OFS_DELTA:
529 p = fill(1);
530 c = *p;
531 use(1);
532 base_offset = c & 127;
533 while (c & 128) {
534 base_offset += 1;
535 if (!base_offset || MSB(base_offset, 7))
536 bad_object(obj->idx.offset, _("offset value overflow for delta base object"));
537 p = fill(1);
538 c = *p;
539 use(1);
540 base_offset = (base_offset << 7) + (c & 127);
541 }
542 *ofs_offset = obj->idx.offset - base_offset;
543 if (*ofs_offset <= 0 || *ofs_offset >= obj->idx.offset)
544 bad_object(obj->idx.offset, _("delta base offset is out of bound"));
545 break;
546 case OBJ_COMMIT:
547 case OBJ_TREE:
548 case OBJ_BLOB:
549 case OBJ_TAG:
550 break;
551 default:
552 bad_object(obj->idx.offset, _("unknown object type %d"), obj->type);
553 }
554 obj->hdr_size = consumed_bytes - obj->idx.offset;
555
556 data = unpack_entry_data(obj->idx.offset, obj->size, obj->type, oid);
557 obj->idx.crc32 = input_crc32;
558 return data;
559 }
560
561 static void *unpack_data(struct object_entry *obj,
562 int (*consume)(const unsigned char *, unsigned long, void *),
563 void *cb_data)
564 {
565 off_t from = obj[0].idx.offset + obj[0].hdr_size;
566 off_t len = obj[1].idx.offset - from;
567 unsigned char *data, *inbuf;
568 git_zstream stream;
569 int status;
570
571 data = xmallocz(consume ? 64*1024 : obj->size);
572 inbuf = xmalloc((len < 64*1024) ? (int)len : 64*1024);
573
574 memset(&stream, 0, sizeof(stream));
575 git_inflate_init(&stream);
576 stream.next_out = data;
577 stream.avail_out = consume ? 64*1024 : obj->size;
578
579 do {
580 ssize_t n = (len < 64*1024) ? (ssize_t)len : 64*1024;
581 n = xpread(get_thread_data()->pack_fd, inbuf, n, from);
582 if (n < 0)
583 die_errno(_("cannot pread pack file"));
584 if (!n)
585 die(Q_("premature end of pack file, %"PRIuMAX" byte missing",
586 "premature end of pack file, %"PRIuMAX" bytes missing",
587 len),
588 (uintmax_t)len);
589 from += n;
590 len -= n;
591 stream.next_in = inbuf;
592 stream.avail_in = n;
593 if (!consume)
594 status = git_inflate(&stream, 0);
595 else {
596 do {
597 status = git_inflate(&stream, 0);
598 if (consume(data, stream.next_out - data, cb_data)) {
599 free(inbuf);
600 free(data);
601 return NULL;
602 }
603 stream.next_out = data;
604 stream.avail_out = 64*1024;
605 } while (status == Z_OK && stream.avail_in);
606 }
607 } while (len && status == Z_OK && !stream.avail_in);
608
609 /* This has been inflated OK when first encountered, so... */
610 if (status != Z_STREAM_END || stream.total_out != obj->size)
611 die(_("serious inflate inconsistency"));
612
613 git_inflate_end(&stream);
614 free(inbuf);
615 if (consume) {
616 FREE_AND_NULL(data);
617 }
618 return data;
619 }
620
621 static void *get_data_from_pack(struct object_entry *obj)
622 {
623 return unpack_data(obj, NULL, NULL);
624 }
625
626 static int compare_ofs_delta_bases(off_t offset1, off_t offset2,
627 enum object_type type1,
628 enum object_type type2)
629 {
630 int cmp = type1 - type2;
631 if (cmp)
632 return cmp;
633 return offset1 < offset2 ? -1 :
634 offset1 > offset2 ? 1 :
635 0;
636 }
637
638 static int find_ofs_delta(const off_t offset)
639 {
640 int first = 0, last = nr_ofs_deltas;
641
642 while (first < last) {
643 int next = first + (last - first) / 2;
644 struct ofs_delta_entry *delta = &ofs_deltas[next];
645 int cmp;
646
647 cmp = compare_ofs_delta_bases(offset, delta->offset,
648 OBJ_OFS_DELTA,
649 objects[delta->obj_no].type);
650 if (!cmp)
651 return next;
652 if (cmp < 0) {
653 last = next;
654 continue;
655 }
656 first = next+1;
657 }
658 return -first-1;
659 }
660
661 static void find_ofs_delta_children(off_t offset,
662 int *first_index, int *last_index)
663 {
664 int first = find_ofs_delta(offset);
665 int last = first;
666 int end = nr_ofs_deltas - 1;
667
668 if (first < 0) {
669 *first_index = 0;
670 *last_index = -1;
671 return;
672 }
673 while (first > 0 && ofs_deltas[first - 1].offset == offset)
674 --first;
675 while (last < end && ofs_deltas[last + 1].offset == offset)
676 ++last;
677 *first_index = first;
678 *last_index = last;
679 }
680
681 static int compare_ref_delta_bases(const struct object_id *oid1,
682 const struct object_id *oid2,
683 enum object_type type1,
684 enum object_type type2)
685 {
686 int cmp = type1 - type2;
687 if (cmp)
688 return cmp;
689 return oidcmp(oid1, oid2);
690 }
691
692 static int find_ref_delta(const struct object_id *oid)
693 {
694 int first = 0, last = nr_ref_deltas;
695
696 while (first < last) {
697 int next = first + (last - first) / 2;
698 struct ref_delta_entry *delta = &ref_deltas[next];
699 int cmp;
700
701 cmp = compare_ref_delta_bases(oid, &delta->oid,
702 OBJ_REF_DELTA,
703 objects[delta->obj_no].type);
704 if (!cmp)
705 return next;
706 if (cmp < 0) {
707 last = next;
708 continue;
709 }
710 first = next+1;
711 }
712 return -first-1;
713 }
714
715 static void find_ref_delta_children(const struct object_id *oid,
716 int *first_index, int *last_index)
717 {
718 int first = find_ref_delta(oid);
719 int last = first;
720 int end = nr_ref_deltas - 1;
721
722 if (first < 0) {
723 *first_index = 0;
724 *last_index = -1;
725 return;
726 }
727 while (first > 0 && oideq(&ref_deltas[first - 1].oid, oid))
728 --first;
729 while (last < end && oideq(&ref_deltas[last + 1].oid, oid))
730 ++last;
731 *first_index = first;
732 *last_index = last;
733 }
734
735 struct compare_data {
736 struct object_entry *entry;
737 struct git_istream *st;
738 unsigned char *buf;
739 unsigned long buf_size;
740 };
741
742 static int compare_objects(const unsigned char *buf, unsigned long size,
743 void *cb_data)
744 {
745 struct compare_data *data = cb_data;
746
747 if (data->buf_size < size) {
748 free(data->buf);
749 data->buf = xmalloc(size);
750 data->buf_size = size;
751 }
752
753 while (size) {
754 ssize_t len = read_istream(data->st, data->buf, size);
755 if (len == 0)
756 die(_("SHA1 COLLISION FOUND WITH %s !"),
757 oid_to_hex(&data->entry->idx.oid));
758 if (len < 0)
759 die(_("unable to read %s"),
760 oid_to_hex(&data->entry->idx.oid));
761 if (memcmp(buf, data->buf, len))
762 die(_("SHA1 COLLISION FOUND WITH %s !"),
763 oid_to_hex(&data->entry->idx.oid));
764 size -= len;
765 buf += len;
766 }
767 return 0;
768 }
769
770 static int check_collison(struct object_entry *entry)
771 {
772 struct compare_data data;
773 enum object_type type;
774 unsigned long size;
775
776 if (entry->size <= big_file_threshold || entry->type != OBJ_BLOB)
777 return -1;
778
779 memset(&data, 0, sizeof(data));
780 data.entry = entry;
781 data.st = open_istream(the_repository, &entry->idx.oid, &type, &size,
782 NULL);
783 if (!data.st)
784 return -1;
785 if (size != entry->size || type != entry->type)
786 die(_("SHA1 COLLISION FOUND WITH %s !"),
787 oid_to_hex(&entry->idx.oid));
788 unpack_data(entry, compare_objects, &data);
789 close_istream(data.st);
790 free(data.buf);
791 return 0;
792 }
793
794 static void sha1_object(const void *data, struct object_entry *obj_entry,
795 unsigned long size, enum object_type type,
796 const struct object_id *oid)
797 {
798 void *new_data = NULL;
799 int collision_test_needed = 0;
800
801 assert(data || obj_entry);
802
803 if (startup_info->have_repository) {
804 read_lock();
805 collision_test_needed =
806 has_object_file_with_flags(oid, OBJECT_INFO_QUICK);
807 read_unlock();
808 }
809
810 if (collision_test_needed && !data) {
811 read_lock();
812 if (!check_collison(obj_entry))
813 collision_test_needed = 0;
814 read_unlock();
815 }
816 if (collision_test_needed) {
817 void *has_data;
818 enum object_type has_type;
819 unsigned long has_size;
820 read_lock();
821 has_type = oid_object_info(the_repository, oid, &has_size);
822 if (has_type < 0)
823 die(_("cannot read existing object info %s"), oid_to_hex(oid));
824 if (has_type != type || has_size != size)
825 die(_("SHA1 COLLISION FOUND WITH %s !"), oid_to_hex(oid));
826 has_data = read_object_file(oid, &has_type, &has_size);
827 read_unlock();
828 if (!data)
829 data = new_data = get_data_from_pack(obj_entry);
830 if (!has_data)
831 die(_("cannot read existing object %s"), oid_to_hex(oid));
832 if (size != has_size || type != has_type ||
833 memcmp(data, has_data, size) != 0)
834 die(_("SHA1 COLLISION FOUND WITH %s !"), oid_to_hex(oid));
835 free(has_data);
836 }
837
838 if (strict || do_fsck_object) {
839 read_lock();
840 if (type == OBJ_BLOB) {
841 struct blob *blob = lookup_blob(the_repository, oid);
842 if (blob)
843 blob->object.flags |= FLAG_CHECKED;
844 else
845 die(_("invalid blob object %s"), oid_to_hex(oid));
846 if (do_fsck_object &&
847 fsck_object(&blob->object, (void *)data, size, &fsck_options))
848 die(_("fsck error in packed object"));
849 } else {
850 struct object *obj;
851 int eaten;
852 void *buf = (void *) data;
853
854 assert(data && "data can only be NULL for large _blobs_");
855
856 /*
857 * we do not need to free the memory here, as the
858 * buf is deleted by the caller.
859 */
860 obj = parse_object_buffer(the_repository, oid, type,
861 size, buf,
862 &eaten);
863 if (!obj)
864 die(_("invalid %s"), type_name(type));
865 if (do_fsck_object &&
866 fsck_object(obj, buf, size, &fsck_options))
867 die(_("fsck error in packed object"));
868 if (strict && fsck_walk(obj, NULL, &fsck_options))
869 die(_("Not all child objects of %s are reachable"), oid_to_hex(&obj->oid));
870
871 if (obj->type == OBJ_TREE) {
872 struct tree *item = (struct tree *) obj;
873 item->buffer = NULL;
874 obj->parsed = 0;
875 }
876 if (obj->type == OBJ_COMMIT) {
877 struct commit *commit = (struct commit *) obj;
878 if (detach_commit_buffer(commit, NULL) != data)
879 BUG("parse_object_buffer transmogrified our buffer");
880 }
881 obj->flags |= FLAG_CHECKED;
882 }
883 read_unlock();
884 }
885
886 free(new_data);
887 }
888
889 /*
890 * Ensure that this node has been reconstructed and return its contents.
891 *
892 * In the typical and best case, this node would already be reconstructed
893 * (through the invocation to resolve_delta() in threaded_second_pass()) and it
894 * would not be pruned. However, if pruning of this node was necessary due to
895 * reaching delta_base_cache_limit, this function will find the closest
896 * ancestor with reconstructed data that has not been pruned (or if there is
897 * none, the ultimate base object), and reconstruct each node in the delta
898 * chain in order to generate the reconstructed data for this node.
899 */
900 static void *get_base_data(struct base_data *c)
901 {
902 if (!c->data) {
903 struct object_entry *obj = c->obj;
904 struct base_data **delta = NULL;
905 int delta_nr = 0, delta_alloc = 0;
906
907 while (is_delta_type(c->obj->type) && !c->data) {
908 ALLOC_GROW(delta, delta_nr + 1, delta_alloc);
909 delta[delta_nr++] = c;
910 c = c->base;
911 }
912 if (!delta_nr) {
913 c->data = get_data_from_pack(obj);
914 c->size = obj->size;
915 base_cache_used += c->size;
916 prune_base_data(c);
917 }
918 for (; delta_nr > 0; delta_nr--) {
919 void *base, *raw;
920 c = delta[delta_nr - 1];
921 obj = c->obj;
922 base = get_base_data(c->base);
923 raw = get_data_from_pack(obj);
924 c->data = patch_delta(
925 base, c->base->size,
926 raw, obj->size,
927 &c->size);
928 free(raw);
929 if (!c->data)
930 bad_object(obj->idx.offset, _("failed to apply delta"));
931 base_cache_used += c->size;
932 prune_base_data(c);
933 }
934 free(delta);
935 }
936 return c->data;
937 }
938
939 static struct base_data *make_base(struct object_entry *obj,
940 struct base_data *parent)
941 {
942 struct base_data *base = xcalloc(1, sizeof(struct base_data));
943 base->base = parent;
944 base->obj = obj;
945 find_ref_delta_children(&obj->idx.oid,
946 &base->ref_first, &base->ref_last);
947 find_ofs_delta_children(obj->idx.offset,
948 &base->ofs_first, &base->ofs_last);
949 base->children_remaining = base->ref_last - base->ref_first +
950 base->ofs_last - base->ofs_first + 2;
951 return base;
952 }
953
954 static struct base_data *resolve_delta(struct object_entry *delta_obj,
955 struct base_data *base)
956 {
957 void *delta_data, *result_data;
958 struct base_data *result;
959 unsigned long result_size;
960
961 if (show_stat) {
962 int i = delta_obj - objects;
963 int j = base->obj - objects;
964 obj_stat[i].delta_depth = obj_stat[j].delta_depth + 1;
965 deepest_delta_lock();
966 if (deepest_delta < obj_stat[i].delta_depth)
967 deepest_delta = obj_stat[i].delta_depth;
968 deepest_delta_unlock();
969 obj_stat[i].base_object_no = j;
970 }
971 delta_data = get_data_from_pack(delta_obj);
972 assert(base->data);
973 result_data = patch_delta(base->data, base->size,
974 delta_data, delta_obj->size, &result_size);
975 free(delta_data);
976 if (!result_data)
977 bad_object(delta_obj->idx.offset, _("failed to apply delta"));
978 hash_object_file(the_hash_algo, result_data, result_size,
979 delta_obj->real_type, &delta_obj->idx.oid);
980 sha1_object(result_data, NULL, result_size, delta_obj->real_type,
981 &delta_obj->idx.oid);
982
983 result = make_base(delta_obj, base);
984 result->data = result_data;
985 result->size = result_size;
986
987 counter_lock();
988 nr_resolved_deltas++;
989 counter_unlock();
990
991 return result;
992 }
993
994 static int compare_ofs_delta_entry(const void *a, const void *b)
995 {
996 const struct ofs_delta_entry *delta_a = a;
997 const struct ofs_delta_entry *delta_b = b;
998
999 return delta_a->offset < delta_b->offset ? -1 :
1000 delta_a->offset > delta_b->offset ? 1 :
1001 0;
1002 }
1003
1004 static int compare_ref_delta_entry(const void *a, const void *b)
1005 {
1006 const struct ref_delta_entry *delta_a = a;
1007 const struct ref_delta_entry *delta_b = b;
1008
1009 return oidcmp(&delta_a->oid, &delta_b->oid);
1010 }
1011
1012 static void *threaded_second_pass(void *data)
1013 {
1014 if (data)
1015 set_thread_data(data);
1016 for (;;) {
1017 struct base_data *parent = NULL;
1018 struct object_entry *child_obj;
1019 struct base_data *child;
1020
1021 counter_lock();
1022 display_progress(progress, nr_resolved_deltas);
1023 counter_unlock();
1024
1025 work_lock();
1026 if (list_empty(&work_head)) {
1027 /*
1028 * Take an object from the object array.
1029 */
1030 while (nr_dispatched < nr_objects &&
1031 is_delta_type(objects[nr_dispatched].type))
1032 nr_dispatched++;
1033 if (nr_dispatched >= nr_objects) {
1034 work_unlock();
1035 break;
1036 }
1037 child_obj = &objects[nr_dispatched++];
1038 } else {
1039 /*
1040 * Peek at the top of the stack, and take a child from
1041 * it.
1042 */
1043 parent = list_first_entry(&work_head, struct base_data,
1044 list);
1045
1046 if (parent->ref_first <= parent->ref_last) {
1047 int offset = ref_deltas[parent->ref_first++].obj_no;
1048 child_obj = objects + offset;
1049 if (child_obj->real_type != OBJ_REF_DELTA)
1050 die("REF_DELTA at offset %"PRIuMAX" already resolved (duplicate base %s?)",
1051 (uintmax_t) child_obj->idx.offset,
1052 oid_to_hex(&parent->obj->idx.oid));
1053 child_obj->real_type = parent->obj->real_type;
1054 } else {
1055 child_obj = objects +
1056 ofs_deltas[parent->ofs_first++].obj_no;
1057 assert(child_obj->real_type == OBJ_OFS_DELTA);
1058 child_obj->real_type = parent->obj->real_type;
1059 }
1060
1061 if (parent->ref_first > parent->ref_last &&
1062 parent->ofs_first > parent->ofs_last) {
1063 /*
1064 * This parent has run out of children, so move
1065 * it to done_head.
1066 */
1067 list_del(&parent->list);
1068 list_add(&parent->list, &done_head);
1069 }
1070
1071 /*
1072 * Ensure that the parent has data, since we will need
1073 * it later.
1074 *
1075 * NEEDSWORK: If parent data needs to be reloaded, this
1076 * prolongs the time that the current thread spends in
1077 * the mutex. A mitigating factor is that parent data
1078 * needs to be reloaded only if the delta base cache
1079 * limit is exceeded, so in the typical case, this does
1080 * not happen.
1081 */
1082 get_base_data(parent);
1083 parent->retain_data++;
1084 }
1085 work_unlock();
1086
1087 if (parent) {
1088 child = resolve_delta(child_obj, parent);
1089 if (!child->children_remaining)
1090 FREE_AND_NULL(child->data);
1091 } else {
1092 child = make_base(child_obj, NULL);
1093 if (child->children_remaining) {
1094 /*
1095 * Since this child has its own delta children,
1096 * we will need this data in the future.
1097 * Inflate now so that future iterations will
1098 * have access to this object's data while
1099 * outside the work mutex.
1100 */
1101 child->data = get_data_from_pack(child_obj);
1102 child->size = child_obj->size;
1103 }
1104 }
1105
1106 work_lock();
1107 if (parent)
1108 parent->retain_data--;
1109 if (child->data) {
1110 /*
1111 * This child has its own children, so add it to
1112 * work_head.
1113 */
1114 list_add(&child->list, &work_head);
1115 base_cache_used += child->size;
1116 prune_base_data(NULL);
1117 free_base_data(child);
1118 } else {
1119 /*
1120 * This child does not have its own children. It may be
1121 * the last descendant of its ancestors; free those
1122 * that we can.
1123 */
1124 struct base_data *p = parent;
1125
1126 while (p) {
1127 struct base_data *next_p;
1128
1129 p->children_remaining--;
1130 if (p->children_remaining)
1131 break;
1132
1133 next_p = p->base;
1134 free_base_data(p);
1135 list_del(&p->list);
1136 free(p);
1137
1138 p = next_p;
1139 }
1140 FREE_AND_NULL(child);
1141 }
1142 work_unlock();
1143 }
1144 return NULL;
1145 }
1146
1147 /*
1148 * First pass:
1149 * - find locations of all objects;
1150 * - calculate SHA1 of all non-delta objects;
1151 * - remember base (SHA1 or offset) for all deltas.
1152 */
1153 static void parse_pack_objects(unsigned char *hash)
1154 {
1155 int i, nr_delays = 0;
1156 struct ofs_delta_entry *ofs_delta = ofs_deltas;
1157 struct object_id ref_delta_oid;
1158 struct stat st;
1159
1160 if (verbose)
1161 progress = start_progress(
1162 progress_title ? progress_title :
1163 from_stdin ? _("Receiving objects") : _("Indexing objects"),
1164 nr_objects);
1165 for (i = 0; i < nr_objects; i++) {
1166 struct object_entry *obj = &objects[i];
1167 void *data = unpack_raw_entry(obj, &ofs_delta->offset,
1168 &ref_delta_oid,
1169 &obj->idx.oid);
1170 obj->real_type = obj->type;
1171 if (obj->type == OBJ_OFS_DELTA) {
1172 nr_ofs_deltas++;
1173 ofs_delta->obj_no = i;
1174 ofs_delta++;
1175 } else if (obj->type == OBJ_REF_DELTA) {
1176 ALLOC_GROW(ref_deltas, nr_ref_deltas + 1, ref_deltas_alloc);
1177 oidcpy(&ref_deltas[nr_ref_deltas].oid, &ref_delta_oid);
1178 ref_deltas[nr_ref_deltas].obj_no = i;
1179 nr_ref_deltas++;
1180 } else if (!data) {
1181 /* large blobs, check later */
1182 obj->real_type = OBJ_BAD;
1183 nr_delays++;
1184 } else
1185 sha1_object(data, NULL, obj->size, obj->type,
1186 &obj->idx.oid);
1187 free(data);
1188 display_progress(progress, i+1);
1189 }
1190 objects[i].idx.offset = consumed_bytes;
1191 stop_progress(&progress);
1192
1193 /* Check pack integrity */
1194 flush();
1195 the_hash_algo->final_fn(hash, &input_ctx);
1196 if (!hasheq(fill(the_hash_algo->rawsz), hash))
1197 die(_("pack is corrupted (SHA1 mismatch)"));
1198 use(the_hash_algo->rawsz);
1199
1200 /* If input_fd is a file, we should have reached its end now. */
1201 if (fstat(input_fd, &st))
1202 die_errno(_("cannot fstat packfile"));
1203 if (S_ISREG(st.st_mode) &&
1204 lseek(input_fd, 0, SEEK_CUR) - input_len != st.st_size)
1205 die(_("pack has junk at the end"));
1206
1207 for (i = 0; i < nr_objects; i++) {
1208 struct object_entry *obj = &objects[i];
1209 if (obj->real_type != OBJ_BAD)
1210 continue;
1211 obj->real_type = obj->type;
1212 sha1_object(NULL, obj, obj->size, obj->type,
1213 &obj->idx.oid);
1214 nr_delays--;
1215 }
1216 if (nr_delays)
1217 die(_("confusion beyond insanity in parse_pack_objects()"));
1218 }
1219
1220 /*
1221 * Second pass:
1222 * - for all non-delta objects, look if it is used as a base for
1223 * deltas;
1224 * - if used as a base, uncompress the object and apply all deltas,
1225 * recursively checking if the resulting object is used as a base
1226 * for some more deltas.
1227 */
1228 static void resolve_deltas(void)
1229 {
1230 int i;
1231
1232 if (!nr_ofs_deltas && !nr_ref_deltas)
1233 return;
1234
1235 /* Sort deltas by base SHA1/offset for fast searching */
1236 QSORT(ofs_deltas, nr_ofs_deltas, compare_ofs_delta_entry);
1237 QSORT(ref_deltas, nr_ref_deltas, compare_ref_delta_entry);
1238
1239 if (verbose || show_resolving_progress)
1240 progress = start_progress(_("Resolving deltas"),
1241 nr_ref_deltas + nr_ofs_deltas);
1242
1243 nr_dispatched = 0;
1244 base_cache_limit = delta_base_cache_limit * nr_threads;
1245 if (nr_threads > 1 || getenv("GIT_FORCE_THREADS")) {
1246 init_thread();
1247 for (i = 0; i < nr_threads; i++) {
1248 int ret = pthread_create(&thread_data[i].thread, NULL,
1249 threaded_second_pass, thread_data + i);
1250 if (ret)
1251 die(_("unable to create thread: %s"),
1252 strerror(ret));
1253 }
1254 for (i = 0; i < nr_threads; i++)
1255 pthread_join(thread_data[i].thread, NULL);
1256 cleanup_thread();
1257 return;
1258 }
1259 threaded_second_pass(&nothread_data);
1260 }
1261
1262 /*
1263 * Third pass:
1264 * - append objects to convert thin pack to full pack if required
1265 * - write the final pack hash
1266 */
1267 static void fix_unresolved_deltas(struct hashfile *f);
1268 static void conclude_pack(int fix_thin_pack, const char *curr_pack, unsigned char *pack_hash)
1269 {
1270 if (nr_ref_deltas + nr_ofs_deltas == nr_resolved_deltas) {
1271 stop_progress(&progress);
1272 /* Flush remaining pack final hash. */
1273 flush();
1274 return;
1275 }
1276
1277 if (fix_thin_pack) {
1278 struct hashfile *f;
1279 unsigned char read_hash[GIT_MAX_RAWSZ], tail_hash[GIT_MAX_RAWSZ];
1280 struct strbuf msg = STRBUF_INIT;
1281 int nr_unresolved = nr_ofs_deltas + nr_ref_deltas - nr_resolved_deltas;
1282 int nr_objects_initial = nr_objects;
1283 if (nr_unresolved <= 0)
1284 die(_("confusion beyond insanity"));
1285 REALLOC_ARRAY(objects, nr_objects + nr_unresolved + 1);
1286 memset(objects + nr_objects + 1, 0,
1287 nr_unresolved * sizeof(*objects));
1288 f = hashfd(output_fd, curr_pack);
1289 fix_unresolved_deltas(f);
1290 strbuf_addf(&msg, Q_("completed with %d local object",
1291 "completed with %d local objects",
1292 nr_objects - nr_objects_initial),
1293 nr_objects - nr_objects_initial);
1294 stop_progress_msg(&progress, msg.buf);
1295 strbuf_release(&msg);
1296 finalize_hashfile(f, tail_hash, FSYNC_COMPONENT_PACK, 0);
1297 hashcpy(read_hash, pack_hash);
1298 fixup_pack_header_footer(output_fd, pack_hash,
1299 curr_pack, nr_objects,
1300 read_hash, consumed_bytes-the_hash_algo->rawsz);
1301 if (!hasheq(read_hash, tail_hash))
1302 die(_("Unexpected tail checksum for %s "
1303 "(disk corruption?)"), curr_pack);
1304 }
1305 if (nr_ofs_deltas + nr_ref_deltas != nr_resolved_deltas)
1306 die(Q_("pack has %d unresolved delta",
1307 "pack has %d unresolved deltas",
1308 nr_ofs_deltas + nr_ref_deltas - nr_resolved_deltas),
1309 nr_ofs_deltas + nr_ref_deltas - nr_resolved_deltas);
1310 }
1311
1312 static int write_compressed(struct hashfile *f, void *in, unsigned int size)
1313 {
1314 git_zstream stream;
1315 int status;
1316 unsigned char outbuf[4096];
1317
1318 git_deflate_init(&stream, zlib_compression_level);
1319 stream.next_in = in;
1320 stream.avail_in = size;
1321
1322 do {
1323 stream.next_out = outbuf;
1324 stream.avail_out = sizeof(outbuf);
1325 status = git_deflate(&stream, Z_FINISH);
1326 hashwrite(f, outbuf, sizeof(outbuf) - stream.avail_out);
1327 } while (status == Z_OK);
1328
1329 if (status != Z_STREAM_END)
1330 die(_("unable to deflate appended object (%d)"), status);
1331 size = stream.total_out;
1332 git_deflate_end(&stream);
1333 return size;
1334 }
1335
1336 static struct object_entry *append_obj_to_pack(struct hashfile *f,
1337 const unsigned char *sha1, void *buf,
1338 unsigned long size, enum object_type type)
1339 {
1340 struct object_entry *obj = &objects[nr_objects++];
1341 unsigned char header[10];
1342 unsigned long s = size;
1343 int n = 0;
1344 unsigned char c = (type << 4) | (s & 15);
1345 s >>= 4;
1346 while (s) {
1347 header[n++] = c | 0x80;
1348 c = s & 0x7f;
1349 s >>= 7;
1350 }
1351 header[n++] = c;
1352 crc32_begin(f);
1353 hashwrite(f, header, n);
1354 obj[0].size = size;
1355 obj[0].hdr_size = n;
1356 obj[0].type = type;
1357 obj[0].real_type = type;
1358 obj[1].idx.offset = obj[0].idx.offset + n;
1359 obj[1].idx.offset += write_compressed(f, buf, size);
1360 obj[0].idx.crc32 = crc32_end(f);
1361 hashflush(f);
1362 oidread(&obj->idx.oid, sha1);
1363 return obj;
1364 }
1365
1366 static int delta_pos_compare(const void *_a, const void *_b)
1367 {
1368 struct ref_delta_entry *a = *(struct ref_delta_entry **)_a;
1369 struct ref_delta_entry *b = *(struct ref_delta_entry **)_b;
1370 return a->obj_no - b->obj_no;
1371 }
1372
1373 static void fix_unresolved_deltas(struct hashfile *f)
1374 {
1375 struct ref_delta_entry **sorted_by_pos;
1376 int i;
1377
1378 /*
1379 * Since many unresolved deltas may well be themselves base objects
1380 * for more unresolved deltas, we really want to include the
1381 * smallest number of base objects that would cover as much delta
1382 * as possible by picking the
1383 * trunc deltas first, allowing for other deltas to resolve without
1384 * additional base objects. Since most base objects are to be found
1385 * before deltas depending on them, a good heuristic is to start
1386 * resolving deltas in the same order as their position in the pack.
1387 */
1388 ALLOC_ARRAY(sorted_by_pos, nr_ref_deltas);
1389 for (i = 0; i < nr_ref_deltas; i++)
1390 sorted_by_pos[i] = &ref_deltas[i];
1391 QSORT(sorted_by_pos, nr_ref_deltas, delta_pos_compare);
1392
1393 if (has_promisor_remote()) {
1394 /*
1395 * Prefetch the delta bases.
1396 */
1397 struct oid_array to_fetch = OID_ARRAY_INIT;
1398 for (i = 0; i < nr_ref_deltas; i++) {
1399 struct ref_delta_entry *d = sorted_by_pos[i];
1400 if (!oid_object_info_extended(the_repository, &d->oid,
1401 NULL,
1402 OBJECT_INFO_FOR_PREFETCH))
1403 continue;
1404 oid_array_append(&to_fetch, &d->oid);
1405 }
1406 promisor_remote_get_direct(the_repository,
1407 to_fetch.oid, to_fetch.nr);
1408 oid_array_clear(&to_fetch);
1409 }
1410
1411 for (i = 0; i < nr_ref_deltas; i++) {
1412 struct ref_delta_entry *d = sorted_by_pos[i];
1413 enum object_type type;
1414 void *data;
1415 unsigned long size;
1416
1417 if (objects[d->obj_no].real_type != OBJ_REF_DELTA)
1418 continue;
1419 data = read_object_file(&d->oid, &type, &size);
1420 if (!data)
1421 continue;
1422
1423 if (check_object_signature(the_repository, &d->oid, data, size,
1424 type) < 0)
1425 die(_("local object %s is corrupt"), oid_to_hex(&d->oid));
1426
1427 /*
1428 * Add this as an object to the objects array and call
1429 * threaded_second_pass() (which will pick up the added
1430 * object).
1431 */
1432 append_obj_to_pack(f, d->oid.hash, data, size, type);
1433 free(data);
1434 threaded_second_pass(NULL);
1435
1436 display_progress(progress, nr_resolved_deltas);
1437 }
1438 free(sorted_by_pos);
1439 }
1440
1441 static const char *derive_filename(const char *pack_name, const char *strip,
1442 const char *suffix, struct strbuf *buf)
1443 {
1444 size_t len;
1445 if (!strip_suffix(pack_name, strip, &len) || !len ||
1446 pack_name[len - 1] != '.')
1447 die(_("packfile name '%s' does not end with '.%s'"),
1448 pack_name, strip);
1449 strbuf_add(buf, pack_name, len);
1450 strbuf_addstr(buf, suffix);
1451 return buf->buf;
1452 }
1453
1454 static void write_special_file(const char *suffix, const char *msg,
1455 const char *pack_name, const unsigned char *hash,
1456 const char **report)
1457 {
1458 struct strbuf name_buf = STRBUF_INIT;
1459 const char *filename;
1460 int fd;
1461 int msg_len = strlen(msg);
1462
1463 if (pack_name)
1464 filename = derive_filename(pack_name, "pack", suffix, &name_buf);
1465 else
1466 filename = odb_pack_name(&name_buf, hash, suffix);
1467
1468 fd = odb_pack_keep(filename);
1469 if (fd < 0) {
1470 if (errno != EEXIST)
1471 die_errno(_("cannot write %s file '%s'"),
1472 suffix, filename);
1473 } else {
1474 if (msg_len > 0) {
1475 write_or_die(fd, msg, msg_len);
1476 write_or_die(fd, "\n", 1);
1477 }
1478 if (close(fd) != 0)
1479 die_errno(_("cannot close written %s file '%s'"),
1480 suffix, filename);
1481 if (report)
1482 *report = suffix;
1483 }
1484 strbuf_release(&name_buf);
1485 }
1486
1487 static void rename_tmp_packfile(const char **final_name,
1488 const char *curr_name,
1489 struct strbuf *name, unsigned char *hash,
1490 const char *ext, int make_read_only_if_same)
1491 {
1492 if (*final_name != curr_name) {
1493 if (!*final_name)
1494 *final_name = odb_pack_name(name, hash, ext);
1495 if (finalize_object_file(curr_name, *final_name))
1496 die(_("unable to rename temporary '*.%s' file to '%s'"),
1497 ext, *final_name);
1498 } else if (make_read_only_if_same) {
1499 chmod(*final_name, 0444);
1500 }
1501 }
1502
1503 static void final(const char *final_pack_name, const char *curr_pack_name,
1504 const char *final_index_name, const char *curr_index_name,
1505 const char *final_rev_index_name, const char *curr_rev_index_name,
1506 const char *keep_msg, const char *promisor_msg,
1507 unsigned char *hash)
1508 {
1509 const char *report = "pack";
1510 struct strbuf pack_name = STRBUF_INIT;
1511 struct strbuf index_name = STRBUF_INIT;
1512 struct strbuf rev_index_name = STRBUF_INIT;
1513 int err;
1514
1515 if (!from_stdin) {
1516 close(input_fd);
1517 } else {
1518 fsync_component_or_die(FSYNC_COMPONENT_PACK, output_fd, curr_pack_name);
1519 err = close(output_fd);
1520 if (err)
1521 die_errno(_("error while closing pack file"));
1522 }
1523
1524 if (keep_msg)
1525 write_special_file("keep", keep_msg, final_pack_name, hash,
1526 &report);
1527 if (promisor_msg)
1528 write_special_file("promisor", promisor_msg, final_pack_name,
1529 hash, NULL);
1530
1531 rename_tmp_packfile(&final_pack_name, curr_pack_name, &pack_name,
1532 hash, "pack", from_stdin);
1533 if (curr_rev_index_name)
1534 rename_tmp_packfile(&final_rev_index_name, curr_rev_index_name,
1535 &rev_index_name, hash, "rev", 1);
1536 rename_tmp_packfile(&final_index_name, curr_index_name, &index_name,
1537 hash, "idx", 1);
1538
1539 if (do_fsck_object) {
1540 struct packed_git *p;
1541 p = add_packed_git(final_index_name, strlen(final_index_name), 0);
1542 if (p)
1543 install_packed_git(the_repository, p);
1544 }
1545
1546 if (!from_stdin) {
1547 printf("%s\n", hash_to_hex(hash));
1548 } else {
1549 struct strbuf buf = STRBUF_INIT;
1550
1551 strbuf_addf(&buf, "%s\t%s\n", report, hash_to_hex(hash));
1552 write_or_die(1, buf.buf, buf.len);
1553 strbuf_release(&buf);
1554
1555 /*
1556 * Let's just mimic git-unpack-objects here and write
1557 * the last part of the input buffer to stdout.
1558 */
1559 while (input_len) {
1560 err = xwrite(1, input_buffer + input_offset, input_len);
1561 if (err <= 0)
1562 break;
1563 input_len -= err;
1564 input_offset += err;
1565 }
1566 }
1567
1568 strbuf_release(&rev_index_name);
1569 strbuf_release(&index_name);
1570 strbuf_release(&pack_name);
1571 }
1572
1573 static int git_index_pack_config(const char *k, const char *v, void *cb)
1574 {
1575 struct pack_idx_option *opts = cb;
1576
1577 if (!strcmp(k, "pack.indexversion")) {
1578 opts->version = git_config_int(k, v);
1579 if (opts->version > 2)
1580 die(_("bad pack.indexVersion=%"PRIu32), opts->version);
1581 return 0;
1582 }
1583 if (!strcmp(k, "pack.threads")) {
1584 nr_threads = git_config_int(k, v);
1585 if (nr_threads < 0)
1586 die(_("invalid number of threads specified (%d)"),
1587 nr_threads);
1588 if (!HAVE_THREADS && nr_threads != 1) {
1589 warning(_("no threads support, ignoring %s"), k);
1590 nr_threads = 1;
1591 }
1592 return 0;
1593 }
1594 if (!strcmp(k, "pack.writereverseindex")) {
1595 if (git_config_bool(k, v))
1596 opts->flags |= WRITE_REV;
1597 else
1598 opts->flags &= ~WRITE_REV;
1599 }
1600 return git_default_config(k, v, cb);
1601 }
1602
1603 static int cmp_uint32(const void *a_, const void *b_)
1604 {
1605 uint32_t a = *((uint32_t *)a_);
1606 uint32_t b = *((uint32_t *)b_);
1607
1608 return (a < b) ? -1 : (a != b);
1609 }
1610
1611 static void read_v2_anomalous_offsets(struct packed_git *p,
1612 struct pack_idx_option *opts)
1613 {
1614 const uint32_t *idx1, *idx2;
1615 uint32_t i;
1616
1617 /* The address of the 4-byte offset table */
1618 idx1 = (((const uint32_t *)((const uint8_t *)p->index_data + p->crc_offset))
1619 + (size_t)p->num_objects /* CRC32 table */
1620 );
1621
1622 /* The address of the 8-byte offset table */
1623 idx2 = idx1 + p->num_objects;
1624
1625 for (i = 0; i < p->num_objects; i++) {
1626 uint32_t off = ntohl(idx1[i]);
1627 if (!(off & 0x80000000))
1628 continue;
1629 off = off & 0x7fffffff;
1630 check_pack_index_ptr(p, &idx2[off * 2]);
1631 if (idx2[off * 2])
1632 continue;
1633 /*
1634 * The real offset is ntohl(idx2[off * 2]) in high 4
1635 * octets, and ntohl(idx2[off * 2 + 1]) in low 4
1636 * octets. But idx2[off * 2] is Zero!!!
1637 */
1638 ALLOC_GROW(opts->anomaly, opts->anomaly_nr + 1, opts->anomaly_alloc);
1639 opts->anomaly[opts->anomaly_nr++] = ntohl(idx2[off * 2 + 1]);
1640 }
1641
1642 QSORT(opts->anomaly, opts->anomaly_nr, cmp_uint32);
1643 }
1644
1645 static void read_idx_option(struct pack_idx_option *opts, const char *pack_name)
1646 {
1647 struct packed_git *p = add_packed_git(pack_name, strlen(pack_name), 1);
1648
1649 if (!p)
1650 die(_("Cannot open existing pack file '%s'"), pack_name);
1651 if (open_pack_index(p))
1652 die(_("Cannot open existing pack idx file for '%s'"), pack_name);
1653
1654 /* Read the attributes from the existing idx file */
1655 opts->version = p->index_version;
1656
1657 if (opts->version == 2)
1658 read_v2_anomalous_offsets(p, opts);
1659
1660 /*
1661 * Get rid of the idx file as we do not need it anymore.
1662 * NEEDSWORK: extract this bit from free_pack_by_name() in
1663 * object-file.c, perhaps? It shouldn't matter very much as we
1664 * know we haven't installed this pack (hence we never have
1665 * read anything from it).
1666 */
1667 close_pack_index(p);
1668 free(p);
1669 }
1670
1671 static void show_pack_info(int stat_only)
1672 {
1673 int i, baseobjects = nr_objects - nr_ref_deltas - nr_ofs_deltas;
1674 unsigned long *chain_histogram = NULL;
1675
1676 if (deepest_delta)
1677 CALLOC_ARRAY(chain_histogram, deepest_delta);
1678
1679 for (i = 0; i < nr_objects; i++) {
1680 struct object_entry *obj = &objects[i];
1681
1682 if (is_delta_type(obj->type))
1683 chain_histogram[obj_stat[i].delta_depth - 1]++;
1684 if (stat_only)
1685 continue;
1686 printf("%s %-6s %"PRIuMAX" %"PRIuMAX" %"PRIuMAX,
1687 oid_to_hex(&obj->idx.oid),
1688 type_name(obj->real_type), (uintmax_t)obj->size,
1689 (uintmax_t)(obj[1].idx.offset - obj->idx.offset),
1690 (uintmax_t)obj->idx.offset);
1691 if (is_delta_type(obj->type)) {
1692 struct object_entry *bobj = &objects[obj_stat[i].base_object_no];
1693 printf(" %u %s", obj_stat[i].delta_depth,
1694 oid_to_hex(&bobj->idx.oid));
1695 }
1696 putchar('\n');
1697 }
1698
1699 if (baseobjects)
1700 printf_ln(Q_("non delta: %d object",
1701 "non delta: %d objects",
1702 baseobjects),
1703 baseobjects);
1704 for (i = 0; i < deepest_delta; i++) {
1705 if (!chain_histogram[i])
1706 continue;
1707 printf_ln(Q_("chain length = %d: %lu object",
1708 "chain length = %d: %lu objects",
1709 chain_histogram[i]),
1710 i + 1,
1711 chain_histogram[i]);
1712 }
1713 free(chain_histogram);
1714 }
1715
1716 int cmd_index_pack(int argc, const char **argv, const char *prefix)
1717 {
1718 int i, fix_thin_pack = 0, verify = 0, stat_only = 0, rev_index;
1719 const char *curr_index;
1720 const char *curr_rev_index = NULL;
1721 const char *index_name = NULL, *pack_name = NULL, *rev_index_name = NULL;
1722 const char *keep_msg = NULL;
1723 const char *promisor_msg = NULL;
1724 struct strbuf index_name_buf = STRBUF_INIT;
1725 struct strbuf rev_index_name_buf = STRBUF_INIT;
1726 struct pack_idx_entry **idx_objects;
1727 struct pack_idx_option opts;
1728 unsigned char pack_hash[GIT_MAX_RAWSZ];
1729 unsigned foreign_nr = 1; /* zero is a "good" value, assume bad */
1730 int report_end_of_input = 0;
1731 int hash_algo = 0;
1732
1733 /*
1734 * index-pack never needs to fetch missing objects except when
1735 * REF_DELTA bases are missing (which are explicitly handled). It only
1736 * accesses the repo to do hash collision checks and to check which
1737 * REF_DELTA bases need to be fetched.
1738 */
1739 fetch_if_missing = 0;
1740
1741 if (argc == 2 && !strcmp(argv[1], "-h"))
1742 usage(index_pack_usage);
1743
1744 read_replace_refs = 0;
1745 fsck_options.walk = mark_link;
1746
1747 reset_pack_idx_option(&opts);
1748 git_config(git_index_pack_config, &opts);
1749 if (prefix && chdir(prefix))
1750 die(_("Cannot come back to cwd"));
1751
1752 if (git_env_bool(GIT_TEST_WRITE_REV_INDEX, 0))
1753 rev_index = 1;
1754 else
1755 rev_index = !!(opts.flags & (WRITE_REV_VERIFY | WRITE_REV));
1756
1757 for (i = 1; i < argc; i++) {
1758 const char *arg = argv[i];
1759
1760 if (*arg == '-') {
1761 if (!strcmp(arg, "--stdin")) {
1762 from_stdin = 1;
1763 } else if (!strcmp(arg, "--fix-thin")) {
1764 fix_thin_pack = 1;
1765 } else if (skip_to_optional_arg(arg, "--strict", &arg)) {
1766 strict = 1;
1767 do_fsck_object = 1;
1768 fsck_set_msg_types(&fsck_options, arg);
1769 } else if (!strcmp(arg, "--check-self-contained-and-connected")) {
1770 strict = 1;
1771 check_self_contained_and_connected = 1;
1772 } else if (!strcmp(arg, "--fsck-objects")) {
1773 do_fsck_object = 1;
1774 } else if (!strcmp(arg, "--verify")) {
1775 verify = 1;
1776 } else if (!strcmp(arg, "--verify-stat")) {
1777 verify = 1;
1778 show_stat = 1;
1779 } else if (!strcmp(arg, "--verify-stat-only")) {
1780 verify = 1;
1781 show_stat = 1;
1782 stat_only = 1;
1783 } else if (skip_to_optional_arg(arg, "--keep", &keep_msg)) {
1784 ; /* nothing to do */
1785 } else if (skip_to_optional_arg(arg, "--promisor", &promisor_msg)) {
1786 ; /* already parsed */
1787 } else if (starts_with(arg, "--threads=")) {
1788 char *end;
1789 nr_threads = strtoul(arg+10, &end, 0);
1790 if (!arg[10] || *end || nr_threads < 0)
1791 usage(index_pack_usage);
1792 if (!HAVE_THREADS && nr_threads != 1) {
1793 warning(_("no threads support, ignoring %s"), arg);
1794 nr_threads = 1;
1795 }
1796 } else if (starts_with(arg, "--pack_header=")) {
1797 struct pack_header *hdr;
1798 char *c;
1799
1800 hdr = (struct pack_header *)input_buffer;
1801 hdr->hdr_signature = htonl(PACK_SIGNATURE);
1802 hdr->hdr_version = htonl(strtoul(arg + 14, &c, 10));
1803 if (*c != ',')
1804 die(_("bad %s"), arg);
1805 hdr->hdr_entries = htonl(strtoul(c + 1, &c, 10));
1806 if (*c)
1807 die(_("bad %s"), arg);
1808 input_len = sizeof(*hdr);
1809 } else if (!strcmp(arg, "-v")) {
1810 verbose = 1;
1811 } else if (!strcmp(arg, "--progress-title")) {
1812 if (progress_title || (i+1) >= argc)
1813 usage(index_pack_usage);
1814 progress_title = argv[++i];
1815 } else if (!strcmp(arg, "--show-resolving-progress")) {
1816 show_resolving_progress = 1;
1817 } else if (!strcmp(arg, "--report-end-of-input")) {
1818 report_end_of_input = 1;
1819 } else if (!strcmp(arg, "-o")) {
1820 if (index_name || (i+1) >= argc)
1821 usage(index_pack_usage);
1822 index_name = argv[++i];
1823 } else if (starts_with(arg, "--index-version=")) {
1824 char *c;
1825 opts.version = strtoul(arg + 16, &c, 10);
1826 if (opts.version > 2)
1827 die(_("bad %s"), arg);
1828 if (*c == ',')
1829 opts.off32_limit = strtoul(c+1, &c, 0);
1830 if (*c || opts.off32_limit & 0x80000000)
1831 die(_("bad %s"), arg);
1832 } else if (skip_prefix(arg, "--max-input-size=", &arg)) {
1833 max_input_size = strtoumax(arg, NULL, 10);
1834 } else if (skip_prefix(arg, "--object-format=", &arg)) {
1835 hash_algo = hash_algo_by_name(arg);
1836 if (hash_algo == GIT_HASH_UNKNOWN)
1837 die(_("unknown hash algorithm '%s'"), arg);
1838 repo_set_hash_algo(the_repository, hash_algo);
1839 } else if (!strcmp(arg, "--rev-index")) {
1840 rev_index = 1;
1841 } else if (!strcmp(arg, "--no-rev-index")) {
1842 rev_index = 0;
1843 } else
1844 usage(index_pack_usage);
1845 continue;
1846 }
1847
1848 if (pack_name)
1849 usage(index_pack_usage);
1850 pack_name = arg;
1851 }
1852
1853 if (!pack_name && !from_stdin)
1854 usage(index_pack_usage);
1855 if (fix_thin_pack && !from_stdin)
1856 die(_("the option '%s' requires '%s'"), "--fix-thin", "--stdin");
1857 if (from_stdin && !startup_info->have_repository)
1858 die(_("--stdin requires a git repository"));
1859 if (from_stdin && hash_algo)
1860 die(_("options '%s' and '%s' cannot be used together"), "--object-format", "--stdin");
1861 if (!index_name && pack_name)
1862 index_name = derive_filename(pack_name, "pack", "idx", &index_name_buf);
1863
1864 opts.flags &= ~(WRITE_REV | WRITE_REV_VERIFY);
1865 if (rev_index) {
1866 opts.flags |= verify ? WRITE_REV_VERIFY : WRITE_REV;
1867 if (index_name)
1868 rev_index_name = derive_filename(index_name,
1869 "idx", "rev",
1870 &rev_index_name_buf);
1871 }
1872
1873 if (verify) {
1874 if (!index_name)
1875 die(_("--verify with no packfile name given"));
1876 read_idx_option(&opts, index_name);
1877 opts.flags |= WRITE_IDX_VERIFY | WRITE_IDX_STRICT;
1878 }
1879 if (strict)
1880 opts.flags |= WRITE_IDX_STRICT;
1881
1882 if (HAVE_THREADS && !nr_threads) {
1883 nr_threads = online_cpus();
1884 /*
1885 * Experiments show that going above 20 threads doesn't help,
1886 * no matter how many cores you have. Below that, we tend to
1887 * max at half the number of online_cpus(), presumably because
1888 * half of those are hyperthreads rather than full cores. We'll
1889 * never reduce the level below "3", though, to match a
1890 * historical value that nobody complained about.
1891 */
1892 if (nr_threads < 4)
1893 ; /* too few cores to consider capping */
1894 else if (nr_threads < 6)
1895 nr_threads = 3; /* historic cap */
1896 else if (nr_threads < 40)
1897 nr_threads /= 2;
1898 else
1899 nr_threads = 20; /* hard cap */
1900 }
1901
1902 curr_pack = open_pack_file(pack_name);
1903 parse_pack_header();
1904 CALLOC_ARRAY(objects, st_add(nr_objects, 1));
1905 if (show_stat)
1906 CALLOC_ARRAY(obj_stat, st_add(nr_objects, 1));
1907 CALLOC_ARRAY(ofs_deltas, nr_objects);
1908 parse_pack_objects(pack_hash);
1909 if (report_end_of_input)
1910 write_in_full(2, "\0", 1);
1911 resolve_deltas();
1912 conclude_pack(fix_thin_pack, curr_pack, pack_hash);
1913 free(ofs_deltas);
1914 free(ref_deltas);
1915 if (strict)
1916 foreign_nr = check_objects();
1917
1918 if (show_stat)
1919 show_pack_info(stat_only);
1920
1921 ALLOC_ARRAY(idx_objects, nr_objects);
1922 for (i = 0; i < nr_objects; i++)
1923 idx_objects[i] = &objects[i].idx;
1924 curr_index = write_idx_file(index_name, idx_objects, nr_objects, &opts, pack_hash);
1925 if (rev_index)
1926 curr_rev_index = write_rev_file(rev_index_name, idx_objects,
1927 nr_objects, pack_hash,
1928 opts.flags);
1929 free(idx_objects);
1930
1931 if (!verify)
1932 final(pack_name, curr_pack,
1933 index_name, curr_index,
1934 rev_index_name, curr_rev_index,
1935 keep_msg, promisor_msg,
1936 pack_hash);
1937 else
1938 close(input_fd);
1939
1940 if (do_fsck_object && fsck_finish(&fsck_options))
1941 die(_("fsck error in pack objects"));
1942
1943 free(opts.anomaly);
1944 free(objects);
1945 strbuf_release(&index_name_buf);
1946 strbuf_release(&rev_index_name_buf);
1947 if (!pack_name)
1948 free((void *) curr_pack);
1949 if (!index_name)
1950 free((void *) curr_index);
1951 if (!rev_index_name)
1952 free((void *) curr_rev_index);
1953
1954 /*
1955 * Let the caller know this pack is not self contained
1956 */
1957 if (check_self_contained_and_connected && foreign_nr)
1958 return 1;
1959
1960 return 0;
1961 }