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