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