commit-graph, fuzz: add fuzzer for commit-graph
[git] / commit-graph.c
1 #include "cache.h"
2 #include "config.h"
3 #include "dir.h"
4 #include "git-compat-util.h"
5 #include "lockfile.h"
6 #include "pack.h"
7 #include "packfile.h"
8 #include "commit.h"
9 #include "object.h"
10 #include "refs.h"
11 #include "revision.h"
12 #include "sha1-lookup.h"
13 #include "commit-graph.h"
14 #include "object-store.h"
15 #include "alloc.h"
16 #include "hashmap.h"
17 #include "replace-object.h"
18 #include "progress.h"
19
20 #define GRAPH_SIGNATURE 0x43475048 /* "CGPH" */
21 #define GRAPH_CHUNKID_OIDFANOUT 0x4f494446 /* "OIDF" */
22 #define GRAPH_CHUNKID_OIDLOOKUP 0x4f49444c /* "OIDL" */
23 #define GRAPH_CHUNKID_DATA 0x43444154 /* "CDAT" */
24 #define GRAPH_CHUNKID_LARGEEDGES 0x45444745 /* "EDGE" */
25
26 #define GRAPH_DATA_WIDTH 36
27
28 #define GRAPH_VERSION_1 0x1
29 #define GRAPH_VERSION GRAPH_VERSION_1
30
31 #define GRAPH_OID_VERSION_SHA1 1
32 #define GRAPH_OID_LEN_SHA1 GIT_SHA1_RAWSZ
33 #define GRAPH_OID_VERSION GRAPH_OID_VERSION_SHA1
34 #define GRAPH_OID_LEN GRAPH_OID_LEN_SHA1
35
36 #define GRAPH_OCTOPUS_EDGES_NEEDED 0x80000000
37 #define GRAPH_PARENT_MISSING 0x7fffffff
38 #define GRAPH_EDGE_LAST_MASK 0x7fffffff
39 #define GRAPH_PARENT_NONE 0x70000000
40
41 #define GRAPH_LAST_EDGE 0x80000000
42
43 #define GRAPH_HEADER_SIZE 8
44 #define GRAPH_FANOUT_SIZE (4 * 256)
45 #define GRAPH_CHUNKLOOKUP_WIDTH 12
46 #define GRAPH_MIN_SIZE (GRAPH_HEADER_SIZE + 4 * GRAPH_CHUNKLOOKUP_WIDTH \
47                         + GRAPH_FANOUT_SIZE + GRAPH_OID_LEN)
48
49 char *get_commit_graph_filename(const char *obj_dir)
50 {
51         return xstrfmt("%s/info/commit-graph", obj_dir);
52 }
53
54 static struct commit_graph *alloc_commit_graph(void)
55 {
56         struct commit_graph *g = xcalloc(1, sizeof(*g));
57         g->graph_fd = -1;
58
59         return g;
60 }
61
62 extern int read_replace_refs;
63
64 static int commit_graph_compatible(struct repository *r)
65 {
66         if (!r->gitdir)
67                 return 0;
68
69         if (read_replace_refs) {
70                 prepare_replace_object(r);
71                 if (hashmap_get_size(&r->objects->replace_map->map))
72                         return 0;
73         }
74
75         prepare_commit_graft(r);
76         if (r->parsed_objects && r->parsed_objects->grafts_nr)
77                 return 0;
78         if (is_repository_shallow(r))
79                 return 0;
80
81         return 1;
82 }
83
84 struct commit_graph *load_commit_graph_one(const char *graph_file)
85 {
86         void *graph_map;
87         size_t graph_size;
88         struct stat st;
89         struct commit_graph *ret;
90         int fd = git_open(graph_file);
91
92         if (fd < 0)
93                 return NULL;
94         if (fstat(fd, &st)) {
95                 close(fd);
96                 return NULL;
97         }
98         graph_size = xsize_t(st.st_size);
99
100         if (graph_size < GRAPH_MIN_SIZE) {
101                 close(fd);
102                 die(_("graph file %s is too small"), graph_file);
103         }
104         graph_map = xmmap(NULL, graph_size, PROT_READ, MAP_PRIVATE, fd, 0);
105         ret = parse_commit_graph(graph_map, fd, graph_size);
106
107         if (!ret) {
108                 munmap(graph_map, graph_size);
109                 close(fd);
110                 exit(1);
111         }
112
113         return ret;
114 }
115
116 struct commit_graph *parse_commit_graph(void *graph_map, int fd,
117                                         size_t graph_size)
118 {
119         const unsigned char *data, *chunk_lookup;
120         uint32_t i;
121         struct commit_graph *graph;
122         uint64_t last_chunk_offset;
123         uint32_t last_chunk_id;
124         uint32_t graph_signature;
125         unsigned char graph_version, hash_version;
126
127         if (!graph_map)
128                 return NULL;
129
130         if (graph_size < GRAPH_MIN_SIZE)
131                 return NULL;
132
133         data = (const unsigned char *)graph_map;
134
135         graph_signature = get_be32(data);
136         if (graph_signature != GRAPH_SIGNATURE) {
137                 error(_("graph signature %X does not match signature %X"),
138                       graph_signature, GRAPH_SIGNATURE);
139                 return NULL;
140         }
141
142         graph_version = *(unsigned char*)(data + 4);
143         if (graph_version != GRAPH_VERSION) {
144                 error(_("graph version %X does not match version %X"),
145                       graph_version, GRAPH_VERSION);
146                 return NULL;
147         }
148
149         hash_version = *(unsigned char*)(data + 5);
150         if (hash_version != GRAPH_OID_VERSION) {
151                 error(_("hash version %X does not match version %X"),
152                       hash_version, GRAPH_OID_VERSION);
153                 return NULL;
154         }
155
156         graph = alloc_commit_graph();
157
158         graph->hash_len = GRAPH_OID_LEN;
159         graph->num_chunks = *(unsigned char*)(data + 6);
160         graph->graph_fd = fd;
161         graph->data = graph_map;
162         graph->data_len = graph_size;
163
164         last_chunk_id = 0;
165         last_chunk_offset = 8;
166         chunk_lookup = data + 8;
167         for (i = 0; i < graph->num_chunks; i++) {
168                 uint32_t chunk_id = get_be32(chunk_lookup + 0);
169                 uint64_t chunk_offset = get_be64(chunk_lookup + 4);
170                 int chunk_repeated = 0;
171
172                 chunk_lookup += GRAPH_CHUNKLOOKUP_WIDTH;
173
174                 if (chunk_offset > graph_size - GIT_MAX_RAWSZ) {
175                         error(_("improper chunk offset %08x%08x"), (uint32_t)(chunk_offset >> 32),
176                               (uint32_t)chunk_offset);
177                         free(graph);
178                         return NULL;
179                 }
180
181                 switch (chunk_id) {
182                 case GRAPH_CHUNKID_OIDFANOUT:
183                         if (graph->chunk_oid_fanout)
184                                 chunk_repeated = 1;
185                         else
186                                 graph->chunk_oid_fanout = (uint32_t*)(data + chunk_offset);
187                         break;
188
189                 case GRAPH_CHUNKID_OIDLOOKUP:
190                         if (graph->chunk_oid_lookup)
191                                 chunk_repeated = 1;
192                         else
193                                 graph->chunk_oid_lookup = data + chunk_offset;
194                         break;
195
196                 case GRAPH_CHUNKID_DATA:
197                         if (graph->chunk_commit_data)
198                                 chunk_repeated = 1;
199                         else
200                                 graph->chunk_commit_data = data + chunk_offset;
201                         break;
202
203                 case GRAPH_CHUNKID_LARGEEDGES:
204                         if (graph->chunk_large_edges)
205                                 chunk_repeated = 1;
206                         else
207                                 graph->chunk_large_edges = data + chunk_offset;
208                         break;
209                 }
210
211                 if (chunk_repeated) {
212                         error(_("chunk id %08x appears multiple times"), chunk_id);
213                         free(graph);
214                         return NULL;
215                 }
216
217                 if (last_chunk_id == GRAPH_CHUNKID_OIDLOOKUP)
218                 {
219                         graph->num_commits = (chunk_offset - last_chunk_offset)
220                                              / graph->hash_len;
221                 }
222
223                 last_chunk_id = chunk_id;
224                 last_chunk_offset = chunk_offset;
225         }
226
227         return graph;
228 }
229
230 static void prepare_commit_graph_one(struct repository *r, const char *obj_dir)
231 {
232         char *graph_name;
233
234         if (r->objects->commit_graph)
235                 return;
236
237         graph_name = get_commit_graph_filename(obj_dir);
238         r->objects->commit_graph =
239                 load_commit_graph_one(graph_name);
240
241         FREE_AND_NULL(graph_name);
242 }
243
244 /*
245  * Return 1 if commit_graph is non-NULL, and 0 otherwise.
246  *
247  * On the first invocation, this function attemps to load the commit
248  * graph if the_repository is configured to have one.
249  */
250 static int prepare_commit_graph(struct repository *r)
251 {
252         struct object_directory *odb;
253         int config_value;
254
255         if (r->objects->commit_graph_attempted)
256                 return !!r->objects->commit_graph;
257         r->objects->commit_graph_attempted = 1;
258
259         if (!git_env_bool(GIT_TEST_COMMIT_GRAPH, 0) &&
260             (repo_config_get_bool(r, "core.commitgraph", &config_value) ||
261             !config_value))
262                 /*
263                  * This repository is not configured to use commit graphs, so
264                  * do not load one. (But report commit_graph_attempted anyway
265                  * so that commit graph loading is not attempted again for this
266                  * repository.)
267                  */
268                 return 0;
269
270         if (!commit_graph_compatible(r))
271                 return 0;
272
273         prepare_alt_odb(r);
274         for (odb = r->objects->odb;
275              !r->objects->commit_graph && odb;
276              odb = odb->next)
277                 prepare_commit_graph_one(r, odb->path);
278         return !!r->objects->commit_graph;
279 }
280
281 int generation_numbers_enabled(struct repository *r)
282 {
283         uint32_t first_generation;
284         struct commit_graph *g;
285         if (!prepare_commit_graph(r))
286                return 0;
287
288         g = r->objects->commit_graph;
289
290         if (!g->num_commits)
291                 return 0;
292
293         first_generation = get_be32(g->chunk_commit_data +
294                                     g->hash_len + 8) >> 2;
295
296         return !!first_generation;
297 }
298
299 void close_commit_graph(struct repository *r)
300 {
301         free_commit_graph(r->objects->commit_graph);
302         r->objects->commit_graph = NULL;
303 }
304
305 static int bsearch_graph(struct commit_graph *g, struct object_id *oid, uint32_t *pos)
306 {
307         return bsearch_hash(oid->hash, g->chunk_oid_fanout,
308                             g->chunk_oid_lookup, g->hash_len, pos);
309 }
310
311 static struct commit_list **insert_parent_or_die(struct commit_graph *g,
312                                                  uint64_t pos,
313                                                  struct commit_list **pptr)
314 {
315         struct commit *c;
316         struct object_id oid;
317
318         if (pos >= g->num_commits)
319                 die("invalid parent position %"PRIu64, pos);
320
321         hashcpy(oid.hash, g->chunk_oid_lookup + g->hash_len * pos);
322         c = lookup_commit(the_repository, &oid);
323         if (!c)
324                 die(_("could not find commit %s"), oid_to_hex(&oid));
325         c->graph_pos = pos;
326         return &commit_list_insert(c, pptr)->next;
327 }
328
329 static void fill_commit_graph_info(struct commit *item, struct commit_graph *g, uint32_t pos)
330 {
331         const unsigned char *commit_data = g->chunk_commit_data + GRAPH_DATA_WIDTH * pos;
332         item->graph_pos = pos;
333         item->generation = get_be32(commit_data + g->hash_len + 8) >> 2;
334 }
335
336 static int fill_commit_in_graph(struct commit *item, struct commit_graph *g, uint32_t pos)
337 {
338         uint32_t edge_value;
339         uint32_t *parent_data_ptr;
340         uint64_t date_low, date_high;
341         struct commit_list **pptr;
342         const unsigned char *commit_data = g->chunk_commit_data + (g->hash_len + 16) * pos;
343
344         item->object.parsed = 1;
345         item->graph_pos = pos;
346
347         item->maybe_tree = NULL;
348
349         date_high = get_be32(commit_data + g->hash_len + 8) & 0x3;
350         date_low = get_be32(commit_data + g->hash_len + 12);
351         item->date = (timestamp_t)((date_high << 32) | date_low);
352
353         item->generation = get_be32(commit_data + g->hash_len + 8) >> 2;
354
355         pptr = &item->parents;
356
357         edge_value = get_be32(commit_data + g->hash_len);
358         if (edge_value == GRAPH_PARENT_NONE)
359                 return 1;
360         pptr = insert_parent_or_die(g, edge_value, pptr);
361
362         edge_value = get_be32(commit_data + g->hash_len + 4);
363         if (edge_value == GRAPH_PARENT_NONE)
364                 return 1;
365         if (!(edge_value & GRAPH_OCTOPUS_EDGES_NEEDED)) {
366                 pptr = insert_parent_or_die(g, edge_value, pptr);
367                 return 1;
368         }
369
370         parent_data_ptr = (uint32_t*)(g->chunk_large_edges +
371                           4 * (uint64_t)(edge_value & GRAPH_EDGE_LAST_MASK));
372         do {
373                 edge_value = get_be32(parent_data_ptr);
374                 pptr = insert_parent_or_die(g,
375                                             edge_value & GRAPH_EDGE_LAST_MASK,
376                                             pptr);
377                 parent_data_ptr++;
378         } while (!(edge_value & GRAPH_LAST_EDGE));
379
380         return 1;
381 }
382
383 static int find_commit_in_graph(struct commit *item, struct commit_graph *g, uint32_t *pos)
384 {
385         if (item->graph_pos != COMMIT_NOT_FROM_GRAPH) {
386                 *pos = item->graph_pos;
387                 return 1;
388         } else {
389                 return bsearch_graph(g, &(item->object.oid), pos);
390         }
391 }
392
393 static int parse_commit_in_graph_one(struct commit_graph *g, struct commit *item)
394 {
395         uint32_t pos;
396
397         if (item->object.parsed)
398                 return 1;
399
400         if (find_commit_in_graph(item, g, &pos))
401                 return fill_commit_in_graph(item, g, pos);
402
403         return 0;
404 }
405
406 int parse_commit_in_graph(struct repository *r, struct commit *item)
407 {
408         if (!prepare_commit_graph(r))
409                 return 0;
410         return parse_commit_in_graph_one(r->objects->commit_graph, item);
411 }
412
413 void load_commit_graph_info(struct repository *r, struct commit *item)
414 {
415         uint32_t pos;
416         if (!prepare_commit_graph(r))
417                 return;
418         if (find_commit_in_graph(item, r->objects->commit_graph, &pos))
419                 fill_commit_graph_info(item, r->objects->commit_graph, pos);
420 }
421
422 static struct tree *load_tree_for_commit(struct commit_graph *g, struct commit *c)
423 {
424         struct object_id oid;
425         const unsigned char *commit_data = g->chunk_commit_data +
426                                            GRAPH_DATA_WIDTH * (c->graph_pos);
427
428         hashcpy(oid.hash, commit_data);
429         c->maybe_tree = lookup_tree(the_repository, &oid);
430
431         return c->maybe_tree;
432 }
433
434 static struct tree *get_commit_tree_in_graph_one(struct commit_graph *g,
435                                                  const struct commit *c)
436 {
437         if (c->maybe_tree)
438                 return c->maybe_tree;
439         if (c->graph_pos == COMMIT_NOT_FROM_GRAPH)
440                 BUG("get_commit_tree_in_graph_one called from non-commit-graph commit");
441
442         return load_tree_for_commit(g, (struct commit *)c);
443 }
444
445 struct tree *get_commit_tree_in_graph(struct repository *r, const struct commit *c)
446 {
447         return get_commit_tree_in_graph_one(r->objects->commit_graph, c);
448 }
449
450 static void write_graph_chunk_fanout(struct hashfile *f,
451                                      struct commit **commits,
452                                      int nr_commits)
453 {
454         int i, count = 0;
455         struct commit **list = commits;
456
457         /*
458          * Write the first-level table (the list is sorted,
459          * but we use a 256-entry lookup to be able to avoid
460          * having to do eight extra binary search iterations).
461          */
462         for (i = 0; i < 256; i++) {
463                 while (count < nr_commits) {
464                         if ((*list)->object.oid.hash[0] != i)
465                                 break;
466                         count++;
467                         list++;
468                 }
469
470                 hashwrite_be32(f, count);
471         }
472 }
473
474 static void write_graph_chunk_oids(struct hashfile *f, int hash_len,
475                                    struct commit **commits, int nr_commits)
476 {
477         struct commit **list = commits;
478         int count;
479         for (count = 0; count < nr_commits; count++, list++)
480                 hashwrite(f, (*list)->object.oid.hash, (int)hash_len);
481 }
482
483 static const unsigned char *commit_to_sha1(size_t index, void *table)
484 {
485         struct commit **commits = table;
486         return commits[index]->object.oid.hash;
487 }
488
489 static void write_graph_chunk_data(struct hashfile *f, int hash_len,
490                                    struct commit **commits, int nr_commits)
491 {
492         struct commit **list = commits;
493         struct commit **last = commits + nr_commits;
494         uint32_t num_extra_edges = 0;
495
496         while (list < last) {
497                 struct commit_list *parent;
498                 int edge_value;
499                 uint32_t packedDate[2];
500
501                 parse_commit(*list);
502                 hashwrite(f, get_commit_tree_oid(*list)->hash, hash_len);
503
504                 parent = (*list)->parents;
505
506                 if (!parent)
507                         edge_value = GRAPH_PARENT_NONE;
508                 else {
509                         edge_value = sha1_pos(parent->item->object.oid.hash,
510                                               commits,
511                                               nr_commits,
512                                               commit_to_sha1);
513
514                         if (edge_value < 0)
515                                 edge_value = GRAPH_PARENT_MISSING;
516                 }
517
518                 hashwrite_be32(f, edge_value);
519
520                 if (parent)
521                         parent = parent->next;
522
523                 if (!parent)
524                         edge_value = GRAPH_PARENT_NONE;
525                 else if (parent->next)
526                         edge_value = GRAPH_OCTOPUS_EDGES_NEEDED | num_extra_edges;
527                 else {
528                         edge_value = sha1_pos(parent->item->object.oid.hash,
529                                               commits,
530                                               nr_commits,
531                                               commit_to_sha1);
532                         if (edge_value < 0)
533                                 edge_value = GRAPH_PARENT_MISSING;
534                 }
535
536                 hashwrite_be32(f, edge_value);
537
538                 if (edge_value & GRAPH_OCTOPUS_EDGES_NEEDED) {
539                         do {
540                                 num_extra_edges++;
541                                 parent = parent->next;
542                         } while (parent);
543                 }
544
545                 if (sizeof((*list)->date) > 4)
546                         packedDate[0] = htonl(((*list)->date >> 32) & 0x3);
547                 else
548                         packedDate[0] = 0;
549
550                 packedDate[0] |= htonl((*list)->generation << 2);
551
552                 packedDate[1] = htonl((*list)->date);
553                 hashwrite(f, packedDate, 8);
554
555                 list++;
556         }
557 }
558
559 static void write_graph_chunk_large_edges(struct hashfile *f,
560                                           struct commit **commits,
561                                           int nr_commits)
562 {
563         struct commit **list = commits;
564         struct commit **last = commits + nr_commits;
565         struct commit_list *parent;
566
567         while (list < last) {
568                 int num_parents = 0;
569                 for (parent = (*list)->parents; num_parents < 3 && parent;
570                      parent = parent->next)
571                         num_parents++;
572
573                 if (num_parents <= 2) {
574                         list++;
575                         continue;
576                 }
577
578                 /* Since num_parents > 2, this initializer is safe. */
579                 for (parent = (*list)->parents->next; parent; parent = parent->next) {
580                         int edge_value = sha1_pos(parent->item->object.oid.hash,
581                                                   commits,
582                                                   nr_commits,
583                                                   commit_to_sha1);
584
585                         if (edge_value < 0)
586                                 edge_value = GRAPH_PARENT_MISSING;
587                         else if (!parent->next)
588                                 edge_value |= GRAPH_LAST_EDGE;
589
590                         hashwrite_be32(f, edge_value);
591                 }
592
593                 list++;
594         }
595 }
596
597 static int commit_compare(const void *_a, const void *_b)
598 {
599         const struct object_id *a = (const struct object_id *)_a;
600         const struct object_id *b = (const struct object_id *)_b;
601         return oidcmp(a, b);
602 }
603
604 struct packed_commit_list {
605         struct commit **list;
606         int nr;
607         int alloc;
608 };
609
610 struct packed_oid_list {
611         struct object_id *list;
612         int nr;
613         int alloc;
614         struct progress *progress;
615         int progress_done;
616 };
617
618 static int add_packed_commits(const struct object_id *oid,
619                               struct packed_git *pack,
620                               uint32_t pos,
621                               void *data)
622 {
623         struct packed_oid_list *list = (struct packed_oid_list*)data;
624         enum object_type type;
625         off_t offset = nth_packed_object_offset(pack, pos);
626         struct object_info oi = OBJECT_INFO_INIT;
627
628         if (list->progress)
629                 display_progress(list->progress, ++list->progress_done);
630
631         oi.typep = &type;
632         if (packed_object_info(the_repository, pack, offset, &oi) < 0)
633                 die(_("unable to get type of object %s"), oid_to_hex(oid));
634
635         if (type != OBJ_COMMIT)
636                 return 0;
637
638         ALLOC_GROW(list->list, list->nr + 1, list->alloc);
639         oidcpy(&(list->list[list->nr]), oid);
640         list->nr++;
641
642         return 0;
643 }
644
645 static void add_missing_parents(struct packed_oid_list *oids, struct commit *commit)
646 {
647         struct commit_list *parent;
648         for (parent = commit->parents; parent; parent = parent->next) {
649                 if (!(parent->item->object.flags & UNINTERESTING)) {
650                         ALLOC_GROW(oids->list, oids->nr + 1, oids->alloc);
651                         oidcpy(&oids->list[oids->nr], &(parent->item->object.oid));
652                         oids->nr++;
653                         parent->item->object.flags |= UNINTERESTING;
654                 }
655         }
656 }
657
658 static void close_reachable(struct packed_oid_list *oids, int report_progress)
659 {
660         int i, j;
661         struct commit *commit;
662         struct progress *progress = NULL;
663
664         if (report_progress)
665                 progress = start_delayed_progress(
666                         _("Loading known commits in commit graph"), j = 0);
667         for (i = 0; i < oids->nr; i++) {
668                 display_progress(progress, ++j);
669                 commit = lookup_commit(the_repository, &oids->list[i]);
670                 if (commit)
671                         commit->object.flags |= UNINTERESTING;
672         }
673         stop_progress(&progress);
674
675         /*
676          * As this loop runs, oids->nr may grow, but not more
677          * than the number of missing commits in the reachable
678          * closure.
679          */
680         if (report_progress)
681                 progress = start_delayed_progress(
682                         _("Expanding reachable commits in commit graph"), j = 0);
683         for (i = 0; i < oids->nr; i++) {
684                 display_progress(progress, ++j);
685                 commit = lookup_commit(the_repository, &oids->list[i]);
686
687                 if (commit && !parse_commit(commit))
688                         add_missing_parents(oids, commit);
689         }
690         stop_progress(&progress);
691
692         if (report_progress)
693                 progress = start_delayed_progress(
694                         _("Clearing commit marks in commit graph"), j = 0);
695         for (i = 0; i < oids->nr; i++) {
696                 display_progress(progress, ++j);
697                 commit = lookup_commit(the_repository, &oids->list[i]);
698
699                 if (commit)
700                         commit->object.flags &= ~UNINTERESTING;
701         }
702         stop_progress(&progress);
703 }
704
705 static void compute_generation_numbers(struct packed_commit_list* commits,
706                                        int report_progress)
707 {
708         int i;
709         struct commit_list *list = NULL;
710         struct progress *progress = NULL;
711
712         if (report_progress)
713                 progress = start_progress(
714                         _("Computing commit graph generation numbers"),
715                         commits->nr);
716         for (i = 0; i < commits->nr; i++) {
717                 display_progress(progress, i + 1);
718                 if (commits->list[i]->generation != GENERATION_NUMBER_INFINITY &&
719                     commits->list[i]->generation != GENERATION_NUMBER_ZERO)
720                         continue;
721
722                 commit_list_insert(commits->list[i], &list);
723                 while (list) {
724                         struct commit *current = list->item;
725                         struct commit_list *parent;
726                         int all_parents_computed = 1;
727                         uint32_t max_generation = 0;
728
729                         for (parent = current->parents; parent; parent = parent->next) {
730                                 if (parent->item->generation == GENERATION_NUMBER_INFINITY ||
731                                     parent->item->generation == GENERATION_NUMBER_ZERO) {
732                                         all_parents_computed = 0;
733                                         commit_list_insert(parent->item, &list);
734                                         break;
735                                 } else if (parent->item->generation > max_generation) {
736                                         max_generation = parent->item->generation;
737                                 }
738                         }
739
740                         if (all_parents_computed) {
741                                 current->generation = max_generation + 1;
742                                 pop_commit(&list);
743
744                                 if (current->generation > GENERATION_NUMBER_MAX)
745                                         current->generation = GENERATION_NUMBER_MAX;
746                         }
747                 }
748         }
749         stop_progress(&progress);
750 }
751
752 static int add_ref_to_list(const char *refname,
753                            const struct object_id *oid,
754                            int flags, void *cb_data)
755 {
756         struct string_list *list = (struct string_list *)cb_data;
757
758         string_list_append(list, oid_to_hex(oid));
759         return 0;
760 }
761
762 void write_commit_graph_reachable(const char *obj_dir, int append,
763                                   int report_progress)
764 {
765         struct string_list list = STRING_LIST_INIT_DUP;
766
767         for_each_ref(add_ref_to_list, &list);
768         write_commit_graph(obj_dir, NULL, &list, append, report_progress);
769
770         string_list_clear(&list, 0);
771 }
772
773 void write_commit_graph(const char *obj_dir,
774                         struct string_list *pack_indexes,
775                         struct string_list *commit_hex,
776                         int append, int report_progress)
777 {
778         struct packed_oid_list oids;
779         struct packed_commit_list commits;
780         struct hashfile *f;
781         uint32_t i, count_distinct = 0;
782         char *graph_name;
783         struct lock_file lk = LOCK_INIT;
784         uint32_t chunk_ids[5];
785         uint64_t chunk_offsets[5];
786         int num_chunks;
787         int num_extra_edges;
788         struct commit_list *parent;
789         struct progress *progress = NULL;
790
791         if (!commit_graph_compatible(the_repository))
792                 return;
793
794         oids.nr = 0;
795         oids.alloc = approximate_object_count() / 32;
796         oids.progress = NULL;
797         oids.progress_done = 0;
798
799         if (append) {
800                 prepare_commit_graph_one(the_repository, obj_dir);
801                 if (the_repository->objects->commit_graph)
802                         oids.alloc += the_repository->objects->commit_graph->num_commits;
803         }
804
805         if (oids.alloc < 1024)
806                 oids.alloc = 1024;
807         ALLOC_ARRAY(oids.list, oids.alloc);
808
809         if (append && the_repository->objects->commit_graph) {
810                 struct commit_graph *commit_graph =
811                         the_repository->objects->commit_graph;
812                 for (i = 0; i < commit_graph->num_commits; i++) {
813                         const unsigned char *hash = commit_graph->chunk_oid_lookup +
814                                 commit_graph->hash_len * i;
815                         hashcpy(oids.list[oids.nr++].hash, hash);
816                 }
817         }
818
819         if (pack_indexes) {
820                 struct strbuf packname = STRBUF_INIT;
821                 int dirlen;
822                 strbuf_addf(&packname, "%s/pack/", obj_dir);
823                 dirlen = packname.len;
824                 if (report_progress) {
825                         oids.progress = start_delayed_progress(
826                                 _("Finding commits for commit graph"), 0);
827                         oids.progress_done = 0;
828                 }
829                 for (i = 0; i < pack_indexes->nr; i++) {
830                         struct packed_git *p;
831                         strbuf_setlen(&packname, dirlen);
832                         strbuf_addstr(&packname, pack_indexes->items[i].string);
833                         p = add_packed_git(packname.buf, packname.len, 1);
834                         if (!p)
835                                 die(_("error adding pack %s"), packname.buf);
836                         if (open_pack_index(p))
837                                 die(_("error opening index for %s"), packname.buf);
838                         for_each_object_in_pack(p, add_packed_commits, &oids, 0);
839                         close_pack(p);
840                         free(p);
841                 }
842                 stop_progress(&oids.progress);
843                 strbuf_release(&packname);
844         }
845
846         if (commit_hex) {
847                 if (report_progress)
848                         progress = start_delayed_progress(
849                                 _("Finding commits for commit graph"),
850                                 commit_hex->nr);
851                 for (i = 0; i < commit_hex->nr; i++) {
852                         const char *end;
853                         struct object_id oid;
854                         struct commit *result;
855
856                         display_progress(progress, i + 1);
857                         if (commit_hex->items[i].string &&
858                             parse_oid_hex(commit_hex->items[i].string, &oid, &end))
859                                 continue;
860
861                         result = lookup_commit_reference_gently(the_repository, &oid, 1);
862
863                         if (result) {
864                                 ALLOC_GROW(oids.list, oids.nr + 1, oids.alloc);
865                                 oidcpy(&oids.list[oids.nr], &(result->object.oid));
866                                 oids.nr++;
867                         }
868                 }
869                 stop_progress(&progress);
870         }
871
872         if (!pack_indexes && !commit_hex) {
873                 if (report_progress)
874                         oids.progress = start_delayed_progress(
875                                 _("Finding commits for commit graph"), 0);
876                 for_each_packed_object(add_packed_commits, &oids, 0);
877                 stop_progress(&oids.progress);
878         }
879
880         close_reachable(&oids, report_progress);
881
882         QSORT(oids.list, oids.nr, commit_compare);
883
884         count_distinct = 1;
885         for (i = 1; i < oids.nr; i++) {
886                 if (!oideq(&oids.list[i - 1], &oids.list[i]))
887                         count_distinct++;
888         }
889
890         if (count_distinct >= GRAPH_PARENT_MISSING)
891                 die(_("the commit graph format cannot write %d commits"), count_distinct);
892
893         commits.nr = 0;
894         commits.alloc = count_distinct;
895         ALLOC_ARRAY(commits.list, commits.alloc);
896
897         num_extra_edges = 0;
898         for (i = 0; i < oids.nr; i++) {
899                 int num_parents = 0;
900                 if (i > 0 && oideq(&oids.list[i - 1], &oids.list[i]))
901                         continue;
902
903                 commits.list[commits.nr] = lookup_commit(the_repository, &oids.list[i]);
904                 parse_commit(commits.list[commits.nr]);
905
906                 for (parent = commits.list[commits.nr]->parents;
907                      parent; parent = parent->next)
908                         num_parents++;
909
910                 if (num_parents > 2)
911                         num_extra_edges += num_parents - 1;
912
913                 commits.nr++;
914         }
915         num_chunks = num_extra_edges ? 4 : 3;
916
917         if (commits.nr >= GRAPH_PARENT_MISSING)
918                 die(_("too many commits to write graph"));
919
920         compute_generation_numbers(&commits, report_progress);
921
922         graph_name = get_commit_graph_filename(obj_dir);
923         if (safe_create_leading_directories(graph_name)) {
924                 UNLEAK(graph_name);
925                 die_errno(_("unable to create leading directories of %s"),
926                           graph_name);
927         }
928
929         hold_lock_file_for_update(&lk, graph_name, LOCK_DIE_ON_ERROR);
930         f = hashfd(lk.tempfile->fd, lk.tempfile->filename.buf);
931
932         hashwrite_be32(f, GRAPH_SIGNATURE);
933
934         hashwrite_u8(f, GRAPH_VERSION);
935         hashwrite_u8(f, GRAPH_OID_VERSION);
936         hashwrite_u8(f, num_chunks);
937         hashwrite_u8(f, 0); /* unused padding byte */
938
939         chunk_ids[0] = GRAPH_CHUNKID_OIDFANOUT;
940         chunk_ids[1] = GRAPH_CHUNKID_OIDLOOKUP;
941         chunk_ids[2] = GRAPH_CHUNKID_DATA;
942         if (num_extra_edges)
943                 chunk_ids[3] = GRAPH_CHUNKID_LARGEEDGES;
944         else
945                 chunk_ids[3] = 0;
946         chunk_ids[4] = 0;
947
948         chunk_offsets[0] = 8 + (num_chunks + 1) * GRAPH_CHUNKLOOKUP_WIDTH;
949         chunk_offsets[1] = chunk_offsets[0] + GRAPH_FANOUT_SIZE;
950         chunk_offsets[2] = chunk_offsets[1] + GRAPH_OID_LEN * commits.nr;
951         chunk_offsets[3] = chunk_offsets[2] + (GRAPH_OID_LEN + 16) * commits.nr;
952         chunk_offsets[4] = chunk_offsets[3] + 4 * num_extra_edges;
953
954         for (i = 0; i <= num_chunks; i++) {
955                 uint32_t chunk_write[3];
956
957                 chunk_write[0] = htonl(chunk_ids[i]);
958                 chunk_write[1] = htonl(chunk_offsets[i] >> 32);
959                 chunk_write[2] = htonl(chunk_offsets[i] & 0xffffffff);
960                 hashwrite(f, chunk_write, 12);
961         }
962
963         write_graph_chunk_fanout(f, commits.list, commits.nr);
964         write_graph_chunk_oids(f, GRAPH_OID_LEN, commits.list, commits.nr);
965         write_graph_chunk_data(f, GRAPH_OID_LEN, commits.list, commits.nr);
966         write_graph_chunk_large_edges(f, commits.list, commits.nr);
967
968         close_commit_graph(the_repository);
969         finalize_hashfile(f, NULL, CSUM_HASH_IN_STREAM | CSUM_FSYNC);
970         commit_lock_file(&lk);
971
972         free(graph_name);
973         free(commits.list);
974         free(oids.list);
975 }
976
977 #define VERIFY_COMMIT_GRAPH_ERROR_HASH 2
978 static int verify_commit_graph_error;
979
980 static void graph_report(const char *fmt, ...)
981 {
982         va_list ap;
983
984         verify_commit_graph_error = 1;
985         va_start(ap, fmt);
986         vfprintf(stderr, fmt, ap);
987         fprintf(stderr, "\n");
988         va_end(ap);
989 }
990
991 #define GENERATION_ZERO_EXISTS 1
992 #define GENERATION_NUMBER_EXISTS 2
993
994 int verify_commit_graph(struct repository *r, struct commit_graph *g)
995 {
996         uint32_t i, cur_fanout_pos = 0;
997         struct object_id prev_oid, cur_oid, checksum;
998         int generation_zero = 0;
999         struct hashfile *f;
1000         int devnull;
1001         struct progress *progress = NULL;
1002
1003         if (!g) {
1004                 graph_report("no commit-graph file loaded");
1005                 return 1;
1006         }
1007
1008         verify_commit_graph_error = 0;
1009
1010         if (!g->chunk_oid_fanout)
1011                 graph_report("commit-graph is missing the OID Fanout chunk");
1012         if (!g->chunk_oid_lookup)
1013                 graph_report("commit-graph is missing the OID Lookup chunk");
1014         if (!g->chunk_commit_data)
1015                 graph_report("commit-graph is missing the Commit Data chunk");
1016
1017         if (verify_commit_graph_error)
1018                 return verify_commit_graph_error;
1019
1020         devnull = open("/dev/null", O_WRONLY);
1021         f = hashfd(devnull, NULL);
1022         hashwrite(f, g->data, g->data_len - g->hash_len);
1023         finalize_hashfile(f, checksum.hash, CSUM_CLOSE);
1024         if (!hasheq(checksum.hash, g->data + g->data_len - g->hash_len)) {
1025                 graph_report(_("the commit-graph file has incorrect checksum and is likely corrupt"));
1026                 verify_commit_graph_error = VERIFY_COMMIT_GRAPH_ERROR_HASH;
1027         }
1028
1029         for (i = 0; i < g->num_commits; i++) {
1030                 struct commit *graph_commit;
1031
1032                 hashcpy(cur_oid.hash, g->chunk_oid_lookup + g->hash_len * i);
1033
1034                 if (i && oidcmp(&prev_oid, &cur_oid) >= 0)
1035                         graph_report("commit-graph has incorrect OID order: %s then %s",
1036                                      oid_to_hex(&prev_oid),
1037                                      oid_to_hex(&cur_oid));
1038
1039                 oidcpy(&prev_oid, &cur_oid);
1040
1041                 while (cur_oid.hash[0] > cur_fanout_pos) {
1042                         uint32_t fanout_value = get_be32(g->chunk_oid_fanout + cur_fanout_pos);
1043
1044                         if (i != fanout_value)
1045                                 graph_report("commit-graph has incorrect fanout value: fanout[%d] = %u != %u",
1046                                              cur_fanout_pos, fanout_value, i);
1047                         cur_fanout_pos++;
1048                 }
1049
1050                 graph_commit = lookup_commit(r, &cur_oid);
1051                 if (!parse_commit_in_graph_one(g, graph_commit))
1052                         graph_report("failed to parse %s from commit-graph",
1053                                      oid_to_hex(&cur_oid));
1054         }
1055
1056         while (cur_fanout_pos < 256) {
1057                 uint32_t fanout_value = get_be32(g->chunk_oid_fanout + cur_fanout_pos);
1058
1059                 if (g->num_commits != fanout_value)
1060                         graph_report("commit-graph has incorrect fanout value: fanout[%d] = %u != %u",
1061                                      cur_fanout_pos, fanout_value, i);
1062
1063                 cur_fanout_pos++;
1064         }
1065
1066         if (verify_commit_graph_error & ~VERIFY_COMMIT_GRAPH_ERROR_HASH)
1067                 return verify_commit_graph_error;
1068
1069         progress = start_progress(_("Verifying commits in commit graph"),
1070                                   g->num_commits);
1071         for (i = 0; i < g->num_commits; i++) {
1072                 struct commit *graph_commit, *odb_commit;
1073                 struct commit_list *graph_parents, *odb_parents;
1074                 uint32_t max_generation = 0;
1075
1076                 display_progress(progress, i + 1);
1077                 hashcpy(cur_oid.hash, g->chunk_oid_lookup + g->hash_len * i);
1078
1079                 graph_commit = lookup_commit(r, &cur_oid);
1080                 odb_commit = (struct commit *)create_object(r, cur_oid.hash, alloc_commit_node(r));
1081                 if (parse_commit_internal(odb_commit, 0, 0)) {
1082                         graph_report("failed to parse %s from object database",
1083                                      oid_to_hex(&cur_oid));
1084                         continue;
1085                 }
1086
1087                 if (!oideq(&get_commit_tree_in_graph_one(g, graph_commit)->object.oid,
1088                            get_commit_tree_oid(odb_commit)))
1089                         graph_report("root tree OID for commit %s in commit-graph is %s != %s",
1090                                      oid_to_hex(&cur_oid),
1091                                      oid_to_hex(get_commit_tree_oid(graph_commit)),
1092                                      oid_to_hex(get_commit_tree_oid(odb_commit)));
1093
1094                 graph_parents = graph_commit->parents;
1095                 odb_parents = odb_commit->parents;
1096
1097                 while (graph_parents) {
1098                         if (odb_parents == NULL) {
1099                                 graph_report("commit-graph parent list for commit %s is too long",
1100                                              oid_to_hex(&cur_oid));
1101                                 break;
1102                         }
1103
1104                         if (!oideq(&graph_parents->item->object.oid, &odb_parents->item->object.oid))
1105                                 graph_report("commit-graph parent for %s is %s != %s",
1106                                              oid_to_hex(&cur_oid),
1107                                              oid_to_hex(&graph_parents->item->object.oid),
1108                                              oid_to_hex(&odb_parents->item->object.oid));
1109
1110                         if (graph_parents->item->generation > max_generation)
1111                                 max_generation = graph_parents->item->generation;
1112
1113                         graph_parents = graph_parents->next;
1114                         odb_parents = odb_parents->next;
1115                 }
1116
1117                 if (odb_parents != NULL)
1118                         graph_report("commit-graph parent list for commit %s terminates early",
1119                                      oid_to_hex(&cur_oid));
1120
1121                 if (!graph_commit->generation) {
1122                         if (generation_zero == GENERATION_NUMBER_EXISTS)
1123                                 graph_report("commit-graph has generation number zero for commit %s, but non-zero elsewhere",
1124                                              oid_to_hex(&cur_oid));
1125                         generation_zero = GENERATION_ZERO_EXISTS;
1126                 } else if (generation_zero == GENERATION_ZERO_EXISTS)
1127                         graph_report("commit-graph has non-zero generation number for commit %s, but zero elsewhere",
1128                                      oid_to_hex(&cur_oid));
1129
1130                 if (generation_zero == GENERATION_ZERO_EXISTS)
1131                         continue;
1132
1133                 /*
1134                  * If one of our parents has generation GENERATION_NUMBER_MAX, then
1135                  * our generation is also GENERATION_NUMBER_MAX. Decrement to avoid
1136                  * extra logic in the following condition.
1137                  */
1138                 if (max_generation == GENERATION_NUMBER_MAX)
1139                         max_generation--;
1140
1141                 if (graph_commit->generation != max_generation + 1)
1142                         graph_report("commit-graph generation for commit %s is %u != %u",
1143                                      oid_to_hex(&cur_oid),
1144                                      graph_commit->generation,
1145                                      max_generation + 1);
1146
1147                 if (graph_commit->date != odb_commit->date)
1148                         graph_report("commit date for commit %s in commit-graph is %"PRItime" != %"PRItime,
1149                                      oid_to_hex(&cur_oid),
1150                                      graph_commit->date,
1151                                      odb_commit->date);
1152         }
1153         stop_progress(&progress);
1154
1155         return verify_commit_graph_error;
1156 }
1157
1158 void free_commit_graph(struct commit_graph *g)
1159 {
1160         if (!g)
1161                 return;
1162         if (g->graph_fd >= 0) {
1163                 munmap((void *)g->data, g->data_len);
1164                 g->data = NULL;
1165                 close(g->graph_fd);
1166         }
1167         free(g);
1168 }