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