bisect--helper: avoid use-after-free
[git] / fast-import.c
1 #include "builtin.h"
2 #include "cache.h"
3 #include "repository.h"
4 #include "config.h"
5 #include "lockfile.h"
6 #include "object.h"
7 #include "blob.h"
8 #include "tree.h"
9 #include "commit.h"
10 #include "delta.h"
11 #include "pack.h"
12 #include "refs.h"
13 #include "csum-file.h"
14 #include "quote.h"
15 #include "dir.h"
16 #include "run-command.h"
17 #include "packfile.h"
18 #include "object-store.h"
19 #include "mem-pool.h"
20 #include "commit-reach.h"
21
22 #define PACK_ID_BITS 16
23 #define MAX_PACK_ID ((1<<PACK_ID_BITS)-1)
24 #define DEPTH_BITS 13
25 #define MAX_DEPTH ((1<<DEPTH_BITS)-1)
26
27 /*
28  * We abuse the setuid bit on directories to mean "do not delta".
29  */
30 #define NO_DELTA S_ISUID
31
32 struct object_entry {
33         struct pack_idx_entry idx;
34         struct object_entry *next;
35         uint32_t type : TYPE_BITS,
36                 pack_id : PACK_ID_BITS,
37                 depth : DEPTH_BITS;
38 };
39
40 struct object_entry_pool {
41         struct object_entry_pool *next_pool;
42         struct object_entry *next_free;
43         struct object_entry *end;
44         struct object_entry entries[FLEX_ARRAY]; /* more */
45 };
46
47 struct mark_set {
48         union {
49                 struct object_entry *marked[1024];
50                 struct mark_set *sets[1024];
51         } data;
52         unsigned int shift;
53 };
54
55 struct last_object {
56         struct strbuf data;
57         off_t offset;
58         unsigned int depth;
59         unsigned no_swap : 1;
60 };
61
62 struct atom_str {
63         struct atom_str *next_atom;
64         unsigned short str_len;
65         char str_dat[FLEX_ARRAY]; /* more */
66 };
67
68 struct tree_content;
69 struct tree_entry {
70         struct tree_content *tree;
71         struct atom_str *name;
72         struct tree_entry_ms {
73                 uint16_t mode;
74                 struct object_id oid;
75         } versions[2];
76 };
77
78 struct tree_content {
79         unsigned int entry_capacity; /* must match avail_tree_content */
80         unsigned int entry_count;
81         unsigned int delta_depth;
82         struct tree_entry *entries[FLEX_ARRAY]; /* more */
83 };
84
85 struct avail_tree_content {
86         unsigned int entry_capacity; /* must match tree_content */
87         struct avail_tree_content *next_avail;
88 };
89
90 struct branch {
91         struct branch *table_next_branch;
92         struct branch *active_next_branch;
93         const char *name;
94         struct tree_entry branch_tree;
95         uintmax_t last_commit;
96         uintmax_t num_notes;
97         unsigned active : 1;
98         unsigned delete : 1;
99         unsigned pack_id : PACK_ID_BITS;
100         struct object_id oid;
101 };
102
103 struct tag {
104         struct tag *next_tag;
105         const char *name;
106         unsigned int pack_id;
107         struct object_id oid;
108 };
109
110 struct hash_list {
111         struct hash_list *next;
112         struct object_id oid;
113 };
114
115 typedef enum {
116         WHENSPEC_RAW = 1,
117         WHENSPEC_RFC2822,
118         WHENSPEC_NOW
119 } whenspec_type;
120
121 struct recent_command {
122         struct recent_command *prev;
123         struct recent_command *next;
124         char *buf;
125 };
126
127 /* Configured limits on output */
128 static unsigned long max_depth = 50;
129 static off_t max_packsize;
130 static int unpack_limit = 100;
131 static int force_update;
132
133 /* Stats and misc. counters */
134 static uintmax_t alloc_count;
135 static uintmax_t marks_set_count;
136 static uintmax_t object_count_by_type[1 << TYPE_BITS];
137 static uintmax_t duplicate_count_by_type[1 << TYPE_BITS];
138 static uintmax_t delta_count_by_type[1 << TYPE_BITS];
139 static uintmax_t delta_count_attempts_by_type[1 << TYPE_BITS];
140 static unsigned long object_count;
141 static unsigned long branch_count;
142 static unsigned long branch_load_count;
143 static int failure;
144 static FILE *pack_edges;
145 static unsigned int show_stats = 1;
146 static int global_argc;
147 static const char **global_argv;
148
149 /* Memory pools */
150 static struct mem_pool fi_mem_pool =  {NULL, 2*1024*1024 -
151                                        sizeof(struct mp_block), 0 };
152
153 /* Atom management */
154 static unsigned int atom_table_sz = 4451;
155 static unsigned int atom_cnt;
156 static struct atom_str **atom_table;
157
158 /* The .pack file being generated */
159 static struct pack_idx_option pack_idx_opts;
160 static unsigned int pack_id;
161 static struct hashfile *pack_file;
162 static struct packed_git *pack_data;
163 static struct packed_git **all_packs;
164 static off_t pack_size;
165
166 /* Table of objects we've written. */
167 static unsigned int object_entry_alloc = 5000;
168 static struct object_entry_pool *blocks;
169 static struct object_entry *object_table[1 << 16];
170 static struct mark_set *marks;
171 static const char *export_marks_file;
172 static const char *import_marks_file;
173 static int import_marks_file_from_stream;
174 static int import_marks_file_ignore_missing;
175 static int import_marks_file_done;
176 static int relative_marks_paths;
177
178 /* Our last blob */
179 static struct last_object last_blob = { STRBUF_INIT, 0, 0, 0 };
180
181 /* Tree management */
182 static unsigned int tree_entry_alloc = 1000;
183 static void *avail_tree_entry;
184 static unsigned int avail_tree_table_sz = 100;
185 static struct avail_tree_content **avail_tree_table;
186 static size_t tree_entry_allocd;
187 static struct strbuf old_tree = STRBUF_INIT;
188 static struct strbuf new_tree = STRBUF_INIT;
189
190 /* Branch data */
191 static unsigned long max_active_branches = 5;
192 static unsigned long cur_active_branches;
193 static unsigned long branch_table_sz = 1039;
194 static struct branch **branch_table;
195 static struct branch *active_branches;
196
197 /* Tag data */
198 static struct tag *first_tag;
199 static struct tag *last_tag;
200
201 /* Input stream parsing */
202 static whenspec_type whenspec = WHENSPEC_RAW;
203 static struct strbuf command_buf = STRBUF_INIT;
204 static int unread_command_buf;
205 static struct recent_command cmd_hist = {&cmd_hist, &cmd_hist, NULL};
206 static struct recent_command *cmd_tail = &cmd_hist;
207 static struct recent_command *rc_free;
208 static unsigned int cmd_save = 100;
209 static uintmax_t next_mark;
210 static struct strbuf new_data = STRBUF_INIT;
211 static int seen_data_command;
212 static int require_explicit_termination;
213 static int allow_unsafe_features;
214
215 /* Signal handling */
216 static volatile sig_atomic_t checkpoint_requested;
217
218 /* Where to write output of cat-blob commands */
219 static int cat_blob_fd = STDOUT_FILENO;
220
221 static void parse_argv(void);
222 static void parse_get_mark(const char *p);
223 static void parse_cat_blob(const char *p);
224 static void parse_ls(const char *p, struct branch *b);
225
226 static void write_branch_report(FILE *rpt, struct branch *b)
227 {
228         fprintf(rpt, "%s:\n", b->name);
229
230         fprintf(rpt, "  status      :");
231         if (b->active)
232                 fputs(" active", rpt);
233         if (b->branch_tree.tree)
234                 fputs(" loaded", rpt);
235         if (is_null_oid(&b->branch_tree.versions[1].oid))
236                 fputs(" dirty", rpt);
237         fputc('\n', rpt);
238
239         fprintf(rpt, "  tip commit  : %s\n", oid_to_hex(&b->oid));
240         fprintf(rpt, "  old tree    : %s\n",
241                 oid_to_hex(&b->branch_tree.versions[0].oid));
242         fprintf(rpt, "  cur tree    : %s\n",
243                 oid_to_hex(&b->branch_tree.versions[1].oid));
244         fprintf(rpt, "  commit clock: %" PRIuMAX "\n", b->last_commit);
245
246         fputs("  last pack   : ", rpt);
247         if (b->pack_id < MAX_PACK_ID)
248                 fprintf(rpt, "%u", b->pack_id);
249         fputc('\n', rpt);
250
251         fputc('\n', rpt);
252 }
253
254 static void dump_marks_helper(FILE *, uintmax_t, struct mark_set *);
255
256 static void write_crash_report(const char *err)
257 {
258         char *loc = git_pathdup("fast_import_crash_%"PRIuMAX, (uintmax_t) getpid());
259         FILE *rpt = fopen(loc, "w");
260         struct branch *b;
261         unsigned long lu;
262         struct recent_command *rc;
263
264         if (!rpt) {
265                 error_errno("can't write crash report %s", loc);
266                 free(loc);
267                 return;
268         }
269
270         fprintf(stderr, "fast-import: dumping crash report to %s\n", loc);
271
272         fprintf(rpt, "fast-import crash report:\n");
273         fprintf(rpt, "    fast-import process: %"PRIuMAX"\n", (uintmax_t) getpid());
274         fprintf(rpt, "    parent process     : %"PRIuMAX"\n", (uintmax_t) getppid());
275         fprintf(rpt, "    at %s\n", show_date(time(NULL), 0, DATE_MODE(ISO8601)));
276         fputc('\n', rpt);
277
278         fputs("fatal: ", rpt);
279         fputs(err, rpt);
280         fputc('\n', rpt);
281
282         fputc('\n', rpt);
283         fputs("Most Recent Commands Before Crash\n", rpt);
284         fputs("---------------------------------\n", rpt);
285         for (rc = cmd_hist.next; rc != &cmd_hist; rc = rc->next) {
286                 if (rc->next == &cmd_hist)
287                         fputs("* ", rpt);
288                 else
289                         fputs("  ", rpt);
290                 fputs(rc->buf, rpt);
291                 fputc('\n', rpt);
292         }
293
294         fputc('\n', rpt);
295         fputs("Active Branch LRU\n", rpt);
296         fputs("-----------------\n", rpt);
297         fprintf(rpt, "    active_branches = %lu cur, %lu max\n",
298                 cur_active_branches,
299                 max_active_branches);
300         fputc('\n', rpt);
301         fputs("  pos  clock name\n", rpt);
302         fputs("  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", rpt);
303         for (b = active_branches, lu = 0; b; b = b->active_next_branch)
304                 fprintf(rpt, "  %2lu) %6" PRIuMAX" %s\n",
305                         ++lu, b->last_commit, b->name);
306
307         fputc('\n', rpt);
308         fputs("Inactive Branches\n", rpt);
309         fputs("-----------------\n", rpt);
310         for (lu = 0; lu < branch_table_sz; lu++) {
311                 for (b = branch_table[lu]; b; b = b->table_next_branch)
312                         write_branch_report(rpt, b);
313         }
314
315         if (first_tag) {
316                 struct tag *tg;
317                 fputc('\n', rpt);
318                 fputs("Annotated Tags\n", rpt);
319                 fputs("--------------\n", rpt);
320                 for (tg = first_tag; tg; tg = tg->next_tag) {
321                         fputs(oid_to_hex(&tg->oid), rpt);
322                         fputc(' ', rpt);
323                         fputs(tg->name, rpt);
324                         fputc('\n', rpt);
325                 }
326         }
327
328         fputc('\n', rpt);
329         fputs("Marks\n", rpt);
330         fputs("-----\n", rpt);
331         if (export_marks_file)
332                 fprintf(rpt, "  exported to %s\n", export_marks_file);
333         else
334                 dump_marks_helper(rpt, 0, marks);
335
336         fputc('\n', rpt);
337         fputs("-------------------\n", rpt);
338         fputs("END OF CRASH REPORT\n", rpt);
339         fclose(rpt);
340         free(loc);
341 }
342
343 static void end_packfile(void);
344 static void unkeep_all_packs(void);
345 static void dump_marks(void);
346
347 static NORETURN void die_nicely(const char *err, va_list params)
348 {
349         static int zombie;
350         char message[2 * PATH_MAX];
351
352         vsnprintf(message, sizeof(message), err, params);
353         fputs("fatal: ", stderr);
354         fputs(message, stderr);
355         fputc('\n', stderr);
356
357         if (!zombie) {
358                 zombie = 1;
359                 write_crash_report(message);
360                 end_packfile();
361                 unkeep_all_packs();
362                 dump_marks();
363         }
364         exit(128);
365 }
366
367 #ifndef SIGUSR1 /* Windows, for example */
368
369 static void set_checkpoint_signal(void)
370 {
371 }
372
373 #else
374
375 static void checkpoint_signal(int signo)
376 {
377         checkpoint_requested = 1;
378 }
379
380 static void set_checkpoint_signal(void)
381 {
382         struct sigaction sa;
383
384         memset(&sa, 0, sizeof(sa));
385         sa.sa_handler = checkpoint_signal;
386         sigemptyset(&sa.sa_mask);
387         sa.sa_flags = SA_RESTART;
388         sigaction(SIGUSR1, &sa, NULL);
389 }
390
391 #endif
392
393 static void alloc_objects(unsigned int cnt)
394 {
395         struct object_entry_pool *b;
396
397         b = xmalloc(sizeof(struct object_entry_pool)
398                 + cnt * sizeof(struct object_entry));
399         b->next_pool = blocks;
400         b->next_free = b->entries;
401         b->end = b->entries + cnt;
402         blocks = b;
403         alloc_count += cnt;
404 }
405
406 static struct object_entry *new_object(struct object_id *oid)
407 {
408         struct object_entry *e;
409
410         if (blocks->next_free == blocks->end)
411                 alloc_objects(object_entry_alloc);
412
413         e = blocks->next_free++;
414         oidcpy(&e->idx.oid, oid);
415         return e;
416 }
417
418 static struct object_entry *find_object(struct object_id *oid)
419 {
420         unsigned int h = oid->hash[0] << 8 | oid->hash[1];
421         struct object_entry *e;
422         for (e = object_table[h]; e; e = e->next)
423                 if (oideq(oid, &e->idx.oid))
424                         return e;
425         return NULL;
426 }
427
428 static struct object_entry *insert_object(struct object_id *oid)
429 {
430         unsigned int h = oid->hash[0] << 8 | oid->hash[1];
431         struct object_entry *e = object_table[h];
432
433         while (e) {
434                 if (oideq(oid, &e->idx.oid))
435                         return e;
436                 e = e->next;
437         }
438
439         e = new_object(oid);
440         e->next = object_table[h];
441         e->idx.offset = 0;
442         object_table[h] = e;
443         return e;
444 }
445
446 static void invalidate_pack_id(unsigned int id)
447 {
448         unsigned int h;
449         unsigned long lu;
450         struct tag *t;
451
452         for (h = 0; h < ARRAY_SIZE(object_table); h++) {
453                 struct object_entry *e;
454
455                 for (e = object_table[h]; e; e = e->next)
456                         if (e->pack_id == id)
457                                 e->pack_id = MAX_PACK_ID;
458         }
459
460         for (lu = 0; lu < branch_table_sz; lu++) {
461                 struct branch *b;
462
463                 for (b = branch_table[lu]; b; b = b->table_next_branch)
464                         if (b->pack_id == id)
465                                 b->pack_id = MAX_PACK_ID;
466         }
467
468         for (t = first_tag; t; t = t->next_tag)
469                 if (t->pack_id == id)
470                         t->pack_id = MAX_PACK_ID;
471 }
472
473 static unsigned int hc_str(const char *s, size_t len)
474 {
475         unsigned int r = 0;
476         while (len-- > 0)
477                 r = r * 31 + *s++;
478         return r;
479 }
480
481 static char *pool_strdup(const char *s)
482 {
483         size_t len = strlen(s) + 1;
484         char *r = mem_pool_alloc(&fi_mem_pool, len);
485         memcpy(r, s, len);
486         return r;
487 }
488
489 static void insert_mark(uintmax_t idnum, struct object_entry *oe)
490 {
491         struct mark_set *s = marks;
492         while ((idnum >> s->shift) >= 1024) {
493                 s = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct mark_set));
494                 s->shift = marks->shift + 10;
495                 s->data.sets[0] = marks;
496                 marks = s;
497         }
498         while (s->shift) {
499                 uintmax_t i = idnum >> s->shift;
500                 idnum -= i << s->shift;
501                 if (!s->data.sets[i]) {
502                         s->data.sets[i] = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct mark_set));
503                         s->data.sets[i]->shift = s->shift - 10;
504                 }
505                 s = s->data.sets[i];
506         }
507         if (!s->data.marked[idnum])
508                 marks_set_count++;
509         s->data.marked[idnum] = oe;
510 }
511
512 static struct object_entry *find_mark(uintmax_t idnum)
513 {
514         uintmax_t orig_idnum = idnum;
515         struct mark_set *s = marks;
516         struct object_entry *oe = NULL;
517         if ((idnum >> s->shift) < 1024) {
518                 while (s && s->shift) {
519                         uintmax_t i = idnum >> s->shift;
520                         idnum -= i << s->shift;
521                         s = s->data.sets[i];
522                 }
523                 if (s)
524                         oe = s->data.marked[idnum];
525         }
526         if (!oe)
527                 die("mark :%" PRIuMAX " not declared", orig_idnum);
528         return oe;
529 }
530
531 static struct atom_str *to_atom(const char *s, unsigned short len)
532 {
533         unsigned int hc = hc_str(s, len) % atom_table_sz;
534         struct atom_str *c;
535
536         for (c = atom_table[hc]; c; c = c->next_atom)
537                 if (c->str_len == len && !strncmp(s, c->str_dat, len))
538                         return c;
539
540         c = mem_pool_alloc(&fi_mem_pool, sizeof(struct atom_str) + len + 1);
541         c->str_len = len;
542         memcpy(c->str_dat, s, len);
543         c->str_dat[len] = 0;
544         c->next_atom = atom_table[hc];
545         atom_table[hc] = c;
546         atom_cnt++;
547         return c;
548 }
549
550 static struct branch *lookup_branch(const char *name)
551 {
552         unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
553         struct branch *b;
554
555         for (b = branch_table[hc]; b; b = b->table_next_branch)
556                 if (!strcmp(name, b->name))
557                         return b;
558         return NULL;
559 }
560
561 static struct branch *new_branch(const char *name)
562 {
563         unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
564         struct branch *b = lookup_branch(name);
565
566         if (b)
567                 die("Invalid attempt to create duplicate branch: %s", name);
568         if (check_refname_format(name, REFNAME_ALLOW_ONELEVEL))
569                 die("Branch name doesn't conform to GIT standards: %s", name);
570
571         b = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct branch));
572         b->name = pool_strdup(name);
573         b->table_next_branch = branch_table[hc];
574         b->branch_tree.versions[0].mode = S_IFDIR;
575         b->branch_tree.versions[1].mode = S_IFDIR;
576         b->num_notes = 0;
577         b->active = 0;
578         b->pack_id = MAX_PACK_ID;
579         branch_table[hc] = b;
580         branch_count++;
581         return b;
582 }
583
584 static unsigned int hc_entries(unsigned int cnt)
585 {
586         cnt = cnt & 7 ? (cnt / 8) + 1 : cnt / 8;
587         return cnt < avail_tree_table_sz ? cnt : avail_tree_table_sz - 1;
588 }
589
590 static struct tree_content *new_tree_content(unsigned int cnt)
591 {
592         struct avail_tree_content *f, *l = NULL;
593         struct tree_content *t;
594         unsigned int hc = hc_entries(cnt);
595
596         for (f = avail_tree_table[hc]; f; l = f, f = f->next_avail)
597                 if (f->entry_capacity >= cnt)
598                         break;
599
600         if (f) {
601                 if (l)
602                         l->next_avail = f->next_avail;
603                 else
604                         avail_tree_table[hc] = f->next_avail;
605         } else {
606                 cnt = cnt & 7 ? ((cnt / 8) + 1) * 8 : cnt;
607                 f = mem_pool_alloc(&fi_mem_pool, sizeof(*t) + sizeof(t->entries[0]) * cnt);
608                 f->entry_capacity = cnt;
609         }
610
611         t = (struct tree_content*)f;
612         t->entry_count = 0;
613         t->delta_depth = 0;
614         return t;
615 }
616
617 static void release_tree_entry(struct tree_entry *e);
618 static void release_tree_content(struct tree_content *t)
619 {
620         struct avail_tree_content *f = (struct avail_tree_content*)t;
621         unsigned int hc = hc_entries(f->entry_capacity);
622         f->next_avail = avail_tree_table[hc];
623         avail_tree_table[hc] = f;
624 }
625
626 static void release_tree_content_recursive(struct tree_content *t)
627 {
628         unsigned int i;
629         for (i = 0; i < t->entry_count; i++)
630                 release_tree_entry(t->entries[i]);
631         release_tree_content(t);
632 }
633
634 static struct tree_content *grow_tree_content(
635         struct tree_content *t,
636         int amt)
637 {
638         struct tree_content *r = new_tree_content(t->entry_count + amt);
639         r->entry_count = t->entry_count;
640         r->delta_depth = t->delta_depth;
641         memcpy(r->entries,t->entries,t->entry_count*sizeof(t->entries[0]));
642         release_tree_content(t);
643         return r;
644 }
645
646 static struct tree_entry *new_tree_entry(void)
647 {
648         struct tree_entry *e;
649
650         if (!avail_tree_entry) {
651                 unsigned int n = tree_entry_alloc;
652                 tree_entry_allocd += n * sizeof(struct tree_entry);
653                 ALLOC_ARRAY(e, n);
654                 avail_tree_entry = e;
655                 while (n-- > 1) {
656                         *((void**)e) = e + 1;
657                         e++;
658                 }
659                 *((void**)e) = NULL;
660         }
661
662         e = avail_tree_entry;
663         avail_tree_entry = *((void**)e);
664         return e;
665 }
666
667 static void release_tree_entry(struct tree_entry *e)
668 {
669         if (e->tree)
670                 release_tree_content_recursive(e->tree);
671         *((void**)e) = avail_tree_entry;
672         avail_tree_entry = e;
673 }
674
675 static struct tree_content *dup_tree_content(struct tree_content *s)
676 {
677         struct tree_content *d;
678         struct tree_entry *a, *b;
679         unsigned int i;
680
681         if (!s)
682                 return NULL;
683         d = new_tree_content(s->entry_count);
684         for (i = 0; i < s->entry_count; i++) {
685                 a = s->entries[i];
686                 b = new_tree_entry();
687                 memcpy(b, a, sizeof(*a));
688                 if (a->tree && is_null_oid(&b->versions[1].oid))
689                         b->tree = dup_tree_content(a->tree);
690                 else
691                         b->tree = NULL;
692                 d->entries[i] = b;
693         }
694         d->entry_count = s->entry_count;
695         d->delta_depth = s->delta_depth;
696
697         return d;
698 }
699
700 static void start_packfile(void)
701 {
702         struct strbuf tmp_file = STRBUF_INIT;
703         struct packed_git *p;
704         struct pack_header hdr;
705         int pack_fd;
706
707         pack_fd = odb_mkstemp(&tmp_file, "pack/tmp_pack_XXXXXX");
708         FLEX_ALLOC_STR(p, pack_name, tmp_file.buf);
709         strbuf_release(&tmp_file);
710
711         p->pack_fd = pack_fd;
712         p->do_not_close = 1;
713         pack_file = hashfd(pack_fd, p->pack_name);
714
715         hdr.hdr_signature = htonl(PACK_SIGNATURE);
716         hdr.hdr_version = htonl(2);
717         hdr.hdr_entries = 0;
718         hashwrite(pack_file, &hdr, sizeof(hdr));
719
720         pack_data = p;
721         pack_size = sizeof(hdr);
722         object_count = 0;
723
724         REALLOC_ARRAY(all_packs, pack_id + 1);
725         all_packs[pack_id] = p;
726 }
727
728 static const char *create_index(void)
729 {
730         const char *tmpfile;
731         struct pack_idx_entry **idx, **c, **last;
732         struct object_entry *e;
733         struct object_entry_pool *o;
734
735         /* Build the table of object IDs. */
736         ALLOC_ARRAY(idx, object_count);
737         c = idx;
738         for (o = blocks; o; o = o->next_pool)
739                 for (e = o->next_free; e-- != o->entries;)
740                         if (pack_id == e->pack_id)
741                                 *c++ = &e->idx;
742         last = idx + object_count;
743         if (c != last)
744                 die("internal consistency error creating the index");
745
746         tmpfile = write_idx_file(NULL, idx, object_count, &pack_idx_opts, pack_data->sha1);
747         free(idx);
748         return tmpfile;
749 }
750
751 static char *keep_pack(const char *curr_index_name)
752 {
753         static const char *keep_msg = "fast-import";
754         struct strbuf name = STRBUF_INIT;
755         int keep_fd;
756
757         odb_pack_name(&name, pack_data->sha1, "keep");
758         keep_fd = odb_pack_keep(name.buf);
759         if (keep_fd < 0)
760                 die_errno("cannot create keep file");
761         write_or_die(keep_fd, keep_msg, strlen(keep_msg));
762         if (close(keep_fd))
763                 die_errno("failed to write keep file");
764
765         odb_pack_name(&name, pack_data->sha1, "pack");
766         if (finalize_object_file(pack_data->pack_name, name.buf))
767                 die("cannot store pack file");
768
769         odb_pack_name(&name, pack_data->sha1, "idx");
770         if (finalize_object_file(curr_index_name, name.buf))
771                 die("cannot store index file");
772         free((void *)curr_index_name);
773         return strbuf_detach(&name, NULL);
774 }
775
776 static void unkeep_all_packs(void)
777 {
778         struct strbuf name = STRBUF_INIT;
779         int k;
780
781         for (k = 0; k < pack_id; k++) {
782                 struct packed_git *p = all_packs[k];
783                 odb_pack_name(&name, p->sha1, "keep");
784                 unlink_or_warn(name.buf);
785         }
786         strbuf_release(&name);
787 }
788
789 static int loosen_small_pack(const struct packed_git *p)
790 {
791         struct child_process unpack = CHILD_PROCESS_INIT;
792
793         if (lseek(p->pack_fd, 0, SEEK_SET) < 0)
794                 die_errno("Failed seeking to start of '%s'", p->pack_name);
795
796         unpack.in = p->pack_fd;
797         unpack.git_cmd = 1;
798         unpack.stdout_to_stderr = 1;
799         argv_array_push(&unpack.args, "unpack-objects");
800         if (!show_stats)
801                 argv_array_push(&unpack.args, "-q");
802
803         return run_command(&unpack);
804 }
805
806 static void end_packfile(void)
807 {
808         static int running;
809
810         if (running || !pack_data)
811                 return;
812
813         running = 1;
814         clear_delta_base_cache();
815         if (object_count) {
816                 struct packed_git *new_p;
817                 struct object_id cur_pack_oid;
818                 char *idx_name;
819                 int i;
820                 struct branch *b;
821                 struct tag *t;
822
823                 close_pack_windows(pack_data);
824                 finalize_hashfile(pack_file, cur_pack_oid.hash, 0);
825                 fixup_pack_header_footer(pack_data->pack_fd, pack_data->sha1,
826                                     pack_data->pack_name, object_count,
827                                     cur_pack_oid.hash, pack_size);
828
829                 if (object_count <= unpack_limit) {
830                         if (!loosen_small_pack(pack_data)) {
831                                 invalidate_pack_id(pack_id);
832                                 goto discard_pack;
833                         }
834                 }
835
836                 close(pack_data->pack_fd);
837                 idx_name = keep_pack(create_index());
838
839                 /* Register the packfile with core git's machinery. */
840                 new_p = add_packed_git(idx_name, strlen(idx_name), 1);
841                 if (!new_p)
842                         die("core git rejected index %s", idx_name);
843                 all_packs[pack_id] = new_p;
844                 install_packed_git(the_repository, new_p);
845                 free(idx_name);
846
847                 /* Print the boundary */
848                 if (pack_edges) {
849                         fprintf(pack_edges, "%s:", new_p->pack_name);
850                         for (i = 0; i < branch_table_sz; i++) {
851                                 for (b = branch_table[i]; b; b = b->table_next_branch) {
852                                         if (b->pack_id == pack_id)
853                                                 fprintf(pack_edges, " %s",
854                                                         oid_to_hex(&b->oid));
855                                 }
856                         }
857                         for (t = first_tag; t; t = t->next_tag) {
858                                 if (t->pack_id == pack_id)
859                                         fprintf(pack_edges, " %s",
860                                                 oid_to_hex(&t->oid));
861                         }
862                         fputc('\n', pack_edges);
863                         fflush(pack_edges);
864                 }
865
866                 pack_id++;
867         }
868         else {
869 discard_pack:
870                 close(pack_data->pack_fd);
871                 unlink_or_warn(pack_data->pack_name);
872         }
873         FREE_AND_NULL(pack_data);
874         running = 0;
875
876         /* We can't carry a delta across packfiles. */
877         strbuf_release(&last_blob.data);
878         last_blob.offset = 0;
879         last_blob.depth = 0;
880 }
881
882 static void cycle_packfile(void)
883 {
884         end_packfile();
885         start_packfile();
886 }
887
888 static int store_object(
889         enum object_type type,
890         struct strbuf *dat,
891         struct last_object *last,
892         struct object_id *oidout,
893         uintmax_t mark)
894 {
895         void *out, *delta;
896         struct object_entry *e;
897         unsigned char hdr[96];
898         struct object_id oid;
899         unsigned long hdrlen, deltalen;
900         git_hash_ctx c;
901         git_zstream s;
902
903         hdrlen = xsnprintf((char *)hdr, sizeof(hdr), "%s %lu",
904                            type_name(type), (unsigned long)dat->len) + 1;
905         the_hash_algo->init_fn(&c);
906         the_hash_algo->update_fn(&c, hdr, hdrlen);
907         the_hash_algo->update_fn(&c, dat->buf, dat->len);
908         the_hash_algo->final_fn(oid.hash, &c);
909         if (oidout)
910                 oidcpy(oidout, &oid);
911
912         e = insert_object(&oid);
913         if (mark)
914                 insert_mark(mark, e);
915         if (e->idx.offset) {
916                 duplicate_count_by_type[type]++;
917                 return 1;
918         } else if (find_sha1_pack(oid.hash,
919                                   get_all_packs(the_repository))) {
920                 e->type = type;
921                 e->pack_id = MAX_PACK_ID;
922                 e->idx.offset = 1; /* just not zero! */
923                 duplicate_count_by_type[type]++;
924                 return 1;
925         }
926
927         if (last && last->data.len && last->data.buf && last->depth < max_depth
928                 && dat->len > the_hash_algo->rawsz) {
929
930                 delta_count_attempts_by_type[type]++;
931                 delta = diff_delta(last->data.buf, last->data.len,
932                         dat->buf, dat->len,
933                         &deltalen, dat->len - the_hash_algo->rawsz);
934         } else
935                 delta = NULL;
936
937         git_deflate_init(&s, pack_compression_level);
938         if (delta) {
939                 s.next_in = delta;
940                 s.avail_in = deltalen;
941         } else {
942                 s.next_in = (void *)dat->buf;
943                 s.avail_in = dat->len;
944         }
945         s.avail_out = git_deflate_bound(&s, s.avail_in);
946         s.next_out = out = xmalloc(s.avail_out);
947         while (git_deflate(&s, Z_FINISH) == Z_OK)
948                 ; /* nothing */
949         git_deflate_end(&s);
950
951         /* Determine if we should auto-checkpoint. */
952         if ((max_packsize && (pack_size + 60 + s.total_out) > max_packsize)
953                 || (pack_size + 60 + s.total_out) < pack_size) {
954
955                 /* This new object needs to *not* have the current pack_id. */
956                 e->pack_id = pack_id + 1;
957                 cycle_packfile();
958
959                 /* We cannot carry a delta into the new pack. */
960                 if (delta) {
961                         FREE_AND_NULL(delta);
962
963                         git_deflate_init(&s, pack_compression_level);
964                         s.next_in = (void *)dat->buf;
965                         s.avail_in = dat->len;
966                         s.avail_out = git_deflate_bound(&s, s.avail_in);
967                         s.next_out = out = xrealloc(out, s.avail_out);
968                         while (git_deflate(&s, Z_FINISH) == Z_OK)
969                                 ; /* nothing */
970                         git_deflate_end(&s);
971                 }
972         }
973
974         e->type = type;
975         e->pack_id = pack_id;
976         e->idx.offset = pack_size;
977         object_count++;
978         object_count_by_type[type]++;
979
980         crc32_begin(pack_file);
981
982         if (delta) {
983                 off_t ofs = e->idx.offset - last->offset;
984                 unsigned pos = sizeof(hdr) - 1;
985
986                 delta_count_by_type[type]++;
987                 e->depth = last->depth + 1;
988
989                 hdrlen = encode_in_pack_object_header(hdr, sizeof(hdr),
990                                                       OBJ_OFS_DELTA, deltalen);
991                 hashwrite(pack_file, hdr, hdrlen);
992                 pack_size += hdrlen;
993
994                 hdr[pos] = ofs & 127;
995                 while (ofs >>= 7)
996                         hdr[--pos] = 128 | (--ofs & 127);
997                 hashwrite(pack_file, hdr + pos, sizeof(hdr) - pos);
998                 pack_size += sizeof(hdr) - pos;
999         } else {
1000                 e->depth = 0;
1001                 hdrlen = encode_in_pack_object_header(hdr, sizeof(hdr),
1002                                                       type, dat->len);
1003                 hashwrite(pack_file, hdr, hdrlen);
1004                 pack_size += hdrlen;
1005         }
1006
1007         hashwrite(pack_file, out, s.total_out);
1008         pack_size += s.total_out;
1009
1010         e->idx.crc32 = crc32_end(pack_file);
1011
1012         free(out);
1013         free(delta);
1014         if (last) {
1015                 if (last->no_swap) {
1016                         last->data = *dat;
1017                 } else {
1018                         strbuf_swap(&last->data, dat);
1019                 }
1020                 last->offset = e->idx.offset;
1021                 last->depth = e->depth;
1022         }
1023         return 0;
1024 }
1025
1026 static void truncate_pack(struct hashfile_checkpoint *checkpoint)
1027 {
1028         if (hashfile_truncate(pack_file, checkpoint))
1029                 die_errno("cannot truncate pack to skip duplicate");
1030         pack_size = checkpoint->offset;
1031 }
1032
1033 static void stream_blob(uintmax_t len, struct object_id *oidout, uintmax_t mark)
1034 {
1035         size_t in_sz = 64 * 1024, out_sz = 64 * 1024;
1036         unsigned char *in_buf = xmalloc(in_sz);
1037         unsigned char *out_buf = xmalloc(out_sz);
1038         struct object_entry *e;
1039         struct object_id oid;
1040         unsigned long hdrlen;
1041         off_t offset;
1042         git_hash_ctx c;
1043         git_zstream s;
1044         struct hashfile_checkpoint checkpoint;
1045         int status = Z_OK;
1046
1047         /* Determine if we should auto-checkpoint. */
1048         if ((max_packsize && (pack_size + 60 + len) > max_packsize)
1049                 || (pack_size + 60 + len) < pack_size)
1050                 cycle_packfile();
1051
1052         hashfile_checkpoint(pack_file, &checkpoint);
1053         offset = checkpoint.offset;
1054
1055         hdrlen = xsnprintf((char *)out_buf, out_sz, "blob %" PRIuMAX, len) + 1;
1056
1057         the_hash_algo->init_fn(&c);
1058         the_hash_algo->update_fn(&c, out_buf, hdrlen);
1059
1060         crc32_begin(pack_file);
1061
1062         git_deflate_init(&s, pack_compression_level);
1063
1064         hdrlen = encode_in_pack_object_header(out_buf, out_sz, OBJ_BLOB, len);
1065
1066         s.next_out = out_buf + hdrlen;
1067         s.avail_out = out_sz - hdrlen;
1068
1069         while (status != Z_STREAM_END) {
1070                 if (0 < len && !s.avail_in) {
1071                         size_t cnt = in_sz < len ? in_sz : (size_t)len;
1072                         size_t n = fread(in_buf, 1, cnt, stdin);
1073                         if (!n && feof(stdin))
1074                                 die("EOF in data (%" PRIuMAX " bytes remaining)", len);
1075
1076                         the_hash_algo->update_fn(&c, in_buf, n);
1077                         s.next_in = in_buf;
1078                         s.avail_in = n;
1079                         len -= n;
1080                 }
1081
1082                 status = git_deflate(&s, len ? 0 : Z_FINISH);
1083
1084                 if (!s.avail_out || status == Z_STREAM_END) {
1085                         size_t n = s.next_out - out_buf;
1086                         hashwrite(pack_file, out_buf, n);
1087                         pack_size += n;
1088                         s.next_out = out_buf;
1089                         s.avail_out = out_sz;
1090                 }
1091
1092                 switch (status) {
1093                 case Z_OK:
1094                 case Z_BUF_ERROR:
1095                 case Z_STREAM_END:
1096                         continue;
1097                 default:
1098                         die("unexpected deflate failure: %d", status);
1099                 }
1100         }
1101         git_deflate_end(&s);
1102         the_hash_algo->final_fn(oid.hash, &c);
1103
1104         if (oidout)
1105                 oidcpy(oidout, &oid);
1106
1107         e = insert_object(&oid);
1108
1109         if (mark)
1110                 insert_mark(mark, e);
1111
1112         if (e->idx.offset) {
1113                 duplicate_count_by_type[OBJ_BLOB]++;
1114                 truncate_pack(&checkpoint);
1115
1116         } else if (find_sha1_pack(oid.hash,
1117                                   get_all_packs(the_repository))) {
1118                 e->type = OBJ_BLOB;
1119                 e->pack_id = MAX_PACK_ID;
1120                 e->idx.offset = 1; /* just not zero! */
1121                 duplicate_count_by_type[OBJ_BLOB]++;
1122                 truncate_pack(&checkpoint);
1123
1124         } else {
1125                 e->depth = 0;
1126                 e->type = OBJ_BLOB;
1127                 e->pack_id = pack_id;
1128                 e->idx.offset = offset;
1129                 e->idx.crc32 = crc32_end(pack_file);
1130                 object_count++;
1131                 object_count_by_type[OBJ_BLOB]++;
1132         }
1133
1134         free(in_buf);
1135         free(out_buf);
1136 }
1137
1138 /* All calls must be guarded by find_object() or find_mark() to
1139  * ensure the 'struct object_entry' passed was written by this
1140  * process instance.  We unpack the entry by the offset, avoiding
1141  * the need for the corresponding .idx file.  This unpacking rule
1142  * works because we only use OBJ_REF_DELTA within the packfiles
1143  * created by fast-import.
1144  *
1145  * oe must not be NULL.  Such an oe usually comes from giving
1146  * an unknown SHA-1 to find_object() or an undefined mark to
1147  * find_mark().  Callers must test for this condition and use
1148  * the standard read_sha1_file() when it happens.
1149  *
1150  * oe->pack_id must not be MAX_PACK_ID.  Such an oe is usually from
1151  * find_mark(), where the mark was reloaded from an existing marks
1152  * file and is referencing an object that this fast-import process
1153  * instance did not write out to a packfile.  Callers must test for
1154  * this condition and use read_sha1_file() instead.
1155  */
1156 static void *gfi_unpack_entry(
1157         struct object_entry *oe,
1158         unsigned long *sizep)
1159 {
1160         enum object_type type;
1161         struct packed_git *p = all_packs[oe->pack_id];
1162         if (p == pack_data && p->pack_size < (pack_size + the_hash_algo->rawsz)) {
1163                 /* The object is stored in the packfile we are writing to
1164                  * and we have modified it since the last time we scanned
1165                  * back to read a previously written object.  If an old
1166                  * window covered [p->pack_size, p->pack_size + rawsz) its
1167                  * data is stale and is not valid.  Closing all windows
1168                  * and updating the packfile length ensures we can read
1169                  * the newly written data.
1170                  */
1171                 close_pack_windows(p);
1172                 hashflush(pack_file);
1173
1174                 /* We have to offer rawsz bytes additional on the end of
1175                  * the packfile as the core unpacker code assumes the
1176                  * footer is present at the file end and must promise
1177                  * at least rawsz bytes within any window it maps.  But
1178                  * we don't actually create the footer here.
1179                  */
1180                 p->pack_size = pack_size + the_hash_algo->rawsz;
1181         }
1182         return unpack_entry(the_repository, p, oe->idx.offset, &type, sizep);
1183 }
1184
1185 static const char *get_mode(const char *str, uint16_t *modep)
1186 {
1187         unsigned char c;
1188         uint16_t mode = 0;
1189
1190         while ((c = *str++) != ' ') {
1191                 if (c < '0' || c > '7')
1192                         return NULL;
1193                 mode = (mode << 3) + (c - '0');
1194         }
1195         *modep = mode;
1196         return str;
1197 }
1198
1199 static void load_tree(struct tree_entry *root)
1200 {
1201         struct object_id *oid = &root->versions[1].oid;
1202         struct object_entry *myoe;
1203         struct tree_content *t;
1204         unsigned long size;
1205         char *buf;
1206         const char *c;
1207
1208         root->tree = t = new_tree_content(8);
1209         if (is_null_oid(oid))
1210                 return;
1211
1212         myoe = find_object(oid);
1213         if (myoe && myoe->pack_id != MAX_PACK_ID) {
1214                 if (myoe->type != OBJ_TREE)
1215                         die("Not a tree: %s", oid_to_hex(oid));
1216                 t->delta_depth = myoe->depth;
1217                 buf = gfi_unpack_entry(myoe, &size);
1218                 if (!buf)
1219                         die("Can't load tree %s", oid_to_hex(oid));
1220         } else {
1221                 enum object_type type;
1222                 buf = read_object_file(oid, &type, &size);
1223                 if (!buf || type != OBJ_TREE)
1224                         die("Can't load tree %s", oid_to_hex(oid));
1225         }
1226
1227         c = buf;
1228         while (c != (buf + size)) {
1229                 struct tree_entry *e = new_tree_entry();
1230
1231                 if (t->entry_count == t->entry_capacity)
1232                         root->tree = t = grow_tree_content(t, t->entry_count);
1233                 t->entries[t->entry_count++] = e;
1234
1235                 e->tree = NULL;
1236                 c = get_mode(c, &e->versions[1].mode);
1237                 if (!c)
1238                         die("Corrupt mode in %s", oid_to_hex(oid));
1239                 e->versions[0].mode = e->versions[1].mode;
1240                 e->name = to_atom(c, strlen(c));
1241                 c += e->name->str_len + 1;
1242                 hashcpy(e->versions[0].oid.hash, (unsigned char *)c);
1243                 hashcpy(e->versions[1].oid.hash, (unsigned char *)c);
1244                 c += GIT_SHA1_RAWSZ;
1245         }
1246         free(buf);
1247 }
1248
1249 static int tecmp0 (const void *_a, const void *_b)
1250 {
1251         struct tree_entry *a = *((struct tree_entry**)_a);
1252         struct tree_entry *b = *((struct tree_entry**)_b);
1253         return base_name_compare(
1254                 a->name->str_dat, a->name->str_len, a->versions[0].mode,
1255                 b->name->str_dat, b->name->str_len, b->versions[0].mode);
1256 }
1257
1258 static int tecmp1 (const void *_a, const void *_b)
1259 {
1260         struct tree_entry *a = *((struct tree_entry**)_a);
1261         struct tree_entry *b = *((struct tree_entry**)_b);
1262         return base_name_compare(
1263                 a->name->str_dat, a->name->str_len, a->versions[1].mode,
1264                 b->name->str_dat, b->name->str_len, b->versions[1].mode);
1265 }
1266
1267 static void mktree(struct tree_content *t, int v, struct strbuf *b)
1268 {
1269         size_t maxlen = 0;
1270         unsigned int i;
1271
1272         if (!v)
1273                 QSORT(t->entries, t->entry_count, tecmp0);
1274         else
1275                 QSORT(t->entries, t->entry_count, tecmp1);
1276
1277         for (i = 0; i < t->entry_count; i++) {
1278                 if (t->entries[i]->versions[v].mode)
1279                         maxlen += t->entries[i]->name->str_len + 34;
1280         }
1281
1282         strbuf_reset(b);
1283         strbuf_grow(b, maxlen);
1284         for (i = 0; i < t->entry_count; i++) {
1285                 struct tree_entry *e = t->entries[i];
1286                 if (!e->versions[v].mode)
1287                         continue;
1288                 strbuf_addf(b, "%o %s%c",
1289                         (unsigned int)(e->versions[v].mode & ~NO_DELTA),
1290                         e->name->str_dat, '\0');
1291                 strbuf_add(b, e->versions[v].oid.hash, GIT_SHA1_RAWSZ);
1292         }
1293 }
1294
1295 static void store_tree(struct tree_entry *root)
1296 {
1297         struct tree_content *t;
1298         unsigned int i, j, del;
1299         struct last_object lo = { STRBUF_INIT, 0, 0, /* no_swap */ 1 };
1300         struct object_entry *le = NULL;
1301
1302         if (!is_null_oid(&root->versions[1].oid))
1303                 return;
1304
1305         if (!root->tree)
1306                 load_tree(root);
1307         t = root->tree;
1308
1309         for (i = 0; i < t->entry_count; i++) {
1310                 if (t->entries[i]->tree)
1311                         store_tree(t->entries[i]);
1312         }
1313
1314         if (!(root->versions[0].mode & NO_DELTA))
1315                 le = find_object(&root->versions[0].oid);
1316         if (S_ISDIR(root->versions[0].mode) && le && le->pack_id == pack_id) {
1317                 mktree(t, 0, &old_tree);
1318                 lo.data = old_tree;
1319                 lo.offset = le->idx.offset;
1320                 lo.depth = t->delta_depth;
1321         }
1322
1323         mktree(t, 1, &new_tree);
1324         store_object(OBJ_TREE, &new_tree, &lo, &root->versions[1].oid, 0);
1325
1326         t->delta_depth = lo.depth;
1327         for (i = 0, j = 0, del = 0; i < t->entry_count; i++) {
1328                 struct tree_entry *e = t->entries[i];
1329                 if (e->versions[1].mode) {
1330                         e->versions[0].mode = e->versions[1].mode;
1331                         oidcpy(&e->versions[0].oid, &e->versions[1].oid);
1332                         t->entries[j++] = e;
1333                 } else {
1334                         release_tree_entry(e);
1335                         del++;
1336                 }
1337         }
1338         t->entry_count -= del;
1339 }
1340
1341 static void tree_content_replace(
1342         struct tree_entry *root,
1343         const struct object_id *oid,
1344         const uint16_t mode,
1345         struct tree_content *newtree)
1346 {
1347         if (!S_ISDIR(mode))
1348                 die("Root cannot be a non-directory");
1349         oidclr(&root->versions[0].oid);
1350         oidcpy(&root->versions[1].oid, oid);
1351         if (root->tree)
1352                 release_tree_content_recursive(root->tree);
1353         root->tree = newtree;
1354 }
1355
1356 static int tree_content_set(
1357         struct tree_entry *root,
1358         const char *p,
1359         const struct object_id *oid,
1360         const uint16_t mode,
1361         struct tree_content *subtree)
1362 {
1363         struct tree_content *t;
1364         const char *slash1;
1365         unsigned int i, n;
1366         struct tree_entry *e;
1367
1368         slash1 = strchrnul(p, '/');
1369         n = slash1 - p;
1370         if (!n)
1371                 die("Empty path component found in input");
1372         if (!*slash1 && !S_ISDIR(mode) && subtree)
1373                 die("Non-directories cannot have subtrees");
1374
1375         if (!root->tree)
1376                 load_tree(root);
1377         t = root->tree;
1378         for (i = 0; i < t->entry_count; i++) {
1379                 e = t->entries[i];
1380                 if (e->name->str_len == n && !fspathncmp(p, e->name->str_dat, n)) {
1381                         if (!*slash1) {
1382                                 if (!S_ISDIR(mode)
1383                                                 && e->versions[1].mode == mode
1384                                                 && oideq(&e->versions[1].oid, oid))
1385                                         return 0;
1386                                 e->versions[1].mode = mode;
1387                                 oidcpy(&e->versions[1].oid, oid);
1388                                 if (e->tree)
1389                                         release_tree_content_recursive(e->tree);
1390                                 e->tree = subtree;
1391
1392                                 /*
1393                                  * We need to leave e->versions[0].sha1 alone
1394                                  * to avoid modifying the preimage tree used
1395                                  * when writing out the parent directory.
1396                                  * But after replacing the subdir with a
1397                                  * completely different one, it's not a good
1398                                  * delta base any more, and besides, we've
1399                                  * thrown away the tree entries needed to
1400                                  * make a delta against it.
1401                                  *
1402                                  * So let's just explicitly disable deltas
1403                                  * for the subtree.
1404                                  */
1405                                 if (S_ISDIR(e->versions[0].mode))
1406                                         e->versions[0].mode |= NO_DELTA;
1407
1408                                 oidclr(&root->versions[1].oid);
1409                                 return 1;
1410                         }
1411                         if (!S_ISDIR(e->versions[1].mode)) {
1412                                 e->tree = new_tree_content(8);
1413                                 e->versions[1].mode = S_IFDIR;
1414                         }
1415                         if (!e->tree)
1416                                 load_tree(e);
1417                         if (tree_content_set(e, slash1 + 1, oid, mode, subtree)) {
1418                                 oidclr(&root->versions[1].oid);
1419                                 return 1;
1420                         }
1421                         return 0;
1422                 }
1423         }
1424
1425         if (t->entry_count == t->entry_capacity)
1426                 root->tree = t = grow_tree_content(t, t->entry_count);
1427         e = new_tree_entry();
1428         e->name = to_atom(p, n);
1429         e->versions[0].mode = 0;
1430         oidclr(&e->versions[0].oid);
1431         t->entries[t->entry_count++] = e;
1432         if (*slash1) {
1433                 e->tree = new_tree_content(8);
1434                 e->versions[1].mode = S_IFDIR;
1435                 tree_content_set(e, slash1 + 1, oid, mode, subtree);
1436         } else {
1437                 e->tree = subtree;
1438                 e->versions[1].mode = mode;
1439                 oidcpy(&e->versions[1].oid, oid);
1440         }
1441         oidclr(&root->versions[1].oid);
1442         return 1;
1443 }
1444
1445 static int tree_content_remove(
1446         struct tree_entry *root,
1447         const char *p,
1448         struct tree_entry *backup_leaf,
1449         int allow_root)
1450 {
1451         struct tree_content *t;
1452         const char *slash1;
1453         unsigned int i, n;
1454         struct tree_entry *e;
1455
1456         slash1 = strchrnul(p, '/');
1457         n = slash1 - p;
1458
1459         if (!root->tree)
1460                 load_tree(root);
1461
1462         if (!*p && allow_root) {
1463                 e = root;
1464                 goto del_entry;
1465         }
1466
1467         t = root->tree;
1468         for (i = 0; i < t->entry_count; i++) {
1469                 e = t->entries[i];
1470                 if (e->name->str_len == n && !fspathncmp(p, e->name->str_dat, n)) {
1471                         if (*slash1 && !S_ISDIR(e->versions[1].mode))
1472                                 /*
1473                                  * If p names a file in some subdirectory, and a
1474                                  * file or symlink matching the name of the
1475                                  * parent directory of p exists, then p cannot
1476                                  * exist and need not be deleted.
1477                                  */
1478                                 return 1;
1479                         if (!*slash1 || !S_ISDIR(e->versions[1].mode))
1480                                 goto del_entry;
1481                         if (!e->tree)
1482                                 load_tree(e);
1483                         if (tree_content_remove(e, slash1 + 1, backup_leaf, 0)) {
1484                                 for (n = 0; n < e->tree->entry_count; n++) {
1485                                         if (e->tree->entries[n]->versions[1].mode) {
1486                                                 oidclr(&root->versions[1].oid);
1487                                                 return 1;
1488                                         }
1489                                 }
1490                                 backup_leaf = NULL;
1491                                 goto del_entry;
1492                         }
1493                         return 0;
1494                 }
1495         }
1496         return 0;
1497
1498 del_entry:
1499         if (backup_leaf)
1500                 memcpy(backup_leaf, e, sizeof(*backup_leaf));
1501         else if (e->tree)
1502                 release_tree_content_recursive(e->tree);
1503         e->tree = NULL;
1504         e->versions[1].mode = 0;
1505         oidclr(&e->versions[1].oid);
1506         oidclr(&root->versions[1].oid);
1507         return 1;
1508 }
1509
1510 static int tree_content_get(
1511         struct tree_entry *root,
1512         const char *p,
1513         struct tree_entry *leaf,
1514         int allow_root)
1515 {
1516         struct tree_content *t;
1517         const char *slash1;
1518         unsigned int i, n;
1519         struct tree_entry *e;
1520
1521         slash1 = strchrnul(p, '/');
1522         n = slash1 - p;
1523         if (!n && !allow_root)
1524                 die("Empty path component found in input");
1525
1526         if (!root->tree)
1527                 load_tree(root);
1528
1529         if (!n) {
1530                 e = root;
1531                 goto found_entry;
1532         }
1533
1534         t = root->tree;
1535         for (i = 0; i < t->entry_count; i++) {
1536                 e = t->entries[i];
1537                 if (e->name->str_len == n && !fspathncmp(p, e->name->str_dat, n)) {
1538                         if (!*slash1)
1539                                 goto found_entry;
1540                         if (!S_ISDIR(e->versions[1].mode))
1541                                 return 0;
1542                         if (!e->tree)
1543                                 load_tree(e);
1544                         return tree_content_get(e, slash1 + 1, leaf, 0);
1545                 }
1546         }
1547         return 0;
1548
1549 found_entry:
1550         memcpy(leaf, e, sizeof(*leaf));
1551         if (e->tree && is_null_oid(&e->versions[1].oid))
1552                 leaf->tree = dup_tree_content(e->tree);
1553         else
1554                 leaf->tree = NULL;
1555         return 1;
1556 }
1557
1558 static int update_branch(struct branch *b)
1559 {
1560         static const char *msg = "fast-import";
1561         struct ref_transaction *transaction;
1562         struct object_id old_oid;
1563         struct strbuf err = STRBUF_INIT;
1564
1565         if (is_null_oid(&b->oid)) {
1566                 if (b->delete)
1567                         delete_ref(NULL, b->name, NULL, 0);
1568                 return 0;
1569         }
1570         if (read_ref(b->name, &old_oid))
1571                 oidclr(&old_oid);
1572         if (!force_update && !is_null_oid(&old_oid)) {
1573                 struct commit *old_cmit, *new_cmit;
1574
1575                 old_cmit = lookup_commit_reference_gently(the_repository,
1576                                                           &old_oid, 0);
1577                 new_cmit = lookup_commit_reference_gently(the_repository,
1578                                                           &b->oid, 0);
1579                 if (!old_cmit || !new_cmit)
1580                         return error("Branch %s is missing commits.", b->name);
1581
1582                 if (!in_merge_bases(old_cmit, new_cmit)) {
1583                         warning("Not updating %s"
1584                                 " (new tip %s does not contain %s)",
1585                                 b->name, oid_to_hex(&b->oid),
1586                                 oid_to_hex(&old_oid));
1587                         return -1;
1588                 }
1589         }
1590         transaction = ref_transaction_begin(&err);
1591         if (!transaction ||
1592             ref_transaction_update(transaction, b->name, &b->oid, &old_oid,
1593                                    0, msg, &err) ||
1594             ref_transaction_commit(transaction, &err)) {
1595                 ref_transaction_free(transaction);
1596                 error("%s", err.buf);
1597                 strbuf_release(&err);
1598                 return -1;
1599         }
1600         ref_transaction_free(transaction);
1601         strbuf_release(&err);
1602         return 0;
1603 }
1604
1605 static void dump_branches(void)
1606 {
1607         unsigned int i;
1608         struct branch *b;
1609
1610         for (i = 0; i < branch_table_sz; i++) {
1611                 for (b = branch_table[i]; b; b = b->table_next_branch)
1612                         failure |= update_branch(b);
1613         }
1614 }
1615
1616 static void dump_tags(void)
1617 {
1618         static const char *msg = "fast-import";
1619         struct tag *t;
1620         struct strbuf ref_name = STRBUF_INIT;
1621         struct strbuf err = STRBUF_INIT;
1622         struct ref_transaction *transaction;
1623
1624         transaction = ref_transaction_begin(&err);
1625         if (!transaction) {
1626                 failure |= error("%s", err.buf);
1627                 goto cleanup;
1628         }
1629         for (t = first_tag; t; t = t->next_tag) {
1630                 strbuf_reset(&ref_name);
1631                 strbuf_addf(&ref_name, "refs/tags/%s", t->name);
1632
1633                 if (ref_transaction_update(transaction, ref_name.buf,
1634                                            &t->oid, NULL, 0, msg, &err)) {
1635                         failure |= error("%s", err.buf);
1636                         goto cleanup;
1637                 }
1638         }
1639         if (ref_transaction_commit(transaction, &err))
1640                 failure |= error("%s", err.buf);
1641
1642  cleanup:
1643         ref_transaction_free(transaction);
1644         strbuf_release(&ref_name);
1645         strbuf_release(&err);
1646 }
1647
1648 static void dump_marks_helper(FILE *f,
1649         uintmax_t base,
1650         struct mark_set *m)
1651 {
1652         uintmax_t k;
1653         if (m->shift) {
1654                 for (k = 0; k < 1024; k++) {
1655                         if (m->data.sets[k])
1656                                 dump_marks_helper(f, base + (k << m->shift),
1657                                         m->data.sets[k]);
1658                 }
1659         } else {
1660                 for (k = 0; k < 1024; k++) {
1661                         if (m->data.marked[k])
1662                                 fprintf(f, ":%" PRIuMAX " %s\n", base + k,
1663                                         oid_to_hex(&m->data.marked[k]->idx.oid));
1664                 }
1665         }
1666 }
1667
1668 static void dump_marks(void)
1669 {
1670         struct lock_file mark_lock = LOCK_INIT;
1671         FILE *f;
1672
1673         if (!export_marks_file || (import_marks_file && !import_marks_file_done))
1674                 return;
1675
1676         if (safe_create_leading_directories_const(export_marks_file)) {
1677                 failure |= error_errno("unable to create leading directories of %s",
1678                                        export_marks_file);
1679                 return;
1680         }
1681
1682         if (hold_lock_file_for_update(&mark_lock, export_marks_file, 0) < 0) {
1683                 failure |= error_errno("Unable to write marks file %s",
1684                                        export_marks_file);
1685                 return;
1686         }
1687
1688         f = fdopen_lock_file(&mark_lock, "w");
1689         if (!f) {
1690                 int saved_errno = errno;
1691                 rollback_lock_file(&mark_lock);
1692                 failure |= error("Unable to write marks file %s: %s",
1693                         export_marks_file, strerror(saved_errno));
1694                 return;
1695         }
1696
1697         dump_marks_helper(f, 0, marks);
1698         if (commit_lock_file(&mark_lock)) {
1699                 failure |= error_errno("Unable to write file %s",
1700                                        export_marks_file);
1701                 return;
1702         }
1703 }
1704
1705 static void read_marks(void)
1706 {
1707         char line[512];
1708         FILE *f = fopen(import_marks_file, "r");
1709         if (f)
1710                 ;
1711         else if (import_marks_file_ignore_missing && errno == ENOENT)
1712                 goto done; /* Marks file does not exist */
1713         else
1714                 die_errno("cannot read '%s'", import_marks_file);
1715         while (fgets(line, sizeof(line), f)) {
1716                 uintmax_t mark;
1717                 char *end;
1718                 struct object_id oid;
1719                 struct object_entry *e;
1720
1721                 end = strchr(line, '\n');
1722                 if (line[0] != ':' || !end)
1723                         die("corrupt mark line: %s", line);
1724                 *end = 0;
1725                 mark = strtoumax(line + 1, &end, 10);
1726                 if (!mark || end == line + 1
1727                         || *end != ' ' || get_oid_hex(end + 1, &oid))
1728                         die("corrupt mark line: %s", line);
1729                 e = find_object(&oid);
1730                 if (!e) {
1731                         enum object_type type = oid_object_info(the_repository,
1732                                                                 &oid, NULL);
1733                         if (type < 0)
1734                                 die("object not found: %s", oid_to_hex(&oid));
1735                         e = insert_object(&oid);
1736                         e->type = type;
1737                         e->pack_id = MAX_PACK_ID;
1738                         e->idx.offset = 1; /* just not zero! */
1739                 }
1740                 insert_mark(mark, e);
1741         }
1742         fclose(f);
1743 done:
1744         import_marks_file_done = 1;
1745 }
1746
1747
1748 static int read_next_command(void)
1749 {
1750         static int stdin_eof = 0;
1751
1752         if (stdin_eof) {
1753                 unread_command_buf = 0;
1754                 return EOF;
1755         }
1756
1757         for (;;) {
1758                 const char *p;
1759
1760                 if (unread_command_buf) {
1761                         unread_command_buf = 0;
1762                 } else {
1763                         struct recent_command *rc;
1764
1765                         strbuf_detach(&command_buf, NULL);
1766                         stdin_eof = strbuf_getline_lf(&command_buf, stdin);
1767                         if (stdin_eof)
1768                                 return EOF;
1769
1770                         if (!seen_data_command
1771                                 && !starts_with(command_buf.buf, "feature ")
1772                                 && !starts_with(command_buf.buf, "option ")) {
1773                                 parse_argv();
1774                         }
1775
1776                         rc = rc_free;
1777                         if (rc)
1778                                 rc_free = rc->next;
1779                         else {
1780                                 rc = cmd_hist.next;
1781                                 cmd_hist.next = rc->next;
1782                                 cmd_hist.next->prev = &cmd_hist;
1783                                 free(rc->buf);
1784                         }
1785
1786                         rc->buf = command_buf.buf;
1787                         rc->prev = cmd_tail;
1788                         rc->next = cmd_hist.prev;
1789                         rc->prev->next = rc;
1790                         cmd_tail = rc;
1791                 }
1792                 if (skip_prefix(command_buf.buf, "get-mark ", &p)) {
1793                         parse_get_mark(p);
1794                         continue;
1795                 }
1796                 if (skip_prefix(command_buf.buf, "cat-blob ", &p)) {
1797                         parse_cat_blob(p);
1798                         continue;
1799                 }
1800                 if (command_buf.buf[0] == '#')
1801                         continue;
1802                 return 0;
1803         }
1804 }
1805
1806 static void skip_optional_lf(void)
1807 {
1808         int term_char = fgetc(stdin);
1809         if (term_char != '\n' && term_char != EOF)
1810                 ungetc(term_char, stdin);
1811 }
1812
1813 static void parse_mark(void)
1814 {
1815         const char *v;
1816         if (skip_prefix(command_buf.buf, "mark :", &v)) {
1817                 next_mark = strtoumax(v, NULL, 10);
1818                 read_next_command();
1819         }
1820         else
1821                 next_mark = 0;
1822 }
1823
1824 static void parse_original_identifier(void)
1825 {
1826         const char *v;
1827         if (skip_prefix(command_buf.buf, "original-oid ", &v))
1828                 read_next_command();
1829 }
1830
1831 static int parse_data(struct strbuf *sb, uintmax_t limit, uintmax_t *len_res)
1832 {
1833         const char *data;
1834         strbuf_reset(sb);
1835
1836         if (!skip_prefix(command_buf.buf, "data ", &data))
1837                 die("Expected 'data n' command, found: %s", command_buf.buf);
1838
1839         if (skip_prefix(data, "<<", &data)) {
1840                 char *term = xstrdup(data);
1841                 size_t term_len = command_buf.len - (data - command_buf.buf);
1842
1843                 strbuf_detach(&command_buf, NULL);
1844                 for (;;) {
1845                         if (strbuf_getline_lf(&command_buf, stdin) == EOF)
1846                                 die("EOF in data (terminator '%s' not found)", term);
1847                         if (term_len == command_buf.len
1848                                 && !strcmp(term, command_buf.buf))
1849                                 break;
1850                         strbuf_addbuf(sb, &command_buf);
1851                         strbuf_addch(sb, '\n');
1852                 }
1853                 free(term);
1854         }
1855         else {
1856                 uintmax_t len = strtoumax(data, NULL, 10);
1857                 size_t n = 0, length = (size_t)len;
1858
1859                 if (limit && limit < len) {
1860                         *len_res = len;
1861                         return 0;
1862                 }
1863                 if (length < len)
1864                         die("data is too large to use in this context");
1865
1866                 while (n < length) {
1867                         size_t s = strbuf_fread(sb, length - n, stdin);
1868                         if (!s && feof(stdin))
1869                                 die("EOF in data (%lu bytes remaining)",
1870                                         (unsigned long)(length - n));
1871                         n += s;
1872                 }
1873         }
1874
1875         skip_optional_lf();
1876         return 1;
1877 }
1878
1879 static int validate_raw_date(const char *src, struct strbuf *result)
1880 {
1881         const char *orig_src = src;
1882         char *endp;
1883         unsigned long num;
1884
1885         errno = 0;
1886
1887         num = strtoul(src, &endp, 10);
1888         /* NEEDSWORK: perhaps check for reasonable values? */
1889         if (errno || endp == src || *endp != ' ')
1890                 return -1;
1891
1892         src = endp + 1;
1893         if (*src != '-' && *src != '+')
1894                 return -1;
1895
1896         num = strtoul(src + 1, &endp, 10);
1897         if (errno || endp == src + 1 || *endp || 1400 < num)
1898                 return -1;
1899
1900         strbuf_addstr(result, orig_src);
1901         return 0;
1902 }
1903
1904 static char *parse_ident(const char *buf)
1905 {
1906         const char *ltgt;
1907         size_t name_len;
1908         struct strbuf ident = STRBUF_INIT;
1909
1910         /* ensure there is a space delimiter even if there is no name */
1911         if (*buf == '<')
1912                 --buf;
1913
1914         ltgt = buf + strcspn(buf, "<>");
1915         if (*ltgt != '<')
1916                 die("Missing < in ident string: %s", buf);
1917         if (ltgt != buf && ltgt[-1] != ' ')
1918                 die("Missing space before < in ident string: %s", buf);
1919         ltgt = ltgt + 1 + strcspn(ltgt + 1, "<>");
1920         if (*ltgt != '>')
1921                 die("Missing > in ident string: %s", buf);
1922         ltgt++;
1923         if (*ltgt != ' ')
1924                 die("Missing space after > in ident string: %s", buf);
1925         ltgt++;
1926         name_len = ltgt - buf;
1927         strbuf_add(&ident, buf, name_len);
1928
1929         switch (whenspec) {
1930         case WHENSPEC_RAW:
1931                 if (validate_raw_date(ltgt, &ident) < 0)
1932                         die("Invalid raw date \"%s\" in ident: %s", ltgt, buf);
1933                 break;
1934         case WHENSPEC_RFC2822:
1935                 if (parse_date(ltgt, &ident) < 0)
1936                         die("Invalid rfc2822 date \"%s\" in ident: %s", ltgt, buf);
1937                 break;
1938         case WHENSPEC_NOW:
1939                 if (strcmp("now", ltgt))
1940                         die("Date in ident must be 'now': %s", buf);
1941                 datestamp(&ident);
1942                 break;
1943         }
1944
1945         return strbuf_detach(&ident, NULL);
1946 }
1947
1948 static void parse_and_store_blob(
1949         struct last_object *last,
1950         struct object_id *oidout,
1951         uintmax_t mark)
1952 {
1953         static struct strbuf buf = STRBUF_INIT;
1954         uintmax_t len;
1955
1956         if (parse_data(&buf, big_file_threshold, &len))
1957                 store_object(OBJ_BLOB, &buf, last, oidout, mark);
1958         else {
1959                 if (last) {
1960                         strbuf_release(&last->data);
1961                         last->offset = 0;
1962                         last->depth = 0;
1963                 }
1964                 stream_blob(len, oidout, mark);
1965                 skip_optional_lf();
1966         }
1967 }
1968
1969 static void parse_new_blob(void)
1970 {
1971         read_next_command();
1972         parse_mark();
1973         parse_original_identifier();
1974         parse_and_store_blob(&last_blob, NULL, next_mark);
1975 }
1976
1977 static void unload_one_branch(void)
1978 {
1979         while (cur_active_branches
1980                 && cur_active_branches >= max_active_branches) {
1981                 uintmax_t min_commit = ULONG_MAX;
1982                 struct branch *e, *l = NULL, *p = NULL;
1983
1984                 for (e = active_branches; e; e = e->active_next_branch) {
1985                         if (e->last_commit < min_commit) {
1986                                 p = l;
1987                                 min_commit = e->last_commit;
1988                         }
1989                         l = e;
1990                 }
1991
1992                 if (p) {
1993                         e = p->active_next_branch;
1994                         p->active_next_branch = e->active_next_branch;
1995                 } else {
1996                         e = active_branches;
1997                         active_branches = e->active_next_branch;
1998                 }
1999                 e->active = 0;
2000                 e->active_next_branch = NULL;
2001                 if (e->branch_tree.tree) {
2002                         release_tree_content_recursive(e->branch_tree.tree);
2003                         e->branch_tree.tree = NULL;
2004                 }
2005                 cur_active_branches--;
2006         }
2007 }
2008
2009 static void load_branch(struct branch *b)
2010 {
2011         load_tree(&b->branch_tree);
2012         if (!b->active) {
2013                 b->active = 1;
2014                 b->active_next_branch = active_branches;
2015                 active_branches = b;
2016                 cur_active_branches++;
2017                 branch_load_count++;
2018         }
2019 }
2020
2021 static unsigned char convert_num_notes_to_fanout(uintmax_t num_notes)
2022 {
2023         unsigned char fanout = 0;
2024         while ((num_notes >>= 8))
2025                 fanout++;
2026         return fanout;
2027 }
2028
2029 static void construct_path_with_fanout(const char *hex_sha1,
2030                 unsigned char fanout, char *path)
2031 {
2032         unsigned int i = 0, j = 0;
2033         if (fanout >= the_hash_algo->rawsz)
2034                 die("Too large fanout (%u)", fanout);
2035         while (fanout) {
2036                 path[i++] = hex_sha1[j++];
2037                 path[i++] = hex_sha1[j++];
2038                 path[i++] = '/';
2039                 fanout--;
2040         }
2041         memcpy(path + i, hex_sha1 + j, the_hash_algo->hexsz - j);
2042         path[i + the_hash_algo->hexsz - j] = '\0';
2043 }
2044
2045 static uintmax_t do_change_note_fanout(
2046                 struct tree_entry *orig_root, struct tree_entry *root,
2047                 char *hex_oid, unsigned int hex_oid_len,
2048                 char *fullpath, unsigned int fullpath_len,
2049                 unsigned char fanout)
2050 {
2051         struct tree_content *t;
2052         struct tree_entry *e, leaf;
2053         unsigned int i, tmp_hex_oid_len, tmp_fullpath_len;
2054         uintmax_t num_notes = 0;
2055         struct object_id oid;
2056         char realpath[60];
2057
2058         if (!root->tree)
2059                 load_tree(root);
2060         t = root->tree;
2061
2062         for (i = 0; t && i < t->entry_count; i++) {
2063                 e = t->entries[i];
2064                 tmp_hex_oid_len = hex_oid_len + e->name->str_len;
2065                 tmp_fullpath_len = fullpath_len;
2066
2067                 /*
2068                  * We're interested in EITHER existing note entries (entries
2069                  * with exactly 40 hex chars in path, not including directory
2070                  * separators), OR directory entries that may contain note
2071                  * entries (with < 40 hex chars in path).
2072                  * Also, each path component in a note entry must be a multiple
2073                  * of 2 chars.
2074                  */
2075                 if (!e->versions[1].mode ||
2076                     tmp_hex_oid_len > GIT_SHA1_HEXSZ ||
2077                     e->name->str_len % 2)
2078                         continue;
2079
2080                 /* This _may_ be a note entry, or a subdir containing notes */
2081                 memcpy(hex_oid + hex_oid_len, e->name->str_dat,
2082                        e->name->str_len);
2083                 if (tmp_fullpath_len)
2084                         fullpath[tmp_fullpath_len++] = '/';
2085                 memcpy(fullpath + tmp_fullpath_len, e->name->str_dat,
2086                        e->name->str_len);
2087                 tmp_fullpath_len += e->name->str_len;
2088                 fullpath[tmp_fullpath_len] = '\0';
2089
2090                 if (tmp_hex_oid_len == GIT_SHA1_HEXSZ && !get_oid_hex(hex_oid, &oid)) {
2091                         /* This is a note entry */
2092                         if (fanout == 0xff) {
2093                                 /* Counting mode, no rename */
2094                                 num_notes++;
2095                                 continue;
2096                         }
2097                         construct_path_with_fanout(hex_oid, fanout, realpath);
2098                         if (!strcmp(fullpath, realpath)) {
2099                                 /* Note entry is in correct location */
2100                                 num_notes++;
2101                                 continue;
2102                         }
2103
2104                         /* Rename fullpath to realpath */
2105                         if (!tree_content_remove(orig_root, fullpath, &leaf, 0))
2106                                 die("Failed to remove path %s", fullpath);
2107                         tree_content_set(orig_root, realpath,
2108                                 &leaf.versions[1].oid,
2109                                 leaf.versions[1].mode,
2110                                 leaf.tree);
2111                 } else if (S_ISDIR(e->versions[1].mode)) {
2112                         /* This is a subdir that may contain note entries */
2113                         num_notes += do_change_note_fanout(orig_root, e,
2114                                 hex_oid, tmp_hex_oid_len,
2115                                 fullpath, tmp_fullpath_len, fanout);
2116                 }
2117
2118                 /* The above may have reallocated the current tree_content */
2119                 t = root->tree;
2120         }
2121         return num_notes;
2122 }
2123
2124 static uintmax_t change_note_fanout(struct tree_entry *root,
2125                 unsigned char fanout)
2126 {
2127         /*
2128          * The size of path is due to one slash between every two hex digits,
2129          * plus the terminating NUL.  Note that there is no slash at the end, so
2130          * the number of slashes is one less than half the number of hex
2131          * characters.
2132          */
2133         char hex_oid[GIT_MAX_HEXSZ], path[GIT_MAX_HEXSZ + (GIT_MAX_HEXSZ / 2) - 1 + 1];
2134         return do_change_note_fanout(root, root, hex_oid, 0, path, 0, fanout);
2135 }
2136
2137 /*
2138  * Given a pointer into a string, parse a mark reference:
2139  *
2140  *   idnum ::= ':' bigint;
2141  *
2142  * Return the first character after the value in *endptr.
2143  *
2144  * Complain if the following character is not what is expected,
2145  * either a space or end of the string.
2146  */
2147 static uintmax_t parse_mark_ref(const char *p, char **endptr)
2148 {
2149         uintmax_t mark;
2150
2151         assert(*p == ':');
2152         p++;
2153         mark = strtoumax(p, endptr, 10);
2154         if (*endptr == p)
2155                 die("No value after ':' in mark: %s", command_buf.buf);
2156         return mark;
2157 }
2158
2159 /*
2160  * Parse the mark reference, and complain if this is not the end of
2161  * the string.
2162  */
2163 static uintmax_t parse_mark_ref_eol(const char *p)
2164 {
2165         char *end;
2166         uintmax_t mark;
2167
2168         mark = parse_mark_ref(p, &end);
2169         if (*end != '\0')
2170                 die("Garbage after mark: %s", command_buf.buf);
2171         return mark;
2172 }
2173
2174 /*
2175  * Parse the mark reference, demanding a trailing space.  Return a
2176  * pointer to the space.
2177  */
2178 static uintmax_t parse_mark_ref_space(const char **p)
2179 {
2180         uintmax_t mark;
2181         char *end;
2182
2183         mark = parse_mark_ref(*p, &end);
2184         if (*end++ != ' ')
2185                 die("Missing space after mark: %s", command_buf.buf);
2186         *p = end;
2187         return mark;
2188 }
2189
2190 static void file_change_m(const char *p, struct branch *b)
2191 {
2192         static struct strbuf uq = STRBUF_INIT;
2193         const char *endp;
2194         struct object_entry *oe;
2195         struct object_id oid;
2196         uint16_t mode, inline_data = 0;
2197
2198         p = get_mode(p, &mode);
2199         if (!p)
2200                 die("Corrupt mode: %s", command_buf.buf);
2201         switch (mode) {
2202         case 0644:
2203         case 0755:
2204                 mode |= S_IFREG;
2205         case S_IFREG | 0644:
2206         case S_IFREG | 0755:
2207         case S_IFLNK:
2208         case S_IFDIR:
2209         case S_IFGITLINK:
2210                 /* ok */
2211                 break;
2212         default:
2213                 die("Corrupt mode: %s", command_buf.buf);
2214         }
2215
2216         if (*p == ':') {
2217                 oe = find_mark(parse_mark_ref_space(&p));
2218                 oidcpy(&oid, &oe->idx.oid);
2219         } else if (skip_prefix(p, "inline ", &p)) {
2220                 inline_data = 1;
2221                 oe = NULL; /* not used with inline_data, but makes gcc happy */
2222         } else {
2223                 if (parse_oid_hex(p, &oid, &p))
2224                         die("Invalid dataref: %s", command_buf.buf);
2225                 oe = find_object(&oid);
2226                 if (*p++ != ' ')
2227                         die("Missing space after SHA1: %s", command_buf.buf);
2228         }
2229
2230         strbuf_reset(&uq);
2231         if (!unquote_c_style(&uq, p, &endp)) {
2232                 if (*endp)
2233                         die("Garbage after path in: %s", command_buf.buf);
2234                 p = uq.buf;
2235         }
2236
2237         /* Git does not track empty, non-toplevel directories. */
2238         if (S_ISDIR(mode) && is_empty_tree_oid(&oid) && *p) {
2239                 tree_content_remove(&b->branch_tree, p, NULL, 0);
2240                 return;
2241         }
2242
2243         if (S_ISGITLINK(mode)) {
2244                 if (inline_data)
2245                         die("Git links cannot be specified 'inline': %s",
2246                                 command_buf.buf);
2247                 else if (oe) {
2248                         if (oe->type != OBJ_COMMIT)
2249                                 die("Not a commit (actually a %s): %s",
2250                                         type_name(oe->type), command_buf.buf);
2251                 }
2252                 /*
2253                  * Accept the sha1 without checking; it expected to be in
2254                  * another repository.
2255                  */
2256         } else if (inline_data) {
2257                 if (S_ISDIR(mode))
2258                         die("Directories cannot be specified 'inline': %s",
2259                                 command_buf.buf);
2260                 if (p != uq.buf) {
2261                         strbuf_addstr(&uq, p);
2262                         p = uq.buf;
2263                 }
2264                 read_next_command();
2265                 parse_and_store_blob(&last_blob, &oid, 0);
2266         } else {
2267                 enum object_type expected = S_ISDIR(mode) ?
2268                                                 OBJ_TREE: OBJ_BLOB;
2269                 enum object_type type = oe ? oe->type :
2270                                         oid_object_info(the_repository, &oid,
2271                                                         NULL);
2272                 if (type < 0)
2273                         die("%s not found: %s",
2274                                         S_ISDIR(mode) ?  "Tree" : "Blob",
2275                                         command_buf.buf);
2276                 if (type != expected)
2277                         die("Not a %s (actually a %s): %s",
2278                                 type_name(expected), type_name(type),
2279                                 command_buf.buf);
2280         }
2281
2282         if (!*p) {
2283                 tree_content_replace(&b->branch_tree, &oid, mode, NULL);
2284                 return;
2285         }
2286         tree_content_set(&b->branch_tree, p, &oid, mode, NULL);
2287 }
2288
2289 static void file_change_d(const char *p, struct branch *b)
2290 {
2291         static struct strbuf uq = STRBUF_INIT;
2292         const char *endp;
2293
2294         strbuf_reset(&uq);
2295         if (!unquote_c_style(&uq, p, &endp)) {
2296                 if (*endp)
2297                         die("Garbage after path in: %s", command_buf.buf);
2298                 p = uq.buf;
2299         }
2300         tree_content_remove(&b->branch_tree, p, NULL, 1);
2301 }
2302
2303 static void file_change_cr(const char *s, struct branch *b, int rename)
2304 {
2305         const char *d;
2306         static struct strbuf s_uq = STRBUF_INIT;
2307         static struct strbuf d_uq = STRBUF_INIT;
2308         const char *endp;
2309         struct tree_entry leaf;
2310
2311         strbuf_reset(&s_uq);
2312         if (!unquote_c_style(&s_uq, s, &endp)) {
2313                 if (*endp != ' ')
2314                         die("Missing space after source: %s", command_buf.buf);
2315         } else {
2316                 endp = strchr(s, ' ');
2317                 if (!endp)
2318                         die("Missing space after source: %s", command_buf.buf);
2319                 strbuf_add(&s_uq, s, endp - s);
2320         }
2321         s = s_uq.buf;
2322
2323         endp++;
2324         if (!*endp)
2325                 die("Missing dest: %s", command_buf.buf);
2326
2327         d = endp;
2328         strbuf_reset(&d_uq);
2329         if (!unquote_c_style(&d_uq, d, &endp)) {
2330                 if (*endp)
2331                         die("Garbage after dest in: %s", command_buf.buf);
2332                 d = d_uq.buf;
2333         }
2334
2335         memset(&leaf, 0, sizeof(leaf));
2336         if (rename)
2337                 tree_content_remove(&b->branch_tree, s, &leaf, 1);
2338         else
2339                 tree_content_get(&b->branch_tree, s, &leaf, 1);
2340         if (!leaf.versions[1].mode)
2341                 die("Path %s not in branch", s);
2342         if (!*d) {      /* C "path/to/subdir" "" */
2343                 tree_content_replace(&b->branch_tree,
2344                         &leaf.versions[1].oid,
2345                         leaf.versions[1].mode,
2346                         leaf.tree);
2347                 return;
2348         }
2349         tree_content_set(&b->branch_tree, d,
2350                 &leaf.versions[1].oid,
2351                 leaf.versions[1].mode,
2352                 leaf.tree);
2353 }
2354
2355 static void note_change_n(const char *p, struct branch *b, unsigned char *old_fanout)
2356 {
2357         static struct strbuf uq = STRBUF_INIT;
2358         struct object_entry *oe;
2359         struct branch *s;
2360         struct object_id oid, commit_oid;
2361         char path[60];
2362         uint16_t inline_data = 0;
2363         unsigned char new_fanout;
2364
2365         /*
2366          * When loading a branch, we don't traverse its tree to count the real
2367          * number of notes (too expensive to do this for all non-note refs).
2368          * This means that recently loaded notes refs might incorrectly have
2369          * b->num_notes == 0, and consequently, old_fanout might be wrong.
2370          *
2371          * Fix this by traversing the tree and counting the number of notes
2372          * when b->num_notes == 0. If the notes tree is truly empty, the
2373          * calculation should not take long.
2374          */
2375         if (b->num_notes == 0 && *old_fanout == 0) {
2376                 /* Invoke change_note_fanout() in "counting mode". */
2377                 b->num_notes = change_note_fanout(&b->branch_tree, 0xff);
2378                 *old_fanout = convert_num_notes_to_fanout(b->num_notes);
2379         }
2380
2381         /* Now parse the notemodify command. */
2382         /* <dataref> or 'inline' */
2383         if (*p == ':') {
2384                 oe = find_mark(parse_mark_ref_space(&p));
2385                 oidcpy(&oid, &oe->idx.oid);
2386         } else if (skip_prefix(p, "inline ", &p)) {
2387                 inline_data = 1;
2388                 oe = NULL; /* not used with inline_data, but makes gcc happy */
2389         } else {
2390                 if (parse_oid_hex(p, &oid, &p))
2391                         die("Invalid dataref: %s", command_buf.buf);
2392                 oe = find_object(&oid);
2393                 if (*p++ != ' ')
2394                         die("Missing space after SHA1: %s", command_buf.buf);
2395         }
2396
2397         /* <commit-ish> */
2398         s = lookup_branch(p);
2399         if (s) {
2400                 if (is_null_oid(&s->oid))
2401                         die("Can't add a note on empty branch.");
2402                 oidcpy(&commit_oid, &s->oid);
2403         } else if (*p == ':') {
2404                 uintmax_t commit_mark = parse_mark_ref_eol(p);
2405                 struct object_entry *commit_oe = find_mark(commit_mark);
2406                 if (commit_oe->type != OBJ_COMMIT)
2407                         die("Mark :%" PRIuMAX " not a commit", commit_mark);
2408                 oidcpy(&commit_oid, &commit_oe->idx.oid);
2409         } else if (!get_oid(p, &commit_oid)) {
2410                 unsigned long size;
2411                 char *buf = read_object_with_reference(&commit_oid,
2412                                                        commit_type, &size,
2413                                                        &commit_oid);
2414                 if (!buf || size < 46)
2415                         die("Not a valid commit: %s", p);
2416                 free(buf);
2417         } else
2418                 die("Invalid ref name or SHA1 expression: %s", p);
2419
2420         if (inline_data) {
2421                 if (p != uq.buf) {
2422                         strbuf_addstr(&uq, p);
2423                         p = uq.buf;
2424                 }
2425                 read_next_command();
2426                 parse_and_store_blob(&last_blob, &oid, 0);
2427         } else if (oe) {
2428                 if (oe->type != OBJ_BLOB)
2429                         die("Not a blob (actually a %s): %s",
2430                                 type_name(oe->type), command_buf.buf);
2431         } else if (!is_null_oid(&oid)) {
2432                 enum object_type type = oid_object_info(the_repository, &oid,
2433                                                         NULL);
2434                 if (type < 0)
2435                         die("Blob not found: %s", command_buf.buf);
2436                 if (type != OBJ_BLOB)
2437                         die("Not a blob (actually a %s): %s",
2438                             type_name(type), command_buf.buf);
2439         }
2440
2441         construct_path_with_fanout(oid_to_hex(&commit_oid), *old_fanout, path);
2442         if (tree_content_remove(&b->branch_tree, path, NULL, 0))
2443                 b->num_notes--;
2444
2445         if (is_null_oid(&oid))
2446                 return; /* nothing to insert */
2447
2448         b->num_notes++;
2449         new_fanout = convert_num_notes_to_fanout(b->num_notes);
2450         construct_path_with_fanout(oid_to_hex(&commit_oid), new_fanout, path);
2451         tree_content_set(&b->branch_tree, path, &oid, S_IFREG | 0644, NULL);
2452 }
2453
2454 static void file_change_deleteall(struct branch *b)
2455 {
2456         release_tree_content_recursive(b->branch_tree.tree);
2457         oidclr(&b->branch_tree.versions[0].oid);
2458         oidclr(&b->branch_tree.versions[1].oid);
2459         load_tree(&b->branch_tree);
2460         b->num_notes = 0;
2461 }
2462
2463 static void parse_from_commit(struct branch *b, char *buf, unsigned long size)
2464 {
2465         if (!buf || size < GIT_SHA1_HEXSZ + 6)
2466                 die("Not a valid commit: %s", oid_to_hex(&b->oid));
2467         if (memcmp("tree ", buf, 5)
2468                 || get_oid_hex(buf + 5, &b->branch_tree.versions[1].oid))
2469                 die("The commit %s is corrupt", oid_to_hex(&b->oid));
2470         oidcpy(&b->branch_tree.versions[0].oid,
2471                &b->branch_tree.versions[1].oid);
2472 }
2473
2474 static void parse_from_existing(struct branch *b)
2475 {
2476         if (is_null_oid(&b->oid)) {
2477                 oidclr(&b->branch_tree.versions[0].oid);
2478                 oidclr(&b->branch_tree.versions[1].oid);
2479         } else {
2480                 unsigned long size;
2481                 char *buf;
2482
2483                 buf = read_object_with_reference(&b->oid, commit_type, &size,
2484                                                  &b->oid);
2485                 parse_from_commit(b, buf, size);
2486                 free(buf);
2487         }
2488 }
2489
2490 static int parse_from(struct branch *b)
2491 {
2492         const char *from;
2493         struct branch *s;
2494         struct object_id oid;
2495
2496         if (!skip_prefix(command_buf.buf, "from ", &from))
2497                 return 0;
2498
2499         oidcpy(&oid, &b->branch_tree.versions[1].oid);
2500
2501         s = lookup_branch(from);
2502         if (b == s)
2503                 die("Can't create a branch from itself: %s", b->name);
2504         else if (s) {
2505                 struct object_id *t = &s->branch_tree.versions[1].oid;
2506                 oidcpy(&b->oid, &s->oid);
2507                 oidcpy(&b->branch_tree.versions[0].oid, t);
2508                 oidcpy(&b->branch_tree.versions[1].oid, t);
2509         } else if (*from == ':') {
2510                 uintmax_t idnum = parse_mark_ref_eol(from);
2511                 struct object_entry *oe = find_mark(idnum);
2512                 if (oe->type != OBJ_COMMIT)
2513                         die("Mark :%" PRIuMAX " not a commit", idnum);
2514                 if (!oideq(&b->oid, &oe->idx.oid)) {
2515                         oidcpy(&b->oid, &oe->idx.oid);
2516                         if (oe->pack_id != MAX_PACK_ID) {
2517                                 unsigned long size;
2518                                 char *buf = gfi_unpack_entry(oe, &size);
2519                                 parse_from_commit(b, buf, size);
2520                                 free(buf);
2521                         } else
2522                                 parse_from_existing(b);
2523                 }
2524         } else if (!get_oid(from, &b->oid)) {
2525                 parse_from_existing(b);
2526                 if (is_null_oid(&b->oid))
2527                         b->delete = 1;
2528         }
2529         else
2530                 die("Invalid ref name or SHA1 expression: %s", from);
2531
2532         if (b->branch_tree.tree && !oideq(&oid, &b->branch_tree.versions[1].oid)) {
2533                 release_tree_content_recursive(b->branch_tree.tree);
2534                 b->branch_tree.tree = NULL;
2535         }
2536
2537         read_next_command();
2538         return 1;
2539 }
2540
2541 static struct hash_list *parse_merge(unsigned int *count)
2542 {
2543         struct hash_list *list = NULL, **tail = &list, *n;
2544         const char *from;
2545         struct branch *s;
2546
2547         *count = 0;
2548         while (skip_prefix(command_buf.buf, "merge ", &from)) {
2549                 n = xmalloc(sizeof(*n));
2550                 s = lookup_branch(from);
2551                 if (s)
2552                         oidcpy(&n->oid, &s->oid);
2553                 else if (*from == ':') {
2554                         uintmax_t idnum = parse_mark_ref_eol(from);
2555                         struct object_entry *oe = find_mark(idnum);
2556                         if (oe->type != OBJ_COMMIT)
2557                                 die("Mark :%" PRIuMAX " not a commit", idnum);
2558                         oidcpy(&n->oid, &oe->idx.oid);
2559                 } else if (!get_oid(from, &n->oid)) {
2560                         unsigned long size;
2561                         char *buf = read_object_with_reference(&n->oid,
2562                                                                commit_type,
2563                                                                &size, &n->oid);
2564                         if (!buf || size < 46)
2565                                 die("Not a valid commit: %s", from);
2566                         free(buf);
2567                 } else
2568                         die("Invalid ref name or SHA1 expression: %s", from);
2569
2570                 n->next = NULL;
2571                 *tail = n;
2572                 tail = &n->next;
2573
2574                 (*count)++;
2575                 read_next_command();
2576         }
2577         return list;
2578 }
2579
2580 static void parse_new_commit(const char *arg)
2581 {
2582         static struct strbuf msg = STRBUF_INIT;
2583         struct branch *b;
2584         char *author = NULL;
2585         char *committer = NULL;
2586         struct hash_list *merge_list = NULL;
2587         unsigned int merge_count;
2588         unsigned char prev_fanout, new_fanout;
2589         const char *v;
2590
2591         b = lookup_branch(arg);
2592         if (!b)
2593                 b = new_branch(arg);
2594
2595         read_next_command();
2596         parse_mark();
2597         parse_original_identifier();
2598         if (skip_prefix(command_buf.buf, "author ", &v)) {
2599                 author = parse_ident(v);
2600                 read_next_command();
2601         }
2602         if (skip_prefix(command_buf.buf, "committer ", &v)) {
2603                 committer = parse_ident(v);
2604                 read_next_command();
2605         }
2606         if (!committer)
2607                 die("Expected committer but didn't get one");
2608         parse_data(&msg, 0, NULL);
2609         read_next_command();
2610         parse_from(b);
2611         merge_list = parse_merge(&merge_count);
2612
2613         /* ensure the branch is active/loaded */
2614         if (!b->branch_tree.tree || !max_active_branches) {
2615                 unload_one_branch();
2616                 load_branch(b);
2617         }
2618
2619         prev_fanout = convert_num_notes_to_fanout(b->num_notes);
2620
2621         /* file_change* */
2622         while (command_buf.len > 0) {
2623                 if (skip_prefix(command_buf.buf, "M ", &v))
2624                         file_change_m(v, b);
2625                 else if (skip_prefix(command_buf.buf, "D ", &v))
2626                         file_change_d(v, b);
2627                 else if (skip_prefix(command_buf.buf, "R ", &v))
2628                         file_change_cr(v, b, 1);
2629                 else if (skip_prefix(command_buf.buf, "C ", &v))
2630                         file_change_cr(v, b, 0);
2631                 else if (skip_prefix(command_buf.buf, "N ", &v))
2632                         note_change_n(v, b, &prev_fanout);
2633                 else if (!strcmp("deleteall", command_buf.buf))
2634                         file_change_deleteall(b);
2635                 else if (skip_prefix(command_buf.buf, "ls ", &v))
2636                         parse_ls(v, b);
2637                 else {
2638                         unread_command_buf = 1;
2639                         break;
2640                 }
2641                 if (read_next_command() == EOF)
2642                         break;
2643         }
2644
2645         new_fanout = convert_num_notes_to_fanout(b->num_notes);
2646         if (new_fanout != prev_fanout)
2647                 b->num_notes = change_note_fanout(&b->branch_tree, new_fanout);
2648
2649         /* build the tree and the commit */
2650         store_tree(&b->branch_tree);
2651         oidcpy(&b->branch_tree.versions[0].oid,
2652                &b->branch_tree.versions[1].oid);
2653
2654         strbuf_reset(&new_data);
2655         strbuf_addf(&new_data, "tree %s\n",
2656                 oid_to_hex(&b->branch_tree.versions[1].oid));
2657         if (!is_null_oid(&b->oid))
2658                 strbuf_addf(&new_data, "parent %s\n",
2659                             oid_to_hex(&b->oid));
2660         while (merge_list) {
2661                 struct hash_list *next = merge_list->next;
2662                 strbuf_addf(&new_data, "parent %s\n",
2663                             oid_to_hex(&merge_list->oid));
2664                 free(merge_list);
2665                 merge_list = next;
2666         }
2667         strbuf_addf(&new_data,
2668                 "author %s\n"
2669                 "committer %s\n"
2670                 "\n",
2671                 author ? author : committer, committer);
2672         strbuf_addbuf(&new_data, &msg);
2673         free(author);
2674         free(committer);
2675
2676         if (!store_object(OBJ_COMMIT, &new_data, NULL, &b->oid, next_mark))
2677                 b->pack_id = pack_id;
2678         b->last_commit = object_count_by_type[OBJ_COMMIT];
2679 }
2680
2681 static void parse_new_tag(const char *arg)
2682 {
2683         static struct strbuf msg = STRBUF_INIT;
2684         const char *from;
2685         char *tagger;
2686         struct branch *s;
2687         struct tag *t;
2688         uintmax_t from_mark = 0;
2689         struct object_id oid;
2690         enum object_type type;
2691         const char *v;
2692
2693         t = mem_pool_alloc(&fi_mem_pool, sizeof(struct tag));
2694         memset(t, 0, sizeof(struct tag));
2695         t->name = pool_strdup(arg);
2696         if (last_tag)
2697                 last_tag->next_tag = t;
2698         else
2699                 first_tag = t;
2700         last_tag = t;
2701         read_next_command();
2702
2703         /* from ... */
2704         if (!skip_prefix(command_buf.buf, "from ", &from))
2705                 die("Expected from command, got %s", command_buf.buf);
2706         s = lookup_branch(from);
2707         if (s) {
2708                 if (is_null_oid(&s->oid))
2709                         die("Can't tag an empty branch.");
2710                 oidcpy(&oid, &s->oid);
2711                 type = OBJ_COMMIT;
2712         } else if (*from == ':') {
2713                 struct object_entry *oe;
2714                 from_mark = parse_mark_ref_eol(from);
2715                 oe = find_mark(from_mark);
2716                 type = oe->type;
2717                 oidcpy(&oid, &oe->idx.oid);
2718         } else if (!get_oid(from, &oid)) {
2719                 struct object_entry *oe = find_object(&oid);
2720                 if (!oe) {
2721                         type = oid_object_info(the_repository, &oid, NULL);
2722                         if (type < 0)
2723                                 die("Not a valid object: %s", from);
2724                 } else
2725                         type = oe->type;
2726         } else
2727                 die("Invalid ref name or SHA1 expression: %s", from);
2728         read_next_command();
2729
2730         /* original-oid ... */
2731         parse_original_identifier();
2732
2733         /* tagger ... */
2734         if (skip_prefix(command_buf.buf, "tagger ", &v)) {
2735                 tagger = parse_ident(v);
2736                 read_next_command();
2737         } else
2738                 tagger = NULL;
2739
2740         /* tag payload/message */
2741         parse_data(&msg, 0, NULL);
2742
2743         /* build the tag object */
2744         strbuf_reset(&new_data);
2745
2746         strbuf_addf(&new_data,
2747                     "object %s\n"
2748                     "type %s\n"
2749                     "tag %s\n",
2750                     oid_to_hex(&oid), type_name(type), t->name);
2751         if (tagger)
2752                 strbuf_addf(&new_data,
2753                             "tagger %s\n", tagger);
2754         strbuf_addch(&new_data, '\n');
2755         strbuf_addbuf(&new_data, &msg);
2756         free(tagger);
2757
2758         if (store_object(OBJ_TAG, &new_data, NULL, &t->oid, 0))
2759                 t->pack_id = MAX_PACK_ID;
2760         else
2761                 t->pack_id = pack_id;
2762 }
2763
2764 static void parse_reset_branch(const char *arg)
2765 {
2766         struct branch *b;
2767
2768         b = lookup_branch(arg);
2769         if (b) {
2770                 oidclr(&b->oid);
2771                 oidclr(&b->branch_tree.versions[0].oid);
2772                 oidclr(&b->branch_tree.versions[1].oid);
2773                 if (b->branch_tree.tree) {
2774                         release_tree_content_recursive(b->branch_tree.tree);
2775                         b->branch_tree.tree = NULL;
2776                 }
2777         }
2778         else
2779                 b = new_branch(arg);
2780         read_next_command();
2781         parse_from(b);
2782         if (command_buf.len > 0)
2783                 unread_command_buf = 1;
2784 }
2785
2786 static void cat_blob_write(const char *buf, unsigned long size)
2787 {
2788         if (write_in_full(cat_blob_fd, buf, size) < 0)
2789                 die_errno("Write to frontend failed");
2790 }
2791
2792 static void cat_blob(struct object_entry *oe, struct object_id *oid)
2793 {
2794         struct strbuf line = STRBUF_INIT;
2795         unsigned long size;
2796         enum object_type type = 0;
2797         char *buf;
2798
2799         if (!oe || oe->pack_id == MAX_PACK_ID) {
2800                 buf = read_object_file(oid, &type, &size);
2801         } else {
2802                 type = oe->type;
2803                 buf = gfi_unpack_entry(oe, &size);
2804         }
2805
2806         /*
2807          * Output based on batch_one_object() from cat-file.c.
2808          */
2809         if (type <= 0) {
2810                 strbuf_reset(&line);
2811                 strbuf_addf(&line, "%s missing\n", oid_to_hex(oid));
2812                 cat_blob_write(line.buf, line.len);
2813                 strbuf_release(&line);
2814                 free(buf);
2815                 return;
2816         }
2817         if (!buf)
2818                 die("Can't read object %s", oid_to_hex(oid));
2819         if (type != OBJ_BLOB)
2820                 die("Object %s is a %s but a blob was expected.",
2821                     oid_to_hex(oid), type_name(type));
2822         strbuf_reset(&line);
2823         strbuf_addf(&line, "%s %s %"PRIuMAX"\n", oid_to_hex(oid),
2824                     type_name(type), (uintmax_t)size);
2825         cat_blob_write(line.buf, line.len);
2826         strbuf_release(&line);
2827         cat_blob_write(buf, size);
2828         cat_blob_write("\n", 1);
2829         if (oe && oe->pack_id == pack_id) {
2830                 last_blob.offset = oe->idx.offset;
2831                 strbuf_attach(&last_blob.data, buf, size, size);
2832                 last_blob.depth = oe->depth;
2833         } else
2834                 free(buf);
2835 }
2836
2837 static void parse_get_mark(const char *p)
2838 {
2839         struct object_entry *oe;
2840         char output[GIT_MAX_HEXSZ + 2];
2841
2842         /* get-mark SP <object> LF */
2843         if (*p != ':')
2844                 die("Not a mark: %s", p);
2845
2846         oe = find_mark(parse_mark_ref_eol(p));
2847         if (!oe)
2848                 die("Unknown mark: %s", command_buf.buf);
2849
2850         xsnprintf(output, sizeof(output), "%s\n", oid_to_hex(&oe->idx.oid));
2851         cat_blob_write(output, GIT_SHA1_HEXSZ + 1);
2852 }
2853
2854 static void parse_cat_blob(const char *p)
2855 {
2856         struct object_entry *oe;
2857         struct object_id oid;
2858
2859         /* cat-blob SP <object> LF */
2860         if (*p == ':') {
2861                 oe = find_mark(parse_mark_ref_eol(p));
2862                 if (!oe)
2863                         die("Unknown mark: %s", command_buf.buf);
2864                 oidcpy(&oid, &oe->idx.oid);
2865         } else {
2866                 if (parse_oid_hex(p, &oid, &p))
2867                         die("Invalid dataref: %s", command_buf.buf);
2868                 if (*p)
2869                         die("Garbage after SHA1: %s", command_buf.buf);
2870                 oe = find_object(&oid);
2871         }
2872
2873         cat_blob(oe, &oid);
2874 }
2875
2876 static struct object_entry *dereference(struct object_entry *oe,
2877                                         struct object_id *oid)
2878 {
2879         unsigned long size;
2880         char *buf = NULL;
2881         if (!oe) {
2882                 enum object_type type = oid_object_info(the_repository, oid,
2883                                                         NULL);
2884                 if (type < 0)
2885                         die("object not found: %s", oid_to_hex(oid));
2886                 /* cache it! */
2887                 oe = insert_object(oid);
2888                 oe->type = type;
2889                 oe->pack_id = MAX_PACK_ID;
2890                 oe->idx.offset = 1;
2891         }
2892         switch (oe->type) {
2893         case OBJ_TREE:  /* easy case. */
2894                 return oe;
2895         case OBJ_COMMIT:
2896         case OBJ_TAG:
2897                 break;
2898         default:
2899                 die("Not a tree-ish: %s", command_buf.buf);
2900         }
2901
2902         if (oe->pack_id != MAX_PACK_ID) {       /* in a pack being written */
2903                 buf = gfi_unpack_entry(oe, &size);
2904         } else {
2905                 enum object_type unused;
2906                 buf = read_object_file(oid, &unused, &size);
2907         }
2908         if (!buf)
2909                 die("Can't load object %s", oid_to_hex(oid));
2910
2911         /* Peel one layer. */
2912         switch (oe->type) {
2913         case OBJ_TAG:
2914                 if (size < GIT_SHA1_HEXSZ + strlen("object ") ||
2915                     get_oid_hex(buf + strlen("object "), oid))
2916                         die("Invalid SHA1 in tag: %s", command_buf.buf);
2917                 break;
2918         case OBJ_COMMIT:
2919                 if (size < GIT_SHA1_HEXSZ + strlen("tree ") ||
2920                     get_oid_hex(buf + strlen("tree "), oid))
2921                         die("Invalid SHA1 in commit: %s", command_buf.buf);
2922         }
2923
2924         free(buf);
2925         return find_object(oid);
2926 }
2927
2928 static struct object_entry *parse_treeish_dataref(const char **p)
2929 {
2930         struct object_id oid;
2931         struct object_entry *e;
2932
2933         if (**p == ':') {       /* <mark> */
2934                 e = find_mark(parse_mark_ref_space(p));
2935                 if (!e)
2936                         die("Unknown mark: %s", command_buf.buf);
2937                 oidcpy(&oid, &e->idx.oid);
2938         } else {        /* <sha1> */
2939                 if (parse_oid_hex(*p, &oid, p))
2940                         die("Invalid dataref: %s", command_buf.buf);
2941                 e = find_object(&oid);
2942                 if (*(*p)++ != ' ')
2943                         die("Missing space after tree-ish: %s", command_buf.buf);
2944         }
2945
2946         while (!e || e->type != OBJ_TREE)
2947                 e = dereference(e, &oid);
2948         return e;
2949 }
2950
2951 static void print_ls(int mode, const unsigned char *sha1, const char *path)
2952 {
2953         static struct strbuf line = STRBUF_INIT;
2954
2955         /* See show_tree(). */
2956         const char *type =
2957                 S_ISGITLINK(mode) ? commit_type :
2958                 S_ISDIR(mode) ? tree_type :
2959                 blob_type;
2960
2961         if (!mode) {
2962                 /* missing SP path LF */
2963                 strbuf_reset(&line);
2964                 strbuf_addstr(&line, "missing ");
2965                 quote_c_style(path, &line, NULL, 0);
2966                 strbuf_addch(&line, '\n');
2967         } else {
2968                 /* mode SP type SP object_name TAB path LF */
2969                 strbuf_reset(&line);
2970                 strbuf_addf(&line, "%06o %s %s\t",
2971                                 mode & ~NO_DELTA, type, sha1_to_hex(sha1));
2972                 quote_c_style(path, &line, NULL, 0);
2973                 strbuf_addch(&line, '\n');
2974         }
2975         cat_blob_write(line.buf, line.len);
2976 }
2977
2978 static void parse_ls(const char *p, struct branch *b)
2979 {
2980         struct tree_entry *root = NULL;
2981         struct tree_entry leaf = {NULL};
2982
2983         /* ls SP (<tree-ish> SP)? <path> */
2984         if (*p == '"') {
2985                 if (!b)
2986                         die("Not in a commit: %s", command_buf.buf);
2987                 root = &b->branch_tree;
2988         } else {
2989                 struct object_entry *e = parse_treeish_dataref(&p);
2990                 root = new_tree_entry();
2991                 oidcpy(&root->versions[1].oid, &e->idx.oid);
2992                 if (!is_null_oid(&root->versions[1].oid))
2993                         root->versions[1].mode = S_IFDIR;
2994                 load_tree(root);
2995         }
2996         if (*p == '"') {
2997                 static struct strbuf uq = STRBUF_INIT;
2998                 const char *endp;
2999                 strbuf_reset(&uq);
3000                 if (unquote_c_style(&uq, p, &endp))
3001                         die("Invalid path: %s", command_buf.buf);
3002                 if (*endp)
3003                         die("Garbage after path in: %s", command_buf.buf);
3004                 p = uq.buf;
3005         }
3006         tree_content_get(root, p, &leaf, 1);
3007         /*
3008          * A directory in preparation would have a sha1 of zero
3009          * until it is saved.  Save, for simplicity.
3010          */
3011         if (S_ISDIR(leaf.versions[1].mode))
3012                 store_tree(&leaf);
3013
3014         print_ls(leaf.versions[1].mode, leaf.versions[1].oid.hash, p);
3015         if (leaf.tree)
3016                 release_tree_content_recursive(leaf.tree);
3017         if (!b || root != &b->branch_tree)
3018                 release_tree_entry(root);
3019 }
3020
3021 static void checkpoint(void)
3022 {
3023         checkpoint_requested = 0;
3024         if (object_count) {
3025                 cycle_packfile();
3026         }
3027         dump_branches();
3028         dump_tags();
3029         dump_marks();
3030 }
3031
3032 static void parse_checkpoint(void)
3033 {
3034         checkpoint_requested = 1;
3035         skip_optional_lf();
3036 }
3037
3038 static void parse_progress(void)
3039 {
3040         fwrite(command_buf.buf, 1, command_buf.len, stdout);
3041         fputc('\n', stdout);
3042         fflush(stdout);
3043         skip_optional_lf();
3044 }
3045
3046 static char* make_fast_import_path(const char *path)
3047 {
3048         if (!relative_marks_paths || is_absolute_path(path))
3049                 return xstrdup(path);
3050         return git_pathdup("info/fast-import/%s", path);
3051 }
3052
3053 static void option_import_marks(const char *marks,
3054                                         int from_stream, int ignore_missing)
3055 {
3056         if (import_marks_file) {
3057                 if (from_stream)
3058                         die("Only one import-marks command allowed per stream");
3059
3060                 /* read previous mark file */
3061                 if(!import_marks_file_from_stream)
3062                         read_marks();
3063         }
3064
3065         import_marks_file = make_fast_import_path(marks);
3066         import_marks_file_from_stream = from_stream;
3067         import_marks_file_ignore_missing = ignore_missing;
3068 }
3069
3070 static void option_date_format(const char *fmt)
3071 {
3072         if (!strcmp(fmt, "raw"))
3073                 whenspec = WHENSPEC_RAW;
3074         else if (!strcmp(fmt, "rfc2822"))
3075                 whenspec = WHENSPEC_RFC2822;
3076         else if (!strcmp(fmt, "now"))
3077                 whenspec = WHENSPEC_NOW;
3078         else
3079                 die("unknown --date-format argument %s", fmt);
3080 }
3081
3082 static unsigned long ulong_arg(const char *option, const char *arg)
3083 {
3084         char *endptr;
3085         unsigned long rv = strtoul(arg, &endptr, 0);
3086         if (strchr(arg, '-') || endptr == arg || *endptr)
3087                 die("%s: argument must be a non-negative integer", option);
3088         return rv;
3089 }
3090
3091 static void option_depth(const char *depth)
3092 {
3093         max_depth = ulong_arg("--depth", depth);
3094         if (max_depth > MAX_DEPTH)
3095                 die("--depth cannot exceed %u", MAX_DEPTH);
3096 }
3097
3098 static void option_active_branches(const char *branches)
3099 {
3100         max_active_branches = ulong_arg("--active-branches", branches);
3101 }
3102
3103 static void option_export_marks(const char *marks)
3104 {
3105         export_marks_file = make_fast_import_path(marks);
3106 }
3107
3108 static void option_cat_blob_fd(const char *fd)
3109 {
3110         unsigned long n = ulong_arg("--cat-blob-fd", fd);
3111         if (n > (unsigned long) INT_MAX)
3112                 die("--cat-blob-fd cannot exceed %d", INT_MAX);
3113         cat_blob_fd = (int) n;
3114 }
3115
3116 static void option_export_pack_edges(const char *edges)
3117 {
3118         if (pack_edges)
3119                 fclose(pack_edges);
3120         pack_edges = xfopen(edges, "a");
3121 }
3122
3123 static int parse_one_option(const char *option)
3124 {
3125         if (skip_prefix(option, "max-pack-size=", &option)) {
3126                 unsigned long v;
3127                 if (!git_parse_ulong(option, &v))
3128                         return 0;
3129                 if (v < 8192) {
3130                         warning("max-pack-size is now in bytes, assuming --max-pack-size=%lum", v);
3131                         v *= 1024 * 1024;
3132                 } else if (v < 1024 * 1024) {
3133                         warning("minimum max-pack-size is 1 MiB");
3134                         v = 1024 * 1024;
3135                 }
3136                 max_packsize = v;
3137         } else if (skip_prefix(option, "big-file-threshold=", &option)) {
3138                 unsigned long v;
3139                 if (!git_parse_ulong(option, &v))
3140                         return 0;
3141                 big_file_threshold = v;
3142         } else if (skip_prefix(option, "depth=", &option)) {
3143                 option_depth(option);
3144         } else if (skip_prefix(option, "active-branches=", &option)) {
3145                 option_active_branches(option);
3146         } else if (skip_prefix(option, "export-pack-edges=", &option)) {
3147                 option_export_pack_edges(option);
3148         } else if (!strcmp(option, "quiet")) {
3149                 show_stats = 0;
3150         } else if (!strcmp(option, "stats")) {
3151                 show_stats = 1;
3152         } else if (!strcmp(option, "allow-unsafe-features")) {
3153                 ; /* already handled during early option parsing */
3154         } else {
3155                 return 0;
3156         }
3157
3158         return 1;
3159 }
3160
3161 static void check_unsafe_feature(const char *feature, int from_stream)
3162 {
3163         if (from_stream && !allow_unsafe_features)
3164                 die(_("feature '%s' forbidden in input without --allow-unsafe-features"),
3165                     feature);
3166 }
3167
3168 static int parse_one_feature(const char *feature, int from_stream)
3169 {
3170         const char *arg;
3171
3172         if (skip_prefix(feature, "date-format=", &arg)) {
3173                 option_date_format(arg);
3174         } else if (skip_prefix(feature, "import-marks=", &arg)) {
3175                 check_unsafe_feature("import-marks", from_stream);
3176                 option_import_marks(arg, from_stream, 0);
3177         } else if (skip_prefix(feature, "import-marks-if-exists=", &arg)) {
3178                 check_unsafe_feature("import-marks-if-exists", from_stream);
3179                 option_import_marks(arg, from_stream, 1);
3180         } else if (skip_prefix(feature, "export-marks=", &arg)) {
3181                 check_unsafe_feature(feature, from_stream);
3182                 option_export_marks(arg);
3183         } else if (!strcmp(feature, "get-mark")) {
3184                 ; /* Don't die - this feature is supported */
3185         } else if (!strcmp(feature, "cat-blob")) {
3186                 ; /* Don't die - this feature is supported */
3187         } else if (!strcmp(feature, "relative-marks")) {
3188                 relative_marks_paths = 1;
3189         } else if (!strcmp(feature, "no-relative-marks")) {
3190                 relative_marks_paths = 0;
3191         } else if (!strcmp(feature, "done")) {
3192                 require_explicit_termination = 1;
3193         } else if (!strcmp(feature, "force")) {
3194                 force_update = 1;
3195         } else if (!strcmp(feature, "notes") || !strcmp(feature, "ls")) {
3196                 ; /* do nothing; we have the feature */
3197         } else {
3198                 return 0;
3199         }
3200
3201         return 1;
3202 }
3203
3204 static void parse_feature(const char *feature)
3205 {
3206         if (seen_data_command)
3207                 die("Got feature command '%s' after data command", feature);
3208
3209         if (parse_one_feature(feature, 1))
3210                 return;
3211
3212         die("This version of fast-import does not support feature %s.", feature);
3213 }
3214
3215 static void parse_option(const char *option)
3216 {
3217         if (seen_data_command)
3218                 die("Got option command '%s' after data command", option);
3219
3220         if (parse_one_option(option))
3221                 return;
3222
3223         die("This version of fast-import does not support option: %s", option);
3224 }
3225
3226 static void git_pack_config(void)
3227 {
3228         int indexversion_value;
3229         int limit;
3230         unsigned long packsizelimit_value;
3231
3232         if (!git_config_get_ulong("pack.depth", &max_depth)) {
3233                 if (max_depth > MAX_DEPTH)
3234                         max_depth = MAX_DEPTH;
3235         }
3236         if (!git_config_get_int("pack.indexversion", &indexversion_value)) {
3237                 pack_idx_opts.version = indexversion_value;
3238                 if (pack_idx_opts.version > 2)
3239                         git_die_config("pack.indexversion",
3240                                         "bad pack.indexversion=%"PRIu32, pack_idx_opts.version);
3241         }
3242         if (!git_config_get_ulong("pack.packsizelimit", &packsizelimit_value))
3243                 max_packsize = packsizelimit_value;
3244
3245         if (!git_config_get_int("fastimport.unpacklimit", &limit))
3246                 unpack_limit = limit;
3247         else if (!git_config_get_int("transfer.unpacklimit", &limit))
3248                 unpack_limit = limit;
3249
3250         git_config(git_default_config, NULL);
3251 }
3252
3253 static const char fast_import_usage[] =
3254 "git fast-import [--date-format=<f>] [--max-pack-size=<n>] [--big-file-threshold=<n>] [--depth=<n>] [--active-branches=<n>] [--export-marks=<marks.file>]";
3255
3256 static void parse_argv(void)
3257 {
3258         unsigned int i;
3259
3260         for (i = 1; i < global_argc; i++) {
3261                 const char *a = global_argv[i];
3262
3263                 if (*a != '-' || !strcmp(a, "--"))
3264                         break;
3265
3266                 if (!skip_prefix(a, "--", &a))
3267                         die("unknown option %s", a);
3268
3269                 if (parse_one_option(a))
3270                         continue;
3271
3272                 if (parse_one_feature(a, 0))
3273                         continue;
3274
3275                 if (skip_prefix(a, "cat-blob-fd=", &a)) {
3276                         option_cat_blob_fd(a);
3277                         continue;
3278                 }
3279
3280                 die("unknown option --%s", a);
3281         }
3282         if (i != global_argc)
3283                 usage(fast_import_usage);
3284
3285         seen_data_command = 1;
3286         if (import_marks_file)
3287                 read_marks();
3288 }
3289
3290 int cmd_main(int argc, const char **argv)
3291 {
3292         unsigned int i;
3293
3294         if (argc == 2 && !strcmp(argv[1], "-h"))
3295                 usage(fast_import_usage);
3296
3297         setup_git_directory();
3298         reset_pack_idx_option(&pack_idx_opts);
3299         git_pack_config();
3300
3301         alloc_objects(object_entry_alloc);
3302         strbuf_init(&command_buf, 0);
3303         atom_table = xcalloc(atom_table_sz, sizeof(struct atom_str*));
3304         branch_table = xcalloc(branch_table_sz, sizeof(struct branch*));
3305         avail_tree_table = xcalloc(avail_tree_table_sz, sizeof(struct avail_tree_content*));
3306         marks = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct mark_set));
3307
3308         /*
3309          * We don't parse most options until after we've seen the set of
3310          * "feature" lines at the start of the stream (which allows the command
3311          * line to override stream data). But we must do an early parse of any
3312          * command-line options that impact how we interpret the feature lines.
3313          */
3314         for (i = 1; i < argc; i++) {
3315                 const char *arg = argv[i];
3316                 if (*arg != '-' || !strcmp(arg, "--"))
3317                         break;
3318                 if (!strcmp(arg, "--allow-unsafe-features"))
3319                         allow_unsafe_features = 1;
3320         }
3321
3322         global_argc = argc;
3323         global_argv = argv;
3324
3325         rc_free = mem_pool_alloc(&fi_mem_pool, cmd_save * sizeof(*rc_free));
3326         for (i = 0; i < (cmd_save - 1); i++)
3327                 rc_free[i].next = &rc_free[i + 1];
3328         rc_free[cmd_save - 1].next = NULL;
3329
3330         start_packfile();
3331         set_die_routine(die_nicely);
3332         set_checkpoint_signal();
3333         while (read_next_command() != EOF) {
3334                 const char *v;
3335                 if (!strcmp("blob", command_buf.buf))
3336                         parse_new_blob();
3337                 else if (skip_prefix(command_buf.buf, "ls ", &v))
3338                         parse_ls(v, NULL);
3339                 else if (skip_prefix(command_buf.buf, "commit ", &v))
3340                         parse_new_commit(v);
3341                 else if (skip_prefix(command_buf.buf, "tag ", &v))
3342                         parse_new_tag(v);
3343                 else if (skip_prefix(command_buf.buf, "reset ", &v))
3344                         parse_reset_branch(v);
3345                 else if (!strcmp("checkpoint", command_buf.buf))
3346                         parse_checkpoint();
3347                 else if (!strcmp("done", command_buf.buf))
3348                         break;
3349                 else if (starts_with(command_buf.buf, "progress "))
3350                         parse_progress();
3351                 else if (skip_prefix(command_buf.buf, "feature ", &v))
3352                         parse_feature(v);
3353                 else if (skip_prefix(command_buf.buf, "option git ", &v))
3354                         parse_option(v);
3355                 else if (starts_with(command_buf.buf, "option "))
3356                         /* ignore non-git options*/;
3357                 else
3358                         die("Unsupported command: %s", command_buf.buf);
3359
3360                 if (checkpoint_requested)
3361                         checkpoint();
3362         }
3363
3364         /* argv hasn't been parsed yet, do so */
3365         if (!seen_data_command)
3366                 parse_argv();
3367
3368         if (require_explicit_termination && feof(stdin))
3369                 die("stream ends early");
3370
3371         end_packfile();
3372
3373         dump_branches();
3374         dump_tags();
3375         unkeep_all_packs();
3376         dump_marks();
3377
3378         if (pack_edges)
3379                 fclose(pack_edges);
3380
3381         if (show_stats) {
3382                 uintmax_t total_count = 0, duplicate_count = 0;
3383                 for (i = 0; i < ARRAY_SIZE(object_count_by_type); i++)
3384                         total_count += object_count_by_type[i];
3385                 for (i = 0; i < ARRAY_SIZE(duplicate_count_by_type); i++)
3386                         duplicate_count += duplicate_count_by_type[i];
3387
3388                 fprintf(stderr, "%s statistics:\n", argv[0]);
3389                 fprintf(stderr, "---------------------------------------------------------------------\n");
3390                 fprintf(stderr, "Alloc'd objects: %10" PRIuMAX "\n", alloc_count);
3391                 fprintf(stderr, "Total objects:   %10" PRIuMAX " (%10" PRIuMAX " duplicates                  )\n", total_count, duplicate_count);
3392                 fprintf(stderr, "      blobs  :   %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas of %10" PRIuMAX" attempts)\n", object_count_by_type[OBJ_BLOB], duplicate_count_by_type[OBJ_BLOB], delta_count_by_type[OBJ_BLOB], delta_count_attempts_by_type[OBJ_BLOB]);
3393                 fprintf(stderr, "      trees  :   %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas of %10" PRIuMAX" attempts)\n", object_count_by_type[OBJ_TREE], duplicate_count_by_type[OBJ_TREE], delta_count_by_type[OBJ_TREE], delta_count_attempts_by_type[OBJ_TREE]);
3394                 fprintf(stderr, "      commits:   %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas of %10" PRIuMAX" attempts)\n", object_count_by_type[OBJ_COMMIT], duplicate_count_by_type[OBJ_COMMIT], delta_count_by_type[OBJ_COMMIT], delta_count_attempts_by_type[OBJ_COMMIT]);
3395                 fprintf(stderr, "      tags   :   %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas of %10" PRIuMAX" attempts)\n", object_count_by_type[OBJ_TAG], duplicate_count_by_type[OBJ_TAG], delta_count_by_type[OBJ_TAG], delta_count_attempts_by_type[OBJ_TAG]);
3396                 fprintf(stderr, "Total branches:  %10lu (%10lu loads     )\n", branch_count, branch_load_count);
3397                 fprintf(stderr, "      marks:     %10" PRIuMAX " (%10" PRIuMAX " unique    )\n", (((uintmax_t)1) << marks->shift) * 1024, marks_set_count);
3398                 fprintf(stderr, "      atoms:     %10u\n", atom_cnt);
3399                 fprintf(stderr, "Memory total:    %10" PRIuMAX " KiB\n", (tree_entry_allocd + fi_mem_pool.pool_alloc + alloc_count*sizeof(struct object_entry))/1024);
3400                 fprintf(stderr, "       pools:    %10lu KiB\n", (unsigned long)((tree_entry_allocd + fi_mem_pool.pool_alloc) /1024));
3401                 fprintf(stderr, "     objects:    %10" PRIuMAX " KiB\n", (alloc_count*sizeof(struct object_entry))/1024);
3402                 fprintf(stderr, "---------------------------------------------------------------------\n");
3403                 pack_report();
3404                 fprintf(stderr, "---------------------------------------------------------------------\n");
3405                 fprintf(stderr, "\n");
3406         }
3407
3408         return failure ? 1 : 0;
3409 }