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