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