index-pack: smarter memory usage during delta resolution
[git] / index-pack.c
1 #include "cache.h"
2 #include "delta.h"
3 #include "pack.h"
4 #include "csum-file.h"
5 #include "blob.h"
6 #include "commit.h"
7 #include "tag.h"
8 #include "tree.h"
9 #include "progress.h"
10 #include "fsck.h"
11
12 static const char index_pack_usage[] =
13 "git index-pack [-v] [-o <index-file>] [{ ---keep | --keep=<msg> }] [--strict] { <pack-file> | --stdin [--fix-thin] [<pack-file>] }";
14
15 struct object_entry
16 {
17         struct pack_idx_entry idx;
18         unsigned long size;
19         unsigned int hdr_size;
20         enum object_type type;
21         enum object_type real_type;
22 };
23
24 union delta_base {
25         unsigned char sha1[20];
26         off_t offset;
27 };
28
29 struct base_data {
30         struct base_data *base;
31         struct base_data *child;
32         struct object_entry *obj;
33         void *data;
34         unsigned long size;
35 };
36
37 /*
38  * Even if sizeof(union delta_base) == 24 on 64-bit archs, we really want
39  * to memcmp() only the first 20 bytes.
40  */
41 #define UNION_BASE_SZ   20
42
43 #define FLAG_LINK (1u<<20)
44 #define FLAG_CHECKED (1u<<21)
45
46 struct delta_entry
47 {
48         union delta_base base;
49         int obj_no;
50 };
51
52 static struct object_entry *objects;
53 static struct delta_entry *deltas;
54 static struct base_data *base_cache;
55 static size_t base_cache_used;
56 static int nr_objects;
57 static int nr_deltas;
58 static int nr_resolved_deltas;
59
60 static int from_stdin;
61 static int strict;
62 static int verbose;
63
64 static struct progress *progress;
65
66 /* We always read in 4kB chunks. */
67 static unsigned char input_buffer[4096];
68 static unsigned int input_offset, input_len;
69 static off_t consumed_bytes;
70 static git_SHA_CTX input_ctx;
71 static uint32_t input_crc32;
72 static int input_fd, output_fd, pack_fd;
73
74 static int mark_link(struct object *obj, int type, void *data)
75 {
76         if (!obj)
77                 return -1;
78
79         if (type != OBJ_ANY && obj->type != type)
80                 die("object type mismatch at %s", sha1_to_hex(obj->sha1));
81
82         obj->flags |= FLAG_LINK;
83         return 0;
84 }
85
86 /* The content of each linked object must have been checked
87    or it must be already present in the object database */
88 static void check_object(struct object *obj)
89 {
90         if (!obj)
91                 return;
92
93         if (!(obj->flags & FLAG_LINK))
94                 return;
95
96         if (!(obj->flags & FLAG_CHECKED)) {
97                 unsigned long size;
98                 int type = sha1_object_info(obj->sha1, &size);
99                 if (type != obj->type || type <= 0)
100                         die("object of unexpected type");
101                 obj->flags |= FLAG_CHECKED;
102                 return;
103         }
104 }
105
106 static void check_objects(void)
107 {
108         unsigned i, max;
109
110         max = get_max_object_index();
111         for (i = 0; i < max; i++)
112                 check_object(get_indexed_object(i));
113 }
114
115
116 /* Discard current buffer used content. */
117 static void flush(void)
118 {
119         if (input_offset) {
120                 if (output_fd >= 0)
121                         write_or_die(output_fd, input_buffer, input_offset);
122                 git_SHA1_Update(&input_ctx, input_buffer, input_offset);
123                 memmove(input_buffer, input_buffer + input_offset, input_len);
124                 input_offset = 0;
125         }
126 }
127
128 /*
129  * Make sure at least "min" bytes are available in the buffer, and
130  * return the pointer to the buffer.
131  */
132 static void *fill(int min)
133 {
134         if (min <= input_len)
135                 return input_buffer + input_offset;
136         if (min > sizeof(input_buffer))
137                 die("cannot fill %d bytes", min);
138         flush();
139         do {
140                 ssize_t ret = xread(input_fd, input_buffer + input_len,
141                                 sizeof(input_buffer) - input_len);
142                 if (ret <= 0) {
143                         if (!ret)
144                                 die("early EOF");
145                         die("read error on input: %s", strerror(errno));
146                 }
147                 input_len += ret;
148                 if (from_stdin)
149                         display_throughput(progress, consumed_bytes + input_len);
150         } while (input_len < min);
151         return input_buffer;
152 }
153
154 static void use(int bytes)
155 {
156         if (bytes > input_len)
157                 die("used more bytes than were available");
158         input_crc32 = crc32(input_crc32, input_buffer + input_offset, bytes);
159         input_len -= bytes;
160         input_offset += bytes;
161
162         /* make sure off_t is sufficiently large not to wrap */
163         if (consumed_bytes > consumed_bytes + bytes)
164                 die("pack too large for current definition of off_t");
165         consumed_bytes += bytes;
166 }
167
168 static char *open_pack_file(char *pack_name)
169 {
170         if (from_stdin) {
171                 input_fd = 0;
172                 if (!pack_name) {
173                         static char tmpfile[PATH_MAX];
174                         snprintf(tmpfile, sizeof(tmpfile),
175                                  "%s/pack/tmp_pack_XXXXXX", get_object_directory());
176                         output_fd = xmkstemp(tmpfile);
177                         pack_name = xstrdup(tmpfile);
178                 } else
179                         output_fd = open(pack_name, O_CREAT|O_EXCL|O_RDWR, 0600);
180                 if (output_fd < 0)
181                         die("unable to create %s: %s\n", pack_name, strerror(errno));
182                 pack_fd = output_fd;
183         } else {
184                 input_fd = open(pack_name, O_RDONLY);
185                 if (input_fd < 0)
186                         die("cannot open packfile '%s': %s",
187                             pack_name, strerror(errno));
188                 output_fd = -1;
189                 pack_fd = input_fd;
190         }
191         git_SHA1_Init(&input_ctx);
192         return pack_name;
193 }
194
195 static void parse_pack_header(void)
196 {
197         struct pack_header *hdr = fill(sizeof(struct pack_header));
198
199         /* Header consistency check */
200         if (hdr->hdr_signature != htonl(PACK_SIGNATURE))
201                 die("pack signature mismatch");
202         if (!pack_version_ok(hdr->hdr_version))
203                 die("pack version %"PRIu32" unsupported",
204                         ntohl(hdr->hdr_version));
205
206         nr_objects = ntohl(hdr->hdr_entries);
207         use(sizeof(struct pack_header));
208 }
209
210 static void bad_object(unsigned long offset, const char *format,
211                        ...) NORETURN __attribute__((format (printf, 2, 3)));
212
213 static void bad_object(unsigned long offset, const char *format, ...)
214 {
215         va_list params;
216         char buf[1024];
217
218         va_start(params, format);
219         vsnprintf(buf, sizeof(buf), format, params);
220         va_end(params);
221         die("pack has bad object at offset %lu: %s", offset, buf);
222 }
223
224 static void free_base_data(struct base_data *c)
225 {
226         if (c->data) {
227                 free(c->data);
228                 c->data = NULL;
229                 base_cache_used -= c->size;
230         }
231 }
232
233 static void prune_base_data(struct base_data *retain)
234 {
235         struct base_data *b = base_cache;
236         for (b = base_cache;
237              base_cache_used > delta_base_cache_limit && b;
238              b = b->child) {
239                 if (b->data && b != retain)
240                         free_base_data(b);
241         }
242 }
243
244 static void link_base_data(struct base_data *base, struct base_data *c)
245 {
246         if (base)
247                 base->child = c;
248         else
249                 base_cache = c;
250
251         c->base = base;
252         c->child = NULL;
253         if (c->data)
254                 base_cache_used += c->size;
255         prune_base_data(c);
256 }
257
258 static void unlink_base_data(struct base_data *c)
259 {
260         struct base_data *base = c->base;
261         if (base)
262                 base->child = NULL;
263         else
264                 base_cache = NULL;
265         free_base_data(c);
266 }
267
268 static void *unpack_entry_data(unsigned long offset, unsigned long size)
269 {
270         z_stream stream;
271         void *buf = xmalloc(size);
272
273         memset(&stream, 0, sizeof(stream));
274         stream.next_out = buf;
275         stream.avail_out = size;
276         stream.next_in = fill(1);
277         stream.avail_in = input_len;
278         inflateInit(&stream);
279
280         for (;;) {
281                 int ret = inflate(&stream, 0);
282                 use(input_len - stream.avail_in);
283                 if (stream.total_out == size && ret == Z_STREAM_END)
284                         break;
285                 if (ret != Z_OK)
286                         bad_object(offset, "inflate returned %d", ret);
287                 stream.next_in = fill(1);
288                 stream.avail_in = input_len;
289         }
290         inflateEnd(&stream);
291         return buf;
292 }
293
294 static void *unpack_raw_entry(struct object_entry *obj, union delta_base *delta_base)
295 {
296         unsigned char *p, c;
297         unsigned long size;
298         off_t base_offset;
299         unsigned shift;
300         void *data;
301
302         obj->idx.offset = consumed_bytes;
303         input_crc32 = crc32(0, Z_NULL, 0);
304
305         p = fill(1);
306         c = *p;
307         use(1);
308         obj->type = (c >> 4) & 7;
309         size = (c & 15);
310         shift = 4;
311         while (c & 0x80) {
312                 p = fill(1);
313                 c = *p;
314                 use(1);
315                 size += (c & 0x7fUL) << shift;
316                 shift += 7;
317         }
318         obj->size = size;
319
320         switch (obj->type) {
321         case OBJ_REF_DELTA:
322                 hashcpy(delta_base->sha1, fill(20));
323                 use(20);
324                 break;
325         case OBJ_OFS_DELTA:
326                 memset(delta_base, 0, sizeof(*delta_base));
327                 p = fill(1);
328                 c = *p;
329                 use(1);
330                 base_offset = c & 127;
331                 while (c & 128) {
332                         base_offset += 1;
333                         if (!base_offset || MSB(base_offset, 7))
334                                 bad_object(obj->idx.offset, "offset value overflow for delta base object");
335                         p = fill(1);
336                         c = *p;
337                         use(1);
338                         base_offset = (base_offset << 7) + (c & 127);
339                 }
340                 delta_base->offset = obj->idx.offset - base_offset;
341                 if (delta_base->offset >= obj->idx.offset)
342                         bad_object(obj->idx.offset, "delta base offset is out of bound");
343                 break;
344         case OBJ_COMMIT:
345         case OBJ_TREE:
346         case OBJ_BLOB:
347         case OBJ_TAG:
348                 break;
349         default:
350                 bad_object(obj->idx.offset, "unknown object type %d", obj->type);
351         }
352         obj->hdr_size = consumed_bytes - obj->idx.offset;
353
354         data = unpack_entry_data(obj->idx.offset, obj->size);
355         obj->idx.crc32 = input_crc32;
356         return data;
357 }
358
359 static void *get_data_from_pack(struct object_entry *obj)
360 {
361         off_t from = obj[0].idx.offset + obj[0].hdr_size;
362         unsigned long len = obj[1].idx.offset - from;
363         unsigned long rdy = 0;
364         unsigned char *src, *data;
365         z_stream stream;
366         int st;
367
368         src = xmalloc(len);
369         data = src;
370         do {
371                 ssize_t n = pread(pack_fd, data + rdy, len - rdy, from + rdy);
372                 if (n < 0)
373                         die("cannot pread pack file: %s", strerror(errno));
374                 if (!n)
375                         die("premature end of pack file, %lu bytes missing",
376                             len - rdy);
377                 rdy += n;
378         } while (rdy < len);
379         data = xmalloc(obj->size);
380         memset(&stream, 0, sizeof(stream));
381         stream.next_out = data;
382         stream.avail_out = obj->size;
383         stream.next_in = src;
384         stream.avail_in = len;
385         inflateInit(&stream);
386         while ((st = inflate(&stream, Z_FINISH)) == Z_OK);
387         inflateEnd(&stream);
388         if (st != Z_STREAM_END || stream.total_out != obj->size)
389                 die("serious inflate inconsistency");
390         free(src);
391         return data;
392 }
393
394 static int find_delta(const union delta_base *base)
395 {
396         int first = 0, last = nr_deltas;
397
398         while (first < last) {
399                 int next = (first + last) / 2;
400                 struct delta_entry *delta = &deltas[next];
401                 int cmp;
402
403                 cmp = memcmp(base, &delta->base, UNION_BASE_SZ);
404                 if (!cmp)
405                         return next;
406                 if (cmp < 0) {
407                         last = next;
408                         continue;
409                 }
410                 first = next+1;
411         }
412         return -first-1;
413 }
414
415 static void find_delta_children(const union delta_base *base,
416                                 int *first_index, int *last_index)
417 {
418         int first = find_delta(base);
419         int last = first;
420         int end = nr_deltas - 1;
421
422         if (first < 0) {
423                 *first_index = 0;
424                 *last_index = -1;
425                 return;
426         }
427         while (first > 0 && !memcmp(&deltas[first - 1].base, base, UNION_BASE_SZ))
428                 --first;
429         while (last < end && !memcmp(&deltas[last + 1].base, base, UNION_BASE_SZ))
430                 ++last;
431         *first_index = first;
432         *last_index = last;
433 }
434
435 static void sha1_object(const void *data, unsigned long size,
436                         enum object_type type, unsigned char *sha1)
437 {
438         hash_sha1_file(data, size, typename(type), sha1);
439         if (has_sha1_file(sha1)) {
440                 void *has_data;
441                 enum object_type has_type;
442                 unsigned long has_size;
443                 has_data = read_sha1_file(sha1, &has_type, &has_size);
444                 if (!has_data)
445                         die("cannot read existing object %s", sha1_to_hex(sha1));
446                 if (size != has_size || type != has_type ||
447                     memcmp(data, has_data, size) != 0)
448                         die("SHA1 COLLISION FOUND WITH %s !", sha1_to_hex(sha1));
449                 free(has_data);
450         }
451         if (strict) {
452                 if (type == OBJ_BLOB) {
453                         struct blob *blob = lookup_blob(sha1);
454                         if (blob)
455                                 blob->object.flags |= FLAG_CHECKED;
456                         else
457                                 die("invalid blob object %s", sha1_to_hex(sha1));
458                 } else {
459                         struct object *obj;
460                         int eaten;
461                         void *buf = (void *) data;
462
463                         /*
464                          * we do not need to free the memory here, as the
465                          * buf is deleted by the caller.
466                          */
467                         obj = parse_object_buffer(sha1, type, size, buf, &eaten);
468                         if (!obj)
469                                 die("invalid %s", typename(type));
470                         if (fsck_object(obj, 1, fsck_error_function))
471                                 die("Error in object");
472                         if (fsck_walk(obj, mark_link, 0))
473                                 die("Not all child objects of %s are reachable", sha1_to_hex(obj->sha1));
474
475                         if (obj->type == OBJ_TREE) {
476                                 struct tree *item = (struct tree *) obj;
477                                 item->buffer = NULL;
478                         }
479                         if (obj->type == OBJ_COMMIT) {
480                                 struct commit *commit = (struct commit *) obj;
481                                 commit->buffer = NULL;
482                         }
483                         obj->flags |= FLAG_CHECKED;
484                 }
485         }
486 }
487
488 static void *get_base_data(struct base_data *c)
489 {
490         if (!c->data) {
491                 struct object_entry *obj = c->obj;
492
493                 if (obj->type == OBJ_REF_DELTA || obj->type == OBJ_OFS_DELTA) {
494                         void *base = get_base_data(c->base);
495                         void *raw = get_data_from_pack(obj);
496                         c->data = patch_delta(
497                                 base, c->base->size,
498                                 raw, obj->size,
499                                 &c->size);
500                         free(raw);
501                         if (!c->data)
502                                 bad_object(obj->idx.offset, "failed to apply delta");
503                 } else {
504                         c->data = get_data_from_pack(obj);
505                         c->size = obj->size;
506                 }
507
508                 base_cache_used += c->size;
509                 prune_base_data(c);
510         }
511         return c->data;
512 }
513
514 static void resolve_delta(struct object_entry *delta_obj,
515                           struct base_data *base, struct base_data *result)
516 {
517         void *delta_data;
518         unsigned long delta_size;
519
520         delta_obj->real_type = base->obj->type;
521         delta_data = get_data_from_pack(delta_obj);
522         delta_size = delta_obj->size;
523         result->obj = delta_obj;
524         result->data = patch_delta(get_base_data(base), base->obj->size,
525                                    delta_data, delta_size, &result->size);
526         free(delta_data);
527         if (!result->data)
528                 bad_object(delta_obj->idx.offset, "failed to apply delta");
529         sha1_object(result->data, result->size, delta_obj->real_type,
530                     delta_obj->idx.sha1);
531         nr_resolved_deltas++;
532 }
533
534 static void find_unresolved_deltas(struct base_data *base,
535                                    struct base_data *prev_base)
536 {
537         int i, ref_first, ref_last, ofs_first, ofs_last;
538
539         /*
540          * This is a recursive function. Those brackets should help reducing
541          * stack usage by limiting the scope of the delta_base union.
542          */
543         {
544                 union delta_base base_spec;
545
546                 hashcpy(base_spec.sha1, base->obj->idx.sha1);
547                 find_delta_children(&base_spec, &ref_first, &ref_last);
548
549                 memset(&base_spec, 0, sizeof(base_spec));
550                 base_spec.offset = base->obj->idx.offset;
551                 find_delta_children(&base_spec, &ofs_first, &ofs_last);
552         }
553
554         if (ref_last == -1 && ofs_last == -1)
555                 return;
556
557         link_base_data(prev_base, base);
558
559         for (i = ref_first; i <= ref_last; i++) {
560                 struct object_entry *child = objects + deltas[i].obj_no;
561                 if (child->real_type == OBJ_REF_DELTA) {
562                         struct base_data result;
563                         resolve_delta(child, base, &result);
564                         if (i == ref_last && ofs_last == -1)
565                                 free_base_data(base);
566                         find_unresolved_deltas(&result, base);
567                 }
568         }
569
570         for (i = ofs_first; i <= ofs_last; i++) {
571                 struct object_entry *child = objects + deltas[i].obj_no;
572                 if (child->real_type == OBJ_OFS_DELTA) {
573                         struct base_data result;
574                         resolve_delta(child, base, &result);
575                         if (i == ofs_last)
576                                 free_base_data(base);
577                         find_unresolved_deltas(&result, base);
578                 }
579         }
580
581         unlink_base_data(base);
582 }
583
584 static int compare_delta_entry(const void *a, const void *b)
585 {
586         const struct delta_entry *delta_a = a;
587         const struct delta_entry *delta_b = b;
588         return memcmp(&delta_a->base, &delta_b->base, UNION_BASE_SZ);
589 }
590
591 /* Parse all objects and return the pack content SHA1 hash */
592 static void parse_pack_objects(unsigned char *sha1)
593 {
594         int i;
595         struct delta_entry *delta = deltas;
596         struct stat st;
597
598         /*
599          * First pass:
600          * - find locations of all objects;
601          * - calculate SHA1 of all non-delta objects;
602          * - remember base (SHA1 or offset) for all deltas.
603          */
604         if (verbose)
605                 progress = start_progress(
606                                 from_stdin ? "Receiving objects" : "Indexing objects",
607                                 nr_objects);
608         for (i = 0; i < nr_objects; i++) {
609                 struct object_entry *obj = &objects[i];
610                 void *data = unpack_raw_entry(obj, &delta->base);
611                 obj->real_type = obj->type;
612                 if (obj->type == OBJ_REF_DELTA || obj->type == OBJ_OFS_DELTA) {
613                         nr_deltas++;
614                         delta->obj_no = i;
615                         delta++;
616                 } else
617                         sha1_object(data, obj->size, obj->type, obj->idx.sha1);
618                 free(data);
619                 display_progress(progress, i+1);
620         }
621         objects[i].idx.offset = consumed_bytes;
622         stop_progress(&progress);
623
624         /* Check pack integrity */
625         flush();
626         git_SHA1_Final(sha1, &input_ctx);
627         if (hashcmp(fill(20), sha1))
628                 die("pack is corrupted (SHA1 mismatch)");
629         use(20);
630
631         /* If input_fd is a file, we should have reached its end now. */
632         if (fstat(input_fd, &st))
633                 die("cannot fstat packfile: %s", strerror(errno));
634         if (S_ISREG(st.st_mode) &&
635                         lseek(input_fd, 0, SEEK_CUR) - input_len != st.st_size)
636                 die("pack has junk at the end");
637
638         if (!nr_deltas)
639                 return;
640
641         /* Sort deltas by base SHA1/offset for fast searching */
642         qsort(deltas, nr_deltas, sizeof(struct delta_entry),
643               compare_delta_entry);
644
645         /*
646          * Second pass:
647          * - for all non-delta objects, look if it is used as a base for
648          *   deltas;
649          * - if used as a base, uncompress the object and apply all deltas,
650          *   recursively checking if the resulting object is used as a base
651          *   for some more deltas.
652          */
653         if (verbose)
654                 progress = start_progress("Resolving deltas", nr_deltas);
655         for (i = 0; i < nr_objects; i++) {
656                 struct object_entry *obj = &objects[i];
657                 struct base_data base_obj;
658
659                 if (obj->type == OBJ_REF_DELTA || obj->type == OBJ_OFS_DELTA)
660                         continue;
661                 base_obj.obj = obj;
662                 base_obj.data = NULL;
663                 find_unresolved_deltas(&base_obj, NULL);
664                 display_progress(progress, nr_resolved_deltas);
665         }
666 }
667
668 static int write_compressed(struct sha1file *f, void *in, unsigned int size)
669 {
670         z_stream stream;
671         unsigned long maxsize;
672         void *out;
673
674         memset(&stream, 0, sizeof(stream));
675         deflateInit(&stream, zlib_compression_level);
676         maxsize = deflateBound(&stream, size);
677         out = xmalloc(maxsize);
678
679         /* Compress it */
680         stream.next_in = in;
681         stream.avail_in = size;
682         stream.next_out = out;
683         stream.avail_out = maxsize;
684         while (deflate(&stream, Z_FINISH) == Z_OK);
685         deflateEnd(&stream);
686
687         size = stream.total_out;
688         sha1write(f, out, size);
689         free(out);
690         return size;
691 }
692
693 static struct object_entry *append_obj_to_pack(struct sha1file *f,
694                                const unsigned char *sha1, void *buf,
695                                unsigned long size, enum object_type type)
696 {
697         struct object_entry *obj = &objects[nr_objects++];
698         unsigned char header[10];
699         unsigned long s = size;
700         int n = 0;
701         unsigned char c = (type << 4) | (s & 15);
702         s >>= 4;
703         while (s) {
704                 header[n++] = c | 0x80;
705                 c = s & 0x7f;
706                 s >>= 7;
707         }
708         header[n++] = c;
709         crc32_begin(f);
710         sha1write(f, header, n);
711         obj[0].size = size;
712         obj[0].hdr_size = n;
713         obj[0].type = type;
714         obj[0].real_type = type;
715         obj[1].idx.offset = obj[0].idx.offset + n;
716         obj[1].idx.offset += write_compressed(f, buf, size);
717         obj[0].idx.crc32 = crc32_end(f);
718         sha1flush(f);
719         hashcpy(obj->idx.sha1, sha1);
720         return obj;
721 }
722
723 static int delta_pos_compare(const void *_a, const void *_b)
724 {
725         struct delta_entry *a = *(struct delta_entry **)_a;
726         struct delta_entry *b = *(struct delta_entry **)_b;
727         return a->obj_no - b->obj_no;
728 }
729
730 static void fix_unresolved_deltas(struct sha1file *f, int nr_unresolved)
731 {
732         struct delta_entry **sorted_by_pos;
733         int i, n = 0;
734
735         /*
736          * Since many unresolved deltas may well be themselves base objects
737          * for more unresolved deltas, we really want to include the
738          * smallest number of base objects that would cover as much delta
739          * as possible by picking the
740          * trunc deltas first, allowing for other deltas to resolve without
741          * additional base objects.  Since most base objects are to be found
742          * before deltas depending on them, a good heuristic is to start
743          * resolving deltas in the same order as their position in the pack.
744          */
745         sorted_by_pos = xmalloc(nr_unresolved * sizeof(*sorted_by_pos));
746         for (i = 0; i < nr_deltas; i++) {
747                 if (objects[deltas[i].obj_no].real_type != OBJ_REF_DELTA)
748                         continue;
749                 sorted_by_pos[n++] = &deltas[i];
750         }
751         qsort(sorted_by_pos, n, sizeof(*sorted_by_pos), delta_pos_compare);
752
753         for (i = 0; i < n; i++) {
754                 struct delta_entry *d = sorted_by_pos[i];
755                 enum object_type type;
756                 struct base_data base_obj;
757
758                 if (objects[d->obj_no].real_type != OBJ_REF_DELTA)
759                         continue;
760                 base_obj.data = read_sha1_file(d->base.sha1, &type, &base_obj.size);
761                 if (!base_obj.data)
762                         continue;
763
764                 if (check_sha1_signature(d->base.sha1, base_obj.data,
765                                 base_obj.size, typename(type)))
766                         die("local object %s is corrupt", sha1_to_hex(d->base.sha1));
767                 base_obj.obj = append_obj_to_pack(f, d->base.sha1,
768                                         base_obj.data, base_obj.size, type);
769                 find_unresolved_deltas(&base_obj, NULL);
770                 display_progress(progress, nr_resolved_deltas);
771         }
772         free(sorted_by_pos);
773 }
774
775 static void final(const char *final_pack_name, const char *curr_pack_name,
776                   const char *final_index_name, const char *curr_index_name,
777                   const char *keep_name, const char *keep_msg,
778                   unsigned char *sha1)
779 {
780         const char *report = "pack";
781         char name[PATH_MAX];
782         int err;
783
784         if (!from_stdin) {
785                 close(input_fd);
786         } else {
787                 fsync_or_die(output_fd, curr_pack_name);
788                 err = close(output_fd);
789                 if (err)
790                         die("error while closing pack file: %s", strerror(errno));
791                 chmod(curr_pack_name, 0444);
792         }
793
794         if (keep_msg) {
795                 int keep_fd, keep_msg_len = strlen(keep_msg);
796                 if (!keep_name) {
797                         snprintf(name, sizeof(name), "%s/pack/pack-%s.keep",
798                                  get_object_directory(), sha1_to_hex(sha1));
799                         keep_name = name;
800                 }
801                 keep_fd = open(keep_name, O_RDWR|O_CREAT|O_EXCL, 0600);
802                 if (keep_fd < 0) {
803                         if (errno != EEXIST)
804                                 die("cannot write keep file");
805                 } else {
806                         if (keep_msg_len > 0) {
807                                 write_or_die(keep_fd, keep_msg, keep_msg_len);
808                                 write_or_die(keep_fd, "\n", 1);
809                         }
810                         if (close(keep_fd) != 0)
811                                 die("cannot write keep file");
812                         report = "keep";
813                 }
814         }
815
816         if (final_pack_name != curr_pack_name) {
817                 if (!final_pack_name) {
818                         snprintf(name, sizeof(name), "%s/pack/pack-%s.pack",
819                                  get_object_directory(), sha1_to_hex(sha1));
820                         final_pack_name = name;
821                 }
822                 if (move_temp_to_file(curr_pack_name, final_pack_name))
823                         die("cannot store pack file");
824         }
825
826         chmod(curr_index_name, 0444);
827         if (final_index_name != curr_index_name) {
828                 if (!final_index_name) {
829                         snprintf(name, sizeof(name), "%s/pack/pack-%s.idx",
830                                  get_object_directory(), sha1_to_hex(sha1));
831                         final_index_name = name;
832                 }
833                 if (move_temp_to_file(curr_index_name, final_index_name))
834                         die("cannot store index file");
835         }
836
837         if (!from_stdin) {
838                 printf("%s\n", sha1_to_hex(sha1));
839         } else {
840                 char buf[48];
841                 int len = snprintf(buf, sizeof(buf), "%s\t%s\n",
842                                    report, sha1_to_hex(sha1));
843                 write_or_die(1, buf, len);
844
845                 /*
846                  * Let's just mimic git-unpack-objects here and write
847                  * the last part of the input buffer to stdout.
848                  */
849                 while (input_len) {
850                         err = xwrite(1, input_buffer + input_offset, input_len);
851                         if (err <= 0)
852                                 break;
853                         input_len -= err;
854                         input_offset += err;
855                 }
856         }
857 }
858
859 static int git_index_pack_config(const char *k, const char *v, void *cb)
860 {
861         if (!strcmp(k, "pack.indexversion")) {
862                 pack_idx_default_version = git_config_int(k, v);
863                 if (pack_idx_default_version > 2)
864                         die("bad pack.indexversion=%"PRIu32,
865                                 pack_idx_default_version);
866                 return 0;
867         }
868         return git_default_config(k, v, cb);
869 }
870
871 int main(int argc, char **argv)
872 {
873         int i, fix_thin_pack = 0;
874         char *curr_pack, *pack_name = NULL;
875         char *curr_index, *index_name = NULL;
876         const char *keep_name = NULL, *keep_msg = NULL;
877         char *index_name_buf = NULL, *keep_name_buf = NULL;
878         struct pack_idx_entry **idx_objects;
879         unsigned char pack_sha1[20];
880         int nongit = 0;
881
882         setup_git_directory_gently(&nongit);
883         git_config(git_index_pack_config, NULL);
884
885         for (i = 1; i < argc; i++) {
886                 char *arg = argv[i];
887
888                 if (*arg == '-') {
889                         if (!strcmp(arg, "--stdin")) {
890                                 from_stdin = 1;
891                         } else if (!strcmp(arg, "--fix-thin")) {
892                                 fix_thin_pack = 1;
893                         } else if (!strcmp(arg, "--strict")) {
894                                 strict = 1;
895                         } else if (!strcmp(arg, "--keep")) {
896                                 keep_msg = "";
897                         } else if (!prefixcmp(arg, "--keep=")) {
898                                 keep_msg = arg + 7;
899                         } else if (!prefixcmp(arg, "--pack_header=")) {
900                                 struct pack_header *hdr;
901                                 char *c;
902
903                                 hdr = (struct pack_header *)input_buffer;
904                                 hdr->hdr_signature = htonl(PACK_SIGNATURE);
905                                 hdr->hdr_version = htonl(strtoul(arg + 14, &c, 10));
906                                 if (*c != ',')
907                                         die("bad %s", arg);
908                                 hdr->hdr_entries = htonl(strtoul(c + 1, &c, 10));
909                                 if (*c)
910                                         die("bad %s", arg);
911                                 input_len = sizeof(*hdr);
912                         } else if (!strcmp(arg, "-v")) {
913                                 verbose = 1;
914                         } else if (!strcmp(arg, "-o")) {
915                                 if (index_name || (i+1) >= argc)
916                                         usage(index_pack_usage);
917                                 index_name = argv[++i];
918                         } else if (!prefixcmp(arg, "--index-version=")) {
919                                 char *c;
920                                 pack_idx_default_version = strtoul(arg + 16, &c, 10);
921                                 if (pack_idx_default_version > 2)
922                                         die("bad %s", arg);
923                                 if (*c == ',')
924                                         pack_idx_off32_limit = strtoul(c+1, &c, 0);
925                                 if (*c || pack_idx_off32_limit & 0x80000000)
926                                         die("bad %s", arg);
927                         } else
928                                 usage(index_pack_usage);
929                         continue;
930                 }
931
932                 if (pack_name)
933                         usage(index_pack_usage);
934                 pack_name = arg;
935         }
936
937         if (!pack_name && !from_stdin)
938                 usage(index_pack_usage);
939         if (fix_thin_pack && !from_stdin)
940                 die("--fix-thin cannot be used without --stdin");
941         if (!index_name && pack_name) {
942                 int len = strlen(pack_name);
943                 if (!has_extension(pack_name, ".pack"))
944                         die("packfile name '%s' does not end with '.pack'",
945                             pack_name);
946                 index_name_buf = xmalloc(len);
947                 memcpy(index_name_buf, pack_name, len - 5);
948                 strcpy(index_name_buf + len - 5, ".idx");
949                 index_name = index_name_buf;
950         }
951         if (keep_msg && !keep_name && pack_name) {
952                 int len = strlen(pack_name);
953                 if (!has_extension(pack_name, ".pack"))
954                         die("packfile name '%s' does not end with '.pack'",
955                             pack_name);
956                 keep_name_buf = xmalloc(len);
957                 memcpy(keep_name_buf, pack_name, len - 5);
958                 strcpy(keep_name_buf + len - 5, ".keep");
959                 keep_name = keep_name_buf;
960         }
961
962         curr_pack = open_pack_file(pack_name);
963         parse_pack_header();
964         objects = xmalloc((nr_objects + 1) * sizeof(struct object_entry));
965         deltas = xmalloc(nr_objects * sizeof(struct delta_entry));
966         parse_pack_objects(pack_sha1);
967         if (nr_deltas == nr_resolved_deltas) {
968                 stop_progress(&progress);
969                 /* Flush remaining pack final 20-byte SHA1. */
970                 flush();
971         } else {
972                 if (fix_thin_pack) {
973                         struct sha1file *f;
974                         unsigned char read_sha1[20], tail_sha1[20];
975                         char msg[48];
976                         int nr_unresolved = nr_deltas - nr_resolved_deltas;
977                         int nr_objects_initial = nr_objects;
978                         if (nr_unresolved <= 0)
979                                 die("confusion beyond insanity");
980                         objects = xrealloc(objects,
981                                            (nr_objects + nr_unresolved + 1)
982                                            * sizeof(*objects));
983                         f = sha1fd(output_fd, curr_pack);
984                         fix_unresolved_deltas(f, nr_unresolved);
985                         sprintf(msg, "completed with %d local objects",
986                                 nr_objects - nr_objects_initial);
987                         stop_progress_msg(&progress, msg);
988                         sha1close(f, tail_sha1, 0);
989                         hashcpy(read_sha1, pack_sha1);
990                         fixup_pack_header_footer(output_fd, pack_sha1,
991                                                  curr_pack, nr_objects,
992                                                  read_sha1, consumed_bytes-20);
993                         if (hashcmp(read_sha1, tail_sha1) != 0)
994                                 die("Unexpected tail checksum for %s "
995                                     "(disk corruption?)", curr_pack);
996                 }
997                 if (nr_deltas != nr_resolved_deltas)
998                         die("pack has %d unresolved deltas",
999                             nr_deltas - nr_resolved_deltas);
1000         }
1001         free(deltas);
1002         if (strict)
1003                 check_objects();
1004
1005         idx_objects = xmalloc((nr_objects) * sizeof(struct pack_idx_entry *));
1006         for (i = 0; i < nr_objects; i++)
1007                 idx_objects[i] = &objects[i].idx;
1008         curr_index = write_idx_file(index_name, idx_objects, nr_objects, pack_sha1);
1009         free(idx_objects);
1010
1011         final(pack_name, curr_pack,
1012                 index_name, curr_index,
1013                 keep_name, keep_msg,
1014                 pack_sha1);
1015         free(objects);
1016         free(index_name_buf);
1017         free(keep_name_buf);
1018         if (pack_name == NULL)
1019                 free(curr_pack);
1020         if (index_name == NULL)
1021                 free(curr_index);
1022
1023         return 0;
1024 }