commit-graph: define GIT_TEST_COMMIT_GRAPH
[git] / commit-graph.c
1 #include "cache.h"
2 #include "config.h"
3 #include "dir.h"
4 #include "git-compat-util.h"
5 #include "lockfile.h"
6 #include "pack.h"
7 #include "packfile.h"
8 #include "commit.h"
9 #include "object.h"
10 #include "refs.h"
11 #include "revision.h"
12 #include "sha1-lookup.h"
13 #include "commit-graph.h"
14 #include "object-store.h"
15 #include "alloc.h"
16
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 static void close_commit_graph(void)
238 {
239         free_commit_graph(the_repository->objects->commit_graph);
240         the_repository->objects->commit_graph = NULL;
241 }
242
243 static int bsearch_graph(struct commit_graph *g, struct object_id *oid, uint32_t *pos)
244 {
245         return bsearch_hash(oid->hash, g->chunk_oid_fanout,
246                             g->chunk_oid_lookup, g->hash_len, pos);
247 }
248
249 static struct commit_list **insert_parent_or_die(struct commit_graph *g,
250                                                  uint64_t pos,
251                                                  struct commit_list **pptr)
252 {
253         struct commit *c;
254         struct object_id oid;
255
256         if (pos >= g->num_commits)
257                 die("invalid parent position %"PRIu64, pos);
258
259         hashcpy(oid.hash, g->chunk_oid_lookup + g->hash_len * pos);
260         c = lookup_commit(the_repository, &oid);
261         if (!c)
262                 die(_("could not find commit %s"), oid_to_hex(&oid));
263         c->graph_pos = pos;
264         return &commit_list_insert(c, pptr)->next;
265 }
266
267 static void fill_commit_graph_info(struct commit *item, struct commit_graph *g, uint32_t pos)
268 {
269         const unsigned char *commit_data = g->chunk_commit_data + GRAPH_DATA_WIDTH * pos;
270         item->graph_pos = pos;
271         item->generation = get_be32(commit_data + g->hash_len + 8) >> 2;
272 }
273
274 static int fill_commit_in_graph(struct commit *item, struct commit_graph *g, uint32_t pos)
275 {
276         uint32_t edge_value;
277         uint32_t *parent_data_ptr;
278         uint64_t date_low, date_high;
279         struct commit_list **pptr;
280         const unsigned char *commit_data = g->chunk_commit_data + (g->hash_len + 16) * pos;
281
282         item->object.parsed = 1;
283         item->graph_pos = pos;
284
285         item->maybe_tree = NULL;
286
287         date_high = get_be32(commit_data + g->hash_len + 8) & 0x3;
288         date_low = get_be32(commit_data + g->hash_len + 12);
289         item->date = (timestamp_t)((date_high << 32) | date_low);
290
291         item->generation = get_be32(commit_data + g->hash_len + 8) >> 2;
292
293         pptr = &item->parents;
294
295         edge_value = get_be32(commit_data + g->hash_len);
296         if (edge_value == GRAPH_PARENT_NONE)
297                 return 1;
298         pptr = insert_parent_or_die(g, edge_value, pptr);
299
300         edge_value = get_be32(commit_data + g->hash_len + 4);
301         if (edge_value == GRAPH_PARENT_NONE)
302                 return 1;
303         if (!(edge_value & GRAPH_OCTOPUS_EDGES_NEEDED)) {
304                 pptr = insert_parent_or_die(g, edge_value, pptr);
305                 return 1;
306         }
307
308         parent_data_ptr = (uint32_t*)(g->chunk_large_edges +
309                           4 * (uint64_t)(edge_value & GRAPH_EDGE_LAST_MASK));
310         do {
311                 edge_value = get_be32(parent_data_ptr);
312                 pptr = insert_parent_or_die(g,
313                                             edge_value & GRAPH_EDGE_LAST_MASK,
314                                             pptr);
315                 parent_data_ptr++;
316         } while (!(edge_value & GRAPH_LAST_EDGE));
317
318         return 1;
319 }
320
321 static int find_commit_in_graph(struct commit *item, struct commit_graph *g, uint32_t *pos)
322 {
323         if (item->graph_pos != COMMIT_NOT_FROM_GRAPH) {
324                 *pos = item->graph_pos;
325                 return 1;
326         } else {
327                 return bsearch_graph(g, &(item->object.oid), pos);
328         }
329 }
330
331 static int parse_commit_in_graph_one(struct commit_graph *g, struct commit *item)
332 {
333         uint32_t pos;
334
335         if (item->object.parsed)
336                 return 1;
337
338         if (find_commit_in_graph(item, g, &pos))
339                 return fill_commit_in_graph(item, g, pos);
340
341         return 0;
342 }
343
344 int parse_commit_in_graph(struct repository *r, struct commit *item)
345 {
346         if (!prepare_commit_graph(r))
347                 return 0;
348         return parse_commit_in_graph_one(r->objects->commit_graph, item);
349 }
350
351 void load_commit_graph_info(struct repository *r, struct commit *item)
352 {
353         uint32_t pos;
354         if (!prepare_commit_graph(r))
355                 return;
356         if (find_commit_in_graph(item, r->objects->commit_graph, &pos))
357                 fill_commit_graph_info(item, r->objects->commit_graph, pos);
358 }
359
360 static struct tree *load_tree_for_commit(struct commit_graph *g, struct commit *c)
361 {
362         struct object_id oid;
363         const unsigned char *commit_data = g->chunk_commit_data +
364                                            GRAPH_DATA_WIDTH * (c->graph_pos);
365
366         hashcpy(oid.hash, commit_data);
367         c->maybe_tree = lookup_tree(the_repository, &oid);
368
369         return c->maybe_tree;
370 }
371
372 static struct tree *get_commit_tree_in_graph_one(struct commit_graph *g,
373                                                  const struct commit *c)
374 {
375         if (c->maybe_tree)
376                 return c->maybe_tree;
377         if (c->graph_pos == COMMIT_NOT_FROM_GRAPH)
378                 BUG("get_commit_tree_in_graph_one called from non-commit-graph commit");
379
380         return load_tree_for_commit(g, (struct commit *)c);
381 }
382
383 struct tree *get_commit_tree_in_graph(struct repository *r, const struct commit *c)
384 {
385         return get_commit_tree_in_graph_one(r->objects->commit_graph, c);
386 }
387
388 static void write_graph_chunk_fanout(struct hashfile *f,
389                                      struct commit **commits,
390                                      int nr_commits)
391 {
392         int i, count = 0;
393         struct commit **list = commits;
394
395         /*
396          * Write the first-level table (the list is sorted,
397          * but we use a 256-entry lookup to be able to avoid
398          * having to do eight extra binary search iterations).
399          */
400         for (i = 0; i < 256; i++) {
401                 while (count < nr_commits) {
402                         if ((*list)->object.oid.hash[0] != i)
403                                 break;
404                         count++;
405                         list++;
406                 }
407
408                 hashwrite_be32(f, count);
409         }
410 }
411
412 static void write_graph_chunk_oids(struct hashfile *f, int hash_len,
413                                    struct commit **commits, int nr_commits)
414 {
415         struct commit **list = commits;
416         int count;
417         for (count = 0; count < nr_commits; count++, list++)
418                 hashwrite(f, (*list)->object.oid.hash, (int)hash_len);
419 }
420
421 static const unsigned char *commit_to_sha1(size_t index, void *table)
422 {
423         struct commit **commits = table;
424         return commits[index]->object.oid.hash;
425 }
426
427 static void write_graph_chunk_data(struct hashfile *f, int hash_len,
428                                    struct commit **commits, int nr_commits)
429 {
430         struct commit **list = commits;
431         struct commit **last = commits + nr_commits;
432         uint32_t num_extra_edges = 0;
433
434         while (list < last) {
435                 struct commit_list *parent;
436                 int edge_value;
437                 uint32_t packedDate[2];
438
439                 parse_commit(*list);
440                 hashwrite(f, get_commit_tree_oid(*list)->hash, hash_len);
441
442                 parent = (*list)->parents;
443
444                 if (!parent)
445                         edge_value = GRAPH_PARENT_NONE;
446                 else {
447                         edge_value = sha1_pos(parent->item->object.oid.hash,
448                                               commits,
449                                               nr_commits,
450                                               commit_to_sha1);
451
452                         if (edge_value < 0)
453                                 edge_value = GRAPH_PARENT_MISSING;
454                 }
455
456                 hashwrite_be32(f, edge_value);
457
458                 if (parent)
459                         parent = parent->next;
460
461                 if (!parent)
462                         edge_value = GRAPH_PARENT_NONE;
463                 else if (parent->next)
464                         edge_value = GRAPH_OCTOPUS_EDGES_NEEDED | num_extra_edges;
465                 else {
466                         edge_value = sha1_pos(parent->item->object.oid.hash,
467                                               commits,
468                                               nr_commits,
469                                               commit_to_sha1);
470                         if (edge_value < 0)
471                                 edge_value = GRAPH_PARENT_MISSING;
472                 }
473
474                 hashwrite_be32(f, edge_value);
475
476                 if (edge_value & GRAPH_OCTOPUS_EDGES_NEEDED) {
477                         do {
478                                 num_extra_edges++;
479                                 parent = parent->next;
480                         } while (parent);
481                 }
482
483                 if (sizeof((*list)->date) > 4)
484                         packedDate[0] = htonl(((*list)->date >> 32) & 0x3);
485                 else
486                         packedDate[0] = 0;
487
488                 packedDate[0] |= htonl((*list)->generation << 2);
489
490                 packedDate[1] = htonl((*list)->date);
491                 hashwrite(f, packedDate, 8);
492
493                 list++;
494         }
495 }
496
497 static void write_graph_chunk_large_edges(struct hashfile *f,
498                                           struct commit **commits,
499                                           int nr_commits)
500 {
501         struct commit **list = commits;
502         struct commit **last = commits + nr_commits;
503         struct commit_list *parent;
504
505         while (list < last) {
506                 int num_parents = 0;
507                 for (parent = (*list)->parents; num_parents < 3 && parent;
508                      parent = parent->next)
509                         num_parents++;
510
511                 if (num_parents <= 2) {
512                         list++;
513                         continue;
514                 }
515
516                 /* Since num_parents > 2, this initializer is safe. */
517                 for (parent = (*list)->parents->next; parent; parent = parent->next) {
518                         int edge_value = sha1_pos(parent->item->object.oid.hash,
519                                                   commits,
520                                                   nr_commits,
521                                                   commit_to_sha1);
522
523                         if (edge_value < 0)
524                                 edge_value = GRAPH_PARENT_MISSING;
525                         else if (!parent->next)
526                                 edge_value |= GRAPH_LAST_EDGE;
527
528                         hashwrite_be32(f, edge_value);
529                 }
530
531                 list++;
532         }
533 }
534
535 static int commit_compare(const void *_a, const void *_b)
536 {
537         const struct object_id *a = (const struct object_id *)_a;
538         const struct object_id *b = (const struct object_id *)_b;
539         return oidcmp(a, b);
540 }
541
542 struct packed_commit_list {
543         struct commit **list;
544         int nr;
545         int alloc;
546 };
547
548 struct packed_oid_list {
549         struct object_id *list;
550         int nr;
551         int alloc;
552 };
553
554 static int add_packed_commits(const struct object_id *oid,
555                               struct packed_git *pack,
556                               uint32_t pos,
557                               void *data)
558 {
559         struct packed_oid_list *list = (struct packed_oid_list*)data;
560         enum object_type type;
561         off_t offset = nth_packed_object_offset(pack, pos);
562         struct object_info oi = OBJECT_INFO_INIT;
563
564         oi.typep = &type;
565         if (packed_object_info(the_repository, pack, offset, &oi) < 0)
566                 die(_("unable to get type of object %s"), oid_to_hex(oid));
567
568         if (type != OBJ_COMMIT)
569                 return 0;
570
571         ALLOC_GROW(list->list, list->nr + 1, list->alloc);
572         oidcpy(&(list->list[list->nr]), oid);
573         list->nr++;
574
575         return 0;
576 }
577
578 static void add_missing_parents(struct packed_oid_list *oids, struct commit *commit)
579 {
580         struct commit_list *parent;
581         for (parent = commit->parents; parent; parent = parent->next) {
582                 if (!(parent->item->object.flags & UNINTERESTING)) {
583                         ALLOC_GROW(oids->list, oids->nr + 1, oids->alloc);
584                         oidcpy(&oids->list[oids->nr], &(parent->item->object.oid));
585                         oids->nr++;
586                         parent->item->object.flags |= UNINTERESTING;
587                 }
588         }
589 }
590
591 static void close_reachable(struct packed_oid_list *oids)
592 {
593         int i;
594         struct commit *commit;
595
596         for (i = 0; i < oids->nr; i++) {
597                 commit = lookup_commit(the_repository, &oids->list[i]);
598                 if (commit)
599                         commit->object.flags |= UNINTERESTING;
600         }
601
602         /*
603          * As this loop runs, oids->nr may grow, but not more
604          * than the number of missing commits in the reachable
605          * closure.
606          */
607         for (i = 0; i < oids->nr; i++) {
608                 commit = lookup_commit(the_repository, &oids->list[i]);
609
610                 if (commit && !parse_commit(commit))
611                         add_missing_parents(oids, commit);
612         }
613
614         for (i = 0; i < oids->nr; i++) {
615                 commit = lookup_commit(the_repository, &oids->list[i]);
616
617                 if (commit)
618                         commit->object.flags &= ~UNINTERESTING;
619         }
620 }
621
622 static void compute_generation_numbers(struct packed_commit_list* commits)
623 {
624         int i;
625         struct commit_list *list = NULL;
626
627         for (i = 0; i < commits->nr; i++) {
628                 if (commits->list[i]->generation != GENERATION_NUMBER_INFINITY &&
629                     commits->list[i]->generation != GENERATION_NUMBER_ZERO)
630                         continue;
631
632                 commit_list_insert(commits->list[i], &list);
633                 while (list) {
634                         struct commit *current = list->item;
635                         struct commit_list *parent;
636                         int all_parents_computed = 1;
637                         uint32_t max_generation = 0;
638
639                         for (parent = current->parents; parent; parent = parent->next) {
640                                 if (parent->item->generation == GENERATION_NUMBER_INFINITY ||
641                                     parent->item->generation == GENERATION_NUMBER_ZERO) {
642                                         all_parents_computed = 0;
643                                         commit_list_insert(parent->item, &list);
644                                         break;
645                                 } else if (parent->item->generation > max_generation) {
646                                         max_generation = parent->item->generation;
647                                 }
648                         }
649
650                         if (all_parents_computed) {
651                                 current->generation = max_generation + 1;
652                                 pop_commit(&list);
653
654                                 if (current->generation > GENERATION_NUMBER_MAX)
655                                         current->generation = GENERATION_NUMBER_MAX;
656                         }
657                 }
658         }
659 }
660
661 static int add_ref_to_list(const char *refname,
662                            const struct object_id *oid,
663                            int flags, void *cb_data)
664 {
665         struct string_list *list = (struct string_list *)cb_data;
666
667         string_list_append(list, oid_to_hex(oid));
668         return 0;
669 }
670
671 void write_commit_graph_reachable(const char *obj_dir, int append)
672 {
673         struct string_list list;
674
675         string_list_init(&list, 1);
676         for_each_ref(add_ref_to_list, &list);
677         write_commit_graph(obj_dir, NULL, &list, append);
678 }
679
680 void write_commit_graph(const char *obj_dir,
681                         struct string_list *pack_indexes,
682                         struct string_list *commit_hex,
683                         int append)
684 {
685         struct packed_oid_list oids;
686         struct packed_commit_list commits;
687         struct hashfile *f;
688         uint32_t i, count_distinct = 0;
689         char *graph_name;
690         struct lock_file lk = LOCK_INIT;
691         uint32_t chunk_ids[5];
692         uint64_t chunk_offsets[5];
693         int num_chunks;
694         int num_extra_edges;
695         struct commit_list *parent;
696
697         oids.nr = 0;
698         oids.alloc = approximate_object_count() / 4;
699
700         if (append) {
701                 prepare_commit_graph_one(the_repository, obj_dir);
702                 if (the_repository->objects->commit_graph)
703                         oids.alloc += the_repository->objects->commit_graph->num_commits;
704         }
705
706         if (oids.alloc < 1024)
707                 oids.alloc = 1024;
708         ALLOC_ARRAY(oids.list, oids.alloc);
709
710         if (append && the_repository->objects->commit_graph) {
711                 struct commit_graph *commit_graph =
712                         the_repository->objects->commit_graph;
713                 for (i = 0; i < commit_graph->num_commits; i++) {
714                         const unsigned char *hash = commit_graph->chunk_oid_lookup +
715                                 commit_graph->hash_len * i;
716                         hashcpy(oids.list[oids.nr++].hash, hash);
717                 }
718         }
719
720         if (pack_indexes) {
721                 struct strbuf packname = STRBUF_INIT;
722                 int dirlen;
723                 strbuf_addf(&packname, "%s/pack/", obj_dir);
724                 dirlen = packname.len;
725                 for (i = 0; i < pack_indexes->nr; i++) {
726                         struct packed_git *p;
727                         strbuf_setlen(&packname, dirlen);
728                         strbuf_addstr(&packname, pack_indexes->items[i].string);
729                         p = add_packed_git(packname.buf, packname.len, 1);
730                         if (!p)
731                                 die(_("error adding pack %s"), packname.buf);
732                         if (open_pack_index(p))
733                                 die(_("error opening index for %s"), packname.buf);
734                         for_each_object_in_pack(p, add_packed_commits, &oids, 0);
735                         close_pack(p);
736                 }
737                 strbuf_release(&packname);
738         }
739
740         if (commit_hex) {
741                 for (i = 0; i < commit_hex->nr; i++) {
742                         const char *end;
743                         struct object_id oid;
744                         struct commit *result;
745
746                         if (commit_hex->items[i].string &&
747                             parse_oid_hex(commit_hex->items[i].string, &oid, &end))
748                                 continue;
749
750                         result = lookup_commit_reference_gently(the_repository, &oid, 1);
751
752                         if (result) {
753                                 ALLOC_GROW(oids.list, oids.nr + 1, oids.alloc);
754                                 oidcpy(&oids.list[oids.nr], &(result->object.oid));
755                                 oids.nr++;
756                         }
757                 }
758         }
759
760         if (!pack_indexes && !commit_hex)
761                 for_each_packed_object(add_packed_commits, &oids, 0);
762
763         close_reachable(&oids);
764
765         QSORT(oids.list, oids.nr, commit_compare);
766
767         count_distinct = 1;
768         for (i = 1; i < oids.nr; i++) {
769                 if (oidcmp(&oids.list[i-1], &oids.list[i]))
770                         count_distinct++;
771         }
772
773         if (count_distinct >= GRAPH_PARENT_MISSING)
774                 die(_("the commit graph format cannot write %d commits"), count_distinct);
775
776         commits.nr = 0;
777         commits.alloc = count_distinct;
778         ALLOC_ARRAY(commits.list, commits.alloc);
779
780         num_extra_edges = 0;
781         for (i = 0; i < oids.nr; i++) {
782                 int num_parents = 0;
783                 if (i > 0 && !oidcmp(&oids.list[i-1], &oids.list[i]))
784                         continue;
785
786                 commits.list[commits.nr] = lookup_commit(the_repository, &oids.list[i]);
787                 parse_commit(commits.list[commits.nr]);
788
789                 for (parent = commits.list[commits.nr]->parents;
790                      parent; parent = parent->next)
791                         num_parents++;
792
793                 if (num_parents > 2)
794                         num_extra_edges += num_parents - 1;
795
796                 commits.nr++;
797         }
798         num_chunks = num_extra_edges ? 4 : 3;
799
800         if (commits.nr >= GRAPH_PARENT_MISSING)
801                 die(_("too many commits to write graph"));
802
803         compute_generation_numbers(&commits);
804
805         graph_name = get_commit_graph_filename(obj_dir);
806         if (safe_create_leading_directories(graph_name))
807                 die_errno(_("unable to create leading directories of %s"),
808                           graph_name);
809
810         hold_lock_file_for_update(&lk, graph_name, LOCK_DIE_ON_ERROR);
811         f = hashfd(lk.tempfile->fd, lk.tempfile->filename.buf);
812
813         hashwrite_be32(f, GRAPH_SIGNATURE);
814
815         hashwrite_u8(f, GRAPH_VERSION);
816         hashwrite_u8(f, GRAPH_OID_VERSION);
817         hashwrite_u8(f, num_chunks);
818         hashwrite_u8(f, 0); /* unused padding byte */
819
820         chunk_ids[0] = GRAPH_CHUNKID_OIDFANOUT;
821         chunk_ids[1] = GRAPH_CHUNKID_OIDLOOKUP;
822         chunk_ids[2] = GRAPH_CHUNKID_DATA;
823         if (num_extra_edges)
824                 chunk_ids[3] = GRAPH_CHUNKID_LARGEEDGES;
825         else
826                 chunk_ids[3] = 0;
827         chunk_ids[4] = 0;
828
829         chunk_offsets[0] = 8 + (num_chunks + 1) * GRAPH_CHUNKLOOKUP_WIDTH;
830         chunk_offsets[1] = chunk_offsets[0] + GRAPH_FANOUT_SIZE;
831         chunk_offsets[2] = chunk_offsets[1] + GRAPH_OID_LEN * commits.nr;
832         chunk_offsets[3] = chunk_offsets[2] + (GRAPH_OID_LEN + 16) * commits.nr;
833         chunk_offsets[4] = chunk_offsets[3] + 4 * num_extra_edges;
834
835         for (i = 0; i <= num_chunks; i++) {
836                 uint32_t chunk_write[3];
837
838                 chunk_write[0] = htonl(chunk_ids[i]);
839                 chunk_write[1] = htonl(chunk_offsets[i] >> 32);
840                 chunk_write[2] = htonl(chunk_offsets[i] & 0xffffffff);
841                 hashwrite(f, chunk_write, 12);
842         }
843
844         write_graph_chunk_fanout(f, commits.list, commits.nr);
845         write_graph_chunk_oids(f, GRAPH_OID_LEN, commits.list, commits.nr);
846         write_graph_chunk_data(f, GRAPH_OID_LEN, commits.list, commits.nr);
847         write_graph_chunk_large_edges(f, commits.list, commits.nr);
848
849         close_commit_graph();
850         finalize_hashfile(f, NULL, CSUM_HASH_IN_STREAM | CSUM_FSYNC);
851         commit_lock_file(&lk);
852
853         free(oids.list);
854         oids.alloc = 0;
855         oids.nr = 0;
856 }
857
858 #define VERIFY_COMMIT_GRAPH_ERROR_HASH 2
859 static int verify_commit_graph_error;
860
861 static void graph_report(const char *fmt, ...)
862 {
863         va_list ap;
864
865         verify_commit_graph_error = 1;
866         va_start(ap, fmt);
867         vfprintf(stderr, fmt, ap);
868         fprintf(stderr, "\n");
869         va_end(ap);
870 }
871
872 #define GENERATION_ZERO_EXISTS 1
873 #define GENERATION_NUMBER_EXISTS 2
874
875 int verify_commit_graph(struct repository *r, struct commit_graph *g)
876 {
877         uint32_t i, cur_fanout_pos = 0;
878         struct object_id prev_oid, cur_oid, checksum;
879         int generation_zero = 0;
880         struct hashfile *f;
881         int devnull;
882
883         if (!g) {
884                 graph_report("no commit-graph file loaded");
885                 return 1;
886         }
887
888         verify_commit_graph_error = 0;
889
890         if (!g->chunk_oid_fanout)
891                 graph_report("commit-graph is missing the OID Fanout chunk");
892         if (!g->chunk_oid_lookup)
893                 graph_report("commit-graph is missing the OID Lookup chunk");
894         if (!g->chunk_commit_data)
895                 graph_report("commit-graph is missing the Commit Data chunk");
896
897         if (verify_commit_graph_error)
898                 return verify_commit_graph_error;
899
900         devnull = open("/dev/null", O_WRONLY);
901         f = hashfd(devnull, NULL);
902         hashwrite(f, g->data, g->data_len - g->hash_len);
903         finalize_hashfile(f, checksum.hash, CSUM_CLOSE);
904         if (hashcmp(checksum.hash, g->data + g->data_len - g->hash_len)) {
905                 graph_report(_("the commit-graph file has incorrect checksum and is likely corrupt"));
906                 verify_commit_graph_error = VERIFY_COMMIT_GRAPH_ERROR_HASH;
907         }
908
909         for (i = 0; i < g->num_commits; i++) {
910                 struct commit *graph_commit;
911
912                 hashcpy(cur_oid.hash, g->chunk_oid_lookup + g->hash_len * i);
913
914                 if (i && oidcmp(&prev_oid, &cur_oid) >= 0)
915                         graph_report("commit-graph has incorrect OID order: %s then %s",
916                                      oid_to_hex(&prev_oid),
917                                      oid_to_hex(&cur_oid));
918
919                 oidcpy(&prev_oid, &cur_oid);
920
921                 while (cur_oid.hash[0] > cur_fanout_pos) {
922                         uint32_t fanout_value = get_be32(g->chunk_oid_fanout + cur_fanout_pos);
923
924                         if (i != fanout_value)
925                                 graph_report("commit-graph has incorrect fanout value: fanout[%d] = %u != %u",
926                                              cur_fanout_pos, fanout_value, i);
927                         cur_fanout_pos++;
928                 }
929
930                 graph_commit = lookup_commit(r, &cur_oid);
931                 if (!parse_commit_in_graph_one(g, graph_commit))
932                         graph_report("failed to parse %s from commit-graph",
933                                      oid_to_hex(&cur_oid));
934         }
935
936         while (cur_fanout_pos < 256) {
937                 uint32_t fanout_value = get_be32(g->chunk_oid_fanout + cur_fanout_pos);
938
939                 if (g->num_commits != fanout_value)
940                         graph_report("commit-graph has incorrect fanout value: fanout[%d] = %u != %u",
941                                      cur_fanout_pos, fanout_value, i);
942
943                 cur_fanout_pos++;
944         }
945
946         if (verify_commit_graph_error & ~VERIFY_COMMIT_GRAPH_ERROR_HASH)
947                 return verify_commit_graph_error;
948
949         for (i = 0; i < g->num_commits; i++) {
950                 struct commit *graph_commit, *odb_commit;
951                 struct commit_list *graph_parents, *odb_parents;
952                 uint32_t max_generation = 0;
953
954                 hashcpy(cur_oid.hash, g->chunk_oid_lookup + g->hash_len * i);
955
956                 graph_commit = lookup_commit(r, &cur_oid);
957                 odb_commit = (struct commit *)create_object(r, cur_oid.hash, alloc_commit_node(r));
958                 if (parse_commit_internal(odb_commit, 0, 0)) {
959                         graph_report("failed to parse %s from object database",
960                                      oid_to_hex(&cur_oid));
961                         continue;
962                 }
963
964                 if (oidcmp(&get_commit_tree_in_graph_one(g, graph_commit)->object.oid,
965                            get_commit_tree_oid(odb_commit)))
966                         graph_report("root tree OID for commit %s in commit-graph is %s != %s",
967                                      oid_to_hex(&cur_oid),
968                                      oid_to_hex(get_commit_tree_oid(graph_commit)),
969                                      oid_to_hex(get_commit_tree_oid(odb_commit)));
970
971                 graph_parents = graph_commit->parents;
972                 odb_parents = odb_commit->parents;
973
974                 while (graph_parents) {
975                         if (odb_parents == NULL) {
976                                 graph_report("commit-graph parent list for commit %s is too long",
977                                              oid_to_hex(&cur_oid));
978                                 break;
979                         }
980
981                         if (oidcmp(&graph_parents->item->object.oid, &odb_parents->item->object.oid))
982                                 graph_report("commit-graph parent for %s is %s != %s",
983                                              oid_to_hex(&cur_oid),
984                                              oid_to_hex(&graph_parents->item->object.oid),
985                                              oid_to_hex(&odb_parents->item->object.oid));
986
987                         if (graph_parents->item->generation > max_generation)
988                                 max_generation = graph_parents->item->generation;
989
990                         graph_parents = graph_parents->next;
991                         odb_parents = odb_parents->next;
992                 }
993
994                 if (odb_parents != NULL)
995                         graph_report("commit-graph parent list for commit %s terminates early",
996                                      oid_to_hex(&cur_oid));
997
998                 if (!graph_commit->generation) {
999                         if (generation_zero == GENERATION_NUMBER_EXISTS)
1000                                 graph_report("commit-graph has generation number zero for commit %s, but non-zero elsewhere",
1001                                              oid_to_hex(&cur_oid));
1002                         generation_zero = GENERATION_ZERO_EXISTS;
1003                 } else if (generation_zero == GENERATION_ZERO_EXISTS)
1004                         graph_report("commit-graph has non-zero generation number for commit %s, but zero elsewhere",
1005                                      oid_to_hex(&cur_oid));
1006
1007                 if (generation_zero == GENERATION_ZERO_EXISTS)
1008                         continue;
1009
1010                 /*
1011                  * If one of our parents has generation GENERATION_NUMBER_MAX, then
1012                  * our generation is also GENERATION_NUMBER_MAX. Decrement to avoid
1013                  * extra logic in the following condition.
1014                  */
1015                 if (max_generation == GENERATION_NUMBER_MAX)
1016                         max_generation--;
1017
1018                 if (graph_commit->generation != max_generation + 1)
1019                         graph_report("commit-graph generation for commit %s is %u != %u",
1020                                      oid_to_hex(&cur_oid),
1021                                      graph_commit->generation,
1022                                      max_generation + 1);
1023
1024                 if (graph_commit->date != odb_commit->date)
1025                         graph_report("commit date for commit %s in commit-graph is %"PRItime" != %"PRItime,
1026                                      oid_to_hex(&cur_oid),
1027                                      graph_commit->date,
1028                                      odb_commit->date);
1029         }
1030
1031         return verify_commit_graph_error;
1032 }
1033
1034 void free_commit_graph(struct commit_graph *g)
1035 {
1036         if (!g)
1037                 return;
1038         if (g->graph_fd >= 0) {
1039                 munmap((void *)g->data, g->data_len);
1040                 g->data = NULL;
1041                 close(g->graph_fd);
1042         }
1043         free(g);
1044 }