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