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