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