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