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