]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/index-pack.c
git-compat-util: move alloc macros to git-compat-util.h
[thirdparty/git.git] / builtin / index-pack.c
1 #include "builtin.h"
2 #include "config.h"
3 #include "delta.h"
4 #include "environment.h"
5 #include "gettext.h"
6 #include "hex.h"
7 #include "pack.h"
8 #include "csum-file.h"
9 #include "blob.h"
10 #include "commit.h"
11 #include "tag.h"
12 #include "tree.h"
13 #include "progress.h"
14 #include "fsck.h"
15 #include "exec-cmd.h"
16 #include "strbuf.h"
17 #include "streaming.h"
18 #include "thread-utils.h"
19 #include "packfile.h"
20 #include "pack-revindex.h"
21 #include "object-file.h"
22 #include "object-store-ll.h"
23 #include "oid-array.h"
24 #include "replace-object.h"
25 #include "promisor-remote.h"
26 #include "setup.h"
27
28 static const char index_pack_usage[] =
29 "git index-pack [-v] [-o <index-file>] [--keep | --keep=<msg>] [--[no-]rev-index] [--verify] [--strict] (<pack-file> | --stdin [--fix-thin] [<pack-file>])";
30
31 struct object_entry {
32 struct pack_idx_entry idx;
33 unsigned long size;
34 unsigned char hdr_size;
35 signed char type;
36 signed char real_type;
37 };
38
39 struct object_stat {
40 unsigned delta_depth;
41 int base_object_no;
42 };
43
44 struct base_data {
45 /* Initialized by make_base(). */
46 struct base_data *base;
47 struct object_entry *obj;
48 int ref_first, ref_last;
49 int ofs_first, ofs_last;
50 /*
51 * Threads should increment retain_data if they are about to call
52 * patch_delta() using this struct's data as a base, and decrement this
53 * when they are done. While retain_data is nonzero, this struct's data
54 * will not be freed even if the delta base cache limit is exceeded.
55 */
56 int retain_data;
57 /*
58 * The number of direct children that have not been fully processed
59 * (entered work_head, entered done_head, left done_head). When this
60 * number reaches zero, this struct base_data can be freed.
61 */
62 int children_remaining;
63
64 /* Not initialized by make_base(). */
65 struct list_head list;
66 void *data;
67 unsigned long size;
68 };
69
70 /*
71 * Stack of struct base_data that have unprocessed children.
72 * threaded_second_pass() uses this as a source of work (the other being the
73 * objects array).
74 *
75 * Guarded by work_mutex.
76 */
77 static LIST_HEAD(work_head);
78
79 /*
80 * Stack of struct base_data that have children, all of whom have been
81 * processed or are being processed, and at least one child is being processed.
82 * These struct base_data must be kept around until the last child is
83 * processed.
84 *
85 * Guarded by work_mutex.
86 */
87 static LIST_HEAD(done_head);
88
89 /*
90 * All threads share one delta base cache.
91 *
92 * base_cache_used is guarded by work_mutex, and base_cache_limit is read-only
93 * in a thread.
94 */
95 static size_t base_cache_used;
96 static size_t base_cache_limit;
97
98 struct thread_local {
99 pthread_t thread;
100 int pack_fd;
101 };
102
103 /* Remember to update object flag allocation in object.h */
104 #define FLAG_LINK (1u<<20)
105 #define FLAG_CHECKED (1u<<21)
106
107 struct ofs_delta_entry {
108 off_t offset;
109 int obj_no;
110 };
111
112 struct ref_delta_entry {
113 struct object_id oid;
114 int obj_no;
115 };
116
117 static struct object_entry *objects;
118 static struct object_stat *obj_stat;
119 static struct ofs_delta_entry *ofs_deltas;
120 static struct ref_delta_entry *ref_deltas;
121 static struct thread_local nothread_data;
122 static int nr_objects;
123 static int nr_ofs_deltas;
124 static int nr_ref_deltas;
125 static int ref_deltas_alloc;
126 static int nr_resolved_deltas;
127 static int nr_threads;
128
129 static int from_stdin;
130 static int strict;
131 static int do_fsck_object;
132 static struct fsck_options fsck_options = FSCK_OPTIONS_MISSING_GITMODULES;
133 static int verbose;
134 static const char *progress_title;
135 static int show_resolving_progress;
136 static int show_stat;
137 static int check_self_contained_and_connected;
138
139 static struct progress *progress;
140
141 /* We always read in 4kB chunks. */
142 static unsigned char input_buffer[4096];
143 static unsigned int input_offset, input_len;
144 static off_t consumed_bytes;
145 static off_t max_input_size;
146 static unsigned deepest_delta;
147 static git_hash_ctx input_ctx;
148 static uint32_t input_crc32;
149 static int input_fd, output_fd;
150 static const char *curr_pack;
151
152 static struct thread_local *thread_data;
153 static int nr_dispatched;
154 static int threads_active;
155
156 static pthread_mutex_t read_mutex;
157 #define read_lock() lock_mutex(&read_mutex)
158 #define read_unlock() unlock_mutex(&read_mutex)
159
160 static pthread_mutex_t counter_mutex;
161 #define counter_lock() lock_mutex(&counter_mutex)
162 #define counter_unlock() unlock_mutex(&counter_mutex)
163
164 static pthread_mutex_t work_mutex;
165 #define work_lock() lock_mutex(&work_mutex)
166 #define work_unlock() unlock_mutex(&work_mutex)
167
168 static pthread_mutex_t deepest_delta_mutex;
169 #define deepest_delta_lock() lock_mutex(&deepest_delta_mutex)
170 #define deepest_delta_unlock() unlock_mutex(&deepest_delta_mutex)
171
172 static pthread_key_t key;
173
174 static inline void lock_mutex(pthread_mutex_t *mutex)
175 {
176 if (threads_active)
177 pthread_mutex_lock(mutex);
178 }
179
180 static inline void unlock_mutex(pthread_mutex_t *mutex)
181 {
182 if (threads_active)
183 pthread_mutex_unlock(mutex);
184 }
185
186 /*
187 * Mutex and conditional variable can't be statically-initialized on Windows.
188 */
189 static void init_thread(void)
190 {
191 int i;
192 init_recursive_mutex(&read_mutex);
193 pthread_mutex_init(&counter_mutex, NULL);
194 pthread_mutex_init(&work_mutex, NULL);
195 if (show_stat)
196 pthread_mutex_init(&deepest_delta_mutex, NULL);
197 pthread_key_create(&key, NULL);
198 CALLOC_ARRAY(thread_data, nr_threads);
199 for (i = 0; i < nr_threads; i++) {
200 thread_data[i].pack_fd = xopen(curr_pack, O_RDONLY);
201 }
202
203 threads_active = 1;
204 }
205
206 static void cleanup_thread(void)
207 {
208 int i;
209 if (!threads_active)
210 return;
211 threads_active = 0;
212 pthread_mutex_destroy(&read_mutex);
213 pthread_mutex_destroy(&counter_mutex);
214 pthread_mutex_destroy(&work_mutex);
215 if (show_stat)
216 pthread_mutex_destroy(&deepest_delta_mutex);
217 for (i = 0; i < nr_threads; i++)
218 close(thread_data[i].pack_fd);
219 pthread_key_delete(key);
220 free(thread_data);
221 }
222
223 static int mark_link(struct object *obj, enum object_type type,
224 void *data, struct fsck_options *options)
225 {
226 if (!obj)
227 return -1;
228
229 if (type != OBJ_ANY && obj->type != type)
230 die(_("object type mismatch at %s"), oid_to_hex(&obj->oid));
231
232 obj->flags |= FLAG_LINK;
233 return 0;
234 }
235
236 /* The content of each linked object must have been checked
237 or it must be already present in the object database */
238 static unsigned check_object(struct object *obj)
239 {
240 if (!obj)
241 return 0;
242
243 if (!(obj->flags & FLAG_LINK))
244 return 0;
245
246 if (!(obj->flags & FLAG_CHECKED)) {
247 unsigned long size;
248 int type = oid_object_info(the_repository, &obj->oid, &size);
249 if (type <= 0)
250 die(_("did not receive expected object %s"),
251 oid_to_hex(&obj->oid));
252 if (type != obj->type)
253 die(_("object %s: expected type %s, found %s"),
254 oid_to_hex(&obj->oid),
255 type_name(obj->type), type_name(type));
256 obj->flags |= FLAG_CHECKED;
257 return 1;
258 }
259
260 return 0;
261 }
262
263 static unsigned check_objects(void)
264 {
265 unsigned i, max, foreign_nr = 0;
266
267 max = get_max_object_index();
268
269 if (verbose)
270 progress = start_delayed_progress(_("Checking objects"), max);
271
272 for (i = 0; i < max; i++) {
273 foreign_nr += check_object(get_indexed_object(i));
274 display_progress(progress, i + 1);
275 }
276
277 stop_progress(&progress);
278 return foreign_nr;
279 }
280
281
282 /* Discard current buffer used content. */
283 static void flush(void)
284 {
285 if (input_offset) {
286 if (output_fd >= 0)
287 write_or_die(output_fd, input_buffer, input_offset);
288 the_hash_algo->update_fn(&input_ctx, input_buffer, input_offset);
289 memmove(input_buffer, input_buffer + input_offset, input_len);
290 input_offset = 0;
291 }
292 }
293
294 /*
295 * Make sure at least "min" bytes are available in the buffer, and
296 * return the pointer to the buffer.
297 */
298 static void *fill(int min)
299 {
300 if (min <= input_len)
301 return input_buffer + input_offset;
302 if (min > sizeof(input_buffer))
303 die(Q_("cannot fill %d byte",
304 "cannot fill %d bytes",
305 min),
306 min);
307 flush();
308 do {
309 ssize_t ret = xread(input_fd, input_buffer + input_len,
310 sizeof(input_buffer) - input_len);
311 if (ret <= 0) {
312 if (!ret)
313 die(_("early EOF"));
314 die_errno(_("read error on input"));
315 }
316 input_len += ret;
317 if (from_stdin)
318 display_throughput(progress, consumed_bytes + input_len);
319 } while (input_len < min);
320 return input_buffer;
321 }
322
323 static void use(int bytes)
324 {
325 if (bytes > input_len)
326 die(_("used more bytes than were available"));
327 input_crc32 = crc32(input_crc32, input_buffer + input_offset, bytes);
328 input_len -= bytes;
329 input_offset += bytes;
330
331 /* make sure off_t is sufficiently large not to wrap */
332 if (signed_add_overflows(consumed_bytes, bytes))
333 die(_("pack too large for current definition of off_t"));
334 consumed_bytes += bytes;
335 if (max_input_size && consumed_bytes > max_input_size) {
336 struct strbuf size_limit = STRBUF_INIT;
337 strbuf_humanise_bytes(&size_limit, max_input_size);
338 die(_("pack exceeds maximum allowed size (%s)"),
339 size_limit.buf);
340 }
341 }
342
343 static const char *open_pack_file(const char *pack_name)
344 {
345 if (from_stdin) {
346 input_fd = 0;
347 if (!pack_name) {
348 struct strbuf tmp_file = STRBUF_INIT;
349 output_fd = odb_mkstemp(&tmp_file,
350 "pack/tmp_pack_XXXXXX");
351 pack_name = strbuf_detach(&tmp_file, NULL);
352 } else {
353 output_fd = xopen(pack_name, O_CREAT|O_EXCL|O_RDWR, 0600);
354 }
355 nothread_data.pack_fd = output_fd;
356 } else {
357 input_fd = xopen(pack_name, O_RDONLY);
358 output_fd = -1;
359 nothread_data.pack_fd = input_fd;
360 }
361 the_hash_algo->init_fn(&input_ctx);
362 return pack_name;
363 }
364
365 static void parse_pack_header(void)
366 {
367 struct pack_header *hdr = fill(sizeof(struct pack_header));
368
369 /* Header consistency check */
370 if (hdr->hdr_signature != htonl(PACK_SIGNATURE))
371 die(_("pack signature mismatch"));
372 if (!pack_version_ok(hdr->hdr_version))
373 die(_("pack version %"PRIu32" unsupported"),
374 ntohl(hdr->hdr_version));
375
376 nr_objects = ntohl(hdr->hdr_entries);
377 use(sizeof(struct pack_header));
378 }
379
380 __attribute__((format (printf, 2, 3)))
381 static NORETURN void bad_object(off_t offset, const char *format, ...)
382 {
383 va_list params;
384 char buf[1024];
385
386 va_start(params, format);
387 vsnprintf(buf, sizeof(buf), format, params);
388 va_end(params);
389 die(_("pack has bad object at offset %"PRIuMAX": %s"),
390 (uintmax_t)offset, buf);
391 }
392
393 static inline struct thread_local *get_thread_data(void)
394 {
395 if (HAVE_THREADS) {
396 if (threads_active)
397 return pthread_getspecific(key);
398 assert(!threads_active &&
399 "This should only be reached when all threads are gone");
400 }
401 return &nothread_data;
402 }
403
404 static void set_thread_data(struct thread_local *data)
405 {
406 if (threads_active)
407 pthread_setspecific(key, data);
408 }
409
410 static void free_base_data(struct base_data *c)
411 {
412 if (c->data) {
413 FREE_AND_NULL(c->data);
414 base_cache_used -= c->size;
415 }
416 }
417
418 static void prune_base_data(struct base_data *retain)
419 {
420 struct list_head *pos;
421
422 if (base_cache_used <= base_cache_limit)
423 return;
424
425 list_for_each_prev(pos, &done_head) {
426 struct base_data *b = list_entry(pos, struct base_data, list);
427 if (b->retain_data || b == retain)
428 continue;
429 if (b->data) {
430 free_base_data(b);
431 if (base_cache_used <= base_cache_limit)
432 return;
433 }
434 }
435
436 list_for_each_prev(pos, &work_head) {
437 struct base_data *b = list_entry(pos, struct base_data, list);
438 if (b->retain_data || b == retain)
439 continue;
440 if (b->data) {
441 free_base_data(b);
442 if (base_cache_used <= base_cache_limit)
443 return;
444 }
445 }
446 }
447
448 static int is_delta_type(enum object_type type)
449 {
450 return (type == OBJ_REF_DELTA || type == OBJ_OFS_DELTA);
451 }
452
453 static void *unpack_entry_data(off_t offset, unsigned long size,
454 enum object_type type, struct object_id *oid)
455 {
456 static char fixed_buf[8192];
457 int status;
458 git_zstream stream;
459 void *buf;
460 git_hash_ctx c;
461 char hdr[32];
462 int hdrlen;
463
464 if (!is_delta_type(type)) {
465 hdrlen = format_object_header(hdr, sizeof(hdr), type, size);
466 the_hash_algo->init_fn(&c);
467 the_hash_algo->update_fn(&c, hdr, hdrlen);
468 } else
469 oid = NULL;
470 if (type == OBJ_BLOB && size > big_file_threshold)
471 buf = fixed_buf;
472 else
473 buf = xmallocz(size);
474
475 memset(&stream, 0, sizeof(stream));
476 git_inflate_init(&stream);
477 stream.next_out = buf;
478 stream.avail_out = buf == fixed_buf ? sizeof(fixed_buf) : size;
479
480 do {
481 unsigned char *last_out = stream.next_out;
482 stream.next_in = fill(1);
483 stream.avail_in = input_len;
484 status = git_inflate(&stream, 0);
485 use(input_len - stream.avail_in);
486 if (oid)
487 the_hash_algo->update_fn(&c, last_out, stream.next_out - last_out);
488 if (buf == fixed_buf) {
489 stream.next_out = buf;
490 stream.avail_out = sizeof(fixed_buf);
491 }
492 } while (status == Z_OK);
493 if (stream.total_out != size || status != Z_STREAM_END)
494 bad_object(offset, _("inflate returned %d"), status);
495 git_inflate_end(&stream);
496 if (oid)
497 the_hash_algo->final_oid_fn(oid, &c);
498 return buf == fixed_buf ? NULL : buf;
499 }
500
501 static void *unpack_raw_entry(struct object_entry *obj,
502 off_t *ofs_offset,
503 struct object_id *ref_oid,
504 struct object_id *oid)
505 {
506 unsigned char *p;
507 unsigned long size, c;
508 off_t base_offset;
509 unsigned shift;
510 void *data;
511
512 obj->idx.offset = consumed_bytes;
513 input_crc32 = crc32(0, NULL, 0);
514
515 p = fill(1);
516 c = *p;
517 use(1);
518 obj->type = (c >> 4) & 7;
519 size = (c & 15);
520 shift = 4;
521 while (c & 0x80) {
522 p = fill(1);
523 c = *p;
524 use(1);
525 size += (c & 0x7f) << shift;
526 shift += 7;
527 }
528 obj->size = size;
529
530 switch (obj->type) {
531 case OBJ_REF_DELTA:
532 oidread(ref_oid, fill(the_hash_algo->rawsz));
533 use(the_hash_algo->rawsz);
534 break;
535 case OBJ_OFS_DELTA:
536 p = fill(1);
537 c = *p;
538 use(1);
539 base_offset = c & 127;
540 while (c & 128) {
541 base_offset += 1;
542 if (!base_offset || MSB(base_offset, 7))
543 bad_object(obj->idx.offset, _("offset value overflow for delta base object"));
544 p = fill(1);
545 c = *p;
546 use(1);
547 base_offset = (base_offset << 7) + (c & 127);
548 }
549 *ofs_offset = obj->idx.offset - base_offset;
550 if (*ofs_offset <= 0 || *ofs_offset >= obj->idx.offset)
551 bad_object(obj->idx.offset, _("delta base offset is out of bound"));
552 break;
553 case OBJ_COMMIT:
554 case OBJ_TREE:
555 case OBJ_BLOB:
556 case OBJ_TAG:
557 break;
558 default:
559 bad_object(obj->idx.offset, _("unknown object type %d"), obj->type);
560 }
561 obj->hdr_size = consumed_bytes - obj->idx.offset;
562
563 data = unpack_entry_data(obj->idx.offset, obj->size, obj->type, oid);
564 obj->idx.crc32 = input_crc32;
565 return data;
566 }
567
568 static void *unpack_data(struct object_entry *obj,
569 int (*consume)(const unsigned char *, unsigned long, void *),
570 void *cb_data)
571 {
572 off_t from = obj[0].idx.offset + obj[0].hdr_size;
573 off_t len = obj[1].idx.offset - from;
574 unsigned char *data, *inbuf;
575 git_zstream stream;
576 int status;
577
578 data = xmallocz(consume ? 64*1024 : obj->size);
579 inbuf = xmalloc((len < 64*1024) ? (int)len : 64*1024);
580
581 memset(&stream, 0, sizeof(stream));
582 git_inflate_init(&stream);
583 stream.next_out = data;
584 stream.avail_out = consume ? 64*1024 : obj->size;
585
586 do {
587 ssize_t n = (len < 64*1024) ? (ssize_t)len : 64*1024;
588 n = xpread(get_thread_data()->pack_fd, inbuf, n, from);
589 if (n < 0)
590 die_errno(_("cannot pread pack file"));
591 if (!n)
592 die(Q_("premature end of pack file, %"PRIuMAX" byte missing",
593 "premature end of pack file, %"PRIuMAX" bytes missing",
594 len),
595 (uintmax_t)len);
596 from += n;
597 len -= n;
598 stream.next_in = inbuf;
599 stream.avail_in = n;
600 if (!consume)
601 status = git_inflate(&stream, 0);
602 else {
603 do {
604 status = git_inflate(&stream, 0);
605 if (consume(data, stream.next_out - data, cb_data)) {
606 free(inbuf);
607 free(data);
608 return NULL;
609 }
610 stream.next_out = data;
611 stream.avail_out = 64*1024;
612 } while (status == Z_OK && stream.avail_in);
613 }
614 } while (len && status == Z_OK && !stream.avail_in);
615
616 /* This has been inflated OK when first encountered, so... */
617 if (status != Z_STREAM_END || stream.total_out != obj->size)
618 die(_("serious inflate inconsistency"));
619
620 git_inflate_end(&stream);
621 free(inbuf);
622 if (consume) {
623 FREE_AND_NULL(data);
624 }
625 return data;
626 }
627
628 static void *get_data_from_pack(struct object_entry *obj)
629 {
630 return unpack_data(obj, NULL, NULL);
631 }
632
633 static int compare_ofs_delta_bases(off_t offset1, off_t offset2,
634 enum object_type type1,
635 enum object_type type2)
636 {
637 int cmp = type1 - type2;
638 if (cmp)
639 return cmp;
640 return offset1 < offset2 ? -1 :
641 offset1 > offset2 ? 1 :
642 0;
643 }
644
645 static int find_ofs_delta(const off_t offset)
646 {
647 int first = 0, last = nr_ofs_deltas;
648
649 while (first < last) {
650 int next = first + (last - first) / 2;
651 struct ofs_delta_entry *delta = &ofs_deltas[next];
652 int cmp;
653
654 cmp = compare_ofs_delta_bases(offset, delta->offset,
655 OBJ_OFS_DELTA,
656 objects[delta->obj_no].type);
657 if (!cmp)
658 return next;
659 if (cmp < 0) {
660 last = next;
661 continue;
662 }
663 first = next+1;
664 }
665 return -first-1;
666 }
667
668 static void find_ofs_delta_children(off_t offset,
669 int *first_index, int *last_index)
670 {
671 int first = find_ofs_delta(offset);
672 int last = first;
673 int end = nr_ofs_deltas - 1;
674
675 if (first < 0) {
676 *first_index = 0;
677 *last_index = -1;
678 return;
679 }
680 while (first > 0 && ofs_deltas[first - 1].offset == offset)
681 --first;
682 while (last < end && ofs_deltas[last + 1].offset == offset)
683 ++last;
684 *first_index = first;
685 *last_index = last;
686 }
687
688 static int compare_ref_delta_bases(const struct object_id *oid1,
689 const struct object_id *oid2,
690 enum object_type type1,
691 enum object_type type2)
692 {
693 int cmp = type1 - type2;
694 if (cmp)
695 return cmp;
696 return oidcmp(oid1, oid2);
697 }
698
699 static int find_ref_delta(const struct object_id *oid)
700 {
701 int first = 0, last = nr_ref_deltas;
702
703 while (first < last) {
704 int next = first + (last - first) / 2;
705 struct ref_delta_entry *delta = &ref_deltas[next];
706 int cmp;
707
708 cmp = compare_ref_delta_bases(oid, &delta->oid,
709 OBJ_REF_DELTA,
710 objects[delta->obj_no].type);
711 if (!cmp)
712 return next;
713 if (cmp < 0) {
714 last = next;
715 continue;
716 }
717 first = next+1;
718 }
719 return -first-1;
720 }
721
722 static void find_ref_delta_children(const struct object_id *oid,
723 int *first_index, int *last_index)
724 {
725 int first = find_ref_delta(oid);
726 int last = first;
727 int end = nr_ref_deltas - 1;
728
729 if (first < 0) {
730 *first_index = 0;
731 *last_index = -1;
732 return;
733 }
734 while (first > 0 && oideq(&ref_deltas[first - 1].oid, oid))
735 --first;
736 while (last < end && oideq(&ref_deltas[last + 1].oid, oid))
737 ++last;
738 *first_index = first;
739 *last_index = last;
740 }
741
742 struct compare_data {
743 struct object_entry *entry;
744 struct git_istream *st;
745 unsigned char *buf;
746 unsigned long buf_size;
747 };
748
749 static int compare_objects(const unsigned char *buf, unsigned long size,
750 void *cb_data)
751 {
752 struct compare_data *data = cb_data;
753
754 if (data->buf_size < size) {
755 free(data->buf);
756 data->buf = xmalloc(size);
757 data->buf_size = size;
758 }
759
760 while (size) {
761 ssize_t len = read_istream(data->st, data->buf, size);
762 if (len == 0)
763 die(_("SHA1 COLLISION FOUND WITH %s !"),
764 oid_to_hex(&data->entry->idx.oid));
765 if (len < 0)
766 die(_("unable to read %s"),
767 oid_to_hex(&data->entry->idx.oid));
768 if (memcmp(buf, data->buf, len))
769 die(_("SHA1 COLLISION FOUND WITH %s !"),
770 oid_to_hex(&data->entry->idx.oid));
771 size -= len;
772 buf += len;
773 }
774 return 0;
775 }
776
777 static int check_collison(struct object_entry *entry)
778 {
779 struct compare_data data;
780 enum object_type type;
781 unsigned long size;
782
783 if (entry->size <= big_file_threshold || entry->type != OBJ_BLOB)
784 return -1;
785
786 memset(&data, 0, sizeof(data));
787 data.entry = entry;
788 data.st = open_istream(the_repository, &entry->idx.oid, &type, &size,
789 NULL);
790 if (!data.st)
791 return -1;
792 if (size != entry->size || type != entry->type)
793 die(_("SHA1 COLLISION FOUND WITH %s !"),
794 oid_to_hex(&entry->idx.oid));
795 unpack_data(entry, compare_objects, &data);
796 close_istream(data.st);
797 free(data.buf);
798 return 0;
799 }
800
801 static void sha1_object(const void *data, struct object_entry *obj_entry,
802 unsigned long size, enum object_type type,
803 const struct object_id *oid)
804 {
805 void *new_data = NULL;
806 int collision_test_needed = 0;
807
808 assert(data || obj_entry);
809
810 if (startup_info->have_repository) {
811 read_lock();
812 collision_test_needed =
813 repo_has_object_file_with_flags(the_repository, oid,
814 OBJECT_INFO_QUICK);
815 read_unlock();
816 }
817
818 if (collision_test_needed && !data) {
819 read_lock();
820 if (!check_collison(obj_entry))
821 collision_test_needed = 0;
822 read_unlock();
823 }
824 if (collision_test_needed) {
825 void *has_data;
826 enum object_type has_type;
827 unsigned long has_size;
828 read_lock();
829 has_type = oid_object_info(the_repository, oid, &has_size);
830 if (has_type < 0)
831 die(_("cannot read existing object info %s"), oid_to_hex(oid));
832 if (has_type != type || has_size != size)
833 die(_("SHA1 COLLISION FOUND WITH %s !"), oid_to_hex(oid));
834 has_data = repo_read_object_file(the_repository, oid,
835 &has_type, &has_size);
836 read_unlock();
837 if (!data)
838 data = new_data = get_data_from_pack(obj_entry);
839 if (!has_data)
840 die(_("cannot read existing object %s"), oid_to_hex(oid));
841 if (size != has_size || type != has_type ||
842 memcmp(data, has_data, size) != 0)
843 die(_("SHA1 COLLISION FOUND WITH %s !"), oid_to_hex(oid));
844 free(has_data);
845 }
846
847 if (strict || do_fsck_object) {
848 read_lock();
849 if (type == OBJ_BLOB) {
850 struct blob *blob = lookup_blob(the_repository, oid);
851 if (blob)
852 blob->object.flags |= FLAG_CHECKED;
853 else
854 die(_("invalid blob object %s"), oid_to_hex(oid));
855 if (do_fsck_object &&
856 fsck_object(&blob->object, (void *)data, size, &fsck_options))
857 die(_("fsck error in packed object"));
858 } else {
859 struct object *obj;
860 int eaten;
861 void *buf = (void *) data;
862
863 assert(data && "data can only be NULL for large _blobs_");
864
865 /*
866 * we do not need to free the memory here, as the
867 * buf is deleted by the caller.
868 */
869 obj = parse_object_buffer(the_repository, oid, type,
870 size, buf,
871 &eaten);
872 if (!obj)
873 die(_("invalid %s"), type_name(type));
874 if (do_fsck_object &&
875 fsck_object(obj, buf, size, &fsck_options))
876 die(_("fsck error in packed object"));
877 if (strict && fsck_walk(obj, NULL, &fsck_options))
878 die(_("Not all child objects of %s are reachable"), oid_to_hex(&obj->oid));
879
880 if (obj->type == OBJ_TREE) {
881 struct tree *item = (struct tree *) obj;
882 item->buffer = NULL;
883 obj->parsed = 0;
884 }
885 if (obj->type == OBJ_COMMIT) {
886 struct commit *commit = (struct commit *) obj;
887 if (detach_commit_buffer(commit, NULL) != data)
888 BUG("parse_object_buffer transmogrified our buffer");
889 }
890 obj->flags |= FLAG_CHECKED;
891 }
892 read_unlock();
893 }
894
895 free(new_data);
896 }
897
898 /*
899 * Ensure that this node has been reconstructed and return its contents.
900 *
901 * In the typical and best case, this node would already be reconstructed
902 * (through the invocation to resolve_delta() in threaded_second_pass()) and it
903 * would not be pruned. However, if pruning of this node was necessary due to
904 * reaching delta_base_cache_limit, this function will find the closest
905 * ancestor with reconstructed data that has not been pruned (or if there is
906 * none, the ultimate base object), and reconstruct each node in the delta
907 * chain in order to generate the reconstructed data for this node.
908 */
909 static void *get_base_data(struct base_data *c)
910 {
911 if (!c->data) {
912 struct object_entry *obj = c->obj;
913 struct base_data **delta = NULL;
914 int delta_nr = 0, delta_alloc = 0;
915
916 while (is_delta_type(c->obj->type) && !c->data) {
917 ALLOC_GROW(delta, delta_nr + 1, delta_alloc);
918 delta[delta_nr++] = c;
919 c = c->base;
920 }
921 if (!delta_nr) {
922 c->data = get_data_from_pack(obj);
923 c->size = obj->size;
924 base_cache_used += c->size;
925 prune_base_data(c);
926 }
927 for (; delta_nr > 0; delta_nr--) {
928 void *base, *raw;
929 c = delta[delta_nr - 1];
930 obj = c->obj;
931 base = get_base_data(c->base);
932 raw = get_data_from_pack(obj);
933 c->data = patch_delta(
934 base, c->base->size,
935 raw, obj->size,
936 &c->size);
937 free(raw);
938 if (!c->data)
939 bad_object(obj->idx.offset, _("failed to apply delta"));
940 base_cache_used += c->size;
941 prune_base_data(c);
942 }
943 free(delta);
944 }
945 return c->data;
946 }
947
948 static struct base_data *make_base(struct object_entry *obj,
949 struct base_data *parent)
950 {
951 struct base_data *base = xcalloc(1, sizeof(struct base_data));
952 base->base = parent;
953 base->obj = obj;
954 find_ref_delta_children(&obj->idx.oid,
955 &base->ref_first, &base->ref_last);
956 find_ofs_delta_children(obj->idx.offset,
957 &base->ofs_first, &base->ofs_last);
958 base->children_remaining = base->ref_last - base->ref_first +
959 base->ofs_last - base->ofs_first + 2;
960 return base;
961 }
962
963 static struct base_data *resolve_delta(struct object_entry *delta_obj,
964 struct base_data *base)
965 {
966 void *delta_data, *result_data;
967 struct base_data *result;
968 unsigned long result_size;
969
970 if (show_stat) {
971 int i = delta_obj - objects;
972 int j = base->obj - objects;
973 obj_stat[i].delta_depth = obj_stat[j].delta_depth + 1;
974 deepest_delta_lock();
975 if (deepest_delta < obj_stat[i].delta_depth)
976 deepest_delta = obj_stat[i].delta_depth;
977 deepest_delta_unlock();
978 obj_stat[i].base_object_no = j;
979 }
980 delta_data = get_data_from_pack(delta_obj);
981 assert(base->data);
982 result_data = patch_delta(base->data, base->size,
983 delta_data, delta_obj->size, &result_size);
984 free(delta_data);
985 if (!result_data)
986 bad_object(delta_obj->idx.offset, _("failed to apply delta"));
987 hash_object_file(the_hash_algo, result_data, result_size,
988 delta_obj->real_type, &delta_obj->idx.oid);
989 sha1_object(result_data, NULL, result_size, delta_obj->real_type,
990 &delta_obj->idx.oid);
991
992 result = make_base(delta_obj, base);
993 result->data = result_data;
994 result->size = result_size;
995
996 counter_lock();
997 nr_resolved_deltas++;
998 counter_unlock();
999
1000 return result;
1001 }
1002
1003 static int compare_ofs_delta_entry(const void *a, const void *b)
1004 {
1005 const struct ofs_delta_entry *delta_a = a;
1006 const struct ofs_delta_entry *delta_b = b;
1007
1008 return delta_a->offset < delta_b->offset ? -1 :
1009 delta_a->offset > delta_b->offset ? 1 :
1010 0;
1011 }
1012
1013 static int compare_ref_delta_entry(const void *a, const void *b)
1014 {
1015 const struct ref_delta_entry *delta_a = a;
1016 const struct ref_delta_entry *delta_b = b;
1017
1018 return oidcmp(&delta_a->oid, &delta_b->oid);
1019 }
1020
1021 static void *threaded_second_pass(void *data)
1022 {
1023 if (data)
1024 set_thread_data(data);
1025 for (;;) {
1026 struct base_data *parent = NULL;
1027 struct object_entry *child_obj;
1028 struct base_data *child;
1029
1030 counter_lock();
1031 display_progress(progress, nr_resolved_deltas);
1032 counter_unlock();
1033
1034 work_lock();
1035 if (list_empty(&work_head)) {
1036 /*
1037 * Take an object from the object array.
1038 */
1039 while (nr_dispatched < nr_objects &&
1040 is_delta_type(objects[nr_dispatched].type))
1041 nr_dispatched++;
1042 if (nr_dispatched >= nr_objects) {
1043 work_unlock();
1044 break;
1045 }
1046 child_obj = &objects[nr_dispatched++];
1047 } else {
1048 /*
1049 * Peek at the top of the stack, and take a child from
1050 * it.
1051 */
1052 parent = list_first_entry(&work_head, struct base_data,
1053 list);
1054
1055 if (parent->ref_first <= parent->ref_last) {
1056 int offset = ref_deltas[parent->ref_first++].obj_no;
1057 child_obj = objects + offset;
1058 if (child_obj->real_type != OBJ_REF_DELTA)
1059 die("REF_DELTA at offset %"PRIuMAX" already resolved (duplicate base %s?)",
1060 (uintmax_t) child_obj->idx.offset,
1061 oid_to_hex(&parent->obj->idx.oid));
1062 child_obj->real_type = parent->obj->real_type;
1063 } else {
1064 child_obj = objects +
1065 ofs_deltas[parent->ofs_first++].obj_no;
1066 assert(child_obj->real_type == OBJ_OFS_DELTA);
1067 child_obj->real_type = parent->obj->real_type;
1068 }
1069
1070 if (parent->ref_first > parent->ref_last &&
1071 parent->ofs_first > parent->ofs_last) {
1072 /*
1073 * This parent has run out of children, so move
1074 * it to done_head.
1075 */
1076 list_del(&parent->list);
1077 list_add(&parent->list, &done_head);
1078 }
1079
1080 /*
1081 * Ensure that the parent has data, since we will need
1082 * it later.
1083 *
1084 * NEEDSWORK: If parent data needs to be reloaded, this
1085 * prolongs the time that the current thread spends in
1086 * the mutex. A mitigating factor is that parent data
1087 * needs to be reloaded only if the delta base cache
1088 * limit is exceeded, so in the typical case, this does
1089 * not happen.
1090 */
1091 get_base_data(parent);
1092 parent->retain_data++;
1093 }
1094 work_unlock();
1095
1096 if (parent) {
1097 child = resolve_delta(child_obj, parent);
1098 if (!child->children_remaining)
1099 FREE_AND_NULL(child->data);
1100 } else {
1101 child = make_base(child_obj, NULL);
1102 if (child->children_remaining) {
1103 /*
1104 * Since this child has its own delta children,
1105 * we will need this data in the future.
1106 * Inflate now so that future iterations will
1107 * have access to this object's data while
1108 * outside the work mutex.
1109 */
1110 child->data = get_data_from_pack(child_obj);
1111 child->size = child_obj->size;
1112 }
1113 }
1114
1115 work_lock();
1116 if (parent)
1117 parent->retain_data--;
1118 if (child->data) {
1119 /*
1120 * This child has its own children, so add it to
1121 * work_head.
1122 */
1123 list_add(&child->list, &work_head);
1124 base_cache_used += child->size;
1125 prune_base_data(NULL);
1126 free_base_data(child);
1127 } else {
1128 /*
1129 * This child does not have its own children. It may be
1130 * the last descendant of its ancestors; free those
1131 * that we can.
1132 */
1133 struct base_data *p = parent;
1134
1135 while (p) {
1136 struct base_data *next_p;
1137
1138 p->children_remaining--;
1139 if (p->children_remaining)
1140 break;
1141
1142 next_p = p->base;
1143 free_base_data(p);
1144 list_del(&p->list);
1145 free(p);
1146
1147 p = next_p;
1148 }
1149 FREE_AND_NULL(child);
1150 }
1151 work_unlock();
1152 }
1153 return NULL;
1154 }
1155
1156 /*
1157 * First pass:
1158 * - find locations of all objects;
1159 * - calculate SHA1 of all non-delta objects;
1160 * - remember base (SHA1 or offset) for all deltas.
1161 */
1162 static void parse_pack_objects(unsigned char *hash)
1163 {
1164 int i, nr_delays = 0;
1165 struct ofs_delta_entry *ofs_delta = ofs_deltas;
1166 struct object_id ref_delta_oid;
1167 struct stat st;
1168
1169 if (verbose)
1170 progress = start_progress(
1171 progress_title ? progress_title :
1172 from_stdin ? _("Receiving objects") : _("Indexing objects"),
1173 nr_objects);
1174 for (i = 0; i < nr_objects; i++) {
1175 struct object_entry *obj = &objects[i];
1176 void *data = unpack_raw_entry(obj, &ofs_delta->offset,
1177 &ref_delta_oid,
1178 &obj->idx.oid);
1179 obj->real_type = obj->type;
1180 if (obj->type == OBJ_OFS_DELTA) {
1181 nr_ofs_deltas++;
1182 ofs_delta->obj_no = i;
1183 ofs_delta++;
1184 } else if (obj->type == OBJ_REF_DELTA) {
1185 ALLOC_GROW(ref_deltas, nr_ref_deltas + 1, ref_deltas_alloc);
1186 oidcpy(&ref_deltas[nr_ref_deltas].oid, &ref_delta_oid);
1187 ref_deltas[nr_ref_deltas].obj_no = i;
1188 nr_ref_deltas++;
1189 } else if (!data) {
1190 /* large blobs, check later */
1191 obj->real_type = OBJ_BAD;
1192 nr_delays++;
1193 } else
1194 sha1_object(data, NULL, obj->size, obj->type,
1195 &obj->idx.oid);
1196 free(data);
1197 display_progress(progress, i+1);
1198 }
1199 objects[i].idx.offset = consumed_bytes;
1200 stop_progress(&progress);
1201
1202 /* Check pack integrity */
1203 flush();
1204 the_hash_algo->final_fn(hash, &input_ctx);
1205 if (!hasheq(fill(the_hash_algo->rawsz), hash))
1206 die(_("pack is corrupted (SHA1 mismatch)"));
1207 use(the_hash_algo->rawsz);
1208
1209 /* If input_fd is a file, we should have reached its end now. */
1210 if (fstat(input_fd, &st))
1211 die_errno(_("cannot fstat packfile"));
1212 if (S_ISREG(st.st_mode) &&
1213 lseek(input_fd, 0, SEEK_CUR) - input_len != st.st_size)
1214 die(_("pack has junk at the end"));
1215
1216 for (i = 0; i < nr_objects; i++) {
1217 struct object_entry *obj = &objects[i];
1218 if (obj->real_type != OBJ_BAD)
1219 continue;
1220 obj->real_type = obj->type;
1221 sha1_object(NULL, obj, obj->size, obj->type,
1222 &obj->idx.oid);
1223 nr_delays--;
1224 }
1225 if (nr_delays)
1226 die(_("confusion beyond insanity in parse_pack_objects()"));
1227 }
1228
1229 /*
1230 * Second pass:
1231 * - for all non-delta objects, look if it is used as a base for
1232 * deltas;
1233 * - if used as a base, uncompress the object and apply all deltas,
1234 * recursively checking if the resulting object is used as a base
1235 * for some more deltas.
1236 */
1237 static void resolve_deltas(void)
1238 {
1239 int i;
1240
1241 if (!nr_ofs_deltas && !nr_ref_deltas)
1242 return;
1243
1244 /* Sort deltas by base SHA1/offset for fast searching */
1245 QSORT(ofs_deltas, nr_ofs_deltas, compare_ofs_delta_entry);
1246 QSORT(ref_deltas, nr_ref_deltas, compare_ref_delta_entry);
1247
1248 if (verbose || show_resolving_progress)
1249 progress = start_progress(_("Resolving deltas"),
1250 nr_ref_deltas + nr_ofs_deltas);
1251
1252 nr_dispatched = 0;
1253 base_cache_limit = delta_base_cache_limit * nr_threads;
1254 if (nr_threads > 1 || getenv("GIT_FORCE_THREADS")) {
1255 init_thread();
1256 for (i = 0; i < nr_threads; i++) {
1257 int ret = pthread_create(&thread_data[i].thread, NULL,
1258 threaded_second_pass, thread_data + i);
1259 if (ret)
1260 die(_("unable to create thread: %s"),
1261 strerror(ret));
1262 }
1263 for (i = 0; i < nr_threads; i++)
1264 pthread_join(thread_data[i].thread, NULL);
1265 cleanup_thread();
1266 return;
1267 }
1268 threaded_second_pass(&nothread_data);
1269 }
1270
1271 /*
1272 * Third pass:
1273 * - append objects to convert thin pack to full pack if required
1274 * - write the final pack hash
1275 */
1276 static void fix_unresolved_deltas(struct hashfile *f);
1277 static void conclude_pack(int fix_thin_pack, const char *curr_pack, unsigned char *pack_hash)
1278 {
1279 if (nr_ref_deltas + nr_ofs_deltas == nr_resolved_deltas) {
1280 stop_progress(&progress);
1281 /* Flush remaining pack final hash. */
1282 flush();
1283 return;
1284 }
1285
1286 if (fix_thin_pack) {
1287 struct hashfile *f;
1288 unsigned char read_hash[GIT_MAX_RAWSZ], tail_hash[GIT_MAX_RAWSZ];
1289 struct strbuf msg = STRBUF_INIT;
1290 int nr_unresolved = nr_ofs_deltas + nr_ref_deltas - nr_resolved_deltas;
1291 int nr_objects_initial = nr_objects;
1292 if (nr_unresolved <= 0)
1293 die(_("confusion beyond insanity"));
1294 REALLOC_ARRAY(objects, nr_objects + nr_unresolved + 1);
1295 memset(objects + nr_objects + 1, 0,
1296 nr_unresolved * sizeof(*objects));
1297 f = hashfd(output_fd, curr_pack);
1298 fix_unresolved_deltas(f);
1299 strbuf_addf(&msg, Q_("completed with %d local object",
1300 "completed with %d local objects",
1301 nr_objects - nr_objects_initial),
1302 nr_objects - nr_objects_initial);
1303 stop_progress_msg(&progress, msg.buf);
1304 strbuf_release(&msg);
1305 finalize_hashfile(f, tail_hash, FSYNC_COMPONENT_PACK, 0);
1306 hashcpy(read_hash, pack_hash);
1307 fixup_pack_header_footer(output_fd, pack_hash,
1308 curr_pack, nr_objects,
1309 read_hash, consumed_bytes-the_hash_algo->rawsz);
1310 if (!hasheq(read_hash, tail_hash))
1311 die(_("Unexpected tail checksum for %s "
1312 "(disk corruption?)"), curr_pack);
1313 }
1314 if (nr_ofs_deltas + nr_ref_deltas != nr_resolved_deltas)
1315 die(Q_("pack has %d unresolved delta",
1316 "pack has %d unresolved deltas",
1317 nr_ofs_deltas + nr_ref_deltas - nr_resolved_deltas),
1318 nr_ofs_deltas + nr_ref_deltas - nr_resolved_deltas);
1319 }
1320
1321 static int write_compressed(struct hashfile *f, void *in, unsigned int size)
1322 {
1323 git_zstream stream;
1324 int status;
1325 unsigned char outbuf[4096];
1326
1327 git_deflate_init(&stream, zlib_compression_level);
1328 stream.next_in = in;
1329 stream.avail_in = size;
1330
1331 do {
1332 stream.next_out = outbuf;
1333 stream.avail_out = sizeof(outbuf);
1334 status = git_deflate(&stream, Z_FINISH);
1335 hashwrite(f, outbuf, sizeof(outbuf) - stream.avail_out);
1336 } while (status == Z_OK);
1337
1338 if (status != Z_STREAM_END)
1339 die(_("unable to deflate appended object (%d)"), status);
1340 size = stream.total_out;
1341 git_deflate_end(&stream);
1342 return size;
1343 }
1344
1345 static struct object_entry *append_obj_to_pack(struct hashfile *f,
1346 const unsigned char *sha1, void *buf,
1347 unsigned long size, enum object_type type)
1348 {
1349 struct object_entry *obj = &objects[nr_objects++];
1350 unsigned char header[10];
1351 unsigned long s = size;
1352 int n = 0;
1353 unsigned char c = (type << 4) | (s & 15);
1354 s >>= 4;
1355 while (s) {
1356 header[n++] = c | 0x80;
1357 c = s & 0x7f;
1358 s >>= 7;
1359 }
1360 header[n++] = c;
1361 crc32_begin(f);
1362 hashwrite(f, header, n);
1363 obj[0].size = size;
1364 obj[0].hdr_size = n;
1365 obj[0].type = type;
1366 obj[0].real_type = type;
1367 obj[1].idx.offset = obj[0].idx.offset + n;
1368 obj[1].idx.offset += write_compressed(f, buf, size);
1369 obj[0].idx.crc32 = crc32_end(f);
1370 hashflush(f);
1371 oidread(&obj->idx.oid, sha1);
1372 return obj;
1373 }
1374
1375 static int delta_pos_compare(const void *_a, const void *_b)
1376 {
1377 struct ref_delta_entry *a = *(struct ref_delta_entry **)_a;
1378 struct ref_delta_entry *b = *(struct ref_delta_entry **)_b;
1379 return a->obj_no - b->obj_no;
1380 }
1381
1382 static void fix_unresolved_deltas(struct hashfile *f)
1383 {
1384 struct ref_delta_entry **sorted_by_pos;
1385 int i;
1386
1387 /*
1388 * Since many unresolved deltas may well be themselves base objects
1389 * for more unresolved deltas, we really want to include the
1390 * smallest number of base objects that would cover as much delta
1391 * as possible by picking the
1392 * trunc deltas first, allowing for other deltas to resolve without
1393 * additional base objects. Since most base objects are to be found
1394 * before deltas depending on them, a good heuristic is to start
1395 * resolving deltas in the same order as their position in the pack.
1396 */
1397 ALLOC_ARRAY(sorted_by_pos, nr_ref_deltas);
1398 for (i = 0; i < nr_ref_deltas; i++)
1399 sorted_by_pos[i] = &ref_deltas[i];
1400 QSORT(sorted_by_pos, nr_ref_deltas, delta_pos_compare);
1401
1402 if (repo_has_promisor_remote(the_repository)) {
1403 /*
1404 * Prefetch the delta bases.
1405 */
1406 struct oid_array to_fetch = OID_ARRAY_INIT;
1407 for (i = 0; i < nr_ref_deltas; i++) {
1408 struct ref_delta_entry *d = sorted_by_pos[i];
1409 if (!oid_object_info_extended(the_repository, &d->oid,
1410 NULL,
1411 OBJECT_INFO_FOR_PREFETCH))
1412 continue;
1413 oid_array_append(&to_fetch, &d->oid);
1414 }
1415 promisor_remote_get_direct(the_repository,
1416 to_fetch.oid, to_fetch.nr);
1417 oid_array_clear(&to_fetch);
1418 }
1419
1420 for (i = 0; i < nr_ref_deltas; i++) {
1421 struct ref_delta_entry *d = sorted_by_pos[i];
1422 enum object_type type;
1423 void *data;
1424 unsigned long size;
1425
1426 if (objects[d->obj_no].real_type != OBJ_REF_DELTA)
1427 continue;
1428 data = repo_read_object_file(the_repository, &d->oid, &type,
1429 &size);
1430 if (!data)
1431 continue;
1432
1433 if (check_object_signature(the_repository, &d->oid, data, size,
1434 type) < 0)
1435 die(_("local object %s is corrupt"), oid_to_hex(&d->oid));
1436
1437 /*
1438 * Add this as an object to the objects array and call
1439 * threaded_second_pass() (which will pick up the added
1440 * object).
1441 */
1442 append_obj_to_pack(f, d->oid.hash, data, size, type);
1443 free(data);
1444 threaded_second_pass(NULL);
1445
1446 display_progress(progress, nr_resolved_deltas);
1447 }
1448 free(sorted_by_pos);
1449 }
1450
1451 static const char *derive_filename(const char *pack_name, const char *strip,
1452 const char *suffix, struct strbuf *buf)
1453 {
1454 size_t len;
1455 if (!strip_suffix(pack_name, strip, &len) || !len ||
1456 pack_name[len - 1] != '.')
1457 die(_("packfile name '%s' does not end with '.%s'"),
1458 pack_name, strip);
1459 strbuf_add(buf, pack_name, len);
1460 strbuf_addstr(buf, suffix);
1461 return buf->buf;
1462 }
1463
1464 static void write_special_file(const char *suffix, const char *msg,
1465 const char *pack_name, const unsigned char *hash,
1466 const char **report)
1467 {
1468 struct strbuf name_buf = STRBUF_INIT;
1469 const char *filename;
1470 int fd;
1471 int msg_len = strlen(msg);
1472
1473 if (pack_name)
1474 filename = derive_filename(pack_name, "pack", suffix, &name_buf);
1475 else
1476 filename = odb_pack_name(&name_buf, hash, suffix);
1477
1478 fd = odb_pack_keep(filename);
1479 if (fd < 0) {
1480 if (errno != EEXIST)
1481 die_errno(_("cannot write %s file '%s'"),
1482 suffix, filename);
1483 } else {
1484 if (msg_len > 0) {
1485 write_or_die(fd, msg, msg_len);
1486 write_or_die(fd, "\n", 1);
1487 }
1488 if (close(fd) != 0)
1489 die_errno(_("cannot close written %s file '%s'"),
1490 suffix, filename);
1491 if (report)
1492 *report = suffix;
1493 }
1494 strbuf_release(&name_buf);
1495 }
1496
1497 static void rename_tmp_packfile(const char **final_name,
1498 const char *curr_name,
1499 struct strbuf *name, unsigned char *hash,
1500 const char *ext, int make_read_only_if_same)
1501 {
1502 if (*final_name != curr_name) {
1503 if (!*final_name)
1504 *final_name = odb_pack_name(name, hash, ext);
1505 if (finalize_object_file(curr_name, *final_name))
1506 die(_("unable to rename temporary '*.%s' file to '%s'"),
1507 ext, *final_name);
1508 } else if (make_read_only_if_same) {
1509 chmod(*final_name, 0444);
1510 }
1511 }
1512
1513 static void final(const char *final_pack_name, const char *curr_pack_name,
1514 const char *final_index_name, const char *curr_index_name,
1515 const char *final_rev_index_name, const char *curr_rev_index_name,
1516 const char *keep_msg, const char *promisor_msg,
1517 unsigned char *hash)
1518 {
1519 const char *report = "pack";
1520 struct strbuf pack_name = STRBUF_INIT;
1521 struct strbuf index_name = STRBUF_INIT;
1522 struct strbuf rev_index_name = STRBUF_INIT;
1523 int err;
1524
1525 if (!from_stdin) {
1526 close(input_fd);
1527 } else {
1528 fsync_component_or_die(FSYNC_COMPONENT_PACK, output_fd, curr_pack_name);
1529 err = close(output_fd);
1530 if (err)
1531 die_errno(_("error while closing pack file"));
1532 }
1533
1534 if (keep_msg)
1535 write_special_file("keep", keep_msg, final_pack_name, hash,
1536 &report);
1537 if (promisor_msg)
1538 write_special_file("promisor", promisor_msg, final_pack_name,
1539 hash, NULL);
1540
1541 rename_tmp_packfile(&final_pack_name, curr_pack_name, &pack_name,
1542 hash, "pack", from_stdin);
1543 if (curr_rev_index_name)
1544 rename_tmp_packfile(&final_rev_index_name, curr_rev_index_name,
1545 &rev_index_name, hash, "rev", 1);
1546 rename_tmp_packfile(&final_index_name, curr_index_name, &index_name,
1547 hash, "idx", 1);
1548
1549 if (do_fsck_object) {
1550 struct packed_git *p;
1551 p = add_packed_git(final_index_name, strlen(final_index_name), 0);
1552 if (p)
1553 install_packed_git(the_repository, p);
1554 }
1555
1556 if (!from_stdin) {
1557 printf("%s\n", hash_to_hex(hash));
1558 } else {
1559 struct strbuf buf = STRBUF_INIT;
1560
1561 strbuf_addf(&buf, "%s\t%s\n", report, hash_to_hex(hash));
1562 write_or_die(1, buf.buf, buf.len);
1563 strbuf_release(&buf);
1564
1565 /*
1566 * Let's just mimic git-unpack-objects here and write
1567 * the last part of the input buffer to stdout.
1568 */
1569 while (input_len) {
1570 err = xwrite(1, input_buffer + input_offset, input_len);
1571 if (err <= 0)
1572 break;
1573 input_len -= err;
1574 input_offset += err;
1575 }
1576 }
1577
1578 strbuf_release(&rev_index_name);
1579 strbuf_release(&index_name);
1580 strbuf_release(&pack_name);
1581 }
1582
1583 static int git_index_pack_config(const char *k, const char *v, void *cb)
1584 {
1585 struct pack_idx_option *opts = cb;
1586
1587 if (!strcmp(k, "pack.indexversion")) {
1588 opts->version = git_config_int(k, v);
1589 if (opts->version > 2)
1590 die(_("bad pack.indexVersion=%"PRIu32), opts->version);
1591 return 0;
1592 }
1593 if (!strcmp(k, "pack.threads")) {
1594 nr_threads = git_config_int(k, v);
1595 if (nr_threads < 0)
1596 die(_("invalid number of threads specified (%d)"),
1597 nr_threads);
1598 if (!HAVE_THREADS && nr_threads != 1) {
1599 warning(_("no threads support, ignoring %s"), k);
1600 nr_threads = 1;
1601 }
1602 return 0;
1603 }
1604 if (!strcmp(k, "pack.writereverseindex")) {
1605 if (git_config_bool(k, v))
1606 opts->flags |= WRITE_REV;
1607 else
1608 opts->flags &= ~WRITE_REV;
1609 }
1610 return git_default_config(k, v, cb);
1611 }
1612
1613 static int cmp_uint32(const void *a_, const void *b_)
1614 {
1615 uint32_t a = *((uint32_t *)a_);
1616 uint32_t b = *((uint32_t *)b_);
1617
1618 return (a < b) ? -1 : (a != b);
1619 }
1620
1621 static void read_v2_anomalous_offsets(struct packed_git *p,
1622 struct pack_idx_option *opts)
1623 {
1624 const uint32_t *idx1, *idx2;
1625 uint32_t i;
1626
1627 /* The address of the 4-byte offset table */
1628 idx1 = (((const uint32_t *)((const uint8_t *)p->index_data + p->crc_offset))
1629 + (size_t)p->num_objects /* CRC32 table */
1630 );
1631
1632 /* The address of the 8-byte offset table */
1633 idx2 = idx1 + p->num_objects;
1634
1635 for (i = 0; i < p->num_objects; i++) {
1636 uint32_t off = ntohl(idx1[i]);
1637 if (!(off & 0x80000000))
1638 continue;
1639 off = off & 0x7fffffff;
1640 check_pack_index_ptr(p, &idx2[off * 2]);
1641 if (idx2[off * 2])
1642 continue;
1643 /*
1644 * The real offset is ntohl(idx2[off * 2]) in high 4
1645 * octets, and ntohl(idx2[off * 2 + 1]) in low 4
1646 * octets. But idx2[off * 2] is Zero!!!
1647 */
1648 ALLOC_GROW(opts->anomaly, opts->anomaly_nr + 1, opts->anomaly_alloc);
1649 opts->anomaly[opts->anomaly_nr++] = ntohl(idx2[off * 2 + 1]);
1650 }
1651
1652 QSORT(opts->anomaly, opts->anomaly_nr, cmp_uint32);
1653 }
1654
1655 static void read_idx_option(struct pack_idx_option *opts, const char *pack_name)
1656 {
1657 struct packed_git *p = add_packed_git(pack_name, strlen(pack_name), 1);
1658
1659 if (!p)
1660 die(_("Cannot open existing pack file '%s'"), pack_name);
1661 if (open_pack_index(p))
1662 die(_("Cannot open existing pack idx file for '%s'"), pack_name);
1663
1664 /* Read the attributes from the existing idx file */
1665 opts->version = p->index_version;
1666
1667 if (opts->version == 2)
1668 read_v2_anomalous_offsets(p, opts);
1669
1670 /*
1671 * Get rid of the idx file as we do not need it anymore.
1672 * NEEDSWORK: extract this bit from free_pack_by_name() in
1673 * object-file.c, perhaps? It shouldn't matter very much as we
1674 * know we haven't installed this pack (hence we never have
1675 * read anything from it).
1676 */
1677 close_pack_index(p);
1678 free(p);
1679 }
1680
1681 static void show_pack_info(int stat_only)
1682 {
1683 int i, baseobjects = nr_objects - nr_ref_deltas - nr_ofs_deltas;
1684 unsigned long *chain_histogram = NULL;
1685
1686 if (deepest_delta)
1687 CALLOC_ARRAY(chain_histogram, deepest_delta);
1688
1689 for (i = 0; i < nr_objects; i++) {
1690 struct object_entry *obj = &objects[i];
1691
1692 if (is_delta_type(obj->type))
1693 chain_histogram[obj_stat[i].delta_depth - 1]++;
1694 if (stat_only)
1695 continue;
1696 printf("%s %-6s %"PRIuMAX" %"PRIuMAX" %"PRIuMAX,
1697 oid_to_hex(&obj->idx.oid),
1698 type_name(obj->real_type), (uintmax_t)obj->size,
1699 (uintmax_t)(obj[1].idx.offset - obj->idx.offset),
1700 (uintmax_t)obj->idx.offset);
1701 if (is_delta_type(obj->type)) {
1702 struct object_entry *bobj = &objects[obj_stat[i].base_object_no];
1703 printf(" %u %s", obj_stat[i].delta_depth,
1704 oid_to_hex(&bobj->idx.oid));
1705 }
1706 putchar('\n');
1707 }
1708
1709 if (baseobjects)
1710 printf_ln(Q_("non delta: %d object",
1711 "non delta: %d objects",
1712 baseobjects),
1713 baseobjects);
1714 for (i = 0; i < deepest_delta; i++) {
1715 if (!chain_histogram[i])
1716 continue;
1717 printf_ln(Q_("chain length = %d: %lu object",
1718 "chain length = %d: %lu objects",
1719 chain_histogram[i]),
1720 i + 1,
1721 chain_histogram[i]);
1722 }
1723 free(chain_histogram);
1724 }
1725
1726 int cmd_index_pack(int argc, const char **argv, const char *prefix)
1727 {
1728 int i, fix_thin_pack = 0, verify = 0, stat_only = 0, rev_index;
1729 const char *curr_index;
1730 const char *curr_rev_index = NULL;
1731 const char *index_name = NULL, *pack_name = NULL, *rev_index_name = NULL;
1732 const char *keep_msg = NULL;
1733 const char *promisor_msg = NULL;
1734 struct strbuf index_name_buf = STRBUF_INIT;
1735 struct strbuf rev_index_name_buf = STRBUF_INIT;
1736 struct pack_idx_entry **idx_objects;
1737 struct pack_idx_option opts;
1738 unsigned char pack_hash[GIT_MAX_RAWSZ];
1739 unsigned foreign_nr = 1; /* zero is a "good" value, assume bad */
1740 int report_end_of_input = 0;
1741 int hash_algo = 0;
1742
1743 /*
1744 * index-pack never needs to fetch missing objects except when
1745 * REF_DELTA bases are missing (which are explicitly handled). It only
1746 * accesses the repo to do hash collision checks and to check which
1747 * REF_DELTA bases need to be fetched.
1748 */
1749 fetch_if_missing = 0;
1750
1751 if (argc == 2 && !strcmp(argv[1], "-h"))
1752 usage(index_pack_usage);
1753
1754 disable_replace_refs();
1755 fsck_options.walk = mark_link;
1756
1757 reset_pack_idx_option(&opts);
1758 opts.flags |= WRITE_REV;
1759 git_config(git_index_pack_config, &opts);
1760 if (prefix && chdir(prefix))
1761 die(_("Cannot come back to cwd"));
1762
1763 if (git_env_bool(GIT_TEST_NO_WRITE_REV_INDEX, 0))
1764 rev_index = 0;
1765 else
1766 rev_index = !!(opts.flags & (WRITE_REV_VERIFY | WRITE_REV));
1767
1768 for (i = 1; i < argc; i++) {
1769 const char *arg = argv[i];
1770
1771 if (*arg == '-') {
1772 if (!strcmp(arg, "--stdin")) {
1773 from_stdin = 1;
1774 } else if (!strcmp(arg, "--fix-thin")) {
1775 fix_thin_pack = 1;
1776 } else if (skip_to_optional_arg(arg, "--strict", &arg)) {
1777 strict = 1;
1778 do_fsck_object = 1;
1779 fsck_set_msg_types(&fsck_options, arg);
1780 } else if (!strcmp(arg, "--check-self-contained-and-connected")) {
1781 strict = 1;
1782 check_self_contained_and_connected = 1;
1783 } else if (!strcmp(arg, "--fsck-objects")) {
1784 do_fsck_object = 1;
1785 } else if (!strcmp(arg, "--verify")) {
1786 verify = 1;
1787 } else if (!strcmp(arg, "--verify-stat")) {
1788 verify = 1;
1789 show_stat = 1;
1790 } else if (!strcmp(arg, "--verify-stat-only")) {
1791 verify = 1;
1792 show_stat = 1;
1793 stat_only = 1;
1794 } else if (skip_to_optional_arg(arg, "--keep", &keep_msg)) {
1795 ; /* nothing to do */
1796 } else if (skip_to_optional_arg(arg, "--promisor", &promisor_msg)) {
1797 ; /* already parsed */
1798 } else if (starts_with(arg, "--threads=")) {
1799 char *end;
1800 nr_threads = strtoul(arg+10, &end, 0);
1801 if (!arg[10] || *end || nr_threads < 0)
1802 usage(index_pack_usage);
1803 if (!HAVE_THREADS && nr_threads != 1) {
1804 warning(_("no threads support, ignoring %s"), arg);
1805 nr_threads = 1;
1806 }
1807 } else if (starts_with(arg, "--pack_header=")) {
1808 struct pack_header *hdr;
1809 char *c;
1810
1811 hdr = (struct pack_header *)input_buffer;
1812 hdr->hdr_signature = htonl(PACK_SIGNATURE);
1813 hdr->hdr_version = htonl(strtoul(arg + 14, &c, 10));
1814 if (*c != ',')
1815 die(_("bad %s"), arg);
1816 hdr->hdr_entries = htonl(strtoul(c + 1, &c, 10));
1817 if (*c)
1818 die(_("bad %s"), arg);
1819 input_len = sizeof(*hdr);
1820 } else if (!strcmp(arg, "-v")) {
1821 verbose = 1;
1822 } else if (!strcmp(arg, "--progress-title")) {
1823 if (progress_title || (i+1) >= argc)
1824 usage(index_pack_usage);
1825 progress_title = argv[++i];
1826 } else if (!strcmp(arg, "--show-resolving-progress")) {
1827 show_resolving_progress = 1;
1828 } else if (!strcmp(arg, "--report-end-of-input")) {
1829 report_end_of_input = 1;
1830 } else if (!strcmp(arg, "-o")) {
1831 if (index_name || (i+1) >= argc)
1832 usage(index_pack_usage);
1833 index_name = argv[++i];
1834 } else if (starts_with(arg, "--index-version=")) {
1835 char *c;
1836 opts.version = strtoul(arg + 16, &c, 10);
1837 if (opts.version > 2)
1838 die(_("bad %s"), arg);
1839 if (*c == ',')
1840 opts.off32_limit = strtoul(c+1, &c, 0);
1841 if (*c || opts.off32_limit & 0x80000000)
1842 die(_("bad %s"), arg);
1843 } else if (skip_prefix(arg, "--max-input-size=", &arg)) {
1844 max_input_size = strtoumax(arg, NULL, 10);
1845 } else if (skip_prefix(arg, "--object-format=", &arg)) {
1846 hash_algo = hash_algo_by_name(arg);
1847 if (hash_algo == GIT_HASH_UNKNOWN)
1848 die(_("unknown hash algorithm '%s'"), arg);
1849 repo_set_hash_algo(the_repository, hash_algo);
1850 } else if (!strcmp(arg, "--rev-index")) {
1851 rev_index = 1;
1852 } else if (!strcmp(arg, "--no-rev-index")) {
1853 rev_index = 0;
1854 } else
1855 usage(index_pack_usage);
1856 continue;
1857 }
1858
1859 if (pack_name)
1860 usage(index_pack_usage);
1861 pack_name = arg;
1862 }
1863
1864 if (!pack_name && !from_stdin)
1865 usage(index_pack_usage);
1866 if (fix_thin_pack && !from_stdin)
1867 die(_("the option '%s' requires '%s'"), "--fix-thin", "--stdin");
1868 if (from_stdin && !startup_info->have_repository)
1869 die(_("--stdin requires a git repository"));
1870 if (from_stdin && hash_algo)
1871 die(_("options '%s' and '%s' cannot be used together"), "--object-format", "--stdin");
1872 if (!index_name && pack_name)
1873 index_name = derive_filename(pack_name, "pack", "idx", &index_name_buf);
1874
1875 opts.flags &= ~(WRITE_REV | WRITE_REV_VERIFY);
1876 if (rev_index) {
1877 opts.flags |= verify ? WRITE_REV_VERIFY : WRITE_REV;
1878 if (index_name)
1879 rev_index_name = derive_filename(index_name,
1880 "idx", "rev",
1881 &rev_index_name_buf);
1882 }
1883
1884 if (verify) {
1885 if (!index_name)
1886 die(_("--verify with no packfile name given"));
1887 read_idx_option(&opts, index_name);
1888 opts.flags |= WRITE_IDX_VERIFY | WRITE_IDX_STRICT;
1889 }
1890 if (strict)
1891 opts.flags |= WRITE_IDX_STRICT;
1892
1893 if (HAVE_THREADS && !nr_threads) {
1894 nr_threads = online_cpus();
1895 /*
1896 * Experiments show that going above 20 threads doesn't help,
1897 * no matter how many cores you have. Below that, we tend to
1898 * max at half the number of online_cpus(), presumably because
1899 * half of those are hyperthreads rather than full cores. We'll
1900 * never reduce the level below "3", though, to match a
1901 * historical value that nobody complained about.
1902 */
1903 if (nr_threads < 4)
1904 ; /* too few cores to consider capping */
1905 else if (nr_threads < 6)
1906 nr_threads = 3; /* historic cap */
1907 else if (nr_threads < 40)
1908 nr_threads /= 2;
1909 else
1910 nr_threads = 20; /* hard cap */
1911 }
1912
1913 curr_pack = open_pack_file(pack_name);
1914 parse_pack_header();
1915 CALLOC_ARRAY(objects, st_add(nr_objects, 1));
1916 if (show_stat)
1917 CALLOC_ARRAY(obj_stat, st_add(nr_objects, 1));
1918 CALLOC_ARRAY(ofs_deltas, nr_objects);
1919 parse_pack_objects(pack_hash);
1920 if (report_end_of_input)
1921 write_in_full(2, "\0", 1);
1922 resolve_deltas();
1923 conclude_pack(fix_thin_pack, curr_pack, pack_hash);
1924 free(ofs_deltas);
1925 free(ref_deltas);
1926 if (strict)
1927 foreign_nr = check_objects();
1928
1929 if (show_stat)
1930 show_pack_info(stat_only);
1931
1932 ALLOC_ARRAY(idx_objects, nr_objects);
1933 for (i = 0; i < nr_objects; i++)
1934 idx_objects[i] = &objects[i].idx;
1935 curr_index = write_idx_file(index_name, idx_objects, nr_objects, &opts, pack_hash);
1936 if (rev_index)
1937 curr_rev_index = write_rev_file(rev_index_name, idx_objects,
1938 nr_objects, pack_hash,
1939 opts.flags);
1940 free(idx_objects);
1941
1942 if (!verify)
1943 final(pack_name, curr_pack,
1944 index_name, curr_index,
1945 rev_index_name, curr_rev_index,
1946 keep_msg, promisor_msg,
1947 pack_hash);
1948 else
1949 close(input_fd);
1950
1951 if (do_fsck_object && fsck_finish(&fsck_options))
1952 die(_("fsck error in pack objects"));
1953
1954 free(opts.anomaly);
1955 free(objects);
1956 strbuf_release(&index_name_buf);
1957 strbuf_release(&rev_index_name_buf);
1958 if (!pack_name)
1959 free((void *) curr_pack);
1960 if (!index_name)
1961 free((void *) curr_index);
1962 if (!rev_index_name)
1963 free((void *) curr_rev_index);
1964
1965 /*
1966 * Let the caller know this pack is not self contained
1967 */
1968 if (check_self_contained_and_connected && foreign_nr)
1969 return 1;
1970
1971 return 0;
1972 }