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