commit-graph: rearrange chunk count logic
[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_EXTRAEDGES 0x45444745 /* "EDGE" */
25 #define GRAPH_CHUNKID_BASE 0x42415345 /* "BASE" */
26
27 #define GRAPH_DATA_WIDTH (the_hash_algo->rawsz + 16)
28
29 #define GRAPH_VERSION_1 0x1
30 #define GRAPH_VERSION GRAPH_VERSION_1
31
32 #define GRAPH_EXTRA_EDGES_NEEDED 0x80000000
33 #define GRAPH_EDGE_LAST_MASK 0x7fffffff
34 #define GRAPH_PARENT_NONE 0x70000000
35
36 #define GRAPH_LAST_EDGE 0x80000000
37
38 #define GRAPH_HEADER_SIZE 8
39 #define GRAPH_FANOUT_SIZE (4 * 256)
40 #define GRAPH_CHUNKLOOKUP_WIDTH 12
41 #define GRAPH_MIN_SIZE (GRAPH_HEADER_SIZE + 4 * GRAPH_CHUNKLOOKUP_WIDTH \
42                         + GRAPH_FANOUT_SIZE + the_hash_algo->rawsz)
43
44 char *get_commit_graph_filename(const char *obj_dir)
45 {
46         return xstrfmt("%s/info/commit-graph", obj_dir);
47 }
48
49 static char *get_split_graph_filename(const char *obj_dir,
50                                       const char *oid_hex)
51 {
52         return xstrfmt("%s/info/commit-graphs/graph-%s.graph",
53                        obj_dir,
54                        oid_hex);
55 }
56
57 static char *get_chain_filename(const char *obj_dir)
58 {
59         return xstrfmt("%s/info/commit-graphs/commit-graph-chain", obj_dir);
60 }
61
62 static uint8_t oid_version(void)
63 {
64         return 1;
65 }
66
67 static struct commit_graph *alloc_commit_graph(void)
68 {
69         struct commit_graph *g = xcalloc(1, sizeof(*g));
70         g->graph_fd = -1;
71
72         return g;
73 }
74
75 extern int read_replace_refs;
76
77 static int commit_graph_compatible(struct repository *r)
78 {
79         if (!r->gitdir)
80                 return 0;
81
82         if (read_replace_refs) {
83                 prepare_replace_object(r);
84                 if (hashmap_get_size(&r->objects->replace_map->map))
85                         return 0;
86         }
87
88         prepare_commit_graft(r);
89         if (r->parsed_objects && r->parsed_objects->grafts_nr)
90                 return 0;
91         if (is_repository_shallow(r))
92                 return 0;
93
94         return 1;
95 }
96
97 int open_commit_graph(const char *graph_file, int *fd, struct stat *st)
98 {
99         *fd = git_open(graph_file);
100         if (*fd < 0)
101                 return 0;
102         if (fstat(*fd, st)) {
103                 close(*fd);
104                 return 0;
105         }
106         return 1;
107 }
108
109 struct commit_graph *load_commit_graph_one_fd_st(int fd, struct stat *st)
110 {
111         void *graph_map;
112         size_t graph_size;
113         struct commit_graph *ret;
114
115         graph_size = xsize_t(st->st_size);
116
117         if (graph_size < GRAPH_MIN_SIZE) {
118                 close(fd);
119                 error(_("commit-graph file is too small"));
120                 return NULL;
121         }
122         graph_map = xmmap(NULL, graph_size, PROT_READ, MAP_PRIVATE, fd, 0);
123         ret = parse_commit_graph(graph_map, fd, graph_size);
124
125         if (!ret) {
126                 munmap(graph_map, graph_size);
127                 close(fd);
128         }
129
130         return ret;
131 }
132
133 static int verify_commit_graph_lite(struct commit_graph *g)
134 {
135         /*
136          * Basic validation shared between parse_commit_graph()
137          * which'll be called every time the graph is used, and the
138          * much more expensive verify_commit_graph() used by
139          * "commit-graph verify".
140          *
141          * There should only be very basic checks here to ensure that
142          * we don't e.g. segfault in fill_commit_in_graph(), but
143          * because this is a very hot codepath nothing that e.g. loops
144          * over g->num_commits, or runs a checksum on the commit-graph
145          * itself.
146          */
147         if (!g->chunk_oid_fanout) {
148                 error("commit-graph is missing the OID Fanout chunk");
149                 return 1;
150         }
151         if (!g->chunk_oid_lookup) {
152                 error("commit-graph is missing the OID Lookup chunk");
153                 return 1;
154         }
155         if (!g->chunk_commit_data) {
156                 error("commit-graph is missing the Commit Data chunk");
157                 return 1;
158         }
159
160         return 0;
161 }
162
163 struct commit_graph *parse_commit_graph(void *graph_map, int fd,
164                                         size_t graph_size)
165 {
166         const unsigned char *data, *chunk_lookup;
167         uint32_t i;
168         struct commit_graph *graph;
169         uint64_t last_chunk_offset;
170         uint32_t last_chunk_id;
171         uint32_t graph_signature;
172         unsigned char graph_version, hash_version;
173
174         if (!graph_map)
175                 return NULL;
176
177         if (graph_size < GRAPH_MIN_SIZE)
178                 return NULL;
179
180         data = (const unsigned char *)graph_map;
181
182         graph_signature = get_be32(data);
183         if (graph_signature != GRAPH_SIGNATURE) {
184                 error(_("commit-graph signature %X does not match signature %X"),
185                       graph_signature, GRAPH_SIGNATURE);
186                 return NULL;
187         }
188
189         graph_version = *(unsigned char*)(data + 4);
190         if (graph_version != GRAPH_VERSION) {
191                 error(_("commit-graph version %X does not match version %X"),
192                       graph_version, GRAPH_VERSION);
193                 return NULL;
194         }
195
196         hash_version = *(unsigned char*)(data + 5);
197         if (hash_version != oid_version()) {
198                 error(_("commit-graph hash version %X does not match version %X"),
199                       hash_version, oid_version());
200                 return NULL;
201         }
202
203         graph = alloc_commit_graph();
204
205         graph->hash_len = the_hash_algo->rawsz;
206         graph->num_chunks = *(unsigned char*)(data + 6);
207         graph->graph_fd = fd;
208         graph->data = graph_map;
209         graph->data_len = graph_size;
210
211         last_chunk_id = 0;
212         last_chunk_offset = 8;
213         chunk_lookup = data + 8;
214         for (i = 0; i < graph->num_chunks; i++) {
215                 uint32_t chunk_id;
216                 uint64_t chunk_offset;
217                 int chunk_repeated = 0;
218
219                 if (data + graph_size - chunk_lookup <
220                     GRAPH_CHUNKLOOKUP_WIDTH) {
221                         error(_("commit-graph chunk lookup table entry missing; file may be incomplete"));
222                         free(graph);
223                         return NULL;
224                 }
225
226                 chunk_id = get_be32(chunk_lookup + 0);
227                 chunk_offset = get_be64(chunk_lookup + 4);
228
229                 chunk_lookup += GRAPH_CHUNKLOOKUP_WIDTH;
230
231                 if (chunk_offset > graph_size - the_hash_algo->rawsz) {
232                         error(_("commit-graph improper chunk offset %08x%08x"), (uint32_t)(chunk_offset >> 32),
233                               (uint32_t)chunk_offset);
234                         free(graph);
235                         return NULL;
236                 }
237
238                 switch (chunk_id) {
239                 case GRAPH_CHUNKID_OIDFANOUT:
240                         if (graph->chunk_oid_fanout)
241                                 chunk_repeated = 1;
242                         else
243                                 graph->chunk_oid_fanout = (uint32_t*)(data + chunk_offset);
244                         break;
245
246                 case GRAPH_CHUNKID_OIDLOOKUP:
247                         if (graph->chunk_oid_lookup)
248                                 chunk_repeated = 1;
249                         else
250                                 graph->chunk_oid_lookup = data + chunk_offset;
251                         break;
252
253                 case GRAPH_CHUNKID_DATA:
254                         if (graph->chunk_commit_data)
255                                 chunk_repeated = 1;
256                         else
257                                 graph->chunk_commit_data = data + chunk_offset;
258                         break;
259
260                 case GRAPH_CHUNKID_EXTRAEDGES:
261                         if (graph->chunk_extra_edges)
262                                 chunk_repeated = 1;
263                         else
264                                 graph->chunk_extra_edges = data + chunk_offset;
265                         break;
266
267                 case GRAPH_CHUNKID_BASE:
268                         if (graph->chunk_base_graphs)
269                                 chunk_repeated = 1;
270                         else
271                                 graph->chunk_base_graphs = data + chunk_offset;
272                 }
273
274                 if (chunk_repeated) {
275                         error(_("commit-graph chunk id %08x appears multiple times"), chunk_id);
276                         free(graph);
277                         return NULL;
278                 }
279
280                 if (last_chunk_id == GRAPH_CHUNKID_OIDLOOKUP)
281                 {
282                         graph->num_commits = (chunk_offset - last_chunk_offset)
283                                              / graph->hash_len;
284                 }
285
286                 last_chunk_id = chunk_id;
287                 last_chunk_offset = chunk_offset;
288         }
289
290         hashcpy(graph->oid.hash, graph->data + graph->data_len - graph->hash_len);
291
292         if (verify_commit_graph_lite(graph))
293                 return NULL;
294
295         return graph;
296 }
297
298 static struct commit_graph *load_commit_graph_one(const char *graph_file)
299 {
300
301         struct stat st;
302         int fd;
303         int open_ok = open_commit_graph(graph_file, &fd, &st);
304
305         if (!open_ok)
306                 return NULL;
307
308         return load_commit_graph_one_fd_st(fd, &st);
309 }
310
311 static struct commit_graph *load_commit_graph_v1(struct repository *r, const char *obj_dir)
312 {
313         char *graph_name = get_commit_graph_filename(obj_dir);
314         struct commit_graph *g = load_commit_graph_one(graph_name);
315         free(graph_name);
316
317         return g;
318 }
319
320 static int add_graph_to_chain(struct commit_graph *g,
321                               struct commit_graph *chain,
322                               struct object_id *oids,
323                               int n)
324 {
325         struct commit_graph *cur_g = chain;
326
327         if (n && !g->chunk_base_graphs) {
328                 warning(_("commit-graph has no base graphs chunk"));
329                 return 0;
330         }
331
332         while (n) {
333                 n--;
334
335                 if (!cur_g ||
336                     !oideq(&oids[n], &cur_g->oid) ||
337                     !hasheq(oids[n].hash, g->chunk_base_graphs + g->hash_len * n)) {
338                         warning(_("commit-graph chain does not match"));
339                         return 0;
340                 }
341
342                 cur_g = cur_g->base_graph;
343         }
344
345         g->base_graph = chain;
346
347         if (chain)
348                 g->num_commits_in_base = chain->num_commits + chain->num_commits_in_base;
349
350         return 1;
351 }
352
353 static struct commit_graph *load_commit_graph_chain(struct repository *r, const char *obj_dir)
354 {
355         struct commit_graph *graph_chain = NULL;
356         struct strbuf line = STRBUF_INIT;
357         struct stat st;
358         struct object_id *oids;
359         int i = 0, valid = 1, count;
360         char *chain_name = get_chain_filename(obj_dir);
361         FILE *fp;
362         int stat_res;
363
364         fp = fopen(chain_name, "r");
365         stat_res = stat(chain_name, &st);
366         free(chain_name);
367
368         if (!fp ||
369             stat_res ||
370             st.st_size <= the_hash_algo->hexsz)
371                 return NULL;
372
373         count = st.st_size / (the_hash_algo->hexsz + 1);
374         oids = xcalloc(count, sizeof(struct object_id));
375
376         for (i = 0; i < count && valid; i++) {
377                 char *graph_name;
378                 struct commit_graph *g;
379
380                 if (strbuf_getline_lf(&line, fp) == EOF)
381                         break;
382
383                 if (get_oid_hex(line.buf, &oids[i])) {
384                         warning(_("invalid commit-graph chain: line '%s' not a hash"),
385                                 line.buf);
386                         valid = 0;
387                         break;
388                 }
389
390                 graph_name = get_split_graph_filename(obj_dir, line.buf);
391                 g = load_commit_graph_one(graph_name);
392                 free(graph_name);
393
394                 if (g && add_graph_to_chain(g, graph_chain, oids, i))
395                         graph_chain = g;
396                 else
397                         valid = 0;
398         }
399
400         free(oids);
401         fclose(fp);
402
403         return graph_chain;
404 }
405
406 static struct commit_graph *read_commit_graph_one(struct repository *r, const char *obj_dir)
407 {
408         struct commit_graph *g = load_commit_graph_v1(r, obj_dir);
409
410         if (!g)
411                 g = load_commit_graph_chain(r, obj_dir);
412
413         return g;
414 }
415
416 static void prepare_commit_graph_one(struct repository *r, const char *obj_dir)
417 {
418
419         if (r->objects->commit_graph)
420                 return;
421
422         r->objects->commit_graph = read_commit_graph_one(r, obj_dir);
423 }
424
425 /*
426  * Return 1 if commit_graph is non-NULL, and 0 otherwise.
427  *
428  * On the first invocation, this function attemps to load the commit
429  * graph if the_repository is configured to have one.
430  */
431 static int prepare_commit_graph(struct repository *r)
432 {
433         struct object_directory *odb;
434         int config_value;
435
436         if (git_env_bool(GIT_TEST_COMMIT_GRAPH_DIE_ON_LOAD, 0))
437                 die("dying as requested by the '%s' variable on commit-graph load!",
438                     GIT_TEST_COMMIT_GRAPH_DIE_ON_LOAD);
439
440         if (r->objects->commit_graph_attempted)
441                 return !!r->objects->commit_graph;
442         r->objects->commit_graph_attempted = 1;
443
444         if (!git_env_bool(GIT_TEST_COMMIT_GRAPH, 0) &&
445             (repo_config_get_bool(r, "core.commitgraph", &config_value) ||
446             !config_value))
447                 /*
448                  * This repository is not configured to use commit graphs, so
449                  * do not load one. (But report commit_graph_attempted anyway
450                  * so that commit graph loading is not attempted again for this
451                  * repository.)
452                  */
453                 return 0;
454
455         if (!commit_graph_compatible(r))
456                 return 0;
457
458         prepare_alt_odb(r);
459         for (odb = r->objects->odb;
460              !r->objects->commit_graph && odb;
461              odb = odb->next)
462                 prepare_commit_graph_one(r, odb->path);
463         return !!r->objects->commit_graph;
464 }
465
466 int generation_numbers_enabled(struct repository *r)
467 {
468         uint32_t first_generation;
469         struct commit_graph *g;
470         if (!prepare_commit_graph(r))
471                return 0;
472
473         g = r->objects->commit_graph;
474
475         if (!g->num_commits)
476                 return 0;
477
478         first_generation = get_be32(g->chunk_commit_data +
479                                     g->hash_len + 8) >> 2;
480
481         return !!first_generation;
482 }
483
484 static void close_commit_graph_one(struct commit_graph *g)
485 {
486         if (!g)
487                 return;
488
489         close_commit_graph_one(g->base_graph);
490         free_commit_graph(g);
491 }
492
493 void close_commit_graph(struct raw_object_store *o)
494 {
495         close_commit_graph_one(o->commit_graph);
496         o->commit_graph = NULL;
497 }
498
499 static int bsearch_graph(struct commit_graph *g, struct object_id *oid, uint32_t *pos)
500 {
501         return bsearch_hash(oid->hash, g->chunk_oid_fanout,
502                             g->chunk_oid_lookup, g->hash_len, pos);
503 }
504
505 static void load_oid_from_graph(struct commit_graph *g,
506                                 uint32_t pos,
507                                 struct object_id *oid)
508 {
509         uint32_t lex_index;
510
511         while (g && pos < g->num_commits_in_base)
512                 g = g->base_graph;
513
514         if (!g)
515                 BUG("NULL commit-graph");
516
517         if (pos >= g->num_commits + g->num_commits_in_base)
518                 die(_("invalid commit position. commit-graph is likely corrupt"));
519
520         lex_index = pos - g->num_commits_in_base;
521
522         hashcpy(oid->hash, g->chunk_oid_lookup + g->hash_len * lex_index);
523 }
524
525 static struct commit_list **insert_parent_or_die(struct repository *r,
526                                                  struct commit_graph *g,
527                                                  uint32_t pos,
528                                                  struct commit_list **pptr)
529 {
530         struct commit *c;
531         struct object_id oid;
532
533         if (pos >= g->num_commits + g->num_commits_in_base)
534                 die("invalid parent position %"PRIu32, pos);
535
536         load_oid_from_graph(g, pos, &oid);
537         c = lookup_commit(r, &oid);
538         if (!c)
539                 die(_("could not find commit %s"), oid_to_hex(&oid));
540         c->graph_pos = pos;
541         return &commit_list_insert(c, pptr)->next;
542 }
543
544 static void fill_commit_graph_info(struct commit *item, struct commit_graph *g, uint32_t pos)
545 {
546         const unsigned char *commit_data;
547         uint32_t lex_index;
548
549         while (pos < g->num_commits_in_base)
550                 g = g->base_graph;
551
552         lex_index = pos - g->num_commits_in_base;
553         commit_data = g->chunk_commit_data + GRAPH_DATA_WIDTH * lex_index;
554         item->graph_pos = pos;
555         item->generation = get_be32(commit_data + g->hash_len + 8) >> 2;
556 }
557
558 static int fill_commit_in_graph(struct repository *r,
559                                 struct commit *item,
560                                 struct commit_graph *g, uint32_t pos)
561 {
562         uint32_t edge_value;
563         uint32_t *parent_data_ptr;
564         uint64_t date_low, date_high;
565         struct commit_list **pptr;
566         const unsigned char *commit_data;
567         uint32_t lex_index;
568
569         while (pos < g->num_commits_in_base)
570                 g = g->base_graph;
571
572         if (pos >= g->num_commits + g->num_commits_in_base)
573                 die(_("invalid commit position. commit-graph is likely corrupt"));
574
575         /*
576          * Store the "full" position, but then use the
577          * "local" position for the rest of the calculation.
578          */
579         item->graph_pos = pos;
580         lex_index = pos - g->num_commits_in_base;
581
582         commit_data = g->chunk_commit_data + (g->hash_len + 16) * lex_index;
583
584         item->object.parsed = 1;
585
586         item->maybe_tree = NULL;
587
588         date_high = get_be32(commit_data + g->hash_len + 8) & 0x3;
589         date_low = get_be32(commit_data + g->hash_len + 12);
590         item->date = (timestamp_t)((date_high << 32) | date_low);
591
592         item->generation = get_be32(commit_data + g->hash_len + 8) >> 2;
593
594         pptr = &item->parents;
595
596         edge_value = get_be32(commit_data + g->hash_len);
597         if (edge_value == GRAPH_PARENT_NONE)
598                 return 1;
599         pptr = insert_parent_or_die(r, g, edge_value, pptr);
600
601         edge_value = get_be32(commit_data + g->hash_len + 4);
602         if (edge_value == GRAPH_PARENT_NONE)
603                 return 1;
604         if (!(edge_value & GRAPH_EXTRA_EDGES_NEEDED)) {
605                 pptr = insert_parent_or_die(r, g, edge_value, pptr);
606                 return 1;
607         }
608
609         parent_data_ptr = (uint32_t*)(g->chunk_extra_edges +
610                           4 * (uint64_t)(edge_value & GRAPH_EDGE_LAST_MASK));
611         do {
612                 edge_value = get_be32(parent_data_ptr);
613                 pptr = insert_parent_or_die(r, g,
614                                             edge_value & GRAPH_EDGE_LAST_MASK,
615                                             pptr);
616                 parent_data_ptr++;
617         } while (!(edge_value & GRAPH_LAST_EDGE));
618
619         return 1;
620 }
621
622 static int find_commit_in_graph(struct commit *item, struct commit_graph *g, uint32_t *pos)
623 {
624         if (item->graph_pos != COMMIT_NOT_FROM_GRAPH) {
625                 *pos = item->graph_pos;
626                 return 1;
627         } else {
628                 struct commit_graph *cur_g = g;
629                 uint32_t lex_index;
630
631                 while (cur_g && !bsearch_graph(cur_g, &(item->object.oid), &lex_index))
632                         cur_g = cur_g->base_graph;
633
634                 if (cur_g) {
635                         *pos = lex_index + cur_g->num_commits_in_base;
636                         return 1;
637                 }
638
639                 return 0;
640         }
641 }
642
643 static int parse_commit_in_graph_one(struct repository *r,
644                                      struct commit_graph *g,
645                                      struct commit *item)
646 {
647         uint32_t pos;
648
649         if (item->object.parsed)
650                 return 1;
651
652         if (find_commit_in_graph(item, g, &pos))
653                 return fill_commit_in_graph(r, item, g, pos);
654
655         return 0;
656 }
657
658 int parse_commit_in_graph(struct repository *r, struct commit *item)
659 {
660         if (!prepare_commit_graph(r))
661                 return 0;
662         return parse_commit_in_graph_one(r, r->objects->commit_graph, item);
663 }
664
665 void load_commit_graph_info(struct repository *r, struct commit *item)
666 {
667         uint32_t pos;
668         if (!prepare_commit_graph(r))
669                 return;
670         if (find_commit_in_graph(item, r->objects->commit_graph, &pos))
671                 fill_commit_graph_info(item, r->objects->commit_graph, pos);
672 }
673
674 static struct tree *load_tree_for_commit(struct repository *r,
675                                          struct commit_graph *g,
676                                          struct commit *c)
677 {
678         struct object_id oid;
679         const unsigned char *commit_data;
680
681         while (c->graph_pos < g->num_commits_in_base)
682                 g = g->base_graph;
683
684         commit_data = g->chunk_commit_data +
685                         GRAPH_DATA_WIDTH * (c->graph_pos - g->num_commits_in_base);
686
687         hashcpy(oid.hash, commit_data);
688         c->maybe_tree = lookup_tree(r, &oid);
689
690         return c->maybe_tree;
691 }
692
693 static struct tree *get_commit_tree_in_graph_one(struct repository *r,
694                                                  struct commit_graph *g,
695                                                  const struct commit *c)
696 {
697         if (c->maybe_tree)
698                 return c->maybe_tree;
699         if (c->graph_pos == COMMIT_NOT_FROM_GRAPH)
700                 BUG("get_commit_tree_in_graph_one called from non-commit-graph commit");
701
702         return load_tree_for_commit(r, g, (struct commit *)c);
703 }
704
705 struct tree *get_commit_tree_in_graph(struct repository *r, const struct commit *c)
706 {
707         return get_commit_tree_in_graph_one(r, r->objects->commit_graph, c);
708 }
709
710 struct packed_commit_list {
711         struct commit **list;
712         int nr;
713         int alloc;
714 };
715
716 struct packed_oid_list {
717         struct object_id *list;
718         int nr;
719         int alloc;
720 };
721
722 struct write_commit_graph_context {
723         struct repository *r;
724         const char *obj_dir;
725         char *graph_name;
726         struct packed_oid_list oids;
727         struct packed_commit_list commits;
728         int num_extra_edges;
729         unsigned long approx_nr_objects;
730         struct progress *progress;
731         int progress_done;
732         uint64_t progress_cnt;
733         unsigned append:1,
734                  report_progress:1;
735 };
736
737 static void write_graph_chunk_fanout(struct hashfile *f,
738                                      struct write_commit_graph_context *ctx)
739 {
740         int i, count = 0;
741         struct commit **list = ctx->commits.list;
742
743         /*
744          * Write the first-level table (the list is sorted,
745          * but we use a 256-entry lookup to be able to avoid
746          * having to do eight extra binary search iterations).
747          */
748         for (i = 0; i < 256; i++) {
749                 while (count < ctx->commits.nr) {
750                         if ((*list)->object.oid.hash[0] != i)
751                                 break;
752                         display_progress(ctx->progress, ++ctx->progress_cnt);
753                         count++;
754                         list++;
755                 }
756
757                 hashwrite_be32(f, count);
758         }
759 }
760
761 static void write_graph_chunk_oids(struct hashfile *f, int hash_len,
762                                    struct write_commit_graph_context *ctx)
763 {
764         struct commit **list = ctx->commits.list;
765         int count;
766         for (count = 0; count < ctx->commits.nr; count++, list++) {
767                 display_progress(ctx->progress, ++ctx->progress_cnt);
768                 hashwrite(f, (*list)->object.oid.hash, (int)hash_len);
769         }
770 }
771
772 static const unsigned char *commit_to_sha1(size_t index, void *table)
773 {
774         struct commit **commits = table;
775         return commits[index]->object.oid.hash;
776 }
777
778 static void write_graph_chunk_data(struct hashfile *f, int hash_len,
779                                    struct write_commit_graph_context *ctx)
780 {
781         struct commit **list = ctx->commits.list;
782         struct commit **last = ctx->commits.list + ctx->commits.nr;
783         uint32_t num_extra_edges = 0;
784
785         while (list < last) {
786                 struct commit_list *parent;
787                 int edge_value;
788                 uint32_t packedDate[2];
789                 display_progress(ctx->progress, ++ctx->progress_cnt);
790
791                 parse_commit_no_graph(*list);
792                 hashwrite(f, get_commit_tree_oid(*list)->hash, hash_len);
793
794                 parent = (*list)->parents;
795
796                 if (!parent)
797                         edge_value = GRAPH_PARENT_NONE;
798                 else {
799                         edge_value = sha1_pos(parent->item->object.oid.hash,
800                                               ctx->commits.list,
801                                               ctx->commits.nr,
802                                               commit_to_sha1);
803
804                         if (edge_value < 0)
805                                 BUG("missing parent %s for commit %s",
806                                     oid_to_hex(&parent->item->object.oid),
807                                     oid_to_hex(&(*list)->object.oid));
808                 }
809
810                 hashwrite_be32(f, edge_value);
811
812                 if (parent)
813                         parent = parent->next;
814
815                 if (!parent)
816                         edge_value = GRAPH_PARENT_NONE;
817                 else if (parent->next)
818                         edge_value = GRAPH_EXTRA_EDGES_NEEDED | num_extra_edges;
819                 else {
820                         edge_value = sha1_pos(parent->item->object.oid.hash,
821                                               ctx->commits.list,
822                                               ctx->commits.nr,
823                                               commit_to_sha1);
824                         if (edge_value < 0)
825                                 BUG("missing parent %s for commit %s",
826                                     oid_to_hex(&parent->item->object.oid),
827                                     oid_to_hex(&(*list)->object.oid));
828                 }
829
830                 hashwrite_be32(f, edge_value);
831
832                 if (edge_value & GRAPH_EXTRA_EDGES_NEEDED) {
833                         do {
834                                 num_extra_edges++;
835                                 parent = parent->next;
836                         } while (parent);
837                 }
838
839                 if (sizeof((*list)->date) > 4)
840                         packedDate[0] = htonl(((*list)->date >> 32) & 0x3);
841                 else
842                         packedDate[0] = 0;
843
844                 packedDate[0] |= htonl((*list)->generation << 2);
845
846                 packedDate[1] = htonl((*list)->date);
847                 hashwrite(f, packedDate, 8);
848
849                 list++;
850         }
851 }
852
853 static void write_graph_chunk_extra_edges(struct hashfile *f,
854                                           struct write_commit_graph_context *ctx)
855 {
856         struct commit **list = ctx->commits.list;
857         struct commit **last = ctx->commits.list + ctx->commits.nr;
858         struct commit_list *parent;
859
860         while (list < last) {
861                 int num_parents = 0;
862
863                 display_progress(ctx->progress, ++ctx->progress_cnt);
864
865                 for (parent = (*list)->parents; num_parents < 3 && parent;
866                      parent = parent->next)
867                         num_parents++;
868
869                 if (num_parents <= 2) {
870                         list++;
871                         continue;
872                 }
873
874                 /* Since num_parents > 2, this initializer is safe. */
875                 for (parent = (*list)->parents->next; parent; parent = parent->next) {
876                         int edge_value = sha1_pos(parent->item->object.oid.hash,
877                                                   ctx->commits.list,
878                                                   ctx->commits.nr,
879                                                   commit_to_sha1);
880
881                         if (edge_value < 0)
882                                 BUG("missing parent %s for commit %s",
883                                     oid_to_hex(&parent->item->object.oid),
884                                     oid_to_hex(&(*list)->object.oid));
885                         else if (!parent->next)
886                                 edge_value |= GRAPH_LAST_EDGE;
887
888                         hashwrite_be32(f, edge_value);
889                 }
890
891                 list++;
892         }
893 }
894
895 static int oid_compare(const void *_a, const void *_b)
896 {
897         const struct object_id *a = (const struct object_id *)_a;
898         const struct object_id *b = (const struct object_id *)_b;
899         return oidcmp(a, b);
900 }
901
902 static int add_packed_commits(const struct object_id *oid,
903                               struct packed_git *pack,
904                               uint32_t pos,
905                               void *data)
906 {
907         struct write_commit_graph_context *ctx = (struct write_commit_graph_context*)data;
908         enum object_type type;
909         off_t offset = nth_packed_object_offset(pack, pos);
910         struct object_info oi = OBJECT_INFO_INIT;
911
912         if (ctx->progress)
913                 display_progress(ctx->progress, ++ctx->progress_done);
914
915         oi.typep = &type;
916         if (packed_object_info(ctx->r, pack, offset, &oi) < 0)
917                 die(_("unable to get type of object %s"), oid_to_hex(oid));
918
919         if (type != OBJ_COMMIT)
920                 return 0;
921
922         ALLOC_GROW(ctx->oids.list, ctx->oids.nr + 1, ctx->oids.alloc);
923         oidcpy(&(ctx->oids.list[ctx->oids.nr]), oid);
924         ctx->oids.nr++;
925
926         return 0;
927 }
928
929 static void add_missing_parents(struct write_commit_graph_context *ctx, struct commit *commit)
930 {
931         struct commit_list *parent;
932         for (parent = commit->parents; parent; parent = parent->next) {
933                 if (!(parent->item->object.flags & UNINTERESTING)) {
934                         ALLOC_GROW(ctx->oids.list, ctx->oids.nr + 1, ctx->oids.alloc);
935                         oidcpy(&ctx->oids.list[ctx->oids.nr], &(parent->item->object.oid));
936                         ctx->oids.nr++;
937                         parent->item->object.flags |= UNINTERESTING;
938                 }
939         }
940 }
941
942 static void close_reachable(struct write_commit_graph_context *ctx)
943 {
944         int i;
945         struct commit *commit;
946
947         if (ctx->report_progress)
948                 ctx->progress = start_delayed_progress(
949                                         _("Loading known commits in commit graph"),
950                                         ctx->oids.nr);
951         for (i = 0; i < ctx->oids.nr; i++) {
952                 display_progress(ctx->progress, i + 1);
953                 commit = lookup_commit(ctx->r, &ctx->oids.list[i]);
954                 if (commit)
955                         commit->object.flags |= UNINTERESTING;
956         }
957         stop_progress(&ctx->progress);
958
959         /*
960          * As this loop runs, ctx->oids.nr may grow, but not more
961          * than the number of missing commits in the reachable
962          * closure.
963          */
964         if (ctx->report_progress)
965                 ctx->progress = start_delayed_progress(
966                                         _("Expanding reachable commits in commit graph"),
967                                         ctx->oids.nr);
968         for (i = 0; i < ctx->oids.nr; i++) {
969                 display_progress(ctx->progress, i + 1);
970                 commit = lookup_commit(ctx->r, &ctx->oids.list[i]);
971
972                 if (commit && !parse_commit_no_graph(commit))
973                         add_missing_parents(ctx, commit);
974         }
975         stop_progress(&ctx->progress);
976
977         if (ctx->report_progress)
978                 ctx->progress = start_delayed_progress(
979                                         _("Clearing commit marks in commit graph"),
980                                         ctx->oids.nr);
981         for (i = 0; i < ctx->oids.nr; i++) {
982                 display_progress(ctx->progress, i + 1);
983                 commit = lookup_commit(ctx->r, &ctx->oids.list[i]);
984
985                 if (commit)
986                         commit->object.flags &= ~UNINTERESTING;
987         }
988         stop_progress(&ctx->progress);
989 }
990
991 static void compute_generation_numbers(struct write_commit_graph_context *ctx)
992 {
993         int i;
994         struct commit_list *list = NULL;
995
996         if (ctx->report_progress)
997                 ctx->progress = start_progress(
998                                         _("Computing commit graph generation numbers"),
999                                         ctx->commits.nr);
1000         for (i = 0; i < ctx->commits.nr; i++) {
1001                 display_progress(ctx->progress, i + 1);
1002                 if (ctx->commits.list[i]->generation != GENERATION_NUMBER_INFINITY &&
1003                     ctx->commits.list[i]->generation != GENERATION_NUMBER_ZERO)
1004                         continue;
1005
1006                 commit_list_insert(ctx->commits.list[i], &list);
1007                 while (list) {
1008                         struct commit *current = list->item;
1009                         struct commit_list *parent;
1010                         int all_parents_computed = 1;
1011                         uint32_t max_generation = 0;
1012
1013                         for (parent = current->parents; parent; parent = parent->next) {
1014                                 if (parent->item->generation == GENERATION_NUMBER_INFINITY ||
1015                                     parent->item->generation == GENERATION_NUMBER_ZERO) {
1016                                         all_parents_computed = 0;
1017                                         commit_list_insert(parent->item, &list);
1018                                         break;
1019                                 } else if (parent->item->generation > max_generation) {
1020                                         max_generation = parent->item->generation;
1021                                 }
1022                         }
1023
1024                         if (all_parents_computed) {
1025                                 current->generation = max_generation + 1;
1026                                 pop_commit(&list);
1027
1028                                 if (current->generation > GENERATION_NUMBER_MAX)
1029                                         current->generation = GENERATION_NUMBER_MAX;
1030                         }
1031                 }
1032         }
1033         stop_progress(&ctx->progress);
1034 }
1035
1036 static int add_ref_to_list(const char *refname,
1037                            const struct object_id *oid,
1038                            int flags, void *cb_data)
1039 {
1040         struct string_list *list = (struct string_list *)cb_data;
1041
1042         string_list_append(list, oid_to_hex(oid));
1043         return 0;
1044 }
1045
1046 int write_commit_graph_reachable(const char *obj_dir, unsigned int flags)
1047 {
1048         struct string_list list = STRING_LIST_INIT_DUP;
1049         int result;
1050
1051         for_each_ref(add_ref_to_list, &list);
1052         result = write_commit_graph(obj_dir, NULL, &list,
1053                                     flags);
1054
1055         string_list_clear(&list, 0);
1056         return result;
1057 }
1058
1059 static int fill_oids_from_packs(struct write_commit_graph_context *ctx,
1060                                 struct string_list *pack_indexes)
1061 {
1062         uint32_t i;
1063         struct strbuf progress_title = STRBUF_INIT;
1064         struct strbuf packname = STRBUF_INIT;
1065         int dirlen;
1066
1067         strbuf_addf(&packname, "%s/pack/", ctx->obj_dir);
1068         dirlen = packname.len;
1069         if (ctx->report_progress) {
1070                 strbuf_addf(&progress_title,
1071                             Q_("Finding commits for commit graph in %d pack",
1072                                "Finding commits for commit graph in %d packs",
1073                                pack_indexes->nr),
1074                             pack_indexes->nr);
1075                 ctx->progress = start_delayed_progress(progress_title.buf, 0);
1076                 ctx->progress_done = 0;
1077         }
1078         for (i = 0; i < pack_indexes->nr; i++) {
1079                 struct packed_git *p;
1080                 strbuf_setlen(&packname, dirlen);
1081                 strbuf_addstr(&packname, pack_indexes->items[i].string);
1082                 p = add_packed_git(packname.buf, packname.len, 1);
1083                 if (!p) {
1084                         error(_("error adding pack %s"), packname.buf);
1085                         return -1;
1086                 }
1087                 if (open_pack_index(p)) {
1088                         error(_("error opening index for %s"), packname.buf);
1089                         return -1;
1090                 }
1091                 for_each_object_in_pack(p, add_packed_commits, ctx,
1092                                         FOR_EACH_OBJECT_PACK_ORDER);
1093                 close_pack(p);
1094                 free(p);
1095         }
1096
1097         stop_progress(&ctx->progress);
1098         strbuf_reset(&progress_title);
1099         strbuf_release(&packname);
1100
1101         return 0;
1102 }
1103
1104 static void fill_oids_from_commit_hex(struct write_commit_graph_context *ctx,
1105                                       struct string_list *commit_hex)
1106 {
1107         uint32_t i;
1108         struct strbuf progress_title = STRBUF_INIT;
1109
1110         if (ctx->report_progress) {
1111                 strbuf_addf(&progress_title,
1112                             Q_("Finding commits for commit graph from %d ref",
1113                                "Finding commits for commit graph from %d refs",
1114                                commit_hex->nr),
1115                             commit_hex->nr);
1116                 ctx->progress = start_delayed_progress(
1117                                         progress_title.buf,
1118                                         commit_hex->nr);
1119         }
1120         for (i = 0; i < commit_hex->nr; i++) {
1121                 const char *end;
1122                 struct object_id oid;
1123                 struct commit *result;
1124
1125                 display_progress(ctx->progress, i + 1);
1126                 if (commit_hex->items[i].string &&
1127                     parse_oid_hex(commit_hex->items[i].string, &oid, &end))
1128                         continue;
1129
1130                 result = lookup_commit_reference_gently(ctx->r, &oid, 1);
1131
1132                 if (result) {
1133                         ALLOC_GROW(ctx->oids.list, ctx->oids.nr + 1, ctx->oids.alloc);
1134                         oidcpy(&ctx->oids.list[ctx->oids.nr], &(result->object.oid));
1135                         ctx->oids.nr++;
1136                 }
1137         }
1138         stop_progress(&ctx->progress);
1139         strbuf_release(&progress_title);
1140 }
1141
1142 static void fill_oids_from_all_packs(struct write_commit_graph_context *ctx)
1143 {
1144         if (ctx->report_progress)
1145                 ctx->progress = start_delayed_progress(
1146                         _("Finding commits for commit graph among packed objects"),
1147                         ctx->approx_nr_objects);
1148         for_each_packed_object(add_packed_commits, ctx,
1149                                FOR_EACH_OBJECT_PACK_ORDER);
1150         if (ctx->progress_done < ctx->approx_nr_objects)
1151                 display_progress(ctx->progress, ctx->approx_nr_objects);
1152         stop_progress(&ctx->progress);
1153 }
1154
1155 static uint32_t count_distinct_commits(struct write_commit_graph_context *ctx)
1156 {
1157         uint32_t i, count_distinct = 1;
1158
1159         if (ctx->report_progress)
1160                 ctx->progress = start_delayed_progress(
1161                         _("Counting distinct commits in commit graph"),
1162                         ctx->oids.nr);
1163         display_progress(ctx->progress, 0); /* TODO: Measure QSORT() progress */
1164         QSORT(ctx->oids.list, ctx->oids.nr, oid_compare);
1165
1166         for (i = 1; i < ctx->oids.nr; i++) {
1167                 display_progress(ctx->progress, i + 1);
1168                 if (!oideq(&ctx->oids.list[i - 1], &ctx->oids.list[i]))
1169                         count_distinct++;
1170         }
1171         stop_progress(&ctx->progress);
1172
1173         return count_distinct;
1174 }
1175
1176 static void copy_oids_to_commits(struct write_commit_graph_context *ctx)
1177 {
1178         uint32_t i;
1179         struct commit_list *parent;
1180
1181         ctx->num_extra_edges = 0;
1182         if (ctx->report_progress)
1183                 ctx->progress = start_delayed_progress(
1184                         _("Finding extra edges in commit graph"),
1185                         ctx->oids.nr);
1186         for (i = 0; i < ctx->oids.nr; i++) {
1187                 int num_parents = 0;
1188                 display_progress(ctx->progress, i + 1);
1189                 if (i > 0 && oideq(&ctx->oids.list[i - 1], &ctx->oids.list[i]))
1190                         continue;
1191
1192                 ctx->commits.list[ctx->commits.nr] = lookup_commit(ctx->r, &ctx->oids.list[i]);
1193                 parse_commit_no_graph(ctx->commits.list[ctx->commits.nr]);
1194
1195                 for (parent = ctx->commits.list[ctx->commits.nr]->parents;
1196                      parent; parent = parent->next)
1197                         num_parents++;
1198
1199                 if (num_parents > 2)
1200                         ctx->num_extra_edges += num_parents - 1;
1201
1202                 ctx->commits.nr++;
1203         }
1204         stop_progress(&ctx->progress);
1205 }
1206
1207 static int write_commit_graph_file(struct write_commit_graph_context *ctx)
1208 {
1209         uint32_t i;
1210         struct hashfile *f;
1211         struct lock_file lk = LOCK_INIT;
1212         uint32_t chunk_ids[5];
1213         uint64_t chunk_offsets[5];
1214         const unsigned hashsz = the_hash_algo->rawsz;
1215         struct strbuf progress_title = STRBUF_INIT;
1216         int num_chunks = 3;
1217
1218         ctx->graph_name = get_commit_graph_filename(ctx->obj_dir);
1219         if (safe_create_leading_directories(ctx->graph_name)) {
1220                 UNLEAK(ctx->graph_name);
1221                 error(_("unable to create leading directories of %s"),
1222                         ctx->graph_name);
1223                 return -1;
1224         }
1225
1226         hold_lock_file_for_update(&lk, ctx->graph_name, LOCK_DIE_ON_ERROR);
1227         f = hashfd(lk.tempfile->fd, lk.tempfile->filename.buf);
1228
1229         chunk_ids[0] = GRAPH_CHUNKID_OIDFANOUT;
1230         chunk_ids[1] = GRAPH_CHUNKID_OIDLOOKUP;
1231         chunk_ids[2] = GRAPH_CHUNKID_DATA;
1232         if (ctx->num_extra_edges) {
1233                 chunk_ids[num_chunks] = GRAPH_CHUNKID_EXTRAEDGES;
1234                 num_chunks++;
1235         }
1236
1237         chunk_ids[num_chunks] = 0;
1238
1239         chunk_offsets[0] = 8 + (num_chunks + 1) * GRAPH_CHUNKLOOKUP_WIDTH;
1240         chunk_offsets[1] = chunk_offsets[0] + GRAPH_FANOUT_SIZE;
1241         chunk_offsets[2] = chunk_offsets[1] + hashsz * ctx->commits.nr;
1242         chunk_offsets[3] = chunk_offsets[2] + (hashsz + 16) * ctx->commits.nr;
1243
1244         num_chunks = 3;
1245         if (ctx->num_extra_edges) {
1246                 chunk_offsets[num_chunks + 1] = chunk_offsets[num_chunks] +
1247                                                 4 * ctx->num_extra_edges;
1248                 num_chunks++;
1249         }
1250
1251         hashwrite_be32(f, GRAPH_SIGNATURE);
1252
1253         hashwrite_u8(f, GRAPH_VERSION);
1254         hashwrite_u8(f, oid_version());
1255         hashwrite_u8(f, num_chunks);
1256         hashwrite_u8(f, 0);
1257
1258         for (i = 0; i <= num_chunks; i++) {
1259                 uint32_t chunk_write[3];
1260
1261                 chunk_write[0] = htonl(chunk_ids[i]);
1262                 chunk_write[1] = htonl(chunk_offsets[i] >> 32);
1263                 chunk_write[2] = htonl(chunk_offsets[i] & 0xffffffff);
1264                 hashwrite(f, chunk_write, 12);
1265         }
1266
1267         if (ctx->report_progress) {
1268                 strbuf_addf(&progress_title,
1269                             Q_("Writing out commit graph in %d pass",
1270                                "Writing out commit graph in %d passes",
1271                                num_chunks),
1272                             num_chunks);
1273                 ctx->progress = start_delayed_progress(
1274                         progress_title.buf,
1275                         num_chunks * ctx->commits.nr);
1276         }
1277         write_graph_chunk_fanout(f, ctx);
1278         write_graph_chunk_oids(f, hashsz, ctx);
1279         write_graph_chunk_data(f, hashsz, ctx);
1280         if (ctx->num_extra_edges)
1281                 write_graph_chunk_extra_edges(f, ctx);
1282         stop_progress(&ctx->progress);
1283         strbuf_release(&progress_title);
1284
1285         close_commit_graph(ctx->r->objects);
1286         finalize_hashfile(f, NULL, CSUM_HASH_IN_STREAM | CSUM_FSYNC);
1287         commit_lock_file(&lk);
1288
1289         return 0;
1290 }
1291
1292 int write_commit_graph(const char *obj_dir,
1293                        struct string_list *pack_indexes,
1294                        struct string_list *commit_hex,
1295                        unsigned int flags)
1296 {
1297         struct write_commit_graph_context *ctx;
1298         uint32_t i, count_distinct = 0;
1299         int res = 0;
1300
1301         if (!commit_graph_compatible(the_repository))
1302                 return 0;
1303
1304         ctx = xcalloc(1, sizeof(struct write_commit_graph_context));
1305         ctx->r = the_repository;
1306         ctx->obj_dir = obj_dir;
1307         ctx->append = flags & COMMIT_GRAPH_APPEND ? 1 : 0;
1308         ctx->report_progress = flags & COMMIT_GRAPH_PROGRESS ? 1 : 0;
1309
1310         ctx->approx_nr_objects = approximate_object_count();
1311         ctx->oids.alloc = ctx->approx_nr_objects / 32;
1312
1313         if (ctx->append) {
1314                 prepare_commit_graph_one(ctx->r, ctx->obj_dir);
1315                 if (ctx->r->objects->commit_graph)
1316                         ctx->oids.alloc += ctx->r->objects->commit_graph->num_commits;
1317         }
1318
1319         if (ctx->oids.alloc < 1024)
1320                 ctx->oids.alloc = 1024;
1321         ALLOC_ARRAY(ctx->oids.list, ctx->oids.alloc);
1322
1323         if (ctx->append && ctx->r->objects->commit_graph) {
1324                 struct commit_graph *g = ctx->r->objects->commit_graph;
1325                 for (i = 0; i < g->num_commits; i++) {
1326                         const unsigned char *hash = g->chunk_oid_lookup + g->hash_len * i;
1327                         hashcpy(ctx->oids.list[ctx->oids.nr++].hash, hash);
1328                 }
1329         }
1330
1331         if (pack_indexes) {
1332                 if ((res = fill_oids_from_packs(ctx, pack_indexes)))
1333                         goto cleanup;
1334         }
1335
1336         if (commit_hex)
1337                 fill_oids_from_commit_hex(ctx, commit_hex);
1338
1339         if (!pack_indexes && !commit_hex)
1340                 fill_oids_from_all_packs(ctx);
1341
1342         close_reachable(ctx);
1343
1344         count_distinct = count_distinct_commits(ctx);
1345
1346         if (count_distinct >= GRAPH_EDGE_LAST_MASK) {
1347                 error(_("the commit graph format cannot write %d commits"), count_distinct);
1348                 res = -1;
1349                 goto cleanup;
1350         }
1351
1352         ctx->commits.alloc = count_distinct;
1353         ALLOC_ARRAY(ctx->commits.list, ctx->commits.alloc);
1354
1355         copy_oids_to_commits(ctx);
1356
1357         if (ctx->commits.nr >= GRAPH_EDGE_LAST_MASK) {
1358                 error(_("too many commits to write graph"));
1359                 res = -1;
1360                 goto cleanup;
1361         }
1362
1363         compute_generation_numbers(ctx);
1364
1365         res = write_commit_graph_file(ctx);
1366
1367 cleanup:
1368         free(ctx->graph_name);
1369         free(ctx->commits.list);
1370         free(ctx->oids.list);
1371         free(ctx);
1372
1373         return res;
1374 }
1375
1376 #define VERIFY_COMMIT_GRAPH_ERROR_HASH 2
1377 static int verify_commit_graph_error;
1378
1379 static void graph_report(const char *fmt, ...)
1380 {
1381         va_list ap;
1382
1383         verify_commit_graph_error = 1;
1384         va_start(ap, fmt);
1385         vfprintf(stderr, fmt, ap);
1386         fprintf(stderr, "\n");
1387         va_end(ap);
1388 }
1389
1390 #define GENERATION_ZERO_EXISTS 1
1391 #define GENERATION_NUMBER_EXISTS 2
1392
1393 int verify_commit_graph(struct repository *r, struct commit_graph *g)
1394 {
1395         uint32_t i, cur_fanout_pos = 0;
1396         struct object_id prev_oid, cur_oid, checksum;
1397         int generation_zero = 0;
1398         struct hashfile *f;
1399         int devnull;
1400         struct progress *progress = NULL;
1401
1402         if (!g) {
1403                 graph_report("no commit-graph file loaded");
1404                 return 1;
1405         }
1406
1407         verify_commit_graph_error = verify_commit_graph_lite(g);
1408         if (verify_commit_graph_error)
1409                 return verify_commit_graph_error;
1410
1411         devnull = open("/dev/null", O_WRONLY);
1412         f = hashfd(devnull, NULL);
1413         hashwrite(f, g->data, g->data_len - g->hash_len);
1414         finalize_hashfile(f, checksum.hash, CSUM_CLOSE);
1415         if (!hasheq(checksum.hash, g->data + g->data_len - g->hash_len)) {
1416                 graph_report(_("the commit-graph file has incorrect checksum and is likely corrupt"));
1417                 verify_commit_graph_error = VERIFY_COMMIT_GRAPH_ERROR_HASH;
1418         }
1419
1420         for (i = 0; i < g->num_commits; i++) {
1421                 struct commit *graph_commit;
1422
1423                 hashcpy(cur_oid.hash, g->chunk_oid_lookup + g->hash_len * i);
1424
1425                 if (i && oidcmp(&prev_oid, &cur_oid) >= 0)
1426                         graph_report(_("commit-graph has incorrect OID order: %s then %s"),
1427                                      oid_to_hex(&prev_oid),
1428                                      oid_to_hex(&cur_oid));
1429
1430                 oidcpy(&prev_oid, &cur_oid);
1431
1432                 while (cur_oid.hash[0] > cur_fanout_pos) {
1433                         uint32_t fanout_value = get_be32(g->chunk_oid_fanout + cur_fanout_pos);
1434
1435                         if (i != fanout_value)
1436                                 graph_report(_("commit-graph has incorrect fanout value: fanout[%d] = %u != %u"),
1437                                              cur_fanout_pos, fanout_value, i);
1438                         cur_fanout_pos++;
1439                 }
1440
1441                 graph_commit = lookup_commit(r, &cur_oid);
1442                 if (!parse_commit_in_graph_one(r, g, graph_commit))
1443                         graph_report(_("failed to parse commit %s from commit-graph"),
1444                                      oid_to_hex(&cur_oid));
1445         }
1446
1447         while (cur_fanout_pos < 256) {
1448                 uint32_t fanout_value = get_be32(g->chunk_oid_fanout + cur_fanout_pos);
1449
1450                 if (g->num_commits != fanout_value)
1451                         graph_report(_("commit-graph has incorrect fanout value: fanout[%d] = %u != %u"),
1452                                      cur_fanout_pos, fanout_value, i);
1453
1454                 cur_fanout_pos++;
1455         }
1456
1457         if (verify_commit_graph_error & ~VERIFY_COMMIT_GRAPH_ERROR_HASH)
1458                 return verify_commit_graph_error;
1459
1460         progress = start_progress(_("Verifying commits in commit graph"),
1461                                   g->num_commits);
1462         for (i = 0; i < g->num_commits; i++) {
1463                 struct commit *graph_commit, *odb_commit;
1464                 struct commit_list *graph_parents, *odb_parents;
1465                 uint32_t max_generation = 0;
1466
1467                 display_progress(progress, i + 1);
1468                 hashcpy(cur_oid.hash, g->chunk_oid_lookup + g->hash_len * i);
1469
1470                 graph_commit = lookup_commit(r, &cur_oid);
1471                 odb_commit = (struct commit *)create_object(r, cur_oid.hash, alloc_commit_node(r));
1472                 if (parse_commit_internal(odb_commit, 0, 0)) {
1473                         graph_report(_("failed to parse commit %s from object database for commit-graph"),
1474                                      oid_to_hex(&cur_oid));
1475                         continue;
1476                 }
1477
1478                 if (!oideq(&get_commit_tree_in_graph_one(r, g, graph_commit)->object.oid,
1479                            get_commit_tree_oid(odb_commit)))
1480                         graph_report(_("root tree OID for commit %s in commit-graph is %s != %s"),
1481                                      oid_to_hex(&cur_oid),
1482                                      oid_to_hex(get_commit_tree_oid(graph_commit)),
1483                                      oid_to_hex(get_commit_tree_oid(odb_commit)));
1484
1485                 graph_parents = graph_commit->parents;
1486                 odb_parents = odb_commit->parents;
1487
1488                 while (graph_parents) {
1489                         if (odb_parents == NULL) {
1490                                 graph_report(_("commit-graph parent list for commit %s is too long"),
1491                                              oid_to_hex(&cur_oid));
1492                                 break;
1493                         }
1494
1495                         if (!oideq(&graph_parents->item->object.oid, &odb_parents->item->object.oid))
1496                                 graph_report(_("commit-graph parent for %s is %s != %s"),
1497                                              oid_to_hex(&cur_oid),
1498                                              oid_to_hex(&graph_parents->item->object.oid),
1499                                              oid_to_hex(&odb_parents->item->object.oid));
1500
1501                         if (graph_parents->item->generation > max_generation)
1502                                 max_generation = graph_parents->item->generation;
1503
1504                         graph_parents = graph_parents->next;
1505                         odb_parents = odb_parents->next;
1506                 }
1507
1508                 if (odb_parents != NULL)
1509                         graph_report(_("commit-graph parent list for commit %s terminates early"),
1510                                      oid_to_hex(&cur_oid));
1511
1512                 if (!graph_commit->generation) {
1513                         if (generation_zero == GENERATION_NUMBER_EXISTS)
1514                                 graph_report(_("commit-graph has generation number zero for commit %s, but non-zero elsewhere"),
1515                                              oid_to_hex(&cur_oid));
1516                         generation_zero = GENERATION_ZERO_EXISTS;
1517                 } else if (generation_zero == GENERATION_ZERO_EXISTS)
1518                         graph_report(_("commit-graph has non-zero generation number for commit %s, but zero elsewhere"),
1519                                      oid_to_hex(&cur_oid));
1520
1521                 if (generation_zero == GENERATION_ZERO_EXISTS)
1522                         continue;
1523
1524                 /*
1525                  * If one of our parents has generation GENERATION_NUMBER_MAX, then
1526                  * our generation is also GENERATION_NUMBER_MAX. Decrement to avoid
1527                  * extra logic in the following condition.
1528                  */
1529                 if (max_generation == GENERATION_NUMBER_MAX)
1530                         max_generation--;
1531
1532                 if (graph_commit->generation != max_generation + 1)
1533                         graph_report(_("commit-graph generation for commit %s is %u != %u"),
1534                                      oid_to_hex(&cur_oid),
1535                                      graph_commit->generation,
1536                                      max_generation + 1);
1537
1538                 if (graph_commit->date != odb_commit->date)
1539                         graph_report(_("commit date for commit %s in commit-graph is %"PRItime" != %"PRItime),
1540                                      oid_to_hex(&cur_oid),
1541                                      graph_commit->date,
1542                                      odb_commit->date);
1543         }
1544         stop_progress(&progress);
1545
1546         return verify_commit_graph_error;
1547 }
1548
1549 void free_commit_graph(struct commit_graph *g)
1550 {
1551         if (!g)
1552                 return;
1553         if (g->graph_fd >= 0) {
1554                 munmap((void *)g->data, g->data_len);
1555                 g->data = NULL;
1556                 close(g->graph_fd);
1557         }
1558         free(g);
1559 }