Make sure objects/pack exists before creating a new pack
[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 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                 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                         output_fd = odb_mkstemp(tmpfile, sizeof(tmpfile),
175                                                 "pack/tmp_pack_XXXXXX");
176                         pack_name = xstrdup(tmpfile);
177                 } else
178                         output_fd = open(pack_name, O_CREAT|O_EXCL|O_RDWR, 0600);
179                 if (output_fd < 0)
180                         die("unable to create %s: %s\n", pack_name, strerror(errno));
181                 pack_fd = output_fd;
182         } else {
183                 input_fd = open(pack_name, O_RDONLY);
184                 if (input_fd < 0)
185                         die("cannot open packfile '%s': %s",
186                             pack_name, strerror(errno));
187                 output_fd = -1;
188                 pack_fd = input_fd;
189         }
190         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 prune_base_data(struct base_data *retain)
224 {
225         struct base_data *b = base_cache;
226         for (b = base_cache;
227              base_cache_used > delta_base_cache_limit && b;
228              b = b->child) {
229                 if (b->data && b != retain) {
230                         free(b->data);
231                         b->data = NULL;
232                         base_cache_used -= b->size;
233                 }
234         }
235 }
236
237 static void link_base_data(struct base_data *base, struct base_data *c)
238 {
239         if (base)
240                 base->child = c;
241         else
242                 base_cache = c;
243
244         c->base = base;
245         c->child = NULL;
246         base_cache_used += c->size;
247         prune_base_data(c);
248 }
249
250 static void unlink_base_data(struct base_data *c)
251 {
252         struct base_data *base = c->base;
253         if (base)
254                 base->child = NULL;
255         else
256                 base_cache = NULL;
257         if (c->data) {
258                 free(c->data);
259                 base_cache_used -= c->size;
260         }
261 }
262
263 static void *unpack_entry_data(unsigned long offset, unsigned long size)
264 {
265         z_stream stream;
266         void *buf = xmalloc(size);
267
268         memset(&stream, 0, sizeof(stream));
269         stream.next_out = buf;
270         stream.avail_out = size;
271         stream.next_in = fill(1);
272         stream.avail_in = input_len;
273         inflateInit(&stream);
274
275         for (;;) {
276                 int ret = inflate(&stream, 0);
277                 use(input_len - stream.avail_in);
278                 if (stream.total_out == size && ret == Z_STREAM_END)
279                         break;
280                 if (ret != Z_OK)
281                         bad_object(offset, "inflate returned %d", ret);
282                 stream.next_in = fill(1);
283                 stream.avail_in = input_len;
284         }
285         inflateEnd(&stream);
286         return buf;
287 }
288
289 static void *unpack_raw_entry(struct object_entry *obj, union delta_base *delta_base)
290 {
291         unsigned char *p, c;
292         unsigned long size;
293         off_t base_offset;
294         unsigned shift;
295         void *data;
296
297         obj->idx.offset = consumed_bytes;
298         input_crc32 = crc32(0, Z_NULL, 0);
299
300         p = fill(1);
301         c = *p;
302         use(1);
303         obj->type = (c >> 4) & 7;
304         size = (c & 15);
305         shift = 4;
306         while (c & 0x80) {
307                 p = fill(1);
308                 c = *p;
309                 use(1);
310                 size += (c & 0x7fUL) << shift;
311                 shift += 7;
312         }
313         obj->size = size;
314
315         switch (obj->type) {
316         case OBJ_REF_DELTA:
317                 hashcpy(delta_base->sha1, fill(20));
318                 use(20);
319                 break;
320         case OBJ_OFS_DELTA:
321                 memset(delta_base, 0, sizeof(*delta_base));
322                 p = fill(1);
323                 c = *p;
324                 use(1);
325                 base_offset = c & 127;
326                 while (c & 128) {
327                         base_offset += 1;
328                         if (!base_offset || MSB(base_offset, 7))
329                                 bad_object(obj->idx.offset, "offset value overflow for delta base object");
330                         p = fill(1);
331                         c = *p;
332                         use(1);
333                         base_offset = (base_offset << 7) + (c & 127);
334                 }
335                 delta_base->offset = obj->idx.offset - base_offset;
336                 if (delta_base->offset >= obj->idx.offset)
337                         bad_object(obj->idx.offset, "delta base offset is out of bound");
338                 break;
339         case OBJ_COMMIT:
340         case OBJ_TREE:
341         case OBJ_BLOB:
342         case OBJ_TAG:
343                 break;
344         default:
345                 bad_object(obj->idx.offset, "unknown object type %d", obj->type);
346         }
347         obj->hdr_size = consumed_bytes - obj->idx.offset;
348
349         data = unpack_entry_data(obj->idx.offset, obj->size);
350         obj->idx.crc32 = input_crc32;
351         return data;
352 }
353
354 static void *get_data_from_pack(struct object_entry *obj)
355 {
356         off_t from = obj[0].idx.offset + obj[0].hdr_size;
357         unsigned long len = obj[1].idx.offset - from;
358         unsigned long rdy = 0;
359         unsigned char *src, *data;
360         z_stream stream;
361         int st;
362
363         src = xmalloc(len);
364         data = src;
365         do {
366                 ssize_t n = pread(pack_fd, data + rdy, len - rdy, from + rdy);
367                 if (n < 0)
368                         die("cannot pread pack file: %s", strerror(errno));
369                 if (!n)
370                         die("premature end of pack file, %lu bytes missing",
371                             len - rdy);
372                 rdy += n;
373         } while (rdy < len);
374         data = xmalloc(obj->size);
375         memset(&stream, 0, sizeof(stream));
376         stream.next_out = data;
377         stream.avail_out = obj->size;
378         stream.next_in = src;
379         stream.avail_in = len;
380         inflateInit(&stream);
381         while ((st = inflate(&stream, Z_FINISH)) == Z_OK);
382         inflateEnd(&stream);
383         if (st != Z_STREAM_END || stream.total_out != obj->size)
384                 die("serious inflate inconsistency");
385         free(src);
386         return data;
387 }
388
389 static int find_delta(const union delta_base *base)
390 {
391         int first = 0, last = nr_deltas;
392
393         while (first < last) {
394                 int next = (first + last) / 2;
395                 struct delta_entry *delta = &deltas[next];
396                 int cmp;
397
398                 cmp = memcmp(base, &delta->base, UNION_BASE_SZ);
399                 if (!cmp)
400                         return next;
401                 if (cmp < 0) {
402                         last = next;
403                         continue;
404                 }
405                 first = next+1;
406         }
407         return -first-1;
408 }
409
410 static int find_delta_children(const union delta_base *base,
411                                int *first_index, int *last_index)
412 {
413         int first = find_delta(base);
414         int last = first;
415         int end = nr_deltas - 1;
416
417         if (first < 0)
418                 return -1;
419         while (first > 0 && !memcmp(&deltas[first - 1].base, base, UNION_BASE_SZ))
420                 --first;
421         while (last < end && !memcmp(&deltas[last + 1].base, base, UNION_BASE_SZ))
422                 ++last;
423         *first_index = first;
424         *last_index = last;
425         return 0;
426 }
427
428 static void sha1_object(const void *data, unsigned long size,
429                         enum object_type type, unsigned char *sha1)
430 {
431         hash_sha1_file(data, size, typename(type), sha1);
432         if (has_sha1_file(sha1)) {
433                 void *has_data;
434                 enum object_type has_type;
435                 unsigned long has_size;
436                 has_data = read_sha1_file(sha1, &has_type, &has_size);
437                 if (!has_data)
438                         die("cannot read existing object %s", sha1_to_hex(sha1));
439                 if (size != has_size || type != has_type ||
440                     memcmp(data, has_data, size) != 0)
441                         die("SHA1 COLLISION FOUND WITH %s !", sha1_to_hex(sha1));
442                 free(has_data);
443         }
444         if (strict) {
445                 if (type == OBJ_BLOB) {
446                         struct blob *blob = lookup_blob(sha1);
447                         if (blob)
448                                 blob->object.flags |= FLAG_CHECKED;
449                         else
450                                 die("invalid blob object %s", sha1_to_hex(sha1));
451                 } else {
452                         struct object *obj;
453                         int eaten;
454                         void *buf = (void *) data;
455
456                         /*
457                          * we do not need to free the memory here, as the
458                          * buf is deleted by the caller.
459                          */
460                         obj = parse_object_buffer(sha1, type, size, buf, &eaten);
461                         if (!obj)
462                                 die("invalid %s", typename(type));
463                         if (fsck_object(obj, 1, fsck_error_function))
464                                 die("Error in object");
465                         if (fsck_walk(obj, mark_link, 0))
466                                 die("Not all child objects of %s are reachable", sha1_to_hex(obj->sha1));
467
468                         if (obj->type == OBJ_TREE) {
469                                 struct tree *item = (struct tree *) obj;
470                                 item->buffer = NULL;
471                         }
472                         if (obj->type == OBJ_COMMIT) {
473                                 struct commit *commit = (struct commit *) obj;
474                                 commit->buffer = NULL;
475                         }
476                         obj->flags |= FLAG_CHECKED;
477                 }
478         }
479 }
480
481 static void *get_base_data(struct base_data *c)
482 {
483         if (!c->data) {
484                 struct object_entry *obj = c->obj;
485
486                 if (obj->type == OBJ_REF_DELTA || obj->type == OBJ_OFS_DELTA) {
487                         void *base = get_base_data(c->base);
488                         void *raw = get_data_from_pack(obj);
489                         c->data = patch_delta(
490                                 base, c->base->size,
491                                 raw, obj->size,
492                                 &c->size);
493                         free(raw);
494                         if (!c->data)
495                                 bad_object(obj->idx.offset, "failed to apply delta");
496                 } else
497                         c->data = get_data_from_pack(obj);
498
499                 base_cache_used += c->size;
500                 prune_base_data(c);
501         }
502         return c->data;
503 }
504
505 static void resolve_delta(struct object_entry *delta_obj,
506                           struct base_data *base_obj, enum object_type type)
507 {
508         void *delta_data;
509         unsigned long delta_size;
510         union delta_base delta_base;
511         int j, first, last;
512         struct base_data result;
513
514         delta_obj->real_type = type;
515         delta_data = get_data_from_pack(delta_obj);
516         delta_size = delta_obj->size;
517         result.data = patch_delta(get_base_data(base_obj), base_obj->size,
518                              delta_data, delta_size,
519                              &result.size);
520         free(delta_data);
521         if (!result.data)
522                 bad_object(delta_obj->idx.offset, "failed to apply delta");
523         sha1_object(result.data, result.size, type, delta_obj->idx.sha1);
524         nr_resolved_deltas++;
525
526         result.obj = delta_obj;
527         link_base_data(base_obj, &result);
528
529         hashcpy(delta_base.sha1, delta_obj->idx.sha1);
530         if (!find_delta_children(&delta_base, &first, &last)) {
531                 for (j = first; j <= last; j++) {
532                         struct object_entry *child = objects + deltas[j].obj_no;
533                         if (child->real_type == OBJ_REF_DELTA)
534                                 resolve_delta(child, &result, type);
535                 }
536         }
537
538         memset(&delta_base, 0, sizeof(delta_base));
539         delta_base.offset = delta_obj->idx.offset;
540         if (!find_delta_children(&delta_base, &first, &last)) {
541                 for (j = first; j <= last; j++) {
542                         struct object_entry *child = objects + deltas[j].obj_no;
543                         if (child->real_type == OBJ_OFS_DELTA)
544                                 resolve_delta(child, &result, type);
545                 }
546         }
547
548         unlink_base_data(&result);
549 }
550
551 static int compare_delta_entry(const void *a, const void *b)
552 {
553         const struct delta_entry *delta_a = a;
554         const struct delta_entry *delta_b = b;
555         return memcmp(&delta_a->base, &delta_b->base, UNION_BASE_SZ);
556 }
557
558 /* Parse all objects and return the pack content SHA1 hash */
559 static void parse_pack_objects(unsigned char *sha1)
560 {
561         int i;
562         struct delta_entry *delta = deltas;
563         struct stat st;
564
565         /*
566          * First pass:
567          * - find locations of all objects;
568          * - calculate SHA1 of all non-delta objects;
569          * - remember base (SHA1 or offset) for all deltas.
570          */
571         if (verbose)
572                 progress = start_progress(
573                                 from_stdin ? "Receiving objects" : "Indexing objects",
574                                 nr_objects);
575         for (i = 0; i < nr_objects; i++) {
576                 struct object_entry *obj = &objects[i];
577                 void *data = unpack_raw_entry(obj, &delta->base);
578                 obj->real_type = obj->type;
579                 if (obj->type == OBJ_REF_DELTA || obj->type == OBJ_OFS_DELTA) {
580                         nr_deltas++;
581                         delta->obj_no = i;
582                         delta++;
583                 } else
584                         sha1_object(data, obj->size, obj->type, obj->idx.sha1);
585                 free(data);
586                 display_progress(progress, i+1);
587         }
588         objects[i].idx.offset = consumed_bytes;
589         stop_progress(&progress);
590
591         /* Check pack integrity */
592         flush();
593         SHA1_Final(sha1, &input_ctx);
594         if (hashcmp(fill(20), sha1))
595                 die("pack is corrupted (SHA1 mismatch)");
596         use(20);
597
598         /* If input_fd is a file, we should have reached its end now. */
599         if (fstat(input_fd, &st))
600                 die("cannot fstat packfile: %s", strerror(errno));
601         if (S_ISREG(st.st_mode) &&
602                         lseek(input_fd, 0, SEEK_CUR) - input_len != st.st_size)
603                 die("pack has junk at the end");
604
605         if (!nr_deltas)
606                 return;
607
608         /* Sort deltas by base SHA1/offset for fast searching */
609         qsort(deltas, nr_deltas, sizeof(struct delta_entry),
610               compare_delta_entry);
611
612         /*
613          * Second pass:
614          * - for all non-delta objects, look if it is used as a base for
615          *   deltas;
616          * - if used as a base, uncompress the object and apply all deltas,
617          *   recursively checking if the resulting object is used as a base
618          *   for some more deltas.
619          */
620         if (verbose)
621                 progress = start_progress("Resolving deltas", nr_deltas);
622         for (i = 0; i < nr_objects; i++) {
623                 struct object_entry *obj = &objects[i];
624                 union delta_base base;
625                 int j, ref, ref_first, ref_last, ofs, ofs_first, ofs_last;
626                 struct base_data base_obj;
627
628                 if (obj->type == OBJ_REF_DELTA || obj->type == OBJ_OFS_DELTA)
629                         continue;
630                 hashcpy(base.sha1, obj->idx.sha1);
631                 ref = !find_delta_children(&base, &ref_first, &ref_last);
632                 memset(&base, 0, sizeof(base));
633                 base.offset = obj->idx.offset;
634                 ofs = !find_delta_children(&base, &ofs_first, &ofs_last);
635                 if (!ref && !ofs)
636                         continue;
637                 base_obj.data = get_data_from_pack(obj);
638                 base_obj.size = obj->size;
639                 base_obj.obj = obj;
640                 link_base_data(NULL, &base_obj);
641
642                 if (ref)
643                         for (j = ref_first; j <= ref_last; j++) {
644                                 struct object_entry *child = objects + deltas[j].obj_no;
645                                 if (child->real_type == OBJ_REF_DELTA)
646                                         resolve_delta(child, &base_obj, obj->type);
647                         }
648                 if (ofs)
649                         for (j = ofs_first; j <= ofs_last; j++) {
650                                 struct object_entry *child = objects + deltas[j].obj_no;
651                                 if (child->real_type == OBJ_OFS_DELTA)
652                                         resolve_delta(child, &base_obj, obj->type);
653                         }
654                 unlink_base_data(&base_obj);
655                 display_progress(progress, nr_resolved_deltas);
656         }
657 }
658
659 static int write_compressed(struct sha1file *f, void *in, unsigned int size)
660 {
661         z_stream stream;
662         unsigned long maxsize;
663         void *out;
664
665         memset(&stream, 0, sizeof(stream));
666         deflateInit(&stream, zlib_compression_level);
667         maxsize = deflateBound(&stream, size);
668         out = xmalloc(maxsize);
669
670         /* Compress it */
671         stream.next_in = in;
672         stream.avail_in = size;
673         stream.next_out = out;
674         stream.avail_out = maxsize;
675         while (deflate(&stream, Z_FINISH) == Z_OK);
676         deflateEnd(&stream);
677
678         size = stream.total_out;
679         sha1write(f, out, size);
680         free(out);
681         return size;
682 }
683
684 static struct object_entry *append_obj_to_pack(struct sha1file *f,
685                                const unsigned char *sha1, void *buf,
686                                unsigned long size, enum object_type type)
687 {
688         struct object_entry *obj = &objects[nr_objects++];
689         unsigned char header[10];
690         unsigned long s = size;
691         int n = 0;
692         unsigned char c = (type << 4) | (s & 15);
693         s >>= 4;
694         while (s) {
695                 header[n++] = c | 0x80;
696                 c = s & 0x7f;
697                 s >>= 7;
698         }
699         header[n++] = c;
700         crc32_begin(f);
701         sha1write(f, header, n);
702         obj[0].size = size;
703         obj[0].hdr_size = n;
704         obj[0].type = type;
705         obj[0].real_type = type;
706         obj[1].idx.offset = obj[0].idx.offset + n;
707         obj[1].idx.offset += write_compressed(f, buf, size);
708         obj[0].idx.crc32 = crc32_end(f);
709         sha1flush(f);
710         hashcpy(obj->idx.sha1, sha1);
711         return obj;
712 }
713
714 static int delta_pos_compare(const void *_a, const void *_b)
715 {
716         struct delta_entry *a = *(struct delta_entry **)_a;
717         struct delta_entry *b = *(struct delta_entry **)_b;
718         return a->obj_no - b->obj_no;
719 }
720
721 static void fix_unresolved_deltas(struct sha1file *f, int nr_unresolved)
722 {
723         struct delta_entry **sorted_by_pos;
724         int i, n = 0;
725
726         /*
727          * Since many unresolved deltas may well be themselves base objects
728          * for more unresolved deltas, we really want to include the
729          * smallest number of base objects that would cover as much delta
730          * as possible by picking the
731          * trunc deltas first, allowing for other deltas to resolve without
732          * additional base objects.  Since most base objects are to be found
733          * before deltas depending on them, a good heuristic is to start
734          * resolving deltas in the same order as their position in the pack.
735          */
736         sorted_by_pos = xmalloc(nr_unresolved * sizeof(*sorted_by_pos));
737         for (i = 0; i < nr_deltas; i++) {
738                 if (objects[deltas[i].obj_no].real_type != OBJ_REF_DELTA)
739                         continue;
740                 sorted_by_pos[n++] = &deltas[i];
741         }
742         qsort(sorted_by_pos, n, sizeof(*sorted_by_pos), delta_pos_compare);
743
744         for (i = 0; i < n; i++) {
745                 struct delta_entry *d = sorted_by_pos[i];
746                 enum object_type type;
747                 int j, first, last;
748                 struct base_data base_obj;
749
750                 if (objects[d->obj_no].real_type != OBJ_REF_DELTA)
751                         continue;
752                 base_obj.data = read_sha1_file(d->base.sha1, &type, &base_obj.size);
753                 if (!base_obj.data)
754                         continue;
755
756                 if (check_sha1_signature(d->base.sha1, base_obj.data,
757                                 base_obj.size, typename(type)))
758                         die("local object %s is corrupt", sha1_to_hex(d->base.sha1));
759                 base_obj.obj = append_obj_to_pack(f, d->base.sha1,
760                                         base_obj.data, base_obj.size, type);
761                 link_base_data(NULL, &base_obj);
762
763                 find_delta_children(&d->base, &first, &last);
764                 for (j = first; j <= last; j++) {
765                         struct object_entry *child = objects + deltas[j].obj_no;
766                         if (child->real_type == OBJ_REF_DELTA)
767                                 resolve_delta(child, &base_obj, type);
768                 }
769
770                 unlink_base_data(&base_obj);
771                 display_progress(progress, nr_resolved_deltas);
772         }
773         free(sorted_by_pos);
774 }
775
776 static void final(const char *final_pack_name, const char *curr_pack_name,
777                   const char *final_index_name, const char *curr_index_name,
778                   const char *keep_name, const char *keep_msg,
779                   unsigned char *sha1)
780 {
781         const char *report = "pack";
782         char name[PATH_MAX];
783         int err;
784
785         if (!from_stdin) {
786                 close(input_fd);
787         } else {
788                 fsync_or_die(output_fd, curr_pack_name);
789                 err = close(output_fd);
790                 if (err)
791                         die("error while closing pack file: %s", strerror(errno));
792                 chmod(curr_pack_name, 0444);
793         }
794
795         if (keep_msg) {
796                 int keep_fd, keep_msg_len = strlen(keep_msg);
797
798                 if (!keep_name)
799                         keep_fd = odb_pack_keep(name, sizeof(name), sha1);
800                 else
801                         keep_fd = open(keep_name, O_RDWR|O_CREAT|O_EXCL, 0600);
802
803                 if (keep_fd < 0) {
804                         if (errno != EEXIST)
805                                 die("cannot write keep file '%s' (%s)",
806                                     keep_name, strerror(errno));
807                 } else {
808                         if (keep_msg_len > 0) {
809                                 write_or_die(keep_fd, keep_msg, keep_msg_len);
810                                 write_or_die(keep_fd, "\n", 1);
811                         }
812                         if (close(keep_fd) != 0)
813                                 die("cannot close written keep file '%s' (%s)",
814                                     keep_name, strerror(errno));
815                         report = "keep";
816                 }
817         }
818
819         if (final_pack_name != curr_pack_name) {
820                 if (!final_pack_name) {
821                         snprintf(name, sizeof(name), "%s/pack/pack-%s.pack",
822                                  get_object_directory(), sha1_to_hex(sha1));
823                         final_pack_name = name;
824                 }
825                 if (move_temp_to_file(curr_pack_name, final_pack_name))
826                         die("cannot store pack file");
827         }
828
829         chmod(curr_index_name, 0444);
830         if (final_index_name != curr_index_name) {
831                 if (!final_index_name) {
832                         snprintf(name, sizeof(name), "%s/pack/pack-%s.idx",
833                                  get_object_directory(), sha1_to_hex(sha1));
834                         final_index_name = name;
835                 }
836                 if (move_temp_to_file(curr_index_name, final_index_name))
837                         die("cannot store index file");
838         }
839
840         if (!from_stdin) {
841                 printf("%s\n", sha1_to_hex(sha1));
842         } else {
843                 char buf[48];
844                 int len = snprintf(buf, sizeof(buf), "%s\t%s\n",
845                                    report, sha1_to_hex(sha1));
846                 write_or_die(1, buf, len);
847
848                 /*
849                  * Let's just mimic git-unpack-objects here and write
850                  * the last part of the input buffer to stdout.
851                  */
852                 while (input_len) {
853                         err = xwrite(1, input_buffer + input_offset, input_len);
854                         if (err <= 0)
855                                 break;
856                         input_len -= err;
857                         input_offset += err;
858                 }
859         }
860 }
861
862 static int git_index_pack_config(const char *k, const char *v, void *cb)
863 {
864         if (!strcmp(k, "pack.indexversion")) {
865                 pack_idx_default_version = git_config_int(k, v);
866                 if (pack_idx_default_version > 2)
867                         die("bad pack.indexversion=%"PRIu32,
868                                 pack_idx_default_version);
869                 return 0;
870         }
871         return git_default_config(k, v, cb);
872 }
873
874 int main(int argc, char **argv)
875 {
876         int i, fix_thin_pack = 0;
877         char *curr_pack, *pack_name = NULL;
878         char *curr_index, *index_name = NULL;
879         const char *keep_name = NULL, *keep_msg = NULL;
880         char *index_name_buf = NULL, *keep_name_buf = NULL;
881         struct pack_idx_entry **idx_objects;
882         unsigned char pack_sha1[20];
883
884         /*
885          * We wish to read the repository's config file if any, and
886          * for that it is necessary to call setup_git_directory_gently().
887          * However if the cwd was inside .git/objects/pack/ then we need
888          * to go back there or all the pack name arguments will be wrong.
889          * And in that case we cannot rely on any prefix returned by
890          * setup_git_directory_gently() either.
891          */
892         {
893                 char cwd[PATH_MAX+1];
894                 int nongit;
895
896                 if (!getcwd(cwd, sizeof(cwd)-1))
897                         die("Unable to get current working directory");
898                 setup_git_directory_gently(&nongit);
899                 git_config(git_index_pack_config, NULL);
900                 if (chdir(cwd))
901                         die("Cannot come back to cwd");
902         }
903
904         for (i = 1; i < argc; i++) {
905                 char *arg = argv[i];
906
907                 if (*arg == '-') {
908                         if (!strcmp(arg, "--stdin")) {
909                                 from_stdin = 1;
910                         } else if (!strcmp(arg, "--fix-thin")) {
911                                 fix_thin_pack = 1;
912                         } else if (!strcmp(arg, "--strict")) {
913                                 strict = 1;
914                         } else if (!strcmp(arg, "--keep")) {
915                                 keep_msg = "";
916                         } else if (!prefixcmp(arg, "--keep=")) {
917                                 keep_msg = arg + 7;
918                         } else if (!prefixcmp(arg, "--pack_header=")) {
919                                 struct pack_header *hdr;
920                                 char *c;
921
922                                 hdr = (struct pack_header *)input_buffer;
923                                 hdr->hdr_signature = htonl(PACK_SIGNATURE);
924                                 hdr->hdr_version = htonl(strtoul(arg + 14, &c, 10));
925                                 if (*c != ',')
926                                         die("bad %s", arg);
927                                 hdr->hdr_entries = htonl(strtoul(c + 1, &c, 10));
928                                 if (*c)
929                                         die("bad %s", arg);
930                                 input_len = sizeof(*hdr);
931                         } else if (!strcmp(arg, "-v")) {
932                                 verbose = 1;
933                         } else if (!strcmp(arg, "-o")) {
934                                 if (index_name || (i+1) >= argc)
935                                         usage(index_pack_usage);
936                                 index_name = argv[++i];
937                         } else if (!prefixcmp(arg, "--index-version=")) {
938                                 char *c;
939                                 pack_idx_default_version = strtoul(arg + 16, &c, 10);
940                                 if (pack_idx_default_version > 2)
941                                         die("bad %s", arg);
942                                 if (*c == ',')
943                                         pack_idx_off32_limit = strtoul(c+1, &c, 0);
944                                 if (*c || pack_idx_off32_limit & 0x80000000)
945                                         die("bad %s", arg);
946                         } else
947                                 usage(index_pack_usage);
948                         continue;
949                 }
950
951                 if (pack_name)
952                         usage(index_pack_usage);
953                 pack_name = arg;
954         }
955
956         if (!pack_name && !from_stdin)
957                 usage(index_pack_usage);
958         if (fix_thin_pack && !from_stdin)
959                 die("--fix-thin cannot be used without --stdin");
960         if (!index_name && pack_name) {
961                 int len = strlen(pack_name);
962                 if (!has_extension(pack_name, ".pack"))
963                         die("packfile name '%s' does not end with '.pack'",
964                             pack_name);
965                 index_name_buf = xmalloc(len);
966                 memcpy(index_name_buf, pack_name, len - 5);
967                 strcpy(index_name_buf + len - 5, ".idx");
968                 index_name = index_name_buf;
969         }
970         if (keep_msg && !keep_name && pack_name) {
971                 int len = strlen(pack_name);
972                 if (!has_extension(pack_name, ".pack"))
973                         die("packfile name '%s' does not end with '.pack'",
974                             pack_name);
975                 keep_name_buf = xmalloc(len);
976                 memcpy(keep_name_buf, pack_name, len - 5);
977                 strcpy(keep_name_buf + len - 5, ".keep");
978                 keep_name = keep_name_buf;
979         }
980
981         curr_pack = open_pack_file(pack_name);
982         parse_pack_header();
983         objects = xmalloc((nr_objects + 1) * sizeof(struct object_entry));
984         deltas = xmalloc(nr_objects * sizeof(struct delta_entry));
985         parse_pack_objects(pack_sha1);
986         if (nr_deltas == nr_resolved_deltas) {
987                 stop_progress(&progress);
988                 /* Flush remaining pack final 20-byte SHA1. */
989                 flush();
990         } else {
991                 if (fix_thin_pack) {
992                         struct sha1file *f;
993                         unsigned char read_sha1[20], tail_sha1[20];
994                         char msg[48];
995                         int nr_unresolved = nr_deltas - nr_resolved_deltas;
996                         int nr_objects_initial = nr_objects;
997                         if (nr_unresolved <= 0)
998                                 die("confusion beyond insanity");
999                         objects = xrealloc(objects,
1000                                            (nr_objects + nr_unresolved + 1)
1001                                            * sizeof(*objects));
1002                         f = sha1fd(output_fd, curr_pack);
1003                         fix_unresolved_deltas(f, nr_unresolved);
1004                         sprintf(msg, "completed with %d local objects",
1005                                 nr_objects - nr_objects_initial);
1006                         stop_progress_msg(&progress, msg);
1007                         sha1close(f, tail_sha1, 0);
1008                         hashcpy(read_sha1, pack_sha1);
1009                         fixup_pack_header_footer(output_fd, pack_sha1,
1010                                                  curr_pack, nr_objects,
1011                                                  read_sha1, consumed_bytes-20);
1012                         if (hashcmp(read_sha1, tail_sha1) != 0)
1013                                 die("Unexpected tail checksum for %s "
1014                                     "(disk corruption?)", curr_pack);
1015                 }
1016                 if (nr_deltas != nr_resolved_deltas)
1017                         die("pack has %d unresolved deltas",
1018                             nr_deltas - nr_resolved_deltas);
1019         }
1020         free(deltas);
1021         if (strict)
1022                 check_objects();
1023
1024         idx_objects = xmalloc((nr_objects) * sizeof(struct pack_idx_entry *));
1025         for (i = 0; i < nr_objects; i++)
1026                 idx_objects[i] = &objects[i].idx;
1027         curr_index = write_idx_file(index_name, idx_objects, nr_objects, pack_sha1);
1028         free(idx_objects);
1029
1030         final(pack_name, curr_pack,
1031                 index_name, curr_index,
1032                 keep_name, keep_msg,
1033                 pack_sha1);
1034         free(objects);
1035         free(index_name_buf);
1036         free(keep_name_buf);
1037         if (pack_name == NULL)
1038                 free(curr_pack);
1039         if (index_name == NULL)
1040                 free(curr_index);
1041
1042         return 0;
1043 }