]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/index-pack.c
index-pack --verify: read anomalous offsets from v2 idx file
[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[] =
e337a04d 14"git index-pack [-v] [-o <index-file>] [--keep | --keep=<msg>] [--verify] [--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 */
c03c8315 164 if (signed_add_overflows(consumed_bytes, bytes))
d7dd0223 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{
7ce4721a 269 int status;
9cf6d335
SV
270 z_stream stream;
271 void *buf = xmalloc(size);
272
273 memset(&stream, 0, sizeof(stream));
7ce4721a 274 git_inflate_init(&stream);
9cf6d335
SV
275 stream.next_out = buf;
276 stream.avail_out = size;
9cf6d335 277
7ce4721a 278 do {
2d477051
NP
279 stream.next_in = fill(1);
280 stream.avail_in = input_len;
7ce4721a
NP
281 status = git_inflate(&stream, 0);
282 use(input_len - stream.avail_in);
283 } while (status == Z_OK);
284 if (stream.total_out != size || status != Z_STREAM_END)
285 bad_object(offset, "inflate returned %d", status);
39c68542 286 git_inflate_end(&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{
48fb7deb
LT
292 unsigned char *p;
293 unsigned long size, c;
d7dd0223 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);
48fb7deb 311 size += (c & 0x7f) << shift;
9cf6d335
SV
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 336 delta_base->offset = obj->idx.offset - base_offset;
d8f32556 337 if (delta_base->offset <= 0 || delta_base->offset >= obj->idx.offset)
aa7e44bf 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;
776ea370 359 unsigned char *data, *inbuf;
2d477051 360 z_stream stream;
776ea370 361 int status;
9cf6d335 362
2d477051 363 data = xmalloc(obj->size);
776ea370
NP
364 inbuf = xmalloc((len < 64*1024) ? len : 64*1024);
365
2d477051 366 memset(&stream, 0, sizeof(stream));
776ea370 367 git_inflate_init(&stream);
2d477051
NP
368 stream.next_out = data;
369 stream.avail_out = obj->size;
776ea370
NP
370
371 do {
372 ssize_t n = (len < 64*1024) ? len : 64*1024;
373 n = pread(pack_fd, inbuf, n, from);
374 if (n < 0)
375 die_errno("cannot pread pack file");
376 if (!n)
377 die("premature end of pack file, %lu bytes missing", len);
378 from += n;
379 len -= n;
380 stream.next_in = inbuf;
381 stream.avail_in = n;
382 status = git_inflate(&stream, 0);
383 } while (len && status == Z_OK && !stream.avail_in);
384
385 /* This has been inflated OK when first encountered, so... */
386 if (status != Z_STREAM_END || stream.total_out != obj->size)
2d477051 387 die("serious inflate inconsistency");
776ea370
NP
388
389 git_inflate_end(&stream);
390 free(inbuf);
9cf6d335
SV
391 return data;
392}
393
7218a215
JH
394static int compare_delta_bases(const union delta_base *base1,
395 const union delta_base *base2,
396 enum object_type type1,
397 enum object_type type2)
398{
399 int cmp = type1 - type2;
400 if (cmp)
401 return cmp;
402 return memcmp(base1, base2, UNION_BASE_SZ);
403}
404
405static int find_delta(const union delta_base *base, enum object_type type)
9cf6d335
SV
406{
407 int first = 0, last = nr_deltas;
408
409 while (first < last) {
410 int next = (first + last) / 2;
411 struct delta_entry *delta = &deltas[next];
412 int cmp;
413
7218a215
JH
414 cmp = compare_delta_bases(base, &delta->base,
415 type, objects[delta->obj_no].type);
9cf6d335
SV
416 if (!cmp)
417 return next;
418 if (cmp < 0) {
419 last = next;
420 continue;
421 }
422 first = next+1;
423 }
424 return -first-1;
425}
426
6a87ed97 427static void find_delta_children(const union delta_base *base,
7218a215
JH
428 int *first_index, int *last_index,
429 enum object_type type)
9cf6d335 430{
7218a215 431 int first = find_delta(base, type);
9cf6d335
SV
432 int last = first;
433 int end = nr_deltas - 1;
434
6a87ed97
NP
435 if (first < 0) {
436 *first_index = 0;
437 *last_index = -1;
438 return;
439 }
3c552873 440 while (first > 0 && !memcmp(&deltas[first - 1].base, base, UNION_BASE_SZ))
9cf6d335 441 --first;
3c552873 442 while (last < end && !memcmp(&deltas[last + 1].base, base, UNION_BASE_SZ))
9cf6d335
SV
443 ++last;
444 *first_index = first;
445 *last_index = last;
9cf6d335
SV
446}
447
448static void sha1_object(const void *data, unsigned long size,
9096c660 449 enum object_type type, unsigned char *sha1)
9cf6d335 450{
ce9fbf16 451 hash_sha1_file(data, size, typename(type), sha1);
9096c660 452 if (has_sha1_file(sha1)) {
8685da42
NP
453 void *has_data;
454 enum object_type has_type;
455 unsigned long has_size;
456 has_data = read_sha1_file(sha1, &has_type, &has_size);
457 if (!has_data)
458 die("cannot read existing object %s", sha1_to_hex(sha1));
459 if (size != has_size || type != has_type ||
460 memcmp(data, has_data, size) != 0)
461 die("SHA1 COLLISION FOUND WITH %s !", sha1_to_hex(sha1));
bbf4b41b 462 free(has_data);
8685da42 463 }
0153be05
MK
464 if (strict) {
465 if (type == OBJ_BLOB) {
466 struct blob *blob = lookup_blob(sha1);
467 if (blob)
468 blob->object.flags |= FLAG_CHECKED;
469 else
470 die("invalid blob object %s", sha1_to_hex(sha1));
471 } else {
472 struct object *obj;
473 int eaten;
474 void *buf = (void *) data;
475
476 /*
477 * we do not need to free the memory here, as the
478 * buf is deleted by the caller.
479 */
480 obj = parse_object_buffer(sha1, type, size, buf, &eaten);
481 if (!obj)
482 die("invalid %s", typename(type));
483 if (fsck_object(obj, 1, fsck_error_function))
484 die("Error in object");
2af202be 485 if (fsck_walk(obj, mark_link, NULL))
0153be05
MK
486 die("Not all child objects of %s are reachable", sha1_to_hex(obj->sha1));
487
488 if (obj->type == OBJ_TREE) {
489 struct tree *item = (struct tree *) obj;
490 item->buffer = NULL;
491 }
492 if (obj->type == OBJ_COMMIT) {
493 struct commit *commit = (struct commit *) obj;
494 commit->buffer = NULL;
495 }
496 obj->flags |= FLAG_CHECKED;
497 }
498 }
9cf6d335
SV
499}
500
92392b4a
SP
501static void *get_base_data(struct base_data *c)
502{
503 if (!c->data) {
504 struct object_entry *obj = c->obj;
505
506 if (obj->type == OBJ_REF_DELTA || obj->type == OBJ_OFS_DELTA) {
507 void *base = get_base_data(c->base);
508 void *raw = get_data_from_pack(obj);
509 c->data = patch_delta(
510 base, c->base->size,
511 raw, obj->size,
512 &c->size);
513 free(raw);
514 if (!c->data)
515 bad_object(obj->idx.offset, "failed to apply delta");
9441b61d 516 } else {
92392b4a 517 c->data = get_data_from_pack(obj);
9441b61d
NP
518 c->size = obj->size;
519 }
92392b4a
SP
520
521 base_cache_used += c->size;
522 prune_base_data(c);
523 }
524 return c->data;
525}
526
f41aebd4 527static void resolve_delta(struct object_entry *delta_obj,
9441b61d 528 struct base_data *base, struct base_data *result)
9cf6d335 529{
ce3f6dc6 530 void *base_data, *delta_data;
9cf6d335 531
ce3f6dc6 532 delta_obj->real_type = base->obj->real_type;
636171cb 533 delta_data = get_data_from_pack(delta_obj);
ce3f6dc6 534 base_data = get_base_data(base);
9441b61d 535 result->obj = delta_obj;
ce3f6dc6
NP
536 result->data = patch_delta(base_data, base->size,
537 delta_data, delta_obj->size, &result->size);
9cf6d335 538 free(delta_data);
9441b61d 539 if (!result->data)
aa7e44bf 540 bad_object(delta_obj->idx.offset, "failed to apply delta");
9441b61d
NP
541 sha1_object(result->data, result->size, delta_obj->real_type,
542 delta_obj->idx.sha1);
636171cb 543 nr_resolved_deltas++;
9441b61d
NP
544}
545
546static void find_unresolved_deltas(struct base_data *base,
547 struct base_data *prev_base)
548{
6a87ed97 549 int i, ref_first, ref_last, ofs_first, ofs_last;
9441b61d
NP
550
551 /*
552 * This is a recursive function. Those brackets should help reducing
553 * stack usage by limiting the scope of the delta_base union.
554 */
555 {
556 union delta_base base_spec;
557
558 hashcpy(base_spec.sha1, base->obj->idx.sha1);
7218a215
JH
559 find_delta_children(&base_spec,
560 &ref_first, &ref_last, OBJ_REF_DELTA);
53dda6ff 561
9441b61d
NP
562 memset(&base_spec, 0, sizeof(base_spec));
563 base_spec.offset = base->obj->idx.offset;
7218a215
JH
564 find_delta_children(&base_spec,
565 &ofs_first, &ofs_last, OBJ_OFS_DELTA);
9441b61d 566 }
4a438cab 567
9ed19614
NP
568 if (ref_last == -1 && ofs_last == -1) {
569 free(base->data);
9441b61d 570 return;
9ed19614 571 }
53dda6ff 572
9441b61d 573 link_base_data(prev_base, base);
4a438cab 574
6a87ed97
NP
575 for (i = ref_first; i <= ref_last; i++) {
576 struct object_entry *child = objects + deltas[i].obj_no;
7218a215
JH
577 struct base_data result;
578
579 assert(child->real_type == OBJ_REF_DELTA);
580 resolve_delta(child, base, &result);
581 if (i == ref_last && ofs_last == -1)
582 free_base_data(base);
583 find_unresolved_deltas(&result, base);
53dda6ff
NP
584 }
585
6a87ed97
NP
586 for (i = ofs_first; i <= ofs_last; i++) {
587 struct object_entry *child = objects + deltas[i].obj_no;
7218a215
JH
588 struct base_data result;
589
590 assert(child->real_type == OBJ_OFS_DELTA);
591 resolve_delta(child, base, &result);
592 if (i == ofs_last)
593 free_base_data(base);
594 find_unresolved_deltas(&result, base);
9cf6d335 595 }
53dda6ff 596
9441b61d 597 unlink_base_data(base);
9cf6d335
SV
598}
599
600static int compare_delta_entry(const void *a, const void *b)
601{
602 const struct delta_entry *delta_a = a;
603 const struct delta_entry *delta_b = b;
7218a215
JH
604
605 /* group by type (ref vs ofs) and then by value (sha-1 or offset) */
606 return compare_delta_bases(&delta_a->base, &delta_b->base,
607 objects[delta_a->obj_no].type,
608 objects[delta_b->obj_no].type);
9cf6d335
SV
609}
610
2d477051
NP
611/* Parse all objects and return the pack content SHA1 hash */
612static void parse_pack_objects(unsigned char *sha1)
9cf6d335 613{
96a02f8f 614 int i;
53dda6ff 615 struct delta_entry *delta = deltas;
2d477051 616 struct stat st;
9cf6d335
SV
617
618 /*
619 * First pass:
620 * - find locations of all objects;
621 * - calculate SHA1 of all non-delta objects;
b89c4e93 622 * - remember base (SHA1 or offset) for all deltas.
9cf6d335 623 */
13aaf148 624 if (verbose)
29e63ed3
NP
625 progress = start_progress(
626 from_stdin ? "Receiving objects" : "Indexing objects",
627 nr_objects);
9cf6d335
SV
628 for (i = 0; i < nr_objects; i++) {
629 struct object_entry *obj = &objects[i];
f41aebd4 630 void *data = unpack_raw_entry(obj, &delta->base);
9cf6d335 631 obj->real_type = obj->type;
53dda6ff
NP
632 if (obj->type == OBJ_REF_DELTA || obj->type == OBJ_OFS_DELTA) {
633 nr_deltas++;
636171cb 634 delta->obj_no = i;
53dda6ff 635 delta++;
9cf6d335 636 } else
aa7e44bf 637 sha1_object(data, obj->size, obj->type, obj->idx.sha1);
9cf6d335 638 free(data);
4d4fcc54 639 display_progress(progress, i+1);
9cf6d335 640 }
aa7e44bf 641 objects[i].idx.offset = consumed_bytes;
4d4fcc54 642 stop_progress(&progress);
2d477051
NP
643
644 /* Check pack integrity */
636171cb 645 flush();
9126f009 646 git_SHA1_Final(sha1, &input_ctx);
2d477051 647 if (hashcmp(fill(20), sha1))
e42797f5 648 die("pack is corrupted (SHA1 mismatch)");
9bee2478 649 use(20);
2d477051
NP
650
651 /* If input_fd is a file, we should have reached its end now. */
652 if (fstat(input_fd, &st))
d824cbba 653 die_errno("cannot fstat packfile");
fa257b05
JS
654 if (S_ISREG(st.st_mode) &&
655 lseek(input_fd, 0, SEEK_CUR) - input_len != st.st_size)
e42797f5 656 die("pack has junk at the end");
9cf6d335 657
3c9af366
NP
658 if (!nr_deltas)
659 return;
660
53dda6ff 661 /* Sort deltas by base SHA1/offset for fast searching */
9cf6d335
SV
662 qsort(deltas, nr_deltas, sizeof(struct delta_entry),
663 compare_delta_entry);
664
665 /*
666 * Second pass:
667 * - for all non-delta objects, look if it is used as a base for
668 * deltas;
669 * - if used as a base, uncompress the object and apply all deltas,
670 * recursively checking if the resulting object is used as a base
671 * for some more deltas.
672 */
13aaf148 673 if (verbose)
dc6a0757 674 progress = start_progress("Resolving deltas", nr_deltas);
9cf6d335
SV
675 for (i = 0; i < nr_objects; i++) {
676 struct object_entry *obj = &objects[i];
f41aebd4 677 struct base_data base_obj;
9cf6d335 678
53dda6ff 679 if (obj->type == OBJ_REF_DELTA || obj->type == OBJ_OFS_DELTA)
9cf6d335 680 continue;
03993e13 681 base_obj.obj = obj;
9441b61d
NP
682 base_obj.data = NULL;
683 find_unresolved_deltas(&base_obj, NULL);
4d4fcc54 684 display_progress(progress, nr_resolved_deltas);
9cf6d335 685 }
636171cb
NP
686}
687
8522148f 688static int write_compressed(struct sha1file *f, void *in, unsigned int size)
636171cb
NP
689{
690 z_stream stream;
7734d7f2
NP
691 int status;
692 unsigned char outbuf[4096];
636171cb
NP
693
694 memset(&stream, 0, sizeof(stream));
695 deflateInit(&stream, zlib_compression_level);
636171cb
NP
696 stream.next_in = in;
697 stream.avail_in = size;
636171cb 698
7734d7f2
NP
699 do {
700 stream.next_out = outbuf;
701 stream.avail_out = sizeof(outbuf);
702 status = deflate(&stream, Z_FINISH);
703 sha1write(f, outbuf, sizeof(outbuf) - stream.avail_out);
704 } while (status == Z_OK);
705
706 if (status != Z_STREAM_END)
707 die("unable to deflate appended object (%d)", status);
636171cb 708 size = stream.total_out;
7734d7f2 709 deflateEnd(&stream);
636171cb
NP
710 return size;
711}
712
8522148f 713static struct object_entry *append_obj_to_pack(struct sha1file *f,
03993e13 714 const unsigned char *sha1, void *buf,
636171cb
NP
715 unsigned long size, enum object_type type)
716{
717 struct object_entry *obj = &objects[nr_objects++];
718 unsigned char header[10];
719 unsigned long s = size;
720 int n = 0;
721 unsigned char c = (type << 4) | (s & 15);
722 s >>= 4;
723 while (s) {
724 header[n++] = c | 0x80;
725 c = s & 0x7f;
726 s >>= 7;
727 }
728 header[n++] = c;
8522148f
NP
729 crc32_begin(f);
730 sha1write(f, header, n);
72de2883
BS
731 obj[0].size = size;
732 obj[0].hdr_size = n;
733 obj[0].type = type;
734 obj[0].real_type = type;
aa7e44bf 735 obj[1].idx.offset = obj[0].idx.offset + n;
8522148f
NP
736 obj[1].idx.offset += write_compressed(f, buf, size);
737 obj[0].idx.crc32 = crc32_end(f);
838cd346 738 sha1flush(f);
aa7e44bf 739 hashcpy(obj->idx.sha1, sha1);
03993e13 740 return obj;
636171cb
NP
741}
742
743static int delta_pos_compare(const void *_a, const void *_b)
744{
745 struct delta_entry *a = *(struct delta_entry **)_a;
746 struct delta_entry *b = *(struct delta_entry **)_b;
747 return a->obj_no - b->obj_no;
748}
9cf6d335 749
8522148f 750static void fix_unresolved_deltas(struct sha1file *f, int nr_unresolved)
636171cb
NP
751{
752 struct delta_entry **sorted_by_pos;
96a02f8f 753 int i, n = 0;
636171cb
NP
754
755 /*
756 * Since many unresolved deltas may well be themselves base objects
757 * for more unresolved deltas, we really want to include the
758 * smallest number of base objects that would cover as much delta
759 * as possible by picking the
760 * trunc deltas first, allowing for other deltas to resolve without
761 * additional base objects. Since most base objects are to be found
762 * before deltas depending on them, a good heuristic is to start
763 * resolving deltas in the same order as their position in the pack.
764 */
765 sorted_by_pos = xmalloc(nr_unresolved * sizeof(*sorted_by_pos));
9cf6d335 766 for (i = 0; i < nr_deltas; i++) {
636171cb
NP
767 if (objects[deltas[i].obj_no].real_type != OBJ_REF_DELTA)
768 continue;
769 sorted_by_pos[n++] = &deltas[i];
9cf6d335 770 }
636171cb
NP
771 qsort(sorted_by_pos, n, sizeof(*sorted_by_pos), delta_pos_compare);
772
773 for (i = 0; i < n; i++) {
774 struct delta_entry *d = sorted_by_pos[i];
21666f1a 775 enum object_type type;
f41aebd4 776 struct base_data base_obj;
636171cb
NP
777
778 if (objects[d->obj_no].real_type != OBJ_REF_DELTA)
779 continue;
f41aebd4
SP
780 base_obj.data = read_sha1_file(d->base.sha1, &type, &base_obj.size);
781 if (!base_obj.data)
636171cb 782 continue;
636171cb 783
03993e13
SP
784 if (check_sha1_signature(d->base.sha1, base_obj.data,
785 base_obj.size, typename(type)))
786 die("local object %s is corrupt", sha1_to_hex(d->base.sha1));
8522148f
NP
787 base_obj.obj = append_obj_to_pack(f, d->base.sha1,
788 base_obj.data, base_obj.size, type);
9441b61d 789 find_unresolved_deltas(&base_obj, NULL);
4d4fcc54 790 display_progress(progress, nr_resolved_deltas);
636171cb
NP
791 }
792 free(sorted_by_pos);
793}
794
e42797f5
NP
795static void final(const char *final_pack_name, const char *curr_pack_name,
796 const char *final_index_name, const char *curr_index_name,
b8077709 797 const char *keep_name, const char *keep_msg,
e42797f5
NP
798 unsigned char *sha1)
799{
3a55602e 800 const char *report = "pack";
e42797f5
NP
801 char name[PATH_MAX];
802 int err;
803
804 if (!from_stdin) {
805 close(input_fd);
806 } else {
4c81b03e 807 fsync_or_die(output_fd, curr_pack_name);
e42797f5
NP
808 err = close(output_fd);
809 if (err)
d824cbba 810 die_errno("error while closing pack file");
e42797f5
NP
811 }
812
b8077709
SP
813 if (keep_msg) {
814 int keep_fd, keep_msg_len = strlen(keep_msg);
6e180cdc
JH
815
816 if (!keep_name)
817 keep_fd = odb_pack_keep(name, sizeof(name), sha1);
818 else
819 keep_fd = open(keep_name, O_RDWR|O_CREAT|O_EXCL, 0600);
820
9ca4a201
NP
821 if (keep_fd < 0) {
822 if (errno != EEXIST)
d824cbba
TR
823 die_errno("cannot write keep file '%s'",
824 keep_name);
9ca4a201
NP
825 } else {
826 if (keep_msg_len > 0) {
827 write_or_die(keep_fd, keep_msg, keep_msg_len);
828 write_or_die(keep_fd, "\n", 1);
829 }
91c8d590 830 if (close(keep_fd) != 0)
d824cbba
TR
831 die_errno("cannot close written keep file '%s'",
832 keep_name);
576162a4 833 report = "keep";
b8077709 834 }
b8077709
SP
835 }
836
e42797f5
NP
837 if (final_pack_name != curr_pack_name) {
838 if (!final_pack_name) {
839 snprintf(name, sizeof(name), "%s/pack/pack-%s.pack",
840 get_object_directory(), sha1_to_hex(sha1));
841 final_pack_name = name;
842 }
843 if (move_temp_to_file(curr_pack_name, final_pack_name))
844 die("cannot store pack file");
fb8b1936 845 } else if (from_stdin)
33b65030 846 chmod(final_pack_name, 0444);
e42797f5 847
e42797f5
NP
848 if (final_index_name != curr_index_name) {
849 if (!final_index_name) {
850 snprintf(name, sizeof(name), "%s/pack/pack-%s.idx",
851 get_object_directory(), sha1_to_hex(sha1));
852 final_index_name = name;
853 }
854 if (move_temp_to_file(curr_index_name, final_index_name))
855 die("cannot store index file");
fb8b1936
JH
856 } else
857 chmod(final_index_name, 0444);
576162a4
NP
858
859 if (!from_stdin) {
860 printf("%s\n", sha1_to_hex(sha1));
861 } else {
862 char buf[48];
863 int len = snprintf(buf, sizeof(buf), "%s\t%s\n",
864 report, sha1_to_hex(sha1));
d1b2ddc8 865 write_or_die(1, buf, len);
576162a4
NP
866
867 /*
868 * Let's just mimic git-unpack-objects here and write
869 * the last part of the input buffer to stdout.
870 */
871 while (input_len) {
872 err = xwrite(1, input_buffer + input_offset, input_len);
873 if (err <= 0)
874 break;
875 input_len -= err;
876 input_offset += err;
877 }
878 }
9cf6d335
SV
879}
880
ef90d6d4 881static int git_index_pack_config(const char *k, const char *v, void *cb)
4d00bda2 882{
ebcfb379
JH
883 struct pack_idx_option *opts = cb;
884
4d00bda2 885 if (!strcmp(k, "pack.indexversion")) {
ebcfb379
JH
886 opts->version = git_config_int(k, v);
887 if (opts->version > 2)
888 die("bad pack.indexversion=%"PRIu32, opts->version);
4d00bda2
NP
889 return 0;
890 }
ef90d6d4 891 return git_default_config(k, v, cb);
4d00bda2
NP
892}
893
3c9fc074
JH
894static int cmp_uint32(const void *a_, const void *b_)
895{
896 uint32_t a = *((uint32_t *)a_);
897 uint32_t b = *((uint32_t *)b_);
898
899 return (a < b) ? -1 : (a != b);
900}
901
902static void read_v2_anomalous_offsets(struct packed_git *p,
903 struct pack_idx_option *opts)
904{
905 const uint32_t *idx1, *idx2;
906 uint32_t i;
907
908 /* The address of the 4-byte offset table */
909 idx1 = (((const uint32_t *)p->index_data)
910 + 2 /* 8-byte header */
911 + 256 /* fan out */
912 + 5 * p->num_objects /* 20-byte SHA-1 table */
913 + p->num_objects /* CRC32 table */
914 );
915
916 /* The address of the 8-byte offset table */
917 idx2 = idx1 + p->num_objects;
918
919 for (i = 0; i < p->num_objects; i++) {
920 uint32_t off = ntohl(idx1[i]);
921 if (!(off & 0x80000000))
922 continue;
923 off = off & 0x7fffffff;
924 if (idx2[off * 2])
925 continue;
926 /*
927 * The real offset is ntohl(idx2[off * 2]) in high 4
928 * octets, and ntohl(idx2[off * 2 + 1]) in low 4
929 * octets. But idx2[off * 2] is Zero!!!
930 */
931 ALLOC_GROW(opts->anomaly, opts->anomaly_nr + 1, opts->anomaly_alloc);
932 opts->anomaly[opts->anomaly_nr++] = ntohl(idx2[off * 2 + 1]);
933 }
934
935 if (1 < opts->anomaly_nr)
936 qsort(opts->anomaly, opts->anomaly_nr, sizeof(uint32_t), cmp_uint32);
937}
938
e337a04d
JH
939static void read_idx_option(struct pack_idx_option *opts, const char *pack_name)
940{
941 struct packed_git *p = add_packed_git(pack_name, strlen(pack_name), 1);
942
943 if (!p)
944 die("Cannot open existing pack file '%s'", pack_name);
945 if (open_pack_index(p))
946 die("Cannot open existing pack idx file for '%s'", pack_name);
947
948 /* Read the attributes from the existing idx file */
949 opts->version = p->index_version;
950
3c9fc074
JH
951 if (opts->version == 2)
952 read_v2_anomalous_offsets(p, opts);
953
e337a04d
JH
954 /*
955 * Get rid of the idx file as we do not need it anymore.
956 * NEEDSWORK: extract this bit from free_pack_by_name() in
957 * sha1_file.c, perhaps? It shouldn't matter very much as we
958 * know we haven't installed this pack (hence we never have
959 * read anything from it).
960 */
961 close_pack_index(p);
962 free(p);
963}
964
3bb72562 965int cmd_index_pack(int argc, const char **argv, const char *prefix)
9cf6d335 966{
e337a04d 967 int i, fix_thin_pack = 0, verify = 0;
3bb72562
LT
968 const char *curr_pack, *curr_index;
969 const char *index_name = NULL, *pack_name = NULL;
b8077709
SP
970 const char *keep_name = NULL, *keep_msg = NULL;
971 char *index_name_buf = NULL, *keep_name_buf = NULL;
aa7e44bf 972 struct pack_idx_entry **idx_objects;
ebcfb379 973 struct pack_idx_option opts;
8522148f 974 unsigned char pack_sha1[20];
9cf6d335 975
99caeed0
JN
976 if (argc == 2 && !strcmp(argv[1], "-h"))
977 usage(index_pack_usage);
978
6e2a09d2
NE
979 read_replace_refs = 0;
980
ebcfb379
JH
981 reset_pack_idx_option(&opts);
982 git_config(git_index_pack_config, &opts);
3f8099fc
NTND
983 if (prefix && chdir(prefix))
984 die("Cannot come back to cwd");
4d00bda2 985
9cf6d335 986 for (i = 1; i < argc; i++) {
3bb72562 987 const char *arg = argv[i];
9cf6d335
SV
988
989 if (*arg == '-') {
e42797f5
NP
990 if (!strcmp(arg, "--stdin")) {
991 from_stdin = 1;
636171cb
NP
992 } else if (!strcmp(arg, "--fix-thin")) {
993 fix_thin_pack = 1;
0153be05
MK
994 } else if (!strcmp(arg, "--strict")) {
995 strict = 1;
e337a04d
JH
996 } else if (!strcmp(arg, "--verify")) {
997 verify = 1;
b8077709
SP
998 } else if (!strcmp(arg, "--keep")) {
999 keep_msg = "";
cc44c765 1000 } else if (!prefixcmp(arg, "--keep=")) {
b8077709 1001 keep_msg = arg + 7;
cc44c765 1002 } else if (!prefixcmp(arg, "--pack_header=")) {
bed006fb
NP
1003 struct pack_header *hdr;
1004 char *c;
1005
1006 hdr = (struct pack_header *)input_buffer;
1007 hdr->hdr_signature = htonl(PACK_SIGNATURE);
1008 hdr->hdr_version = htonl(strtoul(arg + 14, &c, 10));
1009 if (*c != ',')
1010 die("bad %s", arg);
1011 hdr->hdr_entries = htonl(strtoul(c + 1, &c, 10));
1012 if (*c)
1013 die("bad %s", arg);
1014 input_len = sizeof(*hdr);
3c9af366
NP
1015 } else if (!strcmp(arg, "-v")) {
1016 verbose = 1;
e42797f5 1017 } else if (!strcmp(arg, "-o")) {
9cf6d335
SV
1018 if (index_name || (i+1) >= argc)
1019 usage(index_pack_usage);
1020 index_name = argv[++i];
4ba7d711
NP
1021 } else if (!prefixcmp(arg, "--index-version=")) {
1022 char *c;
ebcfb379
JH
1023 opts.version = strtoul(arg + 16, &c, 10);
1024 if (opts.version > 2)
4ba7d711
NP
1025 die("bad %s", arg);
1026 if (*c == ',')
ebcfb379
JH
1027 opts.off32_limit = strtoul(c+1, &c, 0);
1028 if (*c || opts.off32_limit & 0x80000000)
4ba7d711 1029 die("bad %s", arg);
9cf6d335
SV
1030 } else
1031 usage(index_pack_usage);
1032 continue;
1033 }
1034
1035 if (pack_name)
1036 usage(index_pack_usage);
1037 pack_name = arg;
1038 }
1039
e42797f5 1040 if (!pack_name && !from_stdin)
9cf6d335 1041 usage(index_pack_usage);
636171cb
NP
1042 if (fix_thin_pack && !from_stdin)
1043 die("--fix-thin cannot be used without --stdin");
e42797f5 1044 if (!index_name && pack_name) {
9cf6d335 1045 int len = strlen(pack_name);
5bb1cda5 1046 if (!has_extension(pack_name, ".pack"))
9cf6d335
SV
1047 die("packfile name '%s' does not end with '.pack'",
1048 pack_name);
6689f087 1049 index_name_buf = xmalloc(len);
9cf6d335
SV
1050 memcpy(index_name_buf, pack_name, len - 5);
1051 strcpy(index_name_buf + len - 5, ".idx");
1052 index_name = index_name_buf;
1053 }
b8077709
SP
1054 if (keep_msg && !keep_name && pack_name) {
1055 int len = strlen(pack_name);
1056 if (!has_extension(pack_name, ".pack"))
1057 die("packfile name '%s' does not end with '.pack'",
1058 pack_name);
1059 keep_name_buf = xmalloc(len);
1060 memcpy(keep_name_buf, pack_name, len - 5);
1061 strcpy(keep_name_buf + len - 5, ".keep");
1062 keep_name = keep_name_buf;
1063 }
e337a04d
JH
1064 if (verify) {
1065 if (!index_name)
1066 die("--verify with no packfile name given");
1067 read_idx_option(&opts, index_name);
1068 opts.flags |= WRITE_IDX_VERIFY;
1069 }
9cf6d335 1070
e42797f5 1071 curr_pack = open_pack_file(pack_name);
9cf6d335 1072 parse_pack_header();
636171cb
NP
1073 objects = xmalloc((nr_objects + 1) * sizeof(struct object_entry));
1074 deltas = xmalloc(nr_objects * sizeof(struct delta_entry));
8522148f 1075 parse_pack_objects(pack_sha1);
96a02f8f 1076 if (nr_deltas == nr_resolved_deltas) {
4d4fcc54 1077 stop_progress(&progress);
96a02f8f
NP
1078 /* Flush remaining pack final 20-byte SHA1. */
1079 flush();
1080 } else {
636171cb 1081 if (fix_thin_pack) {
8522148f
NP
1082 struct sha1file *f;
1083 unsigned char read_sha1[20], tail_sha1[20];
a984a06a 1084 char msg[48];
636171cb 1085 int nr_unresolved = nr_deltas - nr_resolved_deltas;
3c9af366 1086 int nr_objects_initial = nr_objects;
636171cb
NP
1087 if (nr_unresolved <= 0)
1088 die("confusion beyond insanity");
1089 objects = xrealloc(objects,
1090 (nr_objects + nr_unresolved + 1)
1091 * sizeof(*objects));
8522148f
NP
1092 f = sha1fd(output_fd, curr_pack);
1093 fix_unresolved_deltas(f, nr_unresolved);
a984a06a
NP
1094 sprintf(msg, "completed with %d local objects",
1095 nr_objects - nr_objects_initial);
1096 stop_progress_msg(&progress, msg);
8522148f
NP
1097 sha1close(f, tail_sha1, 0);
1098 hashcpy(read_sha1, pack_sha1);
1099 fixup_pack_header_footer(output_fd, pack_sha1,
abeb40e5 1100 curr_pack, nr_objects,
8522148f
NP
1101 read_sha1, consumed_bytes-20);
1102 if (hashcmp(read_sha1, tail_sha1) != 0)
1103 die("Unexpected tail checksum for %s "
1104 "(disk corruption?)", curr_pack);
636171cb
NP
1105 }
1106 if (nr_deltas != nr_resolved_deltas)
1107 die("pack has %d unresolved deltas",
1108 nr_deltas - nr_resolved_deltas);
636171cb 1109 }
9cf6d335 1110 free(deltas);
0153be05
MK
1111 if (strict)
1112 check_objects();
aa7e44bf
GB
1113
1114 idx_objects = xmalloc((nr_objects) * sizeof(struct pack_idx_entry *));
1115 for (i = 0; i < nr_objects; i++)
1116 idx_objects[i] = &objects[i].idx;
ebcfb379 1117 curr_index = write_idx_file(index_name, idx_objects, nr_objects, &opts, pack_sha1);
aa7e44bf
GB
1118 free(idx_objects);
1119
e337a04d
JH
1120 if (!verify)
1121 final(pack_name, curr_pack,
1122 index_name, curr_index,
1123 keep_name, keep_msg,
1124 pack_sha1);
1125 else
1126 close(input_fd);
9cf6d335
SV
1127 free(objects);
1128 free(index_name_buf);
b8077709 1129 free(keep_name_buf);
c85228ed 1130 if (pack_name == NULL)
3bb72562 1131 free((void *) curr_pack);
c85228ed 1132 if (index_name == NULL)
3bb72562 1133 free((void *) curr_index);
9cf6d335
SV
1134
1135 return 0;
1136}