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