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