index-pack: restructure pack processing into three main functions
[git] / builtin / index-pack.c
1 #include "builtin.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>] [--verify] [--strict] (<pack-file> | --stdin [--fix-thin] [<pack-file>])";
15
16 struct object_entry {
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         unsigned delta_depth;
23         int base_object_no;
24 };
25
26 union delta_base {
27         unsigned char sha1[20];
28         off_t offset;
29 };
30
31 struct base_data {
32         struct base_data *base;
33         struct base_data *child;
34         struct object_entry *obj;
35         void *data;
36         unsigned long size;
37         int ref_first, ref_last;
38         int ofs_first, ofs_last;
39 };
40
41 /*
42  * Even if sizeof(union delta_base) == 24 on 64-bit archs, we really want
43  * to memcmp() only the first 20 bytes.
44  */
45 #define UNION_BASE_SZ   20
46
47 #define FLAG_LINK (1u<<20)
48 #define FLAG_CHECKED (1u<<21)
49
50 struct delta_entry {
51         union delta_base base;
52         int obj_no;
53 };
54
55 static struct object_entry *objects;
56 static struct delta_entry *deltas;
57 static struct base_data *base_cache;
58 static size_t base_cache_used;
59 static int nr_objects;
60 static int nr_deltas;
61 static int nr_resolved_deltas;
62
63 static int from_stdin;
64 static int strict;
65 static int verbose;
66
67 static struct progress *progress;
68
69 /* We always read in 4kB chunks. */
70 static unsigned char input_buffer[4096];
71 static unsigned int input_offset, input_len;
72 static off_t consumed_bytes;
73 static unsigned deepest_delta;
74 static git_SHA_CTX input_ctx;
75 static uint32_t input_crc32;
76 static int input_fd, output_fd, pack_fd;
77
78 static int mark_link(struct object *obj, int type, void *data)
79 {
80         if (!obj)
81                 return -1;
82
83         if (type != OBJ_ANY && obj->type != type)
84                 die("object type mismatch at %s", sha1_to_hex(obj->sha1));
85
86         obj->flags |= FLAG_LINK;
87         return 0;
88 }
89
90 /* The content of each linked object must have been checked
91    or it must be already present in the object database */
92 static void check_object(struct object *obj)
93 {
94         if (!obj)
95                 return;
96
97         if (!(obj->flags & FLAG_LINK))
98                 return;
99
100         if (!(obj->flags & FLAG_CHECKED)) {
101                 unsigned long size;
102                 int type = sha1_object_info(obj->sha1, &size);
103                 if (type != obj->type || type <= 0)
104                         die("object of unexpected type");
105                 obj->flags |= FLAG_CHECKED;
106                 return;
107         }
108 }
109
110 static void check_objects(void)
111 {
112         unsigned i, max;
113
114         max = get_max_object_index();
115         for (i = 0; i < max; i++)
116                 check_object(get_indexed_object(i));
117 }
118
119
120 /* Discard current buffer used content. */
121 static void flush(void)
122 {
123         if (input_offset) {
124                 if (output_fd >= 0)
125                         write_or_die(output_fd, input_buffer, input_offset);
126                 git_SHA1_Update(&input_ctx, input_buffer, input_offset);
127                 memmove(input_buffer, input_buffer + input_offset, input_len);
128                 input_offset = 0;
129         }
130 }
131
132 /*
133  * Make sure at least "min" bytes are available in the buffer, and
134  * return the pointer to the buffer.
135  */
136 static void *fill(int min)
137 {
138         if (min <= input_len)
139                 return input_buffer + input_offset;
140         if (min > sizeof(input_buffer))
141                 die("cannot fill %d bytes", min);
142         flush();
143         do {
144                 ssize_t ret = xread(input_fd, input_buffer + input_len,
145                                 sizeof(input_buffer) - input_len);
146                 if (ret <= 0) {
147                         if (!ret)
148                                 die("early EOF");
149                         die_errno("read error on input");
150                 }
151                 input_len += ret;
152                 if (from_stdin)
153                         display_throughput(progress, consumed_bytes + input_len);
154         } while (input_len < min);
155         return input_buffer;
156 }
157
158 static void use(int bytes)
159 {
160         if (bytes > input_len)
161                 die("used more bytes than were available");
162         input_crc32 = crc32(input_crc32, input_buffer + input_offset, bytes);
163         input_len -= bytes;
164         input_offset += bytes;
165
166         /* make sure off_t is sufficiently large not to wrap */
167         if (signed_add_overflows(consumed_bytes, bytes))
168                 die("pack too large for current definition of off_t");
169         consumed_bytes += bytes;
170 }
171
172 static const char *open_pack_file(const char *pack_name)
173 {
174         if (from_stdin) {
175                 input_fd = 0;
176                 if (!pack_name) {
177                         static char tmp_file[PATH_MAX];
178                         output_fd = odb_mkstemp(tmp_file, sizeof(tmp_file),
179                                                 "pack/tmp_pack_XXXXXX");
180                         pack_name = xstrdup(tmp_file);
181                 } else
182                         output_fd = open(pack_name, O_CREAT|O_EXCL|O_RDWR, 0600);
183                 if (output_fd < 0)
184                         die_errno("unable to create '%s'", pack_name);
185                 pack_fd = output_fd;
186         } else {
187                 input_fd = open(pack_name, O_RDONLY);
188                 if (input_fd < 0)
189                         die_errno("cannot open packfile '%s'", pack_name);
190                 output_fd = -1;
191                 pack_fd = input_fd;
192         }
193         git_SHA1_Init(&input_ctx);
194         return pack_name;
195 }
196
197 static void parse_pack_header(void)
198 {
199         struct pack_header *hdr = fill(sizeof(struct pack_header));
200
201         /* Header consistency check */
202         if (hdr->hdr_signature != htonl(PACK_SIGNATURE))
203                 die("pack signature mismatch");
204         if (!pack_version_ok(hdr->hdr_version))
205                 die("pack version %"PRIu32" unsupported",
206                         ntohl(hdr->hdr_version));
207
208         nr_objects = ntohl(hdr->hdr_entries);
209         use(sizeof(struct pack_header));
210 }
211
212 static NORETURN void bad_object(unsigned long offset, const char *format,
213                        ...) __attribute__((format (printf, 2, 3)));
214
215 static NORETURN void bad_object(unsigned long offset, const char *format, ...)
216 {
217         va_list params;
218         char buf[1024];
219
220         va_start(params, format);
221         vsnprintf(buf, sizeof(buf), format, params);
222         va_end(params);
223         die("pack has bad object at offset %lu: %s", offset, buf);
224 }
225
226 static struct base_data *alloc_base_data(void)
227 {
228         struct base_data *base = xmalloc(sizeof(struct base_data));
229         memset(base, 0, sizeof(*base));
230         base->ref_last = -1;
231         base->ofs_last = -1;
232         return base;
233 }
234
235 static void free_base_data(struct base_data *c)
236 {
237         if (c->data) {
238                 free(c->data);
239                 c->data = NULL;
240                 base_cache_used -= c->size;
241         }
242 }
243
244 static void prune_base_data(struct base_data *retain)
245 {
246         struct base_data *b;
247         for (b = base_cache;
248              base_cache_used > delta_base_cache_limit && b;
249              b = b->child) {
250                 if (b->data && b != retain)
251                         free_base_data(b);
252         }
253 }
254
255 static void link_base_data(struct base_data *base, struct base_data *c)
256 {
257         if (base)
258                 base->child = c;
259         else
260                 base_cache = c;
261
262         c->base = base;
263         c->child = NULL;
264         if (c->data)
265                 base_cache_used += c->size;
266         prune_base_data(c);
267 }
268
269 static void unlink_base_data(struct base_data *c)
270 {
271         struct base_data *base = c->base;
272         if (base)
273                 base->child = NULL;
274         else
275                 base_cache = NULL;
276         free_base_data(c);
277 }
278
279 static void *unpack_entry_data(unsigned long offset, unsigned long size)
280 {
281         int status;
282         git_zstream stream;
283         void *buf = xmalloc(size);
284
285         memset(&stream, 0, sizeof(stream));
286         git_inflate_init(&stream);
287         stream.next_out = buf;
288         stream.avail_out = size;
289
290         do {
291                 stream.next_in = fill(1);
292                 stream.avail_in = input_len;
293                 status = git_inflate(&stream, 0);
294                 use(input_len - stream.avail_in);
295         } while (status == Z_OK);
296         if (stream.total_out != size || status != Z_STREAM_END)
297                 bad_object(offset, "inflate returned %d", status);
298         git_inflate_end(&stream);
299         return buf;
300 }
301
302 static void *unpack_raw_entry(struct object_entry *obj, union delta_base *delta_base)
303 {
304         unsigned char *p;
305         unsigned long size, c;
306         off_t base_offset;
307         unsigned shift;
308         void *data;
309
310         obj->idx.offset = consumed_bytes;
311         input_crc32 = crc32(0, NULL, 0);
312
313         p = fill(1);
314         c = *p;
315         use(1);
316         obj->type = (c >> 4) & 7;
317         size = (c & 15);
318         shift = 4;
319         while (c & 0x80) {
320                 p = fill(1);
321                 c = *p;
322                 use(1);
323                 size += (c & 0x7f) << shift;
324                 shift += 7;
325         }
326         obj->size = size;
327
328         switch (obj->type) {
329         case OBJ_REF_DELTA:
330                 hashcpy(delta_base->sha1, fill(20));
331                 use(20);
332                 break;
333         case OBJ_OFS_DELTA:
334                 memset(delta_base, 0, sizeof(*delta_base));
335                 p = fill(1);
336                 c = *p;
337                 use(1);
338                 base_offset = c & 127;
339                 while (c & 128) {
340                         base_offset += 1;
341                         if (!base_offset || MSB(base_offset, 7))
342                                 bad_object(obj->idx.offset, "offset value overflow for delta base object");
343                         p = fill(1);
344                         c = *p;
345                         use(1);
346                         base_offset = (base_offset << 7) + (c & 127);
347                 }
348                 delta_base->offset = obj->idx.offset - base_offset;
349                 if (delta_base->offset <= 0 || delta_base->offset >= obj->idx.offset)
350                         bad_object(obj->idx.offset, "delta base offset is out of bound");
351                 break;
352         case OBJ_COMMIT:
353         case OBJ_TREE:
354         case OBJ_BLOB:
355         case OBJ_TAG:
356                 break;
357         default:
358                 bad_object(obj->idx.offset, "unknown object type %d", obj->type);
359         }
360         obj->hdr_size = consumed_bytes - obj->idx.offset;
361
362         data = unpack_entry_data(obj->idx.offset, obj->size);
363         obj->idx.crc32 = input_crc32;
364         return data;
365 }
366
367 static void *get_data_from_pack(struct object_entry *obj)
368 {
369         off_t from = obj[0].idx.offset + obj[0].hdr_size;
370         unsigned long len = obj[1].idx.offset - from;
371         unsigned char *data, *inbuf;
372         git_zstream stream;
373         int status;
374
375         data = xmalloc(obj->size);
376         inbuf = xmalloc((len < 64*1024) ? len : 64*1024);
377
378         memset(&stream, 0, sizeof(stream));
379         git_inflate_init(&stream);
380         stream.next_out = data;
381         stream.avail_out = obj->size;
382
383         do {
384                 ssize_t n = (len < 64*1024) ? len : 64*1024;
385                 n = pread(pack_fd, inbuf, n, from);
386                 if (n < 0)
387                         die_errno("cannot pread pack file");
388                 if (!n)
389                         die("premature end of pack file, %lu bytes missing", len);
390                 from += n;
391                 len -= n;
392                 stream.next_in = inbuf;
393                 stream.avail_in = n;
394                 status = git_inflate(&stream, 0);
395         } while (len && status == Z_OK && !stream.avail_in);
396
397         /* This has been inflated OK when first encountered, so... */
398         if (status != Z_STREAM_END || stream.total_out != obj->size)
399                 die("serious inflate inconsistency");
400
401         git_inflate_end(&stream);
402         free(inbuf);
403         return data;
404 }
405
406 static int compare_delta_bases(const union delta_base *base1,
407                                const union delta_base *base2,
408                                enum object_type type1,
409                                enum object_type type2)
410 {
411         int cmp = type1 - type2;
412         if (cmp)
413                 return cmp;
414         return memcmp(base1, base2, UNION_BASE_SZ);
415 }
416
417 static int find_delta(const union delta_base *base, enum object_type type)
418 {
419         int first = 0, last = nr_deltas;
420
421         while (first < last) {
422                 int next = (first + last) / 2;
423                 struct delta_entry *delta = &deltas[next];
424                 int cmp;
425
426                 cmp = compare_delta_bases(base, &delta->base,
427                                           type, objects[delta->obj_no].type);
428                 if (!cmp)
429                         return next;
430                 if (cmp < 0) {
431                         last = next;
432                         continue;
433                 }
434                 first = next+1;
435         }
436         return -first-1;
437 }
438
439 static void find_delta_children(const union delta_base *base,
440                                 int *first_index, int *last_index,
441                                 enum object_type type)
442 {
443         int first = find_delta(base, type);
444         int last = first;
445         int end = nr_deltas - 1;
446
447         if (first < 0) {
448                 *first_index = 0;
449                 *last_index = -1;
450                 return;
451         }
452         while (first > 0 && !memcmp(&deltas[first - 1].base, base, UNION_BASE_SZ))
453                 --first;
454         while (last < end && !memcmp(&deltas[last + 1].base, base, UNION_BASE_SZ))
455                 ++last;
456         *first_index = first;
457         *last_index = last;
458 }
459
460 static void sha1_object(const void *data, unsigned long size,
461                         enum object_type type, unsigned char *sha1)
462 {
463         hash_sha1_file(data, size, typename(type), sha1);
464         if (has_sha1_file(sha1)) {
465                 void *has_data;
466                 enum object_type has_type;
467                 unsigned long has_size;
468                 has_data = read_sha1_file(sha1, &has_type, &has_size);
469                 if (!has_data)
470                         die("cannot read existing object %s", sha1_to_hex(sha1));
471                 if (size != has_size || type != has_type ||
472                     memcmp(data, has_data, size) != 0)
473                         die("SHA1 COLLISION FOUND WITH %s !", sha1_to_hex(sha1));
474                 free(has_data);
475         }
476         if (strict) {
477                 if (type == OBJ_BLOB) {
478                         struct blob *blob = lookup_blob(sha1);
479                         if (blob)
480                                 blob->object.flags |= FLAG_CHECKED;
481                         else
482                                 die("invalid blob object %s", sha1_to_hex(sha1));
483                 } else {
484                         struct object *obj;
485                         int eaten;
486                         void *buf = (void *) data;
487
488                         /*
489                          * we do not need to free the memory here, as the
490                          * buf is deleted by the caller.
491                          */
492                         obj = parse_object_buffer(sha1, type, size, buf, &eaten);
493                         if (!obj)
494                                 die("invalid %s", typename(type));
495                         if (fsck_object(obj, 1, fsck_error_function))
496                                 die("Error in object");
497                         if (fsck_walk(obj, mark_link, NULL))
498                                 die("Not all child objects of %s are reachable", sha1_to_hex(obj->sha1));
499
500                         if (obj->type == OBJ_TREE) {
501                                 struct tree *item = (struct tree *) obj;
502                                 item->buffer = NULL;
503                         }
504                         if (obj->type == OBJ_COMMIT) {
505                                 struct commit *commit = (struct commit *) obj;
506                                 commit->buffer = NULL;
507                         }
508                         obj->flags |= FLAG_CHECKED;
509                 }
510         }
511 }
512
513 static int is_delta_type(enum object_type type)
514 {
515         return (type == OBJ_REF_DELTA || type == OBJ_OFS_DELTA);
516 }
517
518 /*
519  * This function is part of find_unresolved_deltas(). There are two
520  * walkers going in the opposite ways.
521  *
522  * The first one in find_unresolved_deltas() traverses down from
523  * parent node to children, deflating nodes along the way. However,
524  * memory for deflated nodes is limited by delta_base_cache_limit, so
525  * at some point parent node's deflated content may be freed.
526  *
527  * The second walker is this function, which goes from current node up
528  * to top parent if necessary to deflate the node. In normal
529  * situation, its parent node would be already deflated, so it just
530  * needs to apply delta.
531  *
532  * In the worst case scenario, parent node is no longer deflated because
533  * we're running out of delta_base_cache_limit; we need to re-deflate
534  * parents, possibly up to the top base.
535  *
536  * All deflated objects here are subject to be freed if we exceed
537  * delta_base_cache_limit, just like in find_unresolved_deltas(), we
538  * just need to make sure the last node is not freed.
539  */
540 static void *get_base_data(struct base_data *c)
541 {
542         if (!c->data) {
543                 struct object_entry *obj = c->obj;
544                 struct base_data **delta = NULL;
545                 int delta_nr = 0, delta_alloc = 0;
546
547                 while (is_delta_type(c->obj->type) && !c->data) {
548                         ALLOC_GROW(delta, delta_nr + 1, delta_alloc);
549                         delta[delta_nr++] = c;
550                         c = c->base;
551                 }
552                 if (!delta_nr) {
553                         c->data = get_data_from_pack(obj);
554                         c->size = obj->size;
555                         base_cache_used += c->size;
556                         prune_base_data(c);
557                 }
558                 for (; delta_nr > 0; delta_nr--) {
559                         void *base, *raw;
560                         c = delta[delta_nr - 1];
561                         obj = c->obj;
562                         base = get_base_data(c->base);
563                         raw = get_data_from_pack(obj);
564                         c->data = patch_delta(
565                                 base, c->base->size,
566                                 raw, obj->size,
567                                 &c->size);
568                         free(raw);
569                         if (!c->data)
570                                 bad_object(obj->idx.offset, "failed to apply delta");
571                         base_cache_used += c->size;
572                         prune_base_data(c);
573                 }
574                 free(delta);
575         }
576         return c->data;
577 }
578
579 static void resolve_delta(struct object_entry *delta_obj,
580                           struct base_data *base, struct base_data *result)
581 {
582         void *base_data, *delta_data;
583
584         delta_obj->real_type = base->obj->real_type;
585         delta_obj->delta_depth = base->obj->delta_depth + 1;
586         if (deepest_delta < delta_obj->delta_depth)
587                 deepest_delta = delta_obj->delta_depth;
588         delta_obj->base_object_no = base->obj - objects;
589         delta_data = get_data_from_pack(delta_obj);
590         base_data = get_base_data(base);
591         result->obj = delta_obj;
592         result->data = patch_delta(base_data, base->size,
593                                    delta_data, delta_obj->size, &result->size);
594         free(delta_data);
595         if (!result->data)
596                 bad_object(delta_obj->idx.offset, "failed to apply delta");
597         sha1_object(result->data, result->size, delta_obj->real_type,
598                     delta_obj->idx.sha1);
599         nr_resolved_deltas++;
600 }
601
602 static struct base_data *find_unresolved_deltas_1(struct base_data *base,
603                                                   struct base_data *prev_base)
604 {
605         if (base->ref_last == -1 && base->ofs_last == -1) {
606                 union delta_base base_spec;
607
608                 hashcpy(base_spec.sha1, base->obj->idx.sha1);
609                 find_delta_children(&base_spec,
610                                     &base->ref_first, &base->ref_last, OBJ_REF_DELTA);
611
612                 memset(&base_spec, 0, sizeof(base_spec));
613                 base_spec.offset = base->obj->idx.offset;
614                 find_delta_children(&base_spec,
615                                     &base->ofs_first, &base->ofs_last, OBJ_OFS_DELTA);
616
617                 if (base->ref_last == -1 && base->ofs_last == -1) {
618                         free(base->data);
619                         return NULL;
620                 }
621
622                 link_base_data(prev_base, base);
623         }
624
625         if (base->ref_first <= base->ref_last) {
626                 struct object_entry *child = objects + deltas[base->ref_first].obj_no;
627                 struct base_data *result = alloc_base_data();
628
629                 assert(child->real_type == OBJ_REF_DELTA);
630                 resolve_delta(child, base, result);
631                 if (base->ref_first == base->ref_last && base->ofs_last == -1)
632                         free_base_data(base);
633
634                 base->ref_first++;
635                 return result;
636         }
637
638         if (base->ofs_first <= base->ofs_last) {
639                 struct object_entry *child = objects + deltas[base->ofs_first].obj_no;
640                 struct base_data *result = alloc_base_data();
641
642                 assert(child->real_type == OBJ_OFS_DELTA);
643                 resolve_delta(child, base, result);
644                 if (base->ofs_first == base->ofs_last)
645                         free_base_data(base);
646
647                 base->ofs_first++;
648                 return result;
649         }
650
651         unlink_base_data(base);
652         return NULL;
653 }
654
655 static void find_unresolved_deltas(struct base_data *base)
656 {
657         struct base_data *new_base, *prev_base = NULL;
658         for (;;) {
659                 new_base = find_unresolved_deltas_1(base, prev_base);
660
661                 if (new_base) {
662                         prev_base = base;
663                         base = new_base;
664                 } else {
665                         free(base);
666                         base = prev_base;
667                         if (!base)
668                                 return;
669                         prev_base = base->base;
670                 }
671         }
672 }
673
674 static int compare_delta_entry(const void *a, const void *b)
675 {
676         const struct delta_entry *delta_a = a;
677         const struct delta_entry *delta_b = b;
678
679         /* group by type (ref vs ofs) and then by value (sha-1 or offset) */
680         return compare_delta_bases(&delta_a->base, &delta_b->base,
681                                    objects[delta_a->obj_no].type,
682                                    objects[delta_b->obj_no].type);
683 }
684
685 static void resolve_base(struct object_entry *obj)
686 {
687         struct base_data *base_obj = alloc_base_data();
688         base_obj->obj = obj;
689         base_obj->data = NULL;
690         find_unresolved_deltas(base_obj);
691 }
692
693 /*
694  * First pass:
695  * - find locations of all objects;
696  * - calculate SHA1 of all non-delta objects;
697  * - remember base (SHA1 or offset) for all deltas.
698  */
699 static void parse_pack_objects(unsigned char *sha1)
700 {
701         int i;
702         struct delta_entry *delta = deltas;
703         struct stat st;
704
705         if (verbose)
706                 progress = start_progress(
707                                 from_stdin ? "Receiving objects" : "Indexing objects",
708                                 nr_objects);
709         for (i = 0; i < nr_objects; i++) {
710                 struct object_entry *obj = &objects[i];
711                 void *data = unpack_raw_entry(obj, &delta->base);
712                 obj->real_type = obj->type;
713                 if (is_delta_type(obj->type)) {
714                         nr_deltas++;
715                         delta->obj_no = i;
716                         delta++;
717                 } else
718                         sha1_object(data, obj->size, obj->type, obj->idx.sha1);
719                 free(data);
720                 display_progress(progress, i+1);
721         }
722         objects[i].idx.offset = consumed_bytes;
723         stop_progress(&progress);
724
725         /* Check pack integrity */
726         flush();
727         git_SHA1_Final(sha1, &input_ctx);
728         if (hashcmp(fill(20), sha1))
729                 die("pack is corrupted (SHA1 mismatch)");
730         use(20);
731
732         /* If input_fd is a file, we should have reached its end now. */
733         if (fstat(input_fd, &st))
734                 die_errno("cannot fstat packfile");
735         if (S_ISREG(st.st_mode) &&
736                         lseek(input_fd, 0, SEEK_CUR) - input_len != st.st_size)
737                 die("pack has junk at the end");
738 }
739
740 /*
741  * Second pass:
742  * - for all non-delta objects, look if it is used as a base for
743  *   deltas;
744  * - if used as a base, uncompress the object and apply all deltas,
745  *   recursively checking if the resulting object is used as a base
746  *   for some more deltas.
747  */
748 static void resolve_deltas(void)
749 {
750         int i;
751
752         if (!nr_deltas)
753                 return;
754
755         /* Sort deltas by base SHA1/offset for fast searching */
756         qsort(deltas, nr_deltas, sizeof(struct delta_entry),
757               compare_delta_entry);
758
759         if (verbose)
760                 progress = start_progress("Resolving deltas", nr_deltas);
761         for (i = 0; i < nr_objects; i++) {
762                 struct object_entry *obj = &objects[i];
763
764                 if (is_delta_type(obj->type))
765                         continue;
766                 resolve_base(obj);
767                 display_progress(progress, nr_resolved_deltas);
768         }
769 }
770
771 /*
772  * Third pass:
773  * - append objects to convert thin pack to full pack if required
774  * - write the final 20-byte SHA-1
775  */
776 static void fix_unresolved_deltas(struct sha1file *f, int nr_unresolved);
777 static void conclude_pack(int fix_thin_pack, const char *curr_pack, unsigned char *pack_sha1)
778 {
779         if (nr_deltas == nr_resolved_deltas) {
780                 stop_progress(&progress);
781                 /* Flush remaining pack final 20-byte SHA1. */
782                 flush();
783                 return;
784         }
785
786         if (fix_thin_pack) {
787                 struct sha1file *f;
788                 unsigned char read_sha1[20], tail_sha1[20];
789                 char msg[48];
790                 int nr_unresolved = nr_deltas - nr_resolved_deltas;
791                 int nr_objects_initial = nr_objects;
792                 if (nr_unresolved <= 0)
793                         die("confusion beyond insanity");
794                 objects = xrealloc(objects,
795                                    (nr_objects + nr_unresolved + 1)
796                                    * sizeof(*objects));
797                 f = sha1fd(output_fd, curr_pack);
798                 fix_unresolved_deltas(f, nr_unresolved);
799                 sprintf(msg, "completed with %d local objects",
800                         nr_objects - nr_objects_initial);
801                 stop_progress_msg(&progress, msg);
802                 sha1close(f, tail_sha1, 0);
803                 hashcpy(read_sha1, pack_sha1);
804                 fixup_pack_header_footer(output_fd, pack_sha1,
805                                          curr_pack, nr_objects,
806                                          read_sha1, consumed_bytes-20);
807                 if (hashcmp(read_sha1, tail_sha1) != 0)
808                         die("Unexpected tail checksum for %s "
809                             "(disk corruption?)", curr_pack);
810         }
811         if (nr_deltas != nr_resolved_deltas)
812                 die("pack has %d unresolved deltas",
813                     nr_deltas - nr_resolved_deltas);
814 }
815
816 static int write_compressed(struct sha1file *f, void *in, unsigned int size)
817 {
818         git_zstream stream;
819         int status;
820         unsigned char outbuf[4096];
821
822         memset(&stream, 0, sizeof(stream));
823         git_deflate_init(&stream, zlib_compression_level);
824         stream.next_in = in;
825         stream.avail_in = size;
826
827         do {
828                 stream.next_out = outbuf;
829                 stream.avail_out = sizeof(outbuf);
830                 status = git_deflate(&stream, Z_FINISH);
831                 sha1write(f, outbuf, sizeof(outbuf) - stream.avail_out);
832         } while (status == Z_OK);
833
834         if (status != Z_STREAM_END)
835                 die("unable to deflate appended object (%d)", status);
836         size = stream.total_out;
837         git_deflate_end(&stream);
838         return size;
839 }
840
841 static struct object_entry *append_obj_to_pack(struct sha1file *f,
842                                const unsigned char *sha1, void *buf,
843                                unsigned long size, enum object_type type)
844 {
845         struct object_entry *obj = &objects[nr_objects++];
846         unsigned char header[10];
847         unsigned long s = size;
848         int n = 0;
849         unsigned char c = (type << 4) | (s & 15);
850         s >>= 4;
851         while (s) {
852                 header[n++] = c | 0x80;
853                 c = s & 0x7f;
854                 s >>= 7;
855         }
856         header[n++] = c;
857         crc32_begin(f);
858         sha1write(f, header, n);
859         obj[0].size = size;
860         obj[0].hdr_size = n;
861         obj[0].type = type;
862         obj[0].real_type = type;
863         obj[1].idx.offset = obj[0].idx.offset + n;
864         obj[1].idx.offset += write_compressed(f, buf, size);
865         obj[0].idx.crc32 = crc32_end(f);
866         sha1flush(f);
867         hashcpy(obj->idx.sha1, sha1);
868         return obj;
869 }
870
871 static int delta_pos_compare(const void *_a, const void *_b)
872 {
873         struct delta_entry *a = *(struct delta_entry **)_a;
874         struct delta_entry *b = *(struct delta_entry **)_b;
875         return a->obj_no - b->obj_no;
876 }
877
878 static void fix_unresolved_deltas(struct sha1file *f, int nr_unresolved)
879 {
880         struct delta_entry **sorted_by_pos;
881         int i, n = 0;
882
883         /*
884          * Since many unresolved deltas may well be themselves base objects
885          * for more unresolved deltas, we really want to include the
886          * smallest number of base objects that would cover as much delta
887          * as possible by picking the
888          * trunc deltas first, allowing for other deltas to resolve without
889          * additional base objects.  Since most base objects are to be found
890          * before deltas depending on them, a good heuristic is to start
891          * resolving deltas in the same order as their position in the pack.
892          */
893         sorted_by_pos = xmalloc(nr_unresolved * sizeof(*sorted_by_pos));
894         for (i = 0; i < nr_deltas; i++) {
895                 if (objects[deltas[i].obj_no].real_type != OBJ_REF_DELTA)
896                         continue;
897                 sorted_by_pos[n++] = &deltas[i];
898         }
899         qsort(sorted_by_pos, n, sizeof(*sorted_by_pos), delta_pos_compare);
900
901         for (i = 0; i < n; i++) {
902                 struct delta_entry *d = sorted_by_pos[i];
903                 enum object_type type;
904                 struct base_data *base_obj = alloc_base_data();
905
906                 if (objects[d->obj_no].real_type != OBJ_REF_DELTA)
907                         continue;
908                 base_obj->data = read_sha1_file(d->base.sha1, &type, &base_obj->size);
909                 if (!base_obj->data)
910                         continue;
911
912                 if (check_sha1_signature(d->base.sha1, base_obj->data,
913                                 base_obj->size, typename(type)))
914                         die("local object %s is corrupt", sha1_to_hex(d->base.sha1));
915                 base_obj->obj = append_obj_to_pack(f, d->base.sha1,
916                                         base_obj->data, base_obj->size, type);
917                 find_unresolved_deltas(base_obj);
918                 display_progress(progress, nr_resolved_deltas);
919         }
920         free(sorted_by_pos);
921 }
922
923 static void final(const char *final_pack_name, const char *curr_pack_name,
924                   const char *final_index_name, const char *curr_index_name,
925                   const char *keep_name, const char *keep_msg,
926                   unsigned char *sha1)
927 {
928         const char *report = "pack";
929         char name[PATH_MAX];
930         int err;
931
932         if (!from_stdin) {
933                 close(input_fd);
934         } else {
935                 fsync_or_die(output_fd, curr_pack_name);
936                 err = close(output_fd);
937                 if (err)
938                         die_errno("error while closing pack file");
939         }
940
941         if (keep_msg) {
942                 int keep_fd, keep_msg_len = strlen(keep_msg);
943
944                 if (!keep_name)
945                         keep_fd = odb_pack_keep(name, sizeof(name), sha1);
946                 else
947                         keep_fd = open(keep_name, O_RDWR|O_CREAT|O_EXCL, 0600);
948
949                 if (keep_fd < 0) {
950                         if (errno != EEXIST)
951                                 die_errno("cannot write keep file '%s'",
952                                           keep_name);
953                 } else {
954                         if (keep_msg_len > 0) {
955                                 write_or_die(keep_fd, keep_msg, keep_msg_len);
956                                 write_or_die(keep_fd, "\n", 1);
957                         }
958                         if (close(keep_fd) != 0)
959                                 die_errno("cannot close written keep file '%s'",
960                                     keep_name);
961                         report = "keep";
962                 }
963         }
964
965         if (final_pack_name != curr_pack_name) {
966                 if (!final_pack_name) {
967                         snprintf(name, sizeof(name), "%s/pack/pack-%s.pack",
968                                  get_object_directory(), sha1_to_hex(sha1));
969                         final_pack_name = name;
970                 }
971                 if (move_temp_to_file(curr_pack_name, final_pack_name))
972                         die("cannot store pack file");
973         } else if (from_stdin)
974                 chmod(final_pack_name, 0444);
975
976         if (final_index_name != curr_index_name) {
977                 if (!final_index_name) {
978                         snprintf(name, sizeof(name), "%s/pack/pack-%s.idx",
979                                  get_object_directory(), sha1_to_hex(sha1));
980                         final_index_name = name;
981                 }
982                 if (move_temp_to_file(curr_index_name, final_index_name))
983                         die("cannot store index file");
984         } else
985                 chmod(final_index_name, 0444);
986
987         if (!from_stdin) {
988                 printf("%s\n", sha1_to_hex(sha1));
989         } else {
990                 char buf[48];
991                 int len = snprintf(buf, sizeof(buf), "%s\t%s\n",
992                                    report, sha1_to_hex(sha1));
993                 write_or_die(1, buf, len);
994
995                 /*
996                  * Let's just mimic git-unpack-objects here and write
997                  * the last part of the input buffer to stdout.
998                  */
999                 while (input_len) {
1000                         err = xwrite(1, input_buffer + input_offset, input_len);
1001                         if (err <= 0)
1002                                 break;
1003                         input_len -= err;
1004                         input_offset += err;
1005                 }
1006         }
1007 }
1008
1009 static int git_index_pack_config(const char *k, const char *v, void *cb)
1010 {
1011         struct pack_idx_option *opts = cb;
1012
1013         if (!strcmp(k, "pack.indexversion")) {
1014                 opts->version = git_config_int(k, v);
1015                 if (opts->version > 2)
1016                         die("bad pack.indexversion=%"PRIu32, opts->version);
1017                 return 0;
1018         }
1019         return git_default_config(k, v, cb);
1020 }
1021
1022 static int cmp_uint32(const void *a_, const void *b_)
1023 {
1024         uint32_t a = *((uint32_t *)a_);
1025         uint32_t b = *((uint32_t *)b_);
1026
1027         return (a < b) ? -1 : (a != b);
1028 }
1029
1030 static void read_v2_anomalous_offsets(struct packed_git *p,
1031                                       struct pack_idx_option *opts)
1032 {
1033         const uint32_t *idx1, *idx2;
1034         uint32_t i;
1035
1036         /* The address of the 4-byte offset table */
1037         idx1 = (((const uint32_t *)p->index_data)
1038                 + 2 /* 8-byte header */
1039                 + 256 /* fan out */
1040                 + 5 * p->num_objects /* 20-byte SHA-1 table */
1041                 + p->num_objects /* CRC32 table */
1042                 );
1043
1044         /* The address of the 8-byte offset table */
1045         idx2 = idx1 + p->num_objects;
1046
1047         for (i = 0; i < p->num_objects; i++) {
1048                 uint32_t off = ntohl(idx1[i]);
1049                 if (!(off & 0x80000000))
1050                         continue;
1051                 off = off & 0x7fffffff;
1052                 if (idx2[off * 2])
1053                         continue;
1054                 /*
1055                  * The real offset is ntohl(idx2[off * 2]) in high 4
1056                  * octets, and ntohl(idx2[off * 2 + 1]) in low 4
1057                  * octets.  But idx2[off * 2] is Zero!!!
1058                  */
1059                 ALLOC_GROW(opts->anomaly, opts->anomaly_nr + 1, opts->anomaly_alloc);
1060                 opts->anomaly[opts->anomaly_nr++] = ntohl(idx2[off * 2 + 1]);
1061         }
1062
1063         if (1 < opts->anomaly_nr)
1064                 qsort(opts->anomaly, opts->anomaly_nr, sizeof(uint32_t), cmp_uint32);
1065 }
1066
1067 static void read_idx_option(struct pack_idx_option *opts, const char *pack_name)
1068 {
1069         struct packed_git *p = add_packed_git(pack_name, strlen(pack_name), 1);
1070
1071         if (!p)
1072                 die("Cannot open existing pack file '%s'", pack_name);
1073         if (open_pack_index(p))
1074                 die("Cannot open existing pack idx file for '%s'", pack_name);
1075
1076         /* Read the attributes from the existing idx file */
1077         opts->version = p->index_version;
1078
1079         if (opts->version == 2)
1080                 read_v2_anomalous_offsets(p, opts);
1081
1082         /*
1083          * Get rid of the idx file as we do not need it anymore.
1084          * NEEDSWORK: extract this bit from free_pack_by_name() in
1085          * sha1_file.c, perhaps?  It shouldn't matter very much as we
1086          * know we haven't installed this pack (hence we never have
1087          * read anything from it).
1088          */
1089         close_pack_index(p);
1090         free(p);
1091 }
1092
1093 static void show_pack_info(int stat_only)
1094 {
1095         int i, baseobjects = nr_objects - nr_deltas;
1096         unsigned long *chain_histogram = NULL;
1097
1098         if (deepest_delta)
1099                 chain_histogram = xcalloc(deepest_delta, sizeof(unsigned long));
1100
1101         for (i = 0; i < nr_objects; i++) {
1102                 struct object_entry *obj = &objects[i];
1103
1104                 if (is_delta_type(obj->type))
1105                         chain_histogram[obj->delta_depth - 1]++;
1106                 if (stat_only)
1107                         continue;
1108                 printf("%s %-6s %lu %lu %"PRIuMAX,
1109                        sha1_to_hex(obj->idx.sha1),
1110                        typename(obj->real_type), obj->size,
1111                        (unsigned long)(obj[1].idx.offset - obj->idx.offset),
1112                        (uintmax_t)obj->idx.offset);
1113                 if (is_delta_type(obj->type)) {
1114                         struct object_entry *bobj = &objects[obj->base_object_no];
1115                         printf(" %u %s", obj->delta_depth, sha1_to_hex(bobj->idx.sha1));
1116                 }
1117                 putchar('\n');
1118         }
1119
1120         if (baseobjects)
1121                 printf("non delta: %d object%s\n",
1122                        baseobjects, baseobjects > 1 ? "s" : "");
1123         for (i = 0; i < deepest_delta; i++) {
1124                 if (!chain_histogram[i])
1125                         continue;
1126                 printf("chain length = %d: %lu object%s\n",
1127                        i + 1,
1128                        chain_histogram[i],
1129                        chain_histogram[i] > 1 ? "s" : "");
1130         }
1131 }
1132
1133 int cmd_index_pack(int argc, const char **argv, const char *prefix)
1134 {
1135         int i, fix_thin_pack = 0, verify = 0, stat_only = 0, stat = 0;
1136         const char *curr_pack, *curr_index;
1137         const char *index_name = NULL, *pack_name = NULL;
1138         const char *keep_name = NULL, *keep_msg = NULL;
1139         char *index_name_buf = NULL, *keep_name_buf = NULL;
1140         struct pack_idx_entry **idx_objects;
1141         struct pack_idx_option opts;
1142         unsigned char pack_sha1[20];
1143
1144         if (argc == 2 && !strcmp(argv[1], "-h"))
1145                 usage(index_pack_usage);
1146
1147         read_replace_refs = 0;
1148
1149         reset_pack_idx_option(&opts);
1150         git_config(git_index_pack_config, &opts);
1151         if (prefix && chdir(prefix))
1152                 die("Cannot come back to cwd");
1153
1154         for (i = 1; i < argc; i++) {
1155                 const char *arg = argv[i];
1156
1157                 if (*arg == '-') {
1158                         if (!strcmp(arg, "--stdin")) {
1159                                 from_stdin = 1;
1160                         } else if (!strcmp(arg, "--fix-thin")) {
1161                                 fix_thin_pack = 1;
1162                         } else if (!strcmp(arg, "--strict")) {
1163                                 strict = 1;
1164                         } else if (!strcmp(arg, "--verify")) {
1165                                 verify = 1;
1166                         } else if (!strcmp(arg, "--verify-stat")) {
1167                                 verify = 1;
1168                                 stat = 1;
1169                         } else if (!strcmp(arg, "--verify-stat-only")) {
1170                                 verify = 1;
1171                                 stat = 1;
1172                                 stat_only = 1;
1173                         } else if (!strcmp(arg, "--keep")) {
1174                                 keep_msg = "";
1175                         } else if (!prefixcmp(arg, "--keep=")) {
1176                                 keep_msg = arg + 7;
1177                         } else if (!prefixcmp(arg, "--pack_header=")) {
1178                                 struct pack_header *hdr;
1179                                 char *c;
1180
1181                                 hdr = (struct pack_header *)input_buffer;
1182                                 hdr->hdr_signature = htonl(PACK_SIGNATURE);
1183                                 hdr->hdr_version = htonl(strtoul(arg + 14, &c, 10));
1184                                 if (*c != ',')
1185                                         die("bad %s", arg);
1186                                 hdr->hdr_entries = htonl(strtoul(c + 1, &c, 10));
1187                                 if (*c)
1188                                         die("bad %s", arg);
1189                                 input_len = sizeof(*hdr);
1190                         } else if (!strcmp(arg, "-v")) {
1191                                 verbose = 1;
1192                         } else if (!strcmp(arg, "-o")) {
1193                                 if (index_name || (i+1) >= argc)
1194                                         usage(index_pack_usage);
1195                                 index_name = argv[++i];
1196                         } else if (!prefixcmp(arg, "--index-version=")) {
1197                                 char *c;
1198                                 opts.version = strtoul(arg + 16, &c, 10);
1199                                 if (opts.version > 2)
1200                                         die("bad %s", arg);
1201                                 if (*c == ',')
1202                                         opts.off32_limit = strtoul(c+1, &c, 0);
1203                                 if (*c || opts.off32_limit & 0x80000000)
1204                                         die("bad %s", arg);
1205                         } else
1206                                 usage(index_pack_usage);
1207                         continue;
1208                 }
1209
1210                 if (pack_name)
1211                         usage(index_pack_usage);
1212                 pack_name = arg;
1213         }
1214
1215         if (!pack_name && !from_stdin)
1216                 usage(index_pack_usage);
1217         if (fix_thin_pack && !from_stdin)
1218                 die("--fix-thin cannot be used without --stdin");
1219         if (!index_name && pack_name) {
1220                 int len = strlen(pack_name);
1221                 if (!has_extension(pack_name, ".pack"))
1222                         die("packfile name '%s' does not end with '.pack'",
1223                             pack_name);
1224                 index_name_buf = xmalloc(len);
1225                 memcpy(index_name_buf, pack_name, len - 5);
1226                 strcpy(index_name_buf + len - 5, ".idx");
1227                 index_name = index_name_buf;
1228         }
1229         if (keep_msg && !keep_name && pack_name) {
1230                 int len = strlen(pack_name);
1231                 if (!has_extension(pack_name, ".pack"))
1232                         die("packfile name '%s' does not end with '.pack'",
1233                             pack_name);
1234                 keep_name_buf = xmalloc(len);
1235                 memcpy(keep_name_buf, pack_name, len - 5);
1236                 strcpy(keep_name_buf + len - 5, ".keep");
1237                 keep_name = keep_name_buf;
1238         }
1239         if (verify) {
1240                 if (!index_name)
1241                         die("--verify with no packfile name given");
1242                 read_idx_option(&opts, index_name);
1243                 opts.flags |= WRITE_IDX_VERIFY | WRITE_IDX_STRICT;
1244         }
1245         if (strict)
1246                 opts.flags |= WRITE_IDX_STRICT;
1247
1248         curr_pack = open_pack_file(pack_name);
1249         parse_pack_header();
1250         objects = xcalloc(nr_objects + 1, sizeof(struct object_entry));
1251         deltas = xcalloc(nr_objects, sizeof(struct delta_entry));
1252         parse_pack_objects(pack_sha1);
1253         resolve_deltas();
1254         conclude_pack(fix_thin_pack, curr_pack, pack_sha1);
1255         free(deltas);
1256         if (strict)
1257                 check_objects();
1258
1259         if (stat)
1260                 show_pack_info(stat_only);
1261
1262         idx_objects = xmalloc((nr_objects) * sizeof(struct pack_idx_entry *));
1263         for (i = 0; i < nr_objects; i++)
1264                 idx_objects[i] = &objects[i].idx;
1265         curr_index = write_idx_file(index_name, idx_objects, nr_objects, &opts, pack_sha1);
1266         free(idx_objects);
1267
1268         if (!verify)
1269                 final(pack_name, curr_pack,
1270                       index_name, curr_index,
1271                       keep_name, keep_msg,
1272                       pack_sha1);
1273         else
1274                 close(input_fd);
1275         free(objects);
1276         free(index_name_buf);
1277         free(keep_name_buf);
1278         if (pack_name == NULL)
1279                 free((void *) curr_pack);
1280         if (index_name == NULL)
1281                 free((void *) curr_index);
1282
1283         return 0;
1284 }