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