Merge branch 'master' into next
[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 #include "exec_cmd.h"
12
13 static const char index_pack_usage[] =
14 "git index-pack [-v] [-o <index-file>] [{ ---keep | --keep=<msg> }] [--strict] { <pack-file> | --stdin [--fix-thin] [<pack-file>] }";
15
16 struct object_entry
17 {
18         struct pack_idx_entry idx;
19         unsigned long size;
20         unsigned int hdr_size;
21         enum object_type type;
22         enum object_type real_type;
23 };
24
25 union delta_base {
26         unsigned char sha1[20];
27         off_t offset;
28 };
29
30 struct base_data {
31         struct base_data *base;
32         struct base_data *child;
33         struct object_entry *obj;
34         void *data;
35         unsigned long size;
36 };
37
38 /*
39  * Even if sizeof(union delta_base) == 24 on 64-bit archs, we really want
40  * to memcmp() only the first 20 bytes.
41  */
42 #define UNION_BASE_SZ   20
43
44 #define FLAG_LINK (1u<<20)
45 #define FLAG_CHECKED (1u<<21)
46
47 struct delta_entry
48 {
49         union delta_base base;
50         int obj_no;
51 };
52
53 static struct object_entry *objects;
54 static struct delta_entry *deltas;
55 static struct base_data *base_cache;
56 static size_t base_cache_used;
57 static int nr_objects;
58 static int nr_deltas;
59 static int nr_resolved_deltas;
60
61 static int from_stdin;
62 static int strict;
63 static int verbose;
64
65 static struct progress *progress;
66
67 /* We always read in 4kB chunks. */
68 static unsigned char input_buffer[4096];
69 static unsigned int input_offset, input_len;
70 static off_t consumed_bytes;
71 static git_SHA_CTX input_ctx;
72 static uint32_t input_crc32;
73 static int input_fd, output_fd, pack_fd;
74
75 static int mark_link(struct object *obj, int type, void *data)
76 {
77         if (!obj)
78                 return -1;
79
80         if (type != OBJ_ANY && obj->type != type)
81                 die("object type mismatch at %s", sha1_to_hex(obj->sha1));
82
83         obj->flags |= FLAG_LINK;
84         return 0;
85 }
86
87 /* The content of each linked object must have been checked
88    or it must be already present in the object database */
89 static void check_object(struct object *obj)
90 {
91         if (!obj)
92                 return;
93
94         if (!(obj->flags & FLAG_LINK))
95                 return;
96
97         if (!(obj->flags & FLAG_CHECKED)) {
98                 unsigned long size;
99                 int type = sha1_object_info(obj->sha1, &size);
100                 if (type != obj->type || type <= 0)
101                         die("object of unexpected type");
102                 obj->flags |= FLAG_CHECKED;
103                 return;
104         }
105 }
106
107 static void check_objects(void)
108 {
109         unsigned i, max;
110
111         max = get_max_object_index();
112         for (i = 0; i < max; i++)
113                 check_object(get_indexed_object(i));
114 }
115
116
117 /* Discard current buffer used content. */
118 static void flush(void)
119 {
120         if (input_offset) {
121                 if (output_fd >= 0)
122                         write_or_die(output_fd, input_buffer, input_offset);
123                 git_SHA1_Update(&input_ctx, input_buffer, input_offset);
124                 memmove(input_buffer, input_buffer + input_offset, input_len);
125                 input_offset = 0;
126         }
127 }
128
129 /*
130  * Make sure at least "min" bytes are available in the buffer, and
131  * return the pointer to the buffer.
132  */
133 static void *fill(int min)
134 {
135         if (min <= input_len)
136                 return input_buffer + input_offset;
137         if (min > sizeof(input_buffer))
138                 die("cannot fill %d bytes", min);
139         flush();
140         do {
141                 ssize_t ret = xread(input_fd, input_buffer + input_len,
142                                 sizeof(input_buffer) - input_len);
143                 if (ret <= 0) {
144                         if (!ret)
145                                 die("early EOF");
146                         die_errno("read error on input");
147                 }
148                 input_len += ret;
149                 if (from_stdin)
150                         display_throughput(progress, consumed_bytes + input_len);
151         } while (input_len < min);
152         return input_buffer;
153 }
154
155 static void use(int bytes)
156 {
157         if (bytes > input_len)
158                 die("used more bytes than were available");
159         input_crc32 = crc32(input_crc32, input_buffer + input_offset, bytes);
160         input_len -= bytes;
161         input_offset += bytes;
162
163         /* make sure off_t is sufficiently large not to wrap */
164         if (consumed_bytes > consumed_bytes + bytes)
165                 die("pack too large for current definition of off_t");
166         consumed_bytes += bytes;
167 }
168
169 static char *open_pack_file(char *pack_name)
170 {
171         if (from_stdin) {
172                 input_fd = 0;
173                 if (!pack_name) {
174                         static char tmpfile[PATH_MAX];
175                         output_fd = odb_mkstemp(tmpfile, sizeof(tmpfile),
176                                                 "pack/tmp_pack_XXXXXX");
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_errno("unable to create '%s'", pack_name);
182                 pack_fd = output_fd;
183         } else {
184                 input_fd = open(pack_name, O_RDONLY);
185                 if (input_fd < 0)
186                         die_errno("cannot open packfile '%s'", pack_name);
187                 output_fd = -1;
188                 pack_fd = input_fd;
189         }
190         git_SHA1_Init(&input_ctx);
191         return pack_name;
192 }
193
194 static void parse_pack_header(void)
195 {
196         struct pack_header *hdr = fill(sizeof(struct pack_header));
197
198         /* Header consistency check */
199         if (hdr->hdr_signature != htonl(PACK_SIGNATURE))
200                 die("pack signature mismatch");
201         if (!pack_version_ok(hdr->hdr_version))
202                 die("pack version %"PRIu32" unsupported",
203                         ntohl(hdr->hdr_version));
204
205         nr_objects = ntohl(hdr->hdr_entries);
206         use(sizeof(struct pack_header));
207 }
208
209 static void bad_object(unsigned long offset, const char *format,
210                        ...) NORETURN __attribute__((format (printf, 2, 3)));
211
212 static void bad_object(unsigned long offset, const char *format, ...)
213 {
214         va_list params;
215         char buf[1024];
216
217         va_start(params, format);
218         vsnprintf(buf, sizeof(buf), format, params);
219         va_end(params);
220         die("pack has bad object at offset %lu: %s", offset, buf);
221 }
222
223 static void free_base_data(struct base_data *c)
224 {
225         if (c->data) {
226                 free(c->data);
227                 c->data = NULL;
228                 base_cache_used -= c->size;
229         }
230 }
231
232 static void prune_base_data(struct base_data *retain)
233 {
234         struct base_data *b;
235         for (b = base_cache;
236              base_cache_used > delta_base_cache_limit && b;
237              b = b->child) {
238                 if (b->data && b != retain)
239                         free_base_data(b);
240         }
241 }
242
243 static void link_base_data(struct base_data *base, struct base_data *c)
244 {
245         if (base)
246                 base->child = c;
247         else
248                 base_cache = c;
249
250         c->base = base;
251         c->child = NULL;
252         if (c->data)
253                 base_cache_used += c->size;
254         prune_base_data(c);
255 }
256
257 static void unlink_base_data(struct base_data *c)
258 {
259         struct base_data *base = c->base;
260         if (base)
261                 base->child = NULL;
262         else
263                 base_cache = NULL;
264         free_base_data(c);
265 }
266
267 static void *unpack_entry_data(unsigned long offset, unsigned long size)
268 {
269         z_stream stream;
270         void *buf = xmalloc(size);
271
272         memset(&stream, 0, sizeof(stream));
273         stream.next_out = buf;
274         stream.avail_out = size;
275         stream.next_in = fill(1);
276         stream.avail_in = input_len;
277         git_inflate_init(&stream);
278
279         for (;;) {
280                 int ret = git_inflate(&stream, 0);
281                 use(input_len - stream.avail_in);
282                 if (stream.total_out == size && ret == Z_STREAM_END)
283                         break;
284                 if (ret != Z_OK)
285                         bad_object(offset, "inflate returned %d", ret);
286                 stream.next_in = fill(1);
287                 stream.avail_in = input_len;
288         }
289         git_inflate_end(&stream);
290         return buf;
291 }
292
293 static void *unpack_raw_entry(struct object_entry *obj, union delta_base *delta_base)
294 {
295         unsigned char *p;
296         unsigned long size, c;
297         off_t base_offset;
298         unsigned shift;
299         void *data;
300
301         obj->idx.offset = consumed_bytes;
302         input_crc32 = crc32(0, Z_NULL, 0);
303
304         p = fill(1);
305         c = *p;
306         use(1);
307         obj->type = (c >> 4) & 7;
308         size = (c & 15);
309         shift = 4;
310         while (c & 0x80) {
311                 p = fill(1);
312                 c = *p;
313                 use(1);
314                 size += (c & 0x7f) << shift;
315                 shift += 7;
316         }
317         obj->size = size;
318
319         switch (obj->type) {
320         case OBJ_REF_DELTA:
321                 hashcpy(delta_base->sha1, fill(20));
322                 use(20);
323                 break;
324         case OBJ_OFS_DELTA:
325                 memset(delta_base, 0, sizeof(*delta_base));
326                 p = fill(1);
327                 c = *p;
328                 use(1);
329                 base_offset = c & 127;
330                 while (c & 128) {
331                         base_offset += 1;
332                         if (!base_offset || MSB(base_offset, 7))
333                                 bad_object(obj->idx.offset, "offset value overflow for delta base object");
334                         p = fill(1);
335                         c = *p;
336                         use(1);
337                         base_offset = (base_offset << 7) + (c & 127);
338                 }
339                 delta_base->offset = obj->idx.offset - base_offset;
340                 if (delta_base->offset <= 0 || delta_base->offset >= obj->idx.offset)
341                         bad_object(obj->idx.offset, "delta base offset is out of bound");
342                 break;
343         case OBJ_COMMIT:
344         case OBJ_TREE:
345         case OBJ_BLOB:
346         case OBJ_TAG:
347                 break;
348         default:
349                 bad_object(obj->idx.offset, "unknown object type %d", obj->type);
350         }
351         obj->hdr_size = consumed_bytes - obj->idx.offset;
352
353         data = unpack_entry_data(obj->idx.offset, obj->size);
354         obj->idx.crc32 = input_crc32;
355         return data;
356 }
357
358 static void *get_data_from_pack(struct object_entry *obj)
359 {
360         off_t from = obj[0].idx.offset + obj[0].hdr_size;
361         unsigned long len = obj[1].idx.offset - from;
362         unsigned long rdy = 0;
363         unsigned char *src, *data;
364         z_stream stream;
365         int st;
366
367         src = xmalloc(len);
368         data = src;
369         do {
370                 ssize_t n = pread(pack_fd, data + rdy, len - rdy, from + rdy);
371                 if (n < 0)
372                         die_errno("cannot pread pack file");
373                 if (!n)
374                         die("premature end of pack file, %lu bytes missing",
375                             len - rdy);
376                 rdy += n;
377         } while (rdy < len);
378         data = xmalloc(obj->size);
379         memset(&stream, 0, sizeof(stream));
380         stream.next_out = data;
381         stream.avail_out = obj->size;
382         stream.next_in = src;
383         stream.avail_in = len;
384         git_inflate_init(&stream);
385         while ((st = git_inflate(&stream, Z_FINISH)) == Z_OK);
386         git_inflate_end(&stream);
387         if (st != Z_STREAM_END || stream.total_out != obj->size)
388                 die("serious inflate inconsistency");
389         free(src);
390         return data;
391 }
392
393 static int find_delta(const union delta_base *base)
394 {
395         int first = 0, last = nr_deltas;
396
397         while (first < last) {
398                 int next = (first + last) / 2;
399                 struct delta_entry *delta = &deltas[next];
400                 int cmp;
401
402                 cmp = memcmp(base, &delta->base, UNION_BASE_SZ);
403                 if (!cmp)
404                         return next;
405                 if (cmp < 0) {
406                         last = next;
407                         continue;
408                 }
409                 first = next+1;
410         }
411         return -first-1;
412 }
413
414 static void find_delta_children(const union delta_base *base,
415                                 int *first_index, int *last_index)
416 {
417         int first = find_delta(base);
418         int last = first;
419         int end = nr_deltas - 1;
420
421         if (first < 0) {
422                 *first_index = 0;
423                 *last_index = -1;
424                 return;
425         }
426         while (first > 0 && !memcmp(&deltas[first - 1].base, base, UNION_BASE_SZ))
427                 --first;
428         while (last < end && !memcmp(&deltas[last + 1].base, base, UNION_BASE_SZ))
429                 ++last;
430         *first_index = first;
431         *last_index = last;
432 }
433
434 static void sha1_object(const void *data, unsigned long size,
435                         enum object_type type, unsigned char *sha1)
436 {
437         hash_sha1_file(data, size, typename(type), sha1);
438         if (has_sha1_file(sha1)) {
439                 void *has_data;
440                 enum object_type has_type;
441                 unsigned long has_size;
442                 has_data = read_sha1_file(sha1, &has_type, &has_size);
443                 if (!has_data)
444                         die("cannot read existing object %s", sha1_to_hex(sha1));
445                 if (size != has_size || type != has_type ||
446                     memcmp(data, has_data, size) != 0)
447                         die("SHA1 COLLISION FOUND WITH %s !", sha1_to_hex(sha1));
448                 free(has_data);
449         }
450         if (strict) {
451                 if (type == OBJ_BLOB) {
452                         struct blob *blob = lookup_blob(sha1);
453                         if (blob)
454                                 blob->object.flags |= FLAG_CHECKED;
455                         else
456                                 die("invalid blob object %s", sha1_to_hex(sha1));
457                 } else {
458                         struct object *obj;
459                         int eaten;
460                         void *buf = (void *) data;
461
462                         /*
463                          * we do not need to free the memory here, as the
464                          * buf is deleted by the caller.
465                          */
466                         obj = parse_object_buffer(sha1, type, size, buf, &eaten);
467                         if (!obj)
468                                 die("invalid %s", typename(type));
469                         if (fsck_object(obj, 1, fsck_error_function))
470                                 die("Error in object");
471                         if (fsck_walk(obj, mark_link, NULL))
472                                 die("Not all child objects of %s are reachable", sha1_to_hex(obj->sha1));
473
474                         if (obj->type == OBJ_TREE) {
475                                 struct tree *item = (struct tree *) obj;
476                                 item->buffer = NULL;
477                         }
478                         if (obj->type == OBJ_COMMIT) {
479                                 struct commit *commit = (struct commit *) obj;
480                                 commit->buffer = NULL;
481                         }
482                         obj->flags |= FLAG_CHECKED;
483                 }
484         }
485 }
486
487 static void *get_base_data(struct base_data *c)
488 {
489         if (!c->data) {
490                 struct object_entry *obj = c->obj;
491
492                 if (obj->type == OBJ_REF_DELTA || obj->type == OBJ_OFS_DELTA) {
493                         void *base = get_base_data(c->base);
494                         void *raw = get_data_from_pack(obj);
495                         c->data = patch_delta(
496                                 base, c->base->size,
497                                 raw, obj->size,
498                                 &c->size);
499                         free(raw);
500                         if (!c->data)
501                                 bad_object(obj->idx.offset, "failed to apply delta");
502                 } else {
503                         c->data = get_data_from_pack(obj);
504                         c->size = obj->size;
505                 }
506
507                 base_cache_used += c->size;
508                 prune_base_data(c);
509         }
510         return c->data;
511 }
512
513 static void resolve_delta(struct object_entry *delta_obj,
514                           struct base_data *base, struct base_data *result)
515 {
516         void *base_data, *delta_data;
517
518         delta_obj->real_type = base->obj->real_type;
519         delta_data = get_data_from_pack(delta_obj);
520         base_data = get_base_data(base);
521         result->obj = delta_obj;
522         result->data = patch_delta(base_data, base->size,
523                                    delta_data, delta_obj->size, &result->size);
524         free(delta_data);
525         if (!result->data)
526                 bad_object(delta_obj->idx.offset, "failed to apply delta");
527         sha1_object(result->data, result->size, delta_obj->real_type,
528                     delta_obj->idx.sha1);
529         nr_resolved_deltas++;
530 }
531
532 static void find_unresolved_deltas(struct base_data *base,
533                                    struct base_data *prev_base)
534 {
535         int i, ref_first, ref_last, ofs_first, ofs_last;
536
537         /*
538          * This is a recursive function. Those brackets should help reducing
539          * stack usage by limiting the scope of the delta_base union.
540          */
541         {
542                 union delta_base base_spec;
543
544                 hashcpy(base_spec.sha1, base->obj->idx.sha1);
545                 find_delta_children(&base_spec, &ref_first, &ref_last);
546
547                 memset(&base_spec, 0, sizeof(base_spec));
548                 base_spec.offset = base->obj->idx.offset;
549                 find_delta_children(&base_spec, &ofs_first, &ofs_last);
550         }
551
552         if (ref_last == -1 && ofs_last == -1) {
553                 free(base->data);
554                 return;
555         }
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_errno("cannot fstat packfile");
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_errno("error while closing pack file");
791         }
792
793         if (keep_msg) {
794                 int keep_fd, keep_msg_len = strlen(keep_msg);
795
796                 if (!keep_name)
797                         keep_fd = odb_pack_keep(name, sizeof(name), sha1);
798                 else
799                         keep_fd = open(keep_name, O_RDWR|O_CREAT|O_EXCL, 0600);
800
801                 if (keep_fd < 0) {
802                         if (errno != EEXIST)
803                                 die_errno("cannot write keep file '%s'",
804                                           keep_name);
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_errno("cannot close written keep file '%s'",
812                                     keep_name);
813                         report = "keep";
814                 }
815         }
816
817         if (final_pack_name != curr_pack_name) {
818                 if (!final_pack_name) {
819                         snprintf(name, sizeof(name), "%s/pack/pack-%s.pack",
820                                  get_object_directory(), sha1_to_hex(sha1));
821                         final_pack_name = name;
822                 }
823                 if (move_temp_to_file(curr_pack_name, final_pack_name))
824                         die("cannot store pack file");
825         } else if (from_stdin)
826                 chmod(final_pack_name, 0444);
827
828         if (final_index_name != curr_index_name) {
829                 if (!final_index_name) {
830                         snprintf(name, sizeof(name), "%s/pack/pack-%s.idx",
831                                  get_object_directory(), sha1_to_hex(sha1));
832                         final_index_name = name;
833                 }
834                 if (move_temp_to_file(curr_index_name, final_index_name))
835                         die("cannot store index file");
836         } else
837                 chmod(final_index_name, 0444);
838
839         if (!from_stdin) {
840                 printf("%s\n", sha1_to_hex(sha1));
841         } else {
842                 char buf[48];
843                 int len = snprintf(buf, sizeof(buf), "%s\t%s\n",
844                                    report, sha1_to_hex(sha1));
845                 write_or_die(1, buf, len);
846
847                 /*
848                  * Let's just mimic git-unpack-objects here and write
849                  * the last part of the input buffer to stdout.
850                  */
851                 while (input_len) {
852                         err = xwrite(1, input_buffer + input_offset, input_len);
853                         if (err <= 0)
854                                 break;
855                         input_len -= err;
856                         input_offset += err;
857                 }
858         }
859 }
860
861 static int git_index_pack_config(const char *k, const char *v, void *cb)
862 {
863         if (!strcmp(k, "pack.indexversion")) {
864                 pack_idx_default_version = git_config_int(k, v);
865                 if (pack_idx_default_version > 2)
866                         die("bad pack.indexversion=%"PRIu32,
867                                 pack_idx_default_version);
868                 return 0;
869         }
870         return git_default_config(k, v, cb);
871 }
872
873 int main(int argc, char **argv)
874 {
875         int i, fix_thin_pack = 0;
876         char *curr_pack, *pack_name = NULL;
877         char *curr_index, *index_name = NULL;
878         const char *keep_name = NULL, *keep_msg = NULL;
879         char *index_name_buf = NULL, *keep_name_buf = NULL;
880         struct pack_idx_entry **idx_objects;
881         unsigned char pack_sha1[20];
882
883         git_extract_argv0_path(argv[0]);
884
885         /*
886          * We wish to read the repository's config file if any, and
887          * for that it is necessary to call setup_git_directory_gently().
888          * However if the cwd was inside .git/objects/pack/ then we need
889          * to go back there or all the pack name arguments will be wrong.
890          * And in that case we cannot rely on any prefix returned by
891          * setup_git_directory_gently() either.
892          */
893         {
894                 char cwd[PATH_MAX+1];
895                 int nongit;
896
897                 if (!getcwd(cwd, sizeof(cwd)-1))
898                         die("Unable to get current working directory");
899                 setup_git_directory_gently(&nongit);
900                 git_config(git_index_pack_config, NULL);
901                 if (chdir(cwd))
902                         die("Cannot come back to cwd");
903         }
904
905         for (i = 1; i < argc; i++) {
906                 char *arg = argv[i];
907
908                 if (*arg == '-') {
909                         if (!strcmp(arg, "--stdin")) {
910                                 from_stdin = 1;
911                         } else if (!strcmp(arg, "--fix-thin")) {
912                                 fix_thin_pack = 1;
913                         } else if (!strcmp(arg, "--strict")) {
914                                 strict = 1;
915                         } else if (!strcmp(arg, "--keep")) {
916                                 keep_msg = "";
917                         } else if (!prefixcmp(arg, "--keep=")) {
918                                 keep_msg = arg + 7;
919                         } else if (!prefixcmp(arg, "--pack_header=")) {
920                                 struct pack_header *hdr;
921                                 char *c;
922
923                                 hdr = (struct pack_header *)input_buffer;
924                                 hdr->hdr_signature = htonl(PACK_SIGNATURE);
925                                 hdr->hdr_version = htonl(strtoul(arg + 14, &c, 10));
926                                 if (*c != ',')
927                                         die("bad %s", arg);
928                                 hdr->hdr_entries = htonl(strtoul(c + 1, &c, 10));
929                                 if (*c)
930                                         die("bad %s", arg);
931                                 input_len = sizeof(*hdr);
932                         } else if (!strcmp(arg, "-v")) {
933                                 verbose = 1;
934                         } else if (!strcmp(arg, "-o")) {
935                                 if (index_name || (i+1) >= argc)
936                                         usage(index_pack_usage);
937                                 index_name = argv[++i];
938                         } else if (!prefixcmp(arg, "--index-version=")) {
939                                 char *c;
940                                 pack_idx_default_version = strtoul(arg + 16, &c, 10);
941                                 if (pack_idx_default_version > 2)
942                                         die("bad %s", arg);
943                                 if (*c == ',')
944                                         pack_idx_off32_limit = strtoul(c+1, &c, 0);
945                                 if (*c || pack_idx_off32_limit & 0x80000000)
946                                         die("bad %s", arg);
947                         } else
948                                 usage(index_pack_usage);
949                         continue;
950                 }
951
952                 if (pack_name)
953                         usage(index_pack_usage);
954                 pack_name = arg;
955         }
956
957         if (!pack_name && !from_stdin)
958                 usage(index_pack_usage);
959         if (fix_thin_pack && !from_stdin)
960                 die("--fix-thin cannot be used without --stdin");
961         if (!index_name && pack_name) {
962                 int len = strlen(pack_name);
963                 if (!has_extension(pack_name, ".pack"))
964                         die("packfile name '%s' does not end with '.pack'",
965                             pack_name);
966                 index_name_buf = xmalloc(len);
967                 memcpy(index_name_buf, pack_name, len - 5);
968                 strcpy(index_name_buf + len - 5, ".idx");
969                 index_name = index_name_buf;
970         }
971         if (keep_msg && !keep_name && pack_name) {
972                 int len = strlen(pack_name);
973                 if (!has_extension(pack_name, ".pack"))
974                         die("packfile name '%s' does not end with '.pack'",
975                             pack_name);
976                 keep_name_buf = xmalloc(len);
977                 memcpy(keep_name_buf, pack_name, len - 5);
978                 strcpy(keep_name_buf + len - 5, ".keep");
979                 keep_name = keep_name_buf;
980         }
981
982         curr_pack = open_pack_file(pack_name);
983         parse_pack_header();
984         objects = xmalloc((nr_objects + 1) * sizeof(struct object_entry));
985         deltas = xmalloc(nr_objects * sizeof(struct delta_entry));
986         parse_pack_objects(pack_sha1);
987         if (nr_deltas == nr_resolved_deltas) {
988                 stop_progress(&progress);
989                 /* Flush remaining pack final 20-byte SHA1. */
990                 flush();
991         } else {
992                 if (fix_thin_pack) {
993                         struct sha1file *f;
994                         unsigned char read_sha1[20], tail_sha1[20];
995                         char msg[48];
996                         int nr_unresolved = nr_deltas - nr_resolved_deltas;
997                         int nr_objects_initial = nr_objects;
998                         if (nr_unresolved <= 0)
999                                 die("confusion beyond insanity");
1000                         objects = xrealloc(objects,
1001                                            (nr_objects + nr_unresolved + 1)
1002                                            * sizeof(*objects));
1003                         f = sha1fd(output_fd, curr_pack);
1004                         fix_unresolved_deltas(f, nr_unresolved);
1005                         sprintf(msg, "completed with %d local objects",
1006                                 nr_objects - nr_objects_initial);
1007                         stop_progress_msg(&progress, msg);
1008                         sha1close(f, tail_sha1, 0);
1009                         hashcpy(read_sha1, pack_sha1);
1010                         fixup_pack_header_footer(output_fd, pack_sha1,
1011                                                  curr_pack, nr_objects,
1012                                                  read_sha1, consumed_bytes-20);
1013                         if (hashcmp(read_sha1, tail_sha1) != 0)
1014                                 die("Unexpected tail checksum for %s "
1015                                     "(disk corruption?)", curr_pack);
1016                 }
1017                 if (nr_deltas != nr_resolved_deltas)
1018                         die("pack has %d unresolved deltas",
1019                             nr_deltas - nr_resolved_deltas);
1020         }
1021         free(deltas);
1022         if (strict)
1023                 check_objects();
1024
1025         idx_objects = xmalloc((nr_objects) * sizeof(struct pack_idx_entry *));
1026         for (i = 0; i < nr_objects; i++)
1027                 idx_objects[i] = &objects[i].idx;
1028         curr_index = write_idx_file(index_name, idx_objects, nr_objects, pack_sha1);
1029         free(idx_objects);
1030
1031         final(pack_name, curr_pack,
1032                 index_name, curr_index,
1033                 keep_name, keep_msg,
1034                 pack_sha1);
1035         free(objects);
1036         free(index_name_buf);
1037         free(keep_name_buf);
1038         if (pack_name == NULL)
1039                 free(curr_pack);
1040         if (index_name == NULL)
1041                 free(curr_index);
1042
1043         return 0;
1044 }