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