]> git.ipfire.org Git - thirdparty/git.git/blob - builtin-pack-objects.c
Merge branches 'lh/submodules' and 'pb/am'
[thirdparty/git.git] / builtin-pack-objects.c
1 #include "builtin.h"
2 #include "cache.h"
3 #include "attr.h"
4 #include "object.h"
5 #include "blob.h"
6 #include "commit.h"
7 #include "tag.h"
8 #include "tree.h"
9 #include "delta.h"
10 #include "pack.h"
11 #include "csum-file.h"
12 #include "tree-walk.h"
13 #include "diff.h"
14 #include "revision.h"
15 #include "list-objects.h"
16 #include "progress.h"
17
18 static const char pack_usage[] = "\
19 git-pack-objects [{ -q | --progress | --all-progress }] [--max-pack-size=N] \n\
20 [--local] [--incremental] [--window=N] [--depth=N] \n\
21 [--no-reuse-delta] [--no-reuse-object] [--delta-base-offset] \n\
22 [--non-empty] [--revs [--unpacked | --all]*] [--reflog] \n\
23 [--stdout | base-name] [<ref-list | <object-list]";
24
25 struct object_entry {
26 unsigned char sha1[20];
27 uint32_t crc32; /* crc of raw pack data for this object */
28 off_t offset; /* offset into the final pack file */
29 unsigned long size; /* uncompressed size */
30 unsigned int hash; /* name hint hash */
31 unsigned int depth; /* delta depth */
32 struct packed_git *in_pack; /* already in pack */
33 off_t in_pack_offset;
34 struct object_entry *delta; /* delta base object */
35 struct object_entry *delta_child; /* deltified objects who bases me */
36 struct object_entry *delta_sibling; /* other deltified objects who
37 * uses the same base as me
38 */
39 void *delta_data; /* cached delta (uncompressed) */
40 unsigned long delta_size; /* delta data size (uncompressed) */
41 enum object_type type;
42 enum object_type in_pack_type; /* could be delta */
43 unsigned char in_pack_header_size;
44 unsigned char preferred_base; /* we do not pack this, but is available
45 * to be used as the base object to delta
46 * objects against.
47 */
48 unsigned char no_try_delta;
49 };
50
51 /*
52 * Objects we are going to pack are collected in objects array (dynamically
53 * expanded). nr_objects & nr_alloc controls this array. They are stored
54 * in the order we see -- typically rev-list --objects order that gives us
55 * nice "minimum seek" order.
56 */
57 static struct object_entry *objects;
58 static struct object_entry **written_list;
59 static uint32_t nr_objects, nr_alloc, nr_result, nr_written;
60
61 static int non_empty;
62 static int no_reuse_delta, no_reuse_object;
63 static int local;
64 static int incremental;
65 static int allow_ofs_delta;
66 static const char *pack_tmp_name, *idx_tmp_name;
67 static char tmpname[PATH_MAX];
68 static const char *base_name;
69 static unsigned char pack_file_sha1[20];
70 static int progress = 1;
71 static int window = 10;
72 static uint32_t pack_size_limit;
73 static int depth = 50;
74 static int pack_to_stdout;
75 static int num_preferred_base;
76 static struct progress progress_state;
77 static int pack_compression_level = Z_DEFAULT_COMPRESSION;
78 static int pack_compression_seen;
79
80 static unsigned long delta_cache_size = 0;
81 static unsigned long max_delta_cache_size = 0;
82 static unsigned long cache_max_small_delta_size = 1000;
83
84 /*
85 * The object names in objects array are hashed with this hashtable,
86 * to help looking up the entry by object name.
87 * This hashtable is built after all the objects are seen.
88 */
89 static int *object_ix;
90 static int object_ix_hashsz;
91
92 /*
93 * Pack index for existing packs give us easy access to the offsets into
94 * corresponding pack file where each object's data starts, but the entries
95 * do not store the size of the compressed representation (uncompressed
96 * size is easily available by examining the pack entry header). It is
97 * also rather expensive to find the sha1 for an object given its offset.
98 *
99 * We build a hashtable of existing packs (pack_revindex), and keep reverse
100 * index here -- pack index file is sorted by object name mapping to offset;
101 * this pack_revindex[].revindex array is a list of offset/index_nr pairs
102 * ordered by offset, so if you know the offset of an object, next offset
103 * is where its packed representation ends and the index_nr can be used to
104 * get the object sha1 from the main index.
105 */
106 struct revindex_entry {
107 off_t offset;
108 unsigned int nr;
109 };
110 struct pack_revindex {
111 struct packed_git *p;
112 struct revindex_entry *revindex;
113 };
114 static struct pack_revindex *pack_revindex;
115 static int pack_revindex_hashsz;
116
117 /*
118 * stats
119 */
120 static uint32_t written, written_delta;
121 static uint32_t reused, reused_delta;
122
123 static int pack_revindex_ix(struct packed_git *p)
124 {
125 unsigned long ui = (unsigned long)p;
126 int i;
127
128 ui = ui ^ (ui >> 16); /* defeat structure alignment */
129 i = (int)(ui % pack_revindex_hashsz);
130 while (pack_revindex[i].p) {
131 if (pack_revindex[i].p == p)
132 return i;
133 if (++i == pack_revindex_hashsz)
134 i = 0;
135 }
136 return -1 - i;
137 }
138
139 static void prepare_pack_ix(void)
140 {
141 int num;
142 struct packed_git *p;
143 for (num = 0, p = packed_git; p; p = p->next)
144 num++;
145 if (!num)
146 return;
147 pack_revindex_hashsz = num * 11;
148 pack_revindex = xcalloc(sizeof(*pack_revindex), pack_revindex_hashsz);
149 for (p = packed_git; p; p = p->next) {
150 num = pack_revindex_ix(p);
151 num = - 1 - num;
152 pack_revindex[num].p = p;
153 }
154 /* revindex elements are lazily initialized */
155 }
156
157 static int cmp_offset(const void *a_, const void *b_)
158 {
159 const struct revindex_entry *a = a_;
160 const struct revindex_entry *b = b_;
161 return (a->offset < b->offset) ? -1 : (a->offset > b->offset) ? 1 : 0;
162 }
163
164 /*
165 * Ordered list of offsets of objects in the pack.
166 */
167 static void prepare_pack_revindex(struct pack_revindex *rix)
168 {
169 struct packed_git *p = rix->p;
170 int num_ent = p->num_objects;
171 int i;
172 const char *index = p->index_data;
173
174 rix->revindex = xmalloc(sizeof(*rix->revindex) * (num_ent + 1));
175 index += 4 * 256;
176
177 if (p->index_version > 1) {
178 const uint32_t *off_32 =
179 (uint32_t *)(index + 8 + p->num_objects * (20 + 4));
180 const uint32_t *off_64 = off_32 + p->num_objects;
181 for (i = 0; i < num_ent; i++) {
182 uint32_t off = ntohl(*off_32++);
183 if (!(off & 0x80000000)) {
184 rix->revindex[i].offset = off;
185 } else {
186 rix->revindex[i].offset =
187 ((uint64_t)ntohl(*off_64++)) << 32;
188 rix->revindex[i].offset |=
189 ntohl(*off_64++);
190 }
191 rix->revindex[i].nr = i;
192 }
193 } else {
194 for (i = 0; i < num_ent; i++) {
195 uint32_t hl = *((uint32_t *)(index + 24 * i));
196 rix->revindex[i].offset = ntohl(hl);
197 rix->revindex[i].nr = i;
198 }
199 }
200
201 /* This knows the pack format -- the 20-byte trailer
202 * follows immediately after the last object data.
203 */
204 rix->revindex[num_ent].offset = p->pack_size - 20;
205 rix->revindex[num_ent].nr = -1;
206 qsort(rix->revindex, num_ent, sizeof(*rix->revindex), cmp_offset);
207 }
208
209 static struct revindex_entry * find_packed_object(struct packed_git *p,
210 off_t ofs)
211 {
212 int num;
213 int lo, hi;
214 struct pack_revindex *rix;
215 struct revindex_entry *revindex;
216 num = pack_revindex_ix(p);
217 if (num < 0)
218 die("internal error: pack revindex uninitialized");
219 rix = &pack_revindex[num];
220 if (!rix->revindex)
221 prepare_pack_revindex(rix);
222 revindex = rix->revindex;
223 lo = 0;
224 hi = p->num_objects + 1;
225 do {
226 int mi = (lo + hi) / 2;
227 if (revindex[mi].offset == ofs) {
228 return revindex + mi;
229 }
230 else if (ofs < revindex[mi].offset)
231 hi = mi;
232 else
233 lo = mi + 1;
234 } while (lo < hi);
235 die("internal error: pack revindex corrupt");
236 }
237
238 static const unsigned char *find_packed_object_name(struct packed_git *p,
239 off_t ofs)
240 {
241 struct revindex_entry *entry = find_packed_object(p, ofs);
242 return nth_packed_object_sha1(p, entry->nr);
243 }
244
245 static void *delta_against(void *buf, unsigned long size, struct object_entry *entry)
246 {
247 unsigned long othersize, delta_size;
248 enum object_type type;
249 void *otherbuf = read_sha1_file(entry->delta->sha1, &type, &othersize);
250 void *delta_buf;
251
252 if (!otherbuf)
253 die("unable to read %s", sha1_to_hex(entry->delta->sha1));
254 delta_buf = diff_delta(otherbuf, othersize,
255 buf, size, &delta_size, 0);
256 if (!delta_buf || delta_size != entry->delta_size)
257 die("delta size changed");
258 free(buf);
259 free(otherbuf);
260 return delta_buf;
261 }
262
263 /*
264 * The per-object header is a pretty dense thing, which is
265 * - first byte: low four bits are "size", then three bits of "type",
266 * and the high bit is "size continues".
267 * - each byte afterwards: low seven bits are size continuation,
268 * with the high bit being "size continues"
269 */
270 static int encode_header(enum object_type type, unsigned long size, unsigned char *hdr)
271 {
272 int n = 1;
273 unsigned char c;
274
275 if (type < OBJ_COMMIT || type > OBJ_REF_DELTA)
276 die("bad type %d", type);
277
278 c = (type << 4) | (size & 15);
279 size >>= 4;
280 while (size) {
281 *hdr++ = c | 0x80;
282 c = size & 0x7f;
283 size >>= 7;
284 n++;
285 }
286 *hdr = c;
287 return n;
288 }
289
290 /*
291 * we are going to reuse the existing object data as is. make
292 * sure it is not corrupt.
293 */
294 static int check_pack_inflate(struct packed_git *p,
295 struct pack_window **w_curs,
296 off_t offset,
297 off_t len,
298 unsigned long expect)
299 {
300 z_stream stream;
301 unsigned char fakebuf[4096], *in;
302 int st;
303
304 memset(&stream, 0, sizeof(stream));
305 inflateInit(&stream);
306 do {
307 in = use_pack(p, w_curs, offset, &stream.avail_in);
308 stream.next_in = in;
309 stream.next_out = fakebuf;
310 stream.avail_out = sizeof(fakebuf);
311 st = inflate(&stream, Z_FINISH);
312 offset += stream.next_in - in;
313 } while (st == Z_OK || st == Z_BUF_ERROR);
314 inflateEnd(&stream);
315 return (st == Z_STREAM_END &&
316 stream.total_out == expect &&
317 stream.total_in == len) ? 0 : -1;
318 }
319
320 static int check_pack_crc(struct packed_git *p, struct pack_window **w_curs,
321 off_t offset, off_t len, unsigned int nr)
322 {
323 const uint32_t *index_crc;
324 uint32_t data_crc = crc32(0, Z_NULL, 0);
325
326 do {
327 unsigned int avail;
328 void *data = use_pack(p, w_curs, offset, &avail);
329 if (avail > len)
330 avail = len;
331 data_crc = crc32(data_crc, data, avail);
332 offset += avail;
333 len -= avail;
334 } while (len);
335
336 index_crc = p->index_data;
337 index_crc += 2 + 256 + p->num_objects * (20/4) + nr;
338
339 return data_crc != ntohl(*index_crc);
340 }
341
342 static void copy_pack_data(struct sha1file *f,
343 struct packed_git *p,
344 struct pack_window **w_curs,
345 off_t offset,
346 off_t len)
347 {
348 unsigned char *in;
349 unsigned int avail;
350
351 while (len) {
352 in = use_pack(p, w_curs, offset, &avail);
353 if (avail > len)
354 avail = (unsigned int)len;
355 sha1write(f, in, avail);
356 offset += avail;
357 len -= avail;
358 }
359 }
360
361 static unsigned long write_object(struct sha1file *f,
362 struct object_entry *entry,
363 off_t write_offset)
364 {
365 unsigned long size;
366 enum object_type type;
367 void *buf;
368 unsigned char header[10];
369 unsigned char dheader[10];
370 unsigned hdrlen;
371 off_t datalen;
372 enum object_type obj_type;
373 int to_reuse = 0;
374 /* write limit if limited packsize and not first object */
375 unsigned long limit = pack_size_limit && nr_written ?
376 pack_size_limit - write_offset : 0;
377 /* no if no delta */
378 int usable_delta = !entry->delta ? 0 :
379 /* yes if unlimited packfile */
380 !pack_size_limit ? 1 :
381 /* no if base written to previous pack */
382 entry->delta->offset == (off_t)-1 ? 0 :
383 /* otherwise double-check written to this
384 * pack, like we do below
385 */
386 entry->delta->offset ? 1 : 0;
387
388 if (!pack_to_stdout)
389 crc32_begin(f);
390
391 obj_type = entry->type;
392 if (no_reuse_object)
393 to_reuse = 0; /* explicit */
394 else if (!entry->in_pack)
395 to_reuse = 0; /* can't reuse what we don't have */
396 else if (obj_type == OBJ_REF_DELTA || obj_type == OBJ_OFS_DELTA)
397 /* check_object() decided it for us ... */
398 to_reuse = usable_delta;
399 /* ... but pack split may override that */
400 else if (obj_type != entry->in_pack_type)
401 to_reuse = 0; /* pack has delta which is unusable */
402 else if (entry->delta)
403 to_reuse = 0; /* we want to pack afresh */
404 else
405 to_reuse = 1; /* we have it in-pack undeltified,
406 * and we do not need to deltify it.
407 */
408
409 if (!to_reuse) {
410 z_stream stream;
411 unsigned long maxsize;
412 void *out;
413 if (!usable_delta) {
414 buf = read_sha1_file(entry->sha1, &obj_type, &size);
415 if (!buf)
416 die("unable to read %s", sha1_to_hex(entry->sha1));
417 } else if (entry->delta_data) {
418 size = entry->delta_size;
419 buf = entry->delta_data;
420 entry->delta_data = NULL;
421 obj_type = (allow_ofs_delta && entry->delta->offset) ?
422 OBJ_OFS_DELTA : OBJ_REF_DELTA;
423 } else {
424 buf = read_sha1_file(entry->sha1, &type, &size);
425 if (!buf)
426 die("unable to read %s", sha1_to_hex(entry->sha1));
427 buf = delta_against(buf, size, entry);
428 size = entry->delta_size;
429 obj_type = (allow_ofs_delta && entry->delta->offset) ?
430 OBJ_OFS_DELTA : OBJ_REF_DELTA;
431 }
432 /* compress the data to store and put compressed length in datalen */
433 memset(&stream, 0, sizeof(stream));
434 deflateInit(&stream, pack_compression_level);
435 maxsize = deflateBound(&stream, size);
436 out = xmalloc(maxsize);
437 /* Compress it */
438 stream.next_in = buf;
439 stream.avail_in = size;
440 stream.next_out = out;
441 stream.avail_out = maxsize;
442 while (deflate(&stream, Z_FINISH) == Z_OK)
443 /* nothing */;
444 deflateEnd(&stream);
445 datalen = stream.total_out;
446 deflateEnd(&stream);
447 /*
448 * The object header is a byte of 'type' followed by zero or
449 * more bytes of length.
450 */
451 hdrlen = encode_header(obj_type, size, header);
452
453 if (obj_type == OBJ_OFS_DELTA) {
454 /*
455 * Deltas with relative base contain an additional
456 * encoding of the relative offset for the delta
457 * base from this object's position in the pack.
458 */
459 off_t ofs = entry->offset - entry->delta->offset;
460 unsigned pos = sizeof(dheader) - 1;
461 dheader[pos] = ofs & 127;
462 while (ofs >>= 7)
463 dheader[--pos] = 128 | (--ofs & 127);
464 if (limit && hdrlen + sizeof(dheader) - pos + datalen + 20 >= limit) {
465 free(out);
466 free(buf);
467 return 0;
468 }
469 sha1write(f, header, hdrlen);
470 sha1write(f, dheader + pos, sizeof(dheader) - pos);
471 hdrlen += sizeof(dheader) - pos;
472 } else if (obj_type == OBJ_REF_DELTA) {
473 /*
474 * Deltas with a base reference contain
475 * an additional 20 bytes for the base sha1.
476 */
477 if (limit && hdrlen + 20 + datalen + 20 >= limit) {
478 free(out);
479 free(buf);
480 return 0;
481 }
482 sha1write(f, header, hdrlen);
483 sha1write(f, entry->delta->sha1, 20);
484 hdrlen += 20;
485 } else {
486 if (limit && hdrlen + datalen + 20 >= limit) {
487 free(out);
488 free(buf);
489 return 0;
490 }
491 sha1write(f, header, hdrlen);
492 }
493 sha1write(f, out, datalen);
494 free(out);
495 free(buf);
496 }
497 else {
498 struct packed_git *p = entry->in_pack;
499 struct pack_window *w_curs = NULL;
500 struct revindex_entry *revidx;
501 off_t offset;
502
503 if (entry->delta) {
504 obj_type = (allow_ofs_delta && entry->delta->offset) ?
505 OBJ_OFS_DELTA : OBJ_REF_DELTA;
506 reused_delta++;
507 }
508 hdrlen = encode_header(obj_type, entry->size, header);
509 offset = entry->in_pack_offset;
510 revidx = find_packed_object(p, offset);
511 datalen = revidx[1].offset - offset;
512 if (!pack_to_stdout && p->index_version > 1 &&
513 check_pack_crc(p, &w_curs, offset, datalen, revidx->nr))
514 die("bad packed object CRC for %s", sha1_to_hex(entry->sha1));
515 offset += entry->in_pack_header_size;
516 datalen -= entry->in_pack_header_size;
517 if (obj_type == OBJ_OFS_DELTA) {
518 off_t ofs = entry->offset - entry->delta->offset;
519 unsigned pos = sizeof(dheader) - 1;
520 dheader[pos] = ofs & 127;
521 while (ofs >>= 7)
522 dheader[--pos] = 128 | (--ofs & 127);
523 if (limit && hdrlen + sizeof(dheader) - pos + datalen + 20 >= limit)
524 return 0;
525 sha1write(f, header, hdrlen);
526 sha1write(f, dheader + pos, sizeof(dheader) - pos);
527 hdrlen += sizeof(dheader) - pos;
528 } else if (obj_type == OBJ_REF_DELTA) {
529 if (limit && hdrlen + 20 + datalen + 20 >= limit)
530 return 0;
531 sha1write(f, header, hdrlen);
532 sha1write(f, entry->delta->sha1, 20);
533 hdrlen += 20;
534 } else {
535 if (limit && hdrlen + datalen + 20 >= limit)
536 return 0;
537 sha1write(f, header, hdrlen);
538 }
539
540 if (!pack_to_stdout && p->index_version == 1 &&
541 check_pack_inflate(p, &w_curs, offset, datalen, entry->size))
542 die("corrupt packed object for %s", sha1_to_hex(entry->sha1));
543 copy_pack_data(f, p, &w_curs, offset, datalen);
544 unuse_pack(&w_curs);
545 reused++;
546 }
547 if (usable_delta)
548 written_delta++;
549 written++;
550 if (!pack_to_stdout)
551 entry->crc32 = crc32_end(f);
552 return hdrlen + datalen;
553 }
554
555 static off_t write_one(struct sha1file *f,
556 struct object_entry *e,
557 off_t offset)
558 {
559 unsigned long size;
560
561 /* offset is non zero if object is written already. */
562 if (e->offset || e->preferred_base)
563 return offset;
564
565 /* if we are deltified, write out base object first. */
566 if (e->delta) {
567 offset = write_one(f, e->delta, offset);
568 if (!offset)
569 return 0;
570 }
571
572 e->offset = offset;
573 size = write_object(f, e, offset);
574 if (!size) {
575 e->offset = 0;
576 return 0;
577 }
578 written_list[nr_written++] = e;
579
580 /* make sure off_t is sufficiently large not to wrap */
581 if (offset > offset + size)
582 die("pack too large for current definition of off_t");
583 return offset + size;
584 }
585
586 static int open_object_dir_tmp(const char *path)
587 {
588 snprintf(tmpname, sizeof(tmpname), "%s/%s", get_object_directory(), path);
589 return mkstemp(tmpname);
590 }
591
592 /* forward declarations for write_pack_file */
593 static void write_index_file(off_t last_obj_offset, unsigned char *sha1);
594 static int adjust_perm(const char *path, mode_t mode);
595
596 static void write_pack_file(void)
597 {
598 uint32_t i = 0, j;
599 struct sha1file *f;
600 off_t offset, offset_one, last_obj_offset = 0;
601 struct pack_header hdr;
602 int do_progress = progress >> pack_to_stdout;
603 uint32_t nr_remaining = nr_result;
604
605 if (do_progress)
606 start_progress(&progress_state, "Writing %u objects...", "", nr_result);
607 written_list = xmalloc(nr_objects * sizeof(struct object_entry *));
608
609 do {
610 if (pack_to_stdout) {
611 f = sha1fd(1, "<stdout>");
612 } else {
613 int fd = open_object_dir_tmp("tmp_pack_XXXXXX");
614 if (fd < 0)
615 die("unable to create %s: %s\n", tmpname, strerror(errno));
616 pack_tmp_name = xstrdup(tmpname);
617 f = sha1fd(fd, pack_tmp_name);
618 }
619
620 hdr.hdr_signature = htonl(PACK_SIGNATURE);
621 hdr.hdr_version = htonl(PACK_VERSION);
622 hdr.hdr_entries = htonl(nr_remaining);
623 sha1write(f, &hdr, sizeof(hdr));
624 offset = sizeof(hdr);
625 nr_written = 0;
626 for (; i < nr_objects; i++) {
627 last_obj_offset = offset;
628 offset_one = write_one(f, objects + i, offset);
629 if (!offset_one)
630 break;
631 offset = offset_one;
632 if (do_progress)
633 display_progress(&progress_state, written);
634 }
635
636 /*
637 * Did we write the wrong # entries in the header?
638 * If so, rewrite it like in fast-import
639 */
640 if (pack_to_stdout || nr_written == nr_remaining) {
641 sha1close(f, pack_file_sha1, 1);
642 } else {
643 sha1close(f, pack_file_sha1, 0);
644 fixup_pack_header_footer(f->fd, pack_file_sha1, pack_tmp_name, nr_written);
645 close(f->fd);
646 }
647
648 if (!pack_to_stdout) {
649 unsigned char object_list_sha1[20];
650 mode_t mode = umask(0);
651
652 umask(mode);
653 mode = 0444 & ~mode;
654
655 write_index_file(last_obj_offset, object_list_sha1);
656 snprintf(tmpname, sizeof(tmpname), "%s-%s.pack",
657 base_name, sha1_to_hex(object_list_sha1));
658 if (adjust_perm(pack_tmp_name, mode))
659 die("unable to make temporary pack file readable: %s",
660 strerror(errno));
661 if (rename(pack_tmp_name, tmpname))
662 die("unable to rename temporary pack file: %s",
663 strerror(errno));
664 snprintf(tmpname, sizeof(tmpname), "%s-%s.idx",
665 base_name, sha1_to_hex(object_list_sha1));
666 if (adjust_perm(idx_tmp_name, mode))
667 die("unable to make temporary index file readable: %s",
668 strerror(errno));
669 if (rename(idx_tmp_name, tmpname))
670 die("unable to rename temporary index file: %s",
671 strerror(errno));
672 puts(sha1_to_hex(object_list_sha1));
673 }
674
675 /* mark written objects as written to previous pack */
676 for (j = 0; j < nr_written; j++) {
677 written_list[j]->offset = (off_t)-1;
678 }
679 nr_remaining -= nr_written;
680 } while (nr_remaining && i < nr_objects);
681
682 free(written_list);
683 if (do_progress)
684 stop_progress(&progress_state);
685 if (written != nr_result)
686 die("wrote %u objects while expecting %u", written, nr_result);
687 /*
688 * We have scanned through [0 ... i). Since we have written
689 * the correct number of objects, the remaining [i ... nr_objects)
690 * items must be either already written (due to out-of-order delta base)
691 * or a preferred base. Count those which are neither and complain if any.
692 */
693 for (j = 0; i < nr_objects; i++) {
694 struct object_entry *e = objects + i;
695 j += !e->offset && !e->preferred_base;
696 }
697 if (j)
698 die("wrote %u objects as expected but %u unwritten", written, j);
699 }
700
701 static int sha1_sort(const void *_a, const void *_b)
702 {
703 const struct object_entry *a = *(struct object_entry **)_a;
704 const struct object_entry *b = *(struct object_entry **)_b;
705 return hashcmp(a->sha1, b->sha1);
706 }
707
708 static uint32_t index_default_version = 1;
709 static uint32_t index_off32_limit = 0x7fffffff;
710
711 static void write_index_file(off_t last_obj_offset, unsigned char *sha1)
712 {
713 struct sha1file *f;
714 struct object_entry **sorted_by_sha, **list, **last;
715 uint32_t array[256];
716 uint32_t i, index_version;
717 SHA_CTX ctx;
718
719 int fd = open_object_dir_tmp("tmp_idx_XXXXXX");
720 if (fd < 0)
721 die("unable to create %s: %s\n", tmpname, strerror(errno));
722 idx_tmp_name = xstrdup(tmpname);
723 f = sha1fd(fd, idx_tmp_name);
724
725 if (nr_written) {
726 sorted_by_sha = written_list;
727 qsort(sorted_by_sha, nr_written, sizeof(*sorted_by_sha), sha1_sort);
728 list = sorted_by_sha;
729 last = sorted_by_sha + nr_written;
730 } else
731 sorted_by_sha = list = last = NULL;
732
733 /* if last object's offset is >= 2^31 we should use index V2 */
734 index_version = (last_obj_offset >> 31) ? 2 : index_default_version;
735
736 /* index versions 2 and above need a header */
737 if (index_version >= 2) {
738 struct pack_idx_header hdr;
739 hdr.idx_signature = htonl(PACK_IDX_SIGNATURE);
740 hdr.idx_version = htonl(index_version);
741 sha1write(f, &hdr, sizeof(hdr));
742 }
743
744 /*
745 * Write the first-level table (the list is sorted,
746 * but we use a 256-entry lookup to be able to avoid
747 * having to do eight extra binary search iterations).
748 */
749 for (i = 0; i < 256; i++) {
750 struct object_entry **next = list;
751 while (next < last) {
752 struct object_entry *entry = *next;
753 if (entry->sha1[0] != i)
754 break;
755 next++;
756 }
757 array[i] = htonl(next - sorted_by_sha);
758 list = next;
759 }
760 sha1write(f, array, 256 * 4);
761
762 /* Compute the SHA1 hash of sorted object names. */
763 SHA1_Init(&ctx);
764
765 /* Write the actual SHA1 entries. */
766 list = sorted_by_sha;
767 for (i = 0; i < nr_written; i++) {
768 struct object_entry *entry = *list++;
769 if (index_version < 2) {
770 uint32_t offset = htonl(entry->offset);
771 sha1write(f, &offset, 4);
772 }
773 sha1write(f, entry->sha1, 20);
774 SHA1_Update(&ctx, entry->sha1, 20);
775 }
776
777 if (index_version >= 2) {
778 unsigned int nr_large_offset = 0;
779
780 /* write the crc32 table */
781 list = sorted_by_sha;
782 for (i = 0; i < nr_written; i++) {
783 struct object_entry *entry = *list++;
784 uint32_t crc32_val = htonl(entry->crc32);
785 sha1write(f, &crc32_val, 4);
786 }
787
788 /* write the 32-bit offset table */
789 list = sorted_by_sha;
790 for (i = 0; i < nr_written; i++) {
791 struct object_entry *entry = *list++;
792 uint32_t offset = (entry->offset <= index_off32_limit) ?
793 entry->offset : (0x80000000 | nr_large_offset++);
794 offset = htonl(offset);
795 sha1write(f, &offset, 4);
796 }
797
798 /* write the large offset table */
799 list = sorted_by_sha;
800 while (nr_large_offset) {
801 struct object_entry *entry = *list++;
802 uint64_t offset = entry->offset;
803 if (offset > index_off32_limit) {
804 uint32_t split[2];
805 split[0] = htonl(offset >> 32);
806 split[1] = htonl(offset & 0xffffffff);
807 sha1write(f, split, 8);
808 nr_large_offset--;
809 }
810 }
811 }
812
813 sha1write(f, pack_file_sha1, 20);
814 sha1close(f, NULL, 1);
815 SHA1_Final(sha1, &ctx);
816 }
817
818 static int locate_object_entry_hash(const unsigned char *sha1)
819 {
820 int i;
821 unsigned int ui;
822 memcpy(&ui, sha1, sizeof(unsigned int));
823 i = ui % object_ix_hashsz;
824 while (0 < object_ix[i]) {
825 if (!hashcmp(sha1, objects[object_ix[i] - 1].sha1))
826 return i;
827 if (++i == object_ix_hashsz)
828 i = 0;
829 }
830 return -1 - i;
831 }
832
833 static struct object_entry *locate_object_entry(const unsigned char *sha1)
834 {
835 int i;
836
837 if (!object_ix_hashsz)
838 return NULL;
839
840 i = locate_object_entry_hash(sha1);
841 if (0 <= i)
842 return &objects[object_ix[i]-1];
843 return NULL;
844 }
845
846 static void rehash_objects(void)
847 {
848 uint32_t i;
849 struct object_entry *oe;
850
851 object_ix_hashsz = nr_objects * 3;
852 if (object_ix_hashsz < 1024)
853 object_ix_hashsz = 1024;
854 object_ix = xrealloc(object_ix, sizeof(int) * object_ix_hashsz);
855 memset(object_ix, 0, sizeof(int) * object_ix_hashsz);
856 for (i = 0, oe = objects; i < nr_objects; i++, oe++) {
857 int ix = locate_object_entry_hash(oe->sha1);
858 if (0 <= ix)
859 continue;
860 ix = -1 - ix;
861 object_ix[ix] = i + 1;
862 }
863 }
864
865 static unsigned name_hash(const char *name)
866 {
867 unsigned char c;
868 unsigned hash = 0;
869
870 if (!name)
871 return 0;
872
873 /*
874 * This effectively just creates a sortable number from the
875 * last sixteen non-whitespace characters. Last characters
876 * count "most", so things that end in ".c" sort together.
877 */
878 while ((c = *name++) != 0) {
879 if (isspace(c))
880 continue;
881 hash = (hash >> 2) + (c << 24);
882 }
883 return hash;
884 }
885
886 static void setup_delta_attr_check(struct git_attr_check *check)
887 {
888 static struct git_attr *attr_delta;
889
890 if (!attr_delta)
891 attr_delta = git_attr("delta", 5);
892
893 check[0].attr = attr_delta;
894 }
895
896 static int no_try_delta(const char *path)
897 {
898 struct git_attr_check check[1];
899
900 setup_delta_attr_check(check);
901 if (git_checkattr(path, ARRAY_SIZE(check), check))
902 return 0;
903 if (ATTR_FALSE(check->value))
904 return 1;
905 return 0;
906 }
907
908 static int add_object_entry(const unsigned char *sha1, enum object_type type,
909 const char *name, int exclude)
910 {
911 struct object_entry *entry;
912 struct packed_git *p, *found_pack = NULL;
913 off_t found_offset = 0;
914 int ix;
915 unsigned hash = name_hash(name);
916
917 ix = nr_objects ? locate_object_entry_hash(sha1) : -1;
918 if (ix >= 0) {
919 if (exclude) {
920 entry = objects + object_ix[ix] - 1;
921 if (!entry->preferred_base)
922 nr_result--;
923 entry->preferred_base = 1;
924 }
925 return 0;
926 }
927
928 for (p = packed_git; p; p = p->next) {
929 off_t offset = find_pack_entry_one(sha1, p);
930 if (offset) {
931 if (!found_pack) {
932 found_offset = offset;
933 found_pack = p;
934 }
935 if (exclude)
936 break;
937 if (incremental)
938 return 0;
939 if (local && !p->pack_local)
940 return 0;
941 }
942 }
943
944 if (nr_objects >= nr_alloc) {
945 nr_alloc = (nr_alloc + 1024) * 3 / 2;
946 objects = xrealloc(objects, nr_alloc * sizeof(*entry));
947 }
948
949 entry = objects + nr_objects++;
950 memset(entry, 0, sizeof(*entry));
951 hashcpy(entry->sha1, sha1);
952 entry->hash = hash;
953 if (type)
954 entry->type = type;
955 if (exclude)
956 entry->preferred_base = 1;
957 else
958 nr_result++;
959 if (found_pack) {
960 entry->in_pack = found_pack;
961 entry->in_pack_offset = found_offset;
962 }
963
964 if (object_ix_hashsz * 3 <= nr_objects * 4)
965 rehash_objects();
966 else
967 object_ix[-1 - ix] = nr_objects;
968
969 if (progress)
970 display_progress(&progress_state, nr_objects);
971
972 if (name && no_try_delta(name))
973 entry->no_try_delta = 1;
974
975 return 1;
976 }
977
978 struct pbase_tree_cache {
979 unsigned char sha1[20];
980 int ref;
981 int temporary;
982 void *tree_data;
983 unsigned long tree_size;
984 };
985
986 static struct pbase_tree_cache *(pbase_tree_cache[256]);
987 static int pbase_tree_cache_ix(const unsigned char *sha1)
988 {
989 return sha1[0] % ARRAY_SIZE(pbase_tree_cache);
990 }
991 static int pbase_tree_cache_ix_incr(int ix)
992 {
993 return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
994 }
995
996 static struct pbase_tree {
997 struct pbase_tree *next;
998 /* This is a phony "cache" entry; we are not
999 * going to evict it nor find it through _get()
1000 * mechanism -- this is for the toplevel node that
1001 * would almost always change with any commit.
1002 */
1003 struct pbase_tree_cache pcache;
1004 } *pbase_tree;
1005
1006 static struct pbase_tree_cache *pbase_tree_get(const unsigned char *sha1)
1007 {
1008 struct pbase_tree_cache *ent, *nent;
1009 void *data;
1010 unsigned long size;
1011 enum object_type type;
1012 int neigh;
1013 int my_ix = pbase_tree_cache_ix(sha1);
1014 int available_ix = -1;
1015
1016 /* pbase-tree-cache acts as a limited hashtable.
1017 * your object will be found at your index or within a few
1018 * slots after that slot if it is cached.
1019 */
1020 for (neigh = 0; neigh < 8; neigh++) {
1021 ent = pbase_tree_cache[my_ix];
1022 if (ent && !hashcmp(ent->sha1, sha1)) {
1023 ent->ref++;
1024 return ent;
1025 }
1026 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
1027 ((0 <= available_ix) &&
1028 (!ent && pbase_tree_cache[available_ix])))
1029 available_ix = my_ix;
1030 if (!ent)
1031 break;
1032 my_ix = pbase_tree_cache_ix_incr(my_ix);
1033 }
1034
1035 /* Did not find one. Either we got a bogus request or
1036 * we need to read and perhaps cache.
1037 */
1038 data = read_sha1_file(sha1, &type, &size);
1039 if (!data)
1040 return NULL;
1041 if (type != OBJ_TREE) {
1042 free(data);
1043 return NULL;
1044 }
1045
1046 /* We need to either cache or return a throwaway copy */
1047
1048 if (available_ix < 0)
1049 ent = NULL;
1050 else {
1051 ent = pbase_tree_cache[available_ix];
1052 my_ix = available_ix;
1053 }
1054
1055 if (!ent) {
1056 nent = xmalloc(sizeof(*nent));
1057 nent->temporary = (available_ix < 0);
1058 }
1059 else {
1060 /* evict and reuse */
1061 free(ent->tree_data);
1062 nent = ent;
1063 }
1064 hashcpy(nent->sha1, sha1);
1065 nent->tree_data = data;
1066 nent->tree_size = size;
1067 nent->ref = 1;
1068 if (!nent->temporary)
1069 pbase_tree_cache[my_ix] = nent;
1070 return nent;
1071 }
1072
1073 static void pbase_tree_put(struct pbase_tree_cache *cache)
1074 {
1075 if (!cache->temporary) {
1076 cache->ref--;
1077 return;
1078 }
1079 free(cache->tree_data);
1080 free(cache);
1081 }
1082
1083 static int name_cmp_len(const char *name)
1084 {
1085 int i;
1086 for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
1087 ;
1088 return i;
1089 }
1090
1091 static void add_pbase_object(struct tree_desc *tree,
1092 const char *name,
1093 int cmplen,
1094 const char *fullname)
1095 {
1096 struct name_entry entry;
1097 int cmp;
1098
1099 while (tree_entry(tree,&entry)) {
1100 cmp = tree_entry_len(entry.path, entry.sha1) != cmplen ? 1 :
1101 memcmp(name, entry.path, cmplen);
1102 if (cmp > 0)
1103 continue;
1104 if (cmp < 0)
1105 return;
1106 if (name[cmplen] != '/') {
1107 add_object_entry(entry.sha1,
1108 S_ISDIR(entry.mode) ? OBJ_TREE : OBJ_BLOB,
1109 fullname, 1);
1110 return;
1111 }
1112 if (S_ISDIR(entry.mode)) {
1113 struct tree_desc sub;
1114 struct pbase_tree_cache *tree;
1115 const char *down = name+cmplen+1;
1116 int downlen = name_cmp_len(down);
1117
1118 tree = pbase_tree_get(entry.sha1);
1119 if (!tree)
1120 return;
1121 init_tree_desc(&sub, tree->tree_data, tree->tree_size);
1122
1123 add_pbase_object(&sub, down, downlen, fullname);
1124 pbase_tree_put(tree);
1125 }
1126 }
1127 }
1128
1129 static unsigned *done_pbase_paths;
1130 static int done_pbase_paths_num;
1131 static int done_pbase_paths_alloc;
1132 static int done_pbase_path_pos(unsigned hash)
1133 {
1134 int lo = 0;
1135 int hi = done_pbase_paths_num;
1136 while (lo < hi) {
1137 int mi = (hi + lo) / 2;
1138 if (done_pbase_paths[mi] == hash)
1139 return mi;
1140 if (done_pbase_paths[mi] < hash)
1141 hi = mi;
1142 else
1143 lo = mi + 1;
1144 }
1145 return -lo-1;
1146 }
1147
1148 static int check_pbase_path(unsigned hash)
1149 {
1150 int pos = (!done_pbase_paths) ? -1 : done_pbase_path_pos(hash);
1151 if (0 <= pos)
1152 return 1;
1153 pos = -pos - 1;
1154 if (done_pbase_paths_alloc <= done_pbase_paths_num) {
1155 done_pbase_paths_alloc = alloc_nr(done_pbase_paths_alloc);
1156 done_pbase_paths = xrealloc(done_pbase_paths,
1157 done_pbase_paths_alloc *
1158 sizeof(unsigned));
1159 }
1160 done_pbase_paths_num++;
1161 if (pos < done_pbase_paths_num)
1162 memmove(done_pbase_paths + pos + 1,
1163 done_pbase_paths + pos,
1164 (done_pbase_paths_num - pos - 1) * sizeof(unsigned));
1165 done_pbase_paths[pos] = hash;
1166 return 0;
1167 }
1168
1169 static void add_preferred_base_object(const char *name)
1170 {
1171 struct pbase_tree *it;
1172 int cmplen;
1173 unsigned hash = name_hash(name);
1174
1175 if (!num_preferred_base || check_pbase_path(hash))
1176 return;
1177
1178 cmplen = name_cmp_len(name);
1179 for (it = pbase_tree; it; it = it->next) {
1180 if (cmplen == 0) {
1181 add_object_entry(it->pcache.sha1, OBJ_TREE, NULL, 1);
1182 }
1183 else {
1184 struct tree_desc tree;
1185 init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
1186 add_pbase_object(&tree, name, cmplen, name);
1187 }
1188 }
1189 }
1190
1191 static void add_preferred_base(unsigned char *sha1)
1192 {
1193 struct pbase_tree *it;
1194 void *data;
1195 unsigned long size;
1196 unsigned char tree_sha1[20];
1197
1198 if (window <= num_preferred_base++)
1199 return;
1200
1201 data = read_object_with_reference(sha1, tree_type, &size, tree_sha1);
1202 if (!data)
1203 return;
1204
1205 for (it = pbase_tree; it; it = it->next) {
1206 if (!hashcmp(it->pcache.sha1, tree_sha1)) {
1207 free(data);
1208 return;
1209 }
1210 }
1211
1212 it = xcalloc(1, sizeof(*it));
1213 it->next = pbase_tree;
1214 pbase_tree = it;
1215
1216 hashcpy(it->pcache.sha1, tree_sha1);
1217 it->pcache.tree_data = data;
1218 it->pcache.tree_size = size;
1219 }
1220
1221 static void check_object(struct object_entry *entry)
1222 {
1223 if (entry->in_pack) {
1224 struct packed_git *p = entry->in_pack;
1225 struct pack_window *w_curs = NULL;
1226 const unsigned char *base_ref = NULL;
1227 struct object_entry *base_entry;
1228 unsigned long used, used_0;
1229 unsigned int avail;
1230 off_t ofs;
1231 unsigned char *buf, c;
1232
1233 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1234
1235 /*
1236 * We want in_pack_type even if we do not reuse delta
1237 * since non-delta representations could still be reused.
1238 */
1239 used = unpack_object_header_gently(buf, avail,
1240 &entry->in_pack_type,
1241 &entry->size);
1242
1243 /*
1244 * Determine if this is a delta and if so whether we can
1245 * reuse it or not. Otherwise let's find out as cheaply as
1246 * possible what the actual type and size for this object is.
1247 */
1248 switch (entry->in_pack_type) {
1249 default:
1250 /* Not a delta hence we've already got all we need. */
1251 entry->type = entry->in_pack_type;
1252 entry->in_pack_header_size = used;
1253 unuse_pack(&w_curs);
1254 return;
1255 case OBJ_REF_DELTA:
1256 if (!no_reuse_delta && !entry->preferred_base)
1257 base_ref = use_pack(p, &w_curs,
1258 entry->in_pack_offset + used, NULL);
1259 entry->in_pack_header_size = used + 20;
1260 break;
1261 case OBJ_OFS_DELTA:
1262 buf = use_pack(p, &w_curs,
1263 entry->in_pack_offset + used, NULL);
1264 used_0 = 0;
1265 c = buf[used_0++];
1266 ofs = c & 127;
1267 while (c & 128) {
1268 ofs += 1;
1269 if (!ofs || MSB(ofs, 7))
1270 die("delta base offset overflow in pack for %s",
1271 sha1_to_hex(entry->sha1));
1272 c = buf[used_0++];
1273 ofs = (ofs << 7) + (c & 127);
1274 }
1275 if (ofs >= entry->in_pack_offset)
1276 die("delta base offset out of bound for %s",
1277 sha1_to_hex(entry->sha1));
1278 ofs = entry->in_pack_offset - ofs;
1279 if (!no_reuse_delta && !entry->preferred_base)
1280 base_ref = find_packed_object_name(p, ofs);
1281 entry->in_pack_header_size = used + used_0;
1282 break;
1283 }
1284
1285 if (base_ref && (base_entry = locate_object_entry(base_ref))) {
1286 /*
1287 * If base_ref was set above that means we wish to
1288 * reuse delta data, and we even found that base
1289 * in the list of objects we want to pack. Goodie!
1290 *
1291 * Depth value does not matter - find_deltas() will
1292 * never consider reused delta as the base object to
1293 * deltify other objects against, in order to avoid
1294 * circular deltas.
1295 */
1296 entry->type = entry->in_pack_type;
1297 entry->delta = base_entry;
1298 entry->delta_sibling = base_entry->delta_child;
1299 base_entry->delta_child = entry;
1300 unuse_pack(&w_curs);
1301 return;
1302 }
1303
1304 if (entry->type) {
1305 /*
1306 * This must be a delta and we already know what the
1307 * final object type is. Let's extract the actual
1308 * object size from the delta header.
1309 */
1310 entry->size = get_size_from_delta(p, &w_curs,
1311 entry->in_pack_offset + entry->in_pack_header_size);
1312 unuse_pack(&w_curs);
1313 return;
1314 }
1315
1316 /*
1317 * No choice but to fall back to the recursive delta walk
1318 * with sha1_object_info() to find about the object type
1319 * at this point...
1320 */
1321 unuse_pack(&w_curs);
1322 }
1323
1324 entry->type = sha1_object_info(entry->sha1, &entry->size);
1325 if (entry->type < 0)
1326 die("unable to get type of object %s",
1327 sha1_to_hex(entry->sha1));
1328 }
1329
1330 static int pack_offset_sort(const void *_a, const void *_b)
1331 {
1332 const struct object_entry *a = *(struct object_entry **)_a;
1333 const struct object_entry *b = *(struct object_entry **)_b;
1334
1335 /* avoid filesystem trashing with loose objects */
1336 if (!a->in_pack && !b->in_pack)
1337 return hashcmp(a->sha1, b->sha1);
1338
1339 if (a->in_pack < b->in_pack)
1340 return -1;
1341 if (a->in_pack > b->in_pack)
1342 return 1;
1343 return a->in_pack_offset < b->in_pack_offset ? -1 :
1344 (a->in_pack_offset > b->in_pack_offset);
1345 }
1346
1347 static void get_object_details(void)
1348 {
1349 uint32_t i;
1350 struct object_entry **sorted_by_offset;
1351
1352 sorted_by_offset = xcalloc(nr_objects, sizeof(struct object_entry *));
1353 for (i = 0; i < nr_objects; i++)
1354 sorted_by_offset[i] = objects + i;
1355 qsort(sorted_by_offset, nr_objects, sizeof(*sorted_by_offset), pack_offset_sort);
1356
1357 prepare_pack_ix();
1358 for (i = 0; i < nr_objects; i++)
1359 check_object(sorted_by_offset[i]);
1360 free(sorted_by_offset);
1361 }
1362
1363 static int type_size_sort(const void *_a, const void *_b)
1364 {
1365 const struct object_entry *a = *(struct object_entry **)_a;
1366 const struct object_entry *b = *(struct object_entry **)_b;
1367
1368 if (a->type < b->type)
1369 return -1;
1370 if (a->type > b->type)
1371 return 1;
1372 if (a->hash < b->hash)
1373 return -1;
1374 if (a->hash > b->hash)
1375 return 1;
1376 if (a->preferred_base < b->preferred_base)
1377 return -1;
1378 if (a->preferred_base > b->preferred_base)
1379 return 1;
1380 if (a->size < b->size)
1381 return -1;
1382 if (a->size > b->size)
1383 return 1;
1384 return a > b ? -1 : (a < b); /* newest last */
1385 }
1386
1387 struct unpacked {
1388 struct object_entry *entry;
1389 void *data;
1390 struct delta_index *index;
1391 };
1392
1393 static int delta_cacheable(struct unpacked *trg, struct unpacked *src,
1394 unsigned long src_size, unsigned long trg_size,
1395 unsigned long delta_size)
1396 {
1397 if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
1398 return 0;
1399
1400 if (delta_size < cache_max_small_delta_size)
1401 return 1;
1402
1403 /* cache delta, if objects are large enough compared to delta size */
1404 if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
1405 return 1;
1406
1407 return 0;
1408 }
1409
1410 /*
1411 * We search for deltas _backwards_ in a list sorted by type and
1412 * by size, so that we see progressively smaller and smaller files.
1413 * That's because we prefer deltas to be from the bigger file
1414 * to the smaller - deletes are potentially cheaper, but perhaps
1415 * more importantly, the bigger file is likely the more recent
1416 * one.
1417 */
1418 static int try_delta(struct unpacked *trg, struct unpacked *src,
1419 unsigned max_depth)
1420 {
1421 struct object_entry *trg_entry = trg->entry;
1422 struct object_entry *src_entry = src->entry;
1423 unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
1424 enum object_type type;
1425 void *delta_buf;
1426
1427 /* Don't bother doing diffs between different types */
1428 if (trg_entry->type != src_entry->type)
1429 return -1;
1430
1431 /* We do not compute delta to *create* objects we are not
1432 * going to pack.
1433 */
1434 if (trg_entry->preferred_base)
1435 return -1;
1436
1437 /*
1438 * We do not bother to try a delta that we discarded
1439 * on an earlier try, but only when reusing delta data.
1440 */
1441 if (!no_reuse_delta && trg_entry->in_pack &&
1442 trg_entry->in_pack == src_entry->in_pack &&
1443 trg_entry->in_pack_type != OBJ_REF_DELTA &&
1444 trg_entry->in_pack_type != OBJ_OFS_DELTA)
1445 return 0;
1446
1447 /* Let's not bust the allowed depth. */
1448 if (src_entry->depth >= max_depth)
1449 return 0;
1450
1451 /* Now some size filtering heuristics. */
1452 trg_size = trg_entry->size;
1453 max_size = trg_size/2 - 20;
1454 max_size = max_size * (max_depth - src_entry->depth) / max_depth;
1455 if (max_size == 0)
1456 return 0;
1457 if (trg_entry->delta && trg_entry->delta_size <= max_size)
1458 max_size = trg_entry->delta_size-1;
1459 src_size = src_entry->size;
1460 sizediff = src_size < trg_size ? trg_size - src_size : 0;
1461 if (sizediff >= max_size)
1462 return 0;
1463
1464 /* Load data if not already done */
1465 if (!trg->data) {
1466 trg->data = read_sha1_file(trg_entry->sha1, &type, &sz);
1467 if (sz != trg_size)
1468 die("object %s inconsistent object length (%lu vs %lu)",
1469 sha1_to_hex(trg_entry->sha1), sz, trg_size);
1470 }
1471 if (!src->data) {
1472 src->data = read_sha1_file(src_entry->sha1, &type, &sz);
1473 if (sz != src_size)
1474 die("object %s inconsistent object length (%lu vs %lu)",
1475 sha1_to_hex(src_entry->sha1), sz, src_size);
1476 }
1477 if (!src->index) {
1478 src->index = create_delta_index(src->data, src_size);
1479 if (!src->index) {
1480 static int warned = 0;
1481 if (!warned++)
1482 warning("suboptimal pack - out of memory");
1483 return 0;
1484 }
1485 }
1486
1487 delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
1488 if (!delta_buf)
1489 return 0;
1490
1491 if (trg_entry->delta_data) {
1492 delta_cache_size -= trg_entry->delta_size;
1493 free(trg_entry->delta_data);
1494 }
1495 trg_entry->delta_data = 0;
1496 trg_entry->delta = src_entry;
1497 trg_entry->delta_size = delta_size;
1498 trg_entry->depth = src_entry->depth + 1;
1499
1500 if (delta_cacheable(src, trg, src_size, trg_size, delta_size)) {
1501 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
1502 delta_cache_size += trg_entry->delta_size;
1503 } else
1504 free(delta_buf);
1505 return 1;
1506 }
1507
1508 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
1509 {
1510 struct object_entry *child = me->delta_child;
1511 unsigned int m = n;
1512 while (child) {
1513 unsigned int c = check_delta_limit(child, n + 1);
1514 if (m < c)
1515 m = c;
1516 child = child->delta_sibling;
1517 }
1518 return m;
1519 }
1520
1521 static void find_deltas(struct object_entry **list, int window, int depth)
1522 {
1523 uint32_t i = nr_objects, idx = 0, processed = 0;
1524 unsigned int array_size = window * sizeof(struct unpacked);
1525 struct unpacked *array;
1526 int max_depth;
1527
1528 if (!nr_objects)
1529 return;
1530 array = xmalloc(array_size);
1531 memset(array, 0, array_size);
1532 if (progress)
1533 start_progress(&progress_state, "Deltifying %u objects...", "", nr_result);
1534
1535 do {
1536 struct object_entry *entry = list[--i];
1537 struct unpacked *n = array + idx;
1538 int j;
1539
1540 if (!entry->preferred_base)
1541 processed++;
1542
1543 if (progress)
1544 display_progress(&progress_state, processed);
1545
1546 if (entry->delta)
1547 /* This happens if we decided to reuse existing
1548 * delta from a pack. "!no_reuse_delta &&" is implied.
1549 */
1550 continue;
1551
1552 if (entry->size < 50)
1553 continue;
1554
1555 if (entry->no_try_delta)
1556 continue;
1557
1558 free_delta_index(n->index);
1559 n->index = NULL;
1560 free(n->data);
1561 n->data = NULL;
1562 n->entry = entry;
1563
1564 /*
1565 * If the current object is at pack edge, take the depth the
1566 * objects that depend on the current object into account
1567 * otherwise they would become too deep.
1568 */
1569 max_depth = depth;
1570 if (entry->delta_child) {
1571 max_depth -= check_delta_limit(entry, 0);
1572 if (max_depth <= 0)
1573 goto next;
1574 }
1575
1576 j = window;
1577 while (--j > 0) {
1578 uint32_t other_idx = idx + j;
1579 struct unpacked *m;
1580 if (other_idx >= window)
1581 other_idx -= window;
1582 m = array + other_idx;
1583 if (!m->entry)
1584 break;
1585 if (try_delta(n, m, max_depth) < 0)
1586 break;
1587 }
1588
1589 /* if we made n a delta, and if n is already at max
1590 * depth, leaving it in the window is pointless. we
1591 * should evict it first.
1592 */
1593 if (entry->delta && depth <= entry->depth)
1594 continue;
1595
1596 next:
1597 idx++;
1598 if (idx >= window)
1599 idx = 0;
1600 } while (i > 0);
1601
1602 if (progress)
1603 stop_progress(&progress_state);
1604
1605 for (i = 0; i < window; ++i) {
1606 free_delta_index(array[i].index);
1607 free(array[i].data);
1608 }
1609 free(array);
1610 }
1611
1612 static void prepare_pack(int window, int depth)
1613 {
1614 struct object_entry **delta_list;
1615 uint32_t i;
1616
1617 get_object_details();
1618
1619 if (!window || !depth)
1620 return;
1621
1622 delta_list = xmalloc(nr_objects * sizeof(*delta_list));
1623 for (i = 0; i < nr_objects; i++)
1624 delta_list[i] = objects + i;
1625 qsort(delta_list, nr_objects, sizeof(*delta_list), type_size_sort);
1626 find_deltas(delta_list, window+1, depth);
1627 free(delta_list);
1628 }
1629
1630 static int git_pack_config(const char *k, const char *v)
1631 {
1632 if(!strcmp(k, "pack.window")) {
1633 window = git_config_int(k, v);
1634 return 0;
1635 }
1636 if(!strcmp(k, "pack.depth")) {
1637 depth = git_config_int(k, v);
1638 return 0;
1639 }
1640 if (!strcmp(k, "pack.compression")) {
1641 int level = git_config_int(k, v);
1642 if (level == -1)
1643 level = Z_DEFAULT_COMPRESSION;
1644 else if (level < 0 || level > Z_BEST_COMPRESSION)
1645 die("bad pack compression level %d", level);
1646 pack_compression_level = level;
1647 pack_compression_seen = 1;
1648 return 0;
1649 }
1650 if (!strcmp(k, "pack.deltacachesize")) {
1651 max_delta_cache_size = git_config_int(k, v);
1652 return 0;
1653 }
1654 if (!strcmp(k, "pack.deltacachelimit")) {
1655 cache_max_small_delta_size = git_config_int(k, v);
1656 return 0;
1657 }
1658 return git_default_config(k, v);
1659 }
1660
1661 static void read_object_list_from_stdin(void)
1662 {
1663 char line[40 + 1 + PATH_MAX + 2];
1664 unsigned char sha1[20];
1665
1666 for (;;) {
1667 if (!fgets(line, sizeof(line), stdin)) {
1668 if (feof(stdin))
1669 break;
1670 if (!ferror(stdin))
1671 die("fgets returned NULL, not EOF, not error!");
1672 if (errno != EINTR)
1673 die("fgets: %s", strerror(errno));
1674 clearerr(stdin);
1675 continue;
1676 }
1677 if (line[0] == '-') {
1678 if (get_sha1_hex(line+1, sha1))
1679 die("expected edge sha1, got garbage:\n %s",
1680 line);
1681 add_preferred_base(sha1);
1682 continue;
1683 }
1684 if (get_sha1_hex(line, sha1))
1685 die("expected sha1, got garbage:\n %s", line);
1686
1687 add_preferred_base_object(line+41);
1688 add_object_entry(sha1, 0, line+41, 0);
1689 }
1690 }
1691
1692 static void show_commit(struct commit *commit)
1693 {
1694 add_object_entry(commit->object.sha1, OBJ_COMMIT, NULL, 0);
1695 }
1696
1697 static void show_object(struct object_array_entry *p)
1698 {
1699 add_preferred_base_object(p->name);
1700 add_object_entry(p->item->sha1, p->item->type, p->name, 0);
1701 }
1702
1703 static void show_edge(struct commit *commit)
1704 {
1705 add_preferred_base(commit->object.sha1);
1706 }
1707
1708 static void get_object_list(int ac, const char **av)
1709 {
1710 struct rev_info revs;
1711 char line[1000];
1712 int flags = 0;
1713
1714 init_revisions(&revs, NULL);
1715 save_commit_buffer = 0;
1716 track_object_refs = 0;
1717 setup_revisions(ac, av, &revs, NULL);
1718
1719 while (fgets(line, sizeof(line), stdin) != NULL) {
1720 int len = strlen(line);
1721 if (line[len - 1] == '\n')
1722 line[--len] = 0;
1723 if (!len)
1724 break;
1725 if (*line == '-') {
1726 if (!strcmp(line, "--not")) {
1727 flags ^= UNINTERESTING;
1728 continue;
1729 }
1730 die("not a rev '%s'", line);
1731 }
1732 if (handle_revision_arg(line, &revs, flags, 1))
1733 die("bad revision '%s'", line);
1734 }
1735
1736 prepare_revision_walk(&revs);
1737 mark_edges_uninteresting(revs.commits, &revs, show_edge);
1738 traverse_commit_list(&revs, show_commit, show_object);
1739 }
1740
1741 static int adjust_perm(const char *path, mode_t mode)
1742 {
1743 if (chmod(path, mode))
1744 return -1;
1745 return adjust_shared_perm(path);
1746 }
1747
1748 int cmd_pack_objects(int argc, const char **argv, const char *prefix)
1749 {
1750 int use_internal_rev_list = 0;
1751 int thin = 0;
1752 uint32_t i;
1753 const char **rp_av;
1754 int rp_ac_alloc = 64;
1755 int rp_ac;
1756
1757 rp_av = xcalloc(rp_ac_alloc, sizeof(*rp_av));
1758
1759 rp_av[0] = "pack-objects";
1760 rp_av[1] = "--objects"; /* --thin will make it --objects-edge */
1761 rp_ac = 2;
1762
1763 git_config(git_pack_config);
1764 if (!pack_compression_seen && core_compression_seen)
1765 pack_compression_level = core_compression_level;
1766
1767 progress = isatty(2);
1768 for (i = 1; i < argc; i++) {
1769 const char *arg = argv[i];
1770
1771 if (*arg != '-')
1772 break;
1773
1774 if (!strcmp("--non-empty", arg)) {
1775 non_empty = 1;
1776 continue;
1777 }
1778 if (!strcmp("--local", arg)) {
1779 local = 1;
1780 continue;
1781 }
1782 if (!strcmp("--incremental", arg)) {
1783 incremental = 1;
1784 continue;
1785 }
1786 if (!prefixcmp(arg, "--compression=")) {
1787 char *end;
1788 int level = strtoul(arg+14, &end, 0);
1789 if (!arg[14] || *end)
1790 usage(pack_usage);
1791 if (level == -1)
1792 level = Z_DEFAULT_COMPRESSION;
1793 else if (level < 0 || level > Z_BEST_COMPRESSION)
1794 die("bad pack compression level %d", level);
1795 pack_compression_level = level;
1796 continue;
1797 }
1798 if (!prefixcmp(arg, "--max-pack-size=")) {
1799 char *end;
1800 pack_size_limit = strtoul(arg+16, &end, 0) * 1024 * 1024;
1801 if (!arg[16] || *end)
1802 usage(pack_usage);
1803 continue;
1804 }
1805 if (!prefixcmp(arg, "--window=")) {
1806 char *end;
1807 window = strtoul(arg+9, &end, 0);
1808 if (!arg[9] || *end)
1809 usage(pack_usage);
1810 continue;
1811 }
1812 if (!prefixcmp(arg, "--depth=")) {
1813 char *end;
1814 depth = strtoul(arg+8, &end, 0);
1815 if (!arg[8] || *end)
1816 usage(pack_usage);
1817 continue;
1818 }
1819 if (!strcmp("--progress", arg)) {
1820 progress = 1;
1821 continue;
1822 }
1823 if (!strcmp("--all-progress", arg)) {
1824 progress = 2;
1825 continue;
1826 }
1827 if (!strcmp("-q", arg)) {
1828 progress = 0;
1829 continue;
1830 }
1831 if (!strcmp("--no-reuse-delta", arg)) {
1832 no_reuse_delta = 1;
1833 continue;
1834 }
1835 if (!strcmp("--no-reuse-object", arg)) {
1836 no_reuse_object = no_reuse_delta = 1;
1837 continue;
1838 }
1839 if (!strcmp("--delta-base-offset", arg)) {
1840 allow_ofs_delta = 1;
1841 continue;
1842 }
1843 if (!strcmp("--stdout", arg)) {
1844 pack_to_stdout = 1;
1845 continue;
1846 }
1847 if (!strcmp("--revs", arg)) {
1848 use_internal_rev_list = 1;
1849 continue;
1850 }
1851 if (!strcmp("--unpacked", arg) ||
1852 !prefixcmp(arg, "--unpacked=") ||
1853 !strcmp("--reflog", arg) ||
1854 !strcmp("--all", arg)) {
1855 use_internal_rev_list = 1;
1856 if (rp_ac >= rp_ac_alloc - 1) {
1857 rp_ac_alloc = alloc_nr(rp_ac_alloc);
1858 rp_av = xrealloc(rp_av,
1859 rp_ac_alloc * sizeof(*rp_av));
1860 }
1861 rp_av[rp_ac++] = arg;
1862 continue;
1863 }
1864 if (!strcmp("--thin", arg)) {
1865 use_internal_rev_list = 1;
1866 thin = 1;
1867 rp_av[1] = "--objects-edge";
1868 continue;
1869 }
1870 if (!prefixcmp(arg, "--index-version=")) {
1871 char *c;
1872 index_default_version = strtoul(arg + 16, &c, 10);
1873 if (index_default_version > 2)
1874 die("bad %s", arg);
1875 if (*c == ',')
1876 index_off32_limit = strtoul(c+1, &c, 0);
1877 if (*c || index_off32_limit & 0x80000000)
1878 die("bad %s", arg);
1879 continue;
1880 }
1881 usage(pack_usage);
1882 }
1883
1884 /* Traditionally "pack-objects [options] base extra" failed;
1885 * we would however want to take refs parameter that would
1886 * have been given to upstream rev-list ourselves, which means
1887 * we somehow want to say what the base name is. So the
1888 * syntax would be:
1889 *
1890 * pack-objects [options] base <refs...>
1891 *
1892 * in other words, we would treat the first non-option as the
1893 * base_name and send everything else to the internal revision
1894 * walker.
1895 */
1896
1897 if (!pack_to_stdout)
1898 base_name = argv[i++];
1899
1900 if (pack_to_stdout != !base_name)
1901 usage(pack_usage);
1902
1903 if (pack_to_stdout && pack_size_limit)
1904 die("--max-pack-size cannot be used to build a pack for transfer.");
1905
1906 if (!pack_to_stdout && thin)
1907 die("--thin cannot be used to build an indexable pack.");
1908
1909 prepare_packed_git();
1910
1911 if (progress)
1912 start_progress(&progress_state, "Generating pack...",
1913 "Counting objects: ", 0);
1914 if (!use_internal_rev_list)
1915 read_object_list_from_stdin();
1916 else {
1917 rp_av[rp_ac] = NULL;
1918 get_object_list(rp_ac, rp_av);
1919 }
1920 if (progress) {
1921 stop_progress(&progress_state);
1922 fprintf(stderr, "Done counting %u objects.\n", nr_objects);
1923 }
1924
1925 if (non_empty && !nr_result)
1926 return 0;
1927 if (progress && (nr_objects != nr_result))
1928 fprintf(stderr, "Result has %u objects.\n", nr_result);
1929 if (nr_result)
1930 prepare_pack(window, depth);
1931 write_pack_file();
1932 if (progress)
1933 fprintf(stderr, "Total %u (delta %u), reused %u (delta %u)\n",
1934 written, written_delta, reused, reused_delta);
1935 return 0;
1936 }