f0698b05996757ae38562ad038400f6fb8889f17
   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        struct commit_graph *g;
 304        int open_ok = open_commit_graph(graph_file, &fd, &st);
 305
 306        if (!open_ok)
 307                return NULL;
 308
 309        g = load_commit_graph_one_fd_st(fd, &st);
 310
 311        if (g)
 312                g->filename = xstrdup(graph_file);
 313
 314        return g;
 315}
 316
 317static struct commit_graph *load_commit_graph_v1(struct repository *r, const char *obj_dir)
 318{
 319        char *graph_name = get_commit_graph_filename(obj_dir);
 320        struct commit_graph *g = load_commit_graph_one(graph_name);
 321        free(graph_name);
 322
 323        return g;
 324}
 325
 326static int add_graph_to_chain(struct commit_graph *g,
 327                              struct commit_graph *chain,
 328                              struct object_id *oids,
 329                              int n)
 330{
 331        struct commit_graph *cur_g = chain;
 332
 333        if (n && !g->chunk_base_graphs) {
 334                warning(_("commit-graph has no base graphs chunk"));
 335                return 0;
 336        }
 337
 338        while (n) {
 339                n--;
 340
 341                if (!cur_g ||
 342                    !oideq(&oids[n], &cur_g->oid) ||
 343                    !hasheq(oids[n].hash, g->chunk_base_graphs + g->hash_len * n)) {
 344                        warning(_("commit-graph chain does not match"));
 345                        return 0;
 346                }
 347
 348                cur_g = cur_g->base_graph;
 349        }
 350
 351        g->base_graph = chain;
 352
 353        if (chain)
 354                g->num_commits_in_base = chain->num_commits + chain->num_commits_in_base;
 355
 356        return 1;
 357}
 358
 359static struct commit_graph *load_commit_graph_chain(struct repository *r, const char *obj_dir)
 360{
 361        struct commit_graph *graph_chain = NULL;
 362        struct strbuf line = STRBUF_INIT;
 363        struct stat st;
 364        struct object_id *oids;
 365        int i = 0, valid = 1, count;
 366        char *chain_name = get_chain_filename(obj_dir);
 367        FILE *fp;
 368        int stat_res;
 369
 370        fp = fopen(chain_name, "r");
 371        stat_res = stat(chain_name, &st);
 372        free(chain_name);
 373
 374        if (!fp ||
 375            stat_res ||
 376            st.st_size <= the_hash_algo->hexsz)
 377                return NULL;
 378
 379        count = st.st_size / (the_hash_algo->hexsz + 1);
 380        oids = xcalloc(count, sizeof(struct object_id));
 381
 382        for (i = 0; i < count && valid; i++) {
 383                char *graph_name;
 384                struct commit_graph *g;
 385
 386                if (strbuf_getline_lf(&line, fp) == EOF)
 387                        break;
 388
 389                if (get_oid_hex(line.buf, &oids[i])) {
 390                        warning(_("invalid commit-graph chain: line '%s' not a hash"),
 391                                line.buf);
 392                        valid = 0;
 393                        break;
 394                }
 395
 396                graph_name = get_split_graph_filename(obj_dir, line.buf);
 397                g = load_commit_graph_one(graph_name);
 398                free(graph_name);
 399
 400                if (g && add_graph_to_chain(g, graph_chain, oids, i))
 401                        graph_chain = g;
 402                else
 403                        valid = 0;
 404        }
 405
 406        free(oids);
 407        fclose(fp);
 408
 409        return graph_chain;
 410}
 411
 412static struct commit_graph *read_commit_graph_one(struct repository *r, const char *obj_dir)
 413{
 414        struct commit_graph *g = load_commit_graph_v1(r, obj_dir);
 415
 416        if (!g)
 417                g = load_commit_graph_chain(r, obj_dir);
 418
 419        return g;
 420}
 421
 422static void prepare_commit_graph_one(struct repository *r, const char *obj_dir)
 423{
 424
 425        if (r->objects->commit_graph)
 426                return;
 427
 428        r->objects->commit_graph = read_commit_graph_one(r, obj_dir);
 429}
 430
 431/*
 432 * Return 1 if commit_graph is non-NULL, and 0 otherwise.
 433 *
 434 * On the first invocation, this function attemps to load the commit
 435 * graph if the_repository is configured to have one.
 436 */
 437static int prepare_commit_graph(struct repository *r)
 438{
 439        struct object_directory *odb;
 440        int config_value;
 441
 442        if (git_env_bool(GIT_TEST_COMMIT_GRAPH_DIE_ON_LOAD, 0))
 443                die("dying as requested by the '%s' variable on commit-graph load!",
 444                    GIT_TEST_COMMIT_GRAPH_DIE_ON_LOAD);
 445
 446        if (r->objects->commit_graph_attempted)
 447                return !!r->objects->commit_graph;
 448        r->objects->commit_graph_attempted = 1;
 449
 450        if (!git_env_bool(GIT_TEST_COMMIT_GRAPH, 0) &&
 451            (repo_config_get_bool(r, "core.commitgraph", &config_value) ||
 452            !config_value))
 453                /*
 454                 * This repository is not configured to use commit graphs, so
 455                 * do not load one. (But report commit_graph_attempted anyway
 456                 * so that commit graph loading is not attempted again for this
 457                 * repository.)
 458                 */
 459                return 0;
 460
 461        if (!commit_graph_compatible(r))
 462                return 0;
 463
 464        prepare_alt_odb(r);
 465        for (odb = r->objects->odb;
 466             !r->objects->commit_graph && odb;
 467             odb = odb->next)
 468                prepare_commit_graph_one(r, odb->path);
 469        return !!r->objects->commit_graph;
 470}
 471
 472int generation_numbers_enabled(struct repository *r)
 473{
 474        uint32_t first_generation;
 475        struct commit_graph *g;
 476        if (!prepare_commit_graph(r))
 477               return 0;
 478
 479        g = r->objects->commit_graph;
 480
 481        if (!g->num_commits)
 482                return 0;
 483
 484        first_generation = get_be32(g->chunk_commit_data +
 485                                    g->hash_len + 8) >> 2;
 486
 487        return !!first_generation;
 488}
 489
 490static void close_commit_graph_one(struct commit_graph *g)
 491{
 492        if (!g)
 493                return;
 494
 495        close_commit_graph_one(g->base_graph);
 496        free_commit_graph(g);
 497}
 498
 499void close_commit_graph(struct raw_object_store *o)
 500{
 501        close_commit_graph_one(o->commit_graph);
 502        o->commit_graph = NULL;
 503}
 504
 505static int bsearch_graph(struct commit_graph *g, struct object_id *oid, uint32_t *pos)
 506{
 507        return bsearch_hash(oid->hash, g->chunk_oid_fanout,
 508                            g->chunk_oid_lookup, g->hash_len, pos);
 509}
 510
 511static void load_oid_from_graph(struct commit_graph *g,
 512                                uint32_t pos,
 513                                struct object_id *oid)
 514{
 515        uint32_t lex_index;
 516
 517        while (g && pos < g->num_commits_in_base)
 518                g = g->base_graph;
 519
 520        if (!g)
 521                BUG("NULL commit-graph");
 522
 523        if (pos >= g->num_commits + g->num_commits_in_base)
 524                die(_("invalid commit position. commit-graph is likely corrupt"));
 525
 526        lex_index = pos - g->num_commits_in_base;
 527
 528        hashcpy(oid->hash, g->chunk_oid_lookup + g->hash_len * lex_index);
 529}
 530
 531static struct commit_list **insert_parent_or_die(struct repository *r,
 532                                                 struct commit_graph *g,
 533                                                 uint32_t pos,
 534                                                 struct commit_list **pptr)
 535{
 536        struct commit *c;
 537        struct object_id oid;
 538
 539        if (pos >= g->num_commits + g->num_commits_in_base)
 540                die("invalid parent position %"PRIu32, pos);
 541
 542        load_oid_from_graph(g, pos, &oid);
 543        c = lookup_commit(r, &oid);
 544        if (!c)
 545                die(_("could not find commit %s"), oid_to_hex(&oid));
 546        c->graph_pos = pos;
 547        return &commit_list_insert(c, pptr)->next;
 548}
 549
 550static void fill_commit_graph_info(struct commit *item, struct commit_graph *g, uint32_t pos)
 551{
 552        const unsigned char *commit_data;
 553        uint32_t lex_index;
 554
 555        while (pos < g->num_commits_in_base)
 556                g = g->base_graph;
 557
 558        lex_index = pos - g->num_commits_in_base;
 559        commit_data = g->chunk_commit_data + GRAPH_DATA_WIDTH * lex_index;
 560        item->graph_pos = pos;
 561        item->generation = get_be32(commit_data + g->hash_len + 8) >> 2;
 562}
 563
 564static int fill_commit_in_graph(struct repository *r,
 565                                struct commit *item,
 566                                struct commit_graph *g, uint32_t pos)
 567{
 568        uint32_t edge_value;
 569        uint32_t *parent_data_ptr;
 570        uint64_t date_low, date_high;
 571        struct commit_list **pptr;
 572        const unsigned char *commit_data;
 573        uint32_t lex_index;
 574
 575        while (pos < g->num_commits_in_base)
 576                g = g->base_graph;
 577
 578        if (pos >= g->num_commits + g->num_commits_in_base)
 579                die(_("invalid commit position. commit-graph is likely corrupt"));
 580
 581        /*
 582         * Store the "full" position, but then use the
 583         * "local" position for the rest of the calculation.
 584         */
 585        item->graph_pos = pos;
 586        lex_index = pos - g->num_commits_in_base;
 587
 588        commit_data = g->chunk_commit_data + (g->hash_len + 16) * lex_index;
 589
 590        item->object.parsed = 1;
 591
 592        item->maybe_tree = NULL;
 593
 594        date_high = get_be32(commit_data + g->hash_len + 8) & 0x3;
 595        date_low = get_be32(commit_data + g->hash_len + 12);
 596        item->date = (timestamp_t)((date_high << 32) | date_low);
 597
 598        item->generation = get_be32(commit_data + g->hash_len + 8) >> 2;
 599
 600        pptr = &item->parents;
 601
 602        edge_value = get_be32(commit_data + g->hash_len);
 603        if (edge_value == GRAPH_PARENT_NONE)
 604                return 1;
 605        pptr = insert_parent_or_die(r, g, edge_value, pptr);
 606
 607        edge_value = get_be32(commit_data + g->hash_len + 4);
 608        if (edge_value == GRAPH_PARENT_NONE)
 609                return 1;
 610        if (!(edge_value & GRAPH_EXTRA_EDGES_NEEDED)) {
 611                pptr = insert_parent_or_die(r, g, edge_value, pptr);
 612                return 1;
 613        }
 614
 615        parent_data_ptr = (uint32_t*)(g->chunk_extra_edges +
 616                          4 * (uint64_t)(edge_value & GRAPH_EDGE_LAST_MASK));
 617        do {
 618                edge_value = get_be32(parent_data_ptr);
 619                pptr = insert_parent_or_die(r, g,
 620                                            edge_value & GRAPH_EDGE_LAST_MASK,
 621                                            pptr);
 622                parent_data_ptr++;
 623        } while (!(edge_value & GRAPH_LAST_EDGE));
 624
 625        return 1;
 626}
 627
 628static int find_commit_in_graph(struct commit *item, struct commit_graph *g, uint32_t *pos)
 629{
 630        if (item->graph_pos != COMMIT_NOT_FROM_GRAPH) {
 631                *pos = item->graph_pos;
 632                return 1;
 633        } else {
 634                struct commit_graph *cur_g = g;
 635                uint32_t lex_index;
 636
 637                while (cur_g && !bsearch_graph(cur_g, &(item->object.oid), &lex_index))
 638                        cur_g = cur_g->base_graph;
 639
 640                if (cur_g) {
 641                        *pos = lex_index + cur_g->num_commits_in_base;
 642                        return 1;
 643                }
 644
 645                return 0;
 646        }
 647}
 648
 649static int parse_commit_in_graph_one(struct repository *r,
 650                                     struct commit_graph *g,
 651                                     struct commit *item)
 652{
 653        uint32_t pos;
 654
 655        if (item->object.parsed)
 656                return 1;
 657
 658        if (find_commit_in_graph(item, g, &pos))
 659                return fill_commit_in_graph(r, item, g, pos);
 660
 661        return 0;
 662}
 663
 664int parse_commit_in_graph(struct repository *r, struct commit *item)
 665{
 666        if (!prepare_commit_graph(r))
 667                return 0;
 668        return parse_commit_in_graph_one(r, r->objects->commit_graph, item);
 669}
 670
 671void load_commit_graph_info(struct repository *r, struct commit *item)
 672{
 673        uint32_t pos;
 674        if (!prepare_commit_graph(r))
 675                return;
 676        if (find_commit_in_graph(item, r->objects->commit_graph, &pos))
 677                fill_commit_graph_info(item, r->objects->commit_graph, pos);
 678}
 679
 680static struct tree *load_tree_for_commit(struct repository *r,
 681                                         struct commit_graph *g,
 682                                         struct commit *c)
 683{
 684        struct object_id oid;
 685        const unsigned char *commit_data;
 686
 687        while (c->graph_pos < g->num_commits_in_base)
 688                g = g->base_graph;
 689
 690        commit_data = g->chunk_commit_data +
 691                        GRAPH_DATA_WIDTH * (c->graph_pos - g->num_commits_in_base);
 692
 693        hashcpy(oid.hash, commit_data);
 694        c->maybe_tree = lookup_tree(r, &oid);
 695
 696        return c->maybe_tree;
 697}
 698
 699static struct tree *get_commit_tree_in_graph_one(struct repository *r,
 700                                                 struct commit_graph *g,
 701                                                 const struct commit *c)
 702{
 703        if (c->maybe_tree)
 704                return c->maybe_tree;
 705        if (c->graph_pos == COMMIT_NOT_FROM_GRAPH)
 706                BUG("get_commit_tree_in_graph_one called from non-commit-graph commit");
 707
 708        return load_tree_for_commit(r, g, (struct commit *)c);
 709}
 710
 711struct tree *get_commit_tree_in_graph(struct repository *r, const struct commit *c)
 712{
 713        return get_commit_tree_in_graph_one(r, r->objects->commit_graph, c);
 714}
 715
 716struct packed_commit_list {
 717        struct commit **list;
 718        int nr;
 719        int alloc;
 720};
 721
 722struct packed_oid_list {
 723        struct object_id *list;
 724        int nr;
 725        int alloc;
 726};
 727
 728struct write_commit_graph_context {
 729        struct repository *r;
 730        const char *obj_dir;
 731        char *graph_name;
 732        struct packed_oid_list oids;
 733        struct packed_commit_list commits;
 734        int num_extra_edges;
 735        unsigned long approx_nr_objects;
 736        struct progress *progress;
 737        int progress_done;
 738        uint64_t progress_cnt;
 739
 740        char *base_graph_name;
 741        int num_commit_graphs_before;
 742        int num_commit_graphs_after;
 743        char **commit_graph_filenames_before;
 744        char **commit_graph_filenames_after;
 745        char **commit_graph_hash_after;
 746        uint32_t new_num_commits_in_base;
 747        struct commit_graph *new_base_graph;
 748
 749        unsigned append:1,
 750                 report_progress:1,
 751                 split:1;
 752};
 753
 754static void write_graph_chunk_fanout(struct hashfile *f,
 755                                     struct write_commit_graph_context *ctx)
 756{
 757        int i, count = 0;
 758        struct commit **list = ctx->commits.list;
 759
 760        /*
 761         * Write the first-level table (the list is sorted,
 762         * but we use a 256-entry lookup to be able to avoid
 763         * having to do eight extra binary search iterations).
 764         */
 765        for (i = 0; i < 256; i++) {
 766                while (count < ctx->commits.nr) {
 767                        if ((*list)->object.oid.hash[0] != i)
 768                                break;
 769                        display_progress(ctx->progress, ++ctx->progress_cnt);
 770                        count++;
 771                        list++;
 772                }
 773
 774                hashwrite_be32(f, count);
 775        }
 776}
 777
 778static void write_graph_chunk_oids(struct hashfile *f, int hash_len,
 779                                   struct write_commit_graph_context *ctx)
 780{
 781        struct commit **list = ctx->commits.list;
 782        int count;
 783        for (count = 0; count < ctx->commits.nr; count++, list++) {
 784                display_progress(ctx->progress, ++ctx->progress_cnt);
 785                hashwrite(f, (*list)->object.oid.hash, (int)hash_len);
 786        }
 787}
 788
 789static const unsigned char *commit_to_sha1(size_t index, void *table)
 790{
 791        struct commit **commits = table;
 792        return commits[index]->object.oid.hash;
 793}
 794
 795static void write_graph_chunk_data(struct hashfile *f, int hash_len,
 796                                   struct write_commit_graph_context *ctx)
 797{
 798        struct commit **list = ctx->commits.list;
 799        struct commit **last = ctx->commits.list + ctx->commits.nr;
 800        uint32_t num_extra_edges = 0;
 801
 802        while (list < last) {
 803                struct commit_list *parent;
 804                int edge_value;
 805                uint32_t packedDate[2];
 806                display_progress(ctx->progress, ++ctx->progress_cnt);
 807
 808                parse_commit_no_graph(*list);
 809                hashwrite(f, get_commit_tree_oid(*list)->hash, hash_len);
 810
 811                parent = (*list)->parents;
 812
 813                if (!parent)
 814                        edge_value = GRAPH_PARENT_NONE;
 815                else {
 816                        edge_value = sha1_pos(parent->item->object.oid.hash,
 817                                              ctx->commits.list,
 818                                              ctx->commits.nr,
 819                                              commit_to_sha1);
 820
 821                        if (edge_value >= 0)
 822                                edge_value += ctx->new_num_commits_in_base;
 823                        else {
 824                                uint32_t pos;
 825                                if (find_commit_in_graph(parent->item,
 826                                                         ctx->new_base_graph,
 827                                                         &pos))
 828                                        edge_value = pos;
 829                        }
 830
 831                        if (edge_value < 0)
 832                                BUG("missing parent %s for commit %s",
 833                                    oid_to_hex(&parent->item->object.oid),
 834                                    oid_to_hex(&(*list)->object.oid));
 835                }
 836
 837                hashwrite_be32(f, edge_value);
 838
 839                if (parent)
 840                        parent = parent->next;
 841
 842                if (!parent)
 843                        edge_value = GRAPH_PARENT_NONE;
 844                else if (parent->next)
 845                        edge_value = GRAPH_EXTRA_EDGES_NEEDED | num_extra_edges;
 846                else {
 847                        edge_value = sha1_pos(parent->item->object.oid.hash,
 848                                              ctx->commits.list,
 849                                              ctx->commits.nr,
 850                                              commit_to_sha1);
 851
 852                        if (edge_value >= 0)
 853                                edge_value += ctx->new_num_commits_in_base;
 854                        else {
 855                                uint32_t pos;
 856                                if (find_commit_in_graph(parent->item,
 857                                                         ctx->new_base_graph,
 858                                                         &pos))
 859                                        edge_value = pos;
 860                        }
 861
 862                        if (edge_value < 0)
 863                                BUG("missing parent %s for commit %s",
 864                                    oid_to_hex(&parent->item->object.oid),
 865                                    oid_to_hex(&(*list)->object.oid));
 866                }
 867
 868                hashwrite_be32(f, edge_value);
 869
 870                if (edge_value & GRAPH_EXTRA_EDGES_NEEDED) {
 871                        do {
 872                                num_extra_edges++;
 873                                parent = parent->next;
 874                        } while (parent);
 875                }
 876
 877                if (sizeof((*list)->date) > 4)
 878                        packedDate[0] = htonl(((*list)->date >> 32) & 0x3);
 879                else
 880                        packedDate[0] = 0;
 881
 882                packedDate[0] |= htonl((*list)->generation << 2);
 883
 884                packedDate[1] = htonl((*list)->date);
 885                hashwrite(f, packedDate, 8);
 886
 887                list++;
 888        }
 889}
 890
 891static void write_graph_chunk_extra_edges(struct hashfile *f,
 892                                          struct write_commit_graph_context *ctx)
 893{
 894        struct commit **list = ctx->commits.list;
 895        struct commit **last = ctx->commits.list + ctx->commits.nr;
 896        struct commit_list *parent;
 897
 898        while (list < last) {
 899                int num_parents = 0;
 900
 901                display_progress(ctx->progress, ++ctx->progress_cnt);
 902
 903                for (parent = (*list)->parents; num_parents < 3 && parent;
 904                     parent = parent->next)
 905                        num_parents++;
 906
 907                if (num_parents <= 2) {
 908                        list++;
 909                        continue;
 910                }
 911
 912                /* Since num_parents > 2, this initializer is safe. */
 913                for (parent = (*list)->parents->next; parent; parent = parent->next) {
 914                        int edge_value = sha1_pos(parent->item->object.oid.hash,
 915                                                  ctx->commits.list,
 916                                                  ctx->commits.nr,
 917                                                  commit_to_sha1);
 918
 919                        if (edge_value >= 0)
 920                                edge_value += ctx->new_num_commits_in_base;
 921                        else {
 922                                uint32_t pos;
 923                                if (find_commit_in_graph(parent->item,
 924                                                         ctx->new_base_graph,
 925                                                         &pos))
 926                                        edge_value = pos;
 927                        }
 928
 929                        if (edge_value < 0)
 930                                BUG("missing parent %s for commit %s",
 931                                    oid_to_hex(&parent->item->object.oid),
 932                                    oid_to_hex(&(*list)->object.oid));
 933                        else if (!parent->next)
 934                                edge_value |= GRAPH_LAST_EDGE;
 935
 936                        hashwrite_be32(f, edge_value);
 937                }
 938
 939                list++;
 940        }
 941}
 942
 943static int oid_compare(const void *_a, const void *_b)
 944{
 945        const struct object_id *a = (const struct object_id *)_a;
 946        const struct object_id *b = (const struct object_id *)_b;
 947        return oidcmp(a, b);
 948}
 949
 950static int add_packed_commits(const struct object_id *oid,
 951                              struct packed_git *pack,
 952                              uint32_t pos,
 953                              void *data)
 954{
 955        struct write_commit_graph_context *ctx = (struct write_commit_graph_context*)data;
 956        enum object_type type;
 957        off_t offset = nth_packed_object_offset(pack, pos);
 958        struct object_info oi = OBJECT_INFO_INIT;
 959
 960        if (ctx->progress)
 961                display_progress(ctx->progress, ++ctx->progress_done);
 962
 963        oi.typep = &type;
 964        if (packed_object_info(ctx->r, pack, offset, &oi) < 0)
 965                die(_("unable to get type of object %s"), oid_to_hex(oid));
 966
 967        if (type != OBJ_COMMIT)
 968                return 0;
 969
 970        ALLOC_GROW(ctx->oids.list, ctx->oids.nr + 1, ctx->oids.alloc);
 971        oidcpy(&(ctx->oids.list[ctx->oids.nr]), oid);
 972        ctx->oids.nr++;
 973
 974        return 0;
 975}
 976
 977static void add_missing_parents(struct write_commit_graph_context *ctx, struct commit *commit)
 978{
 979        struct commit_list *parent;
 980        for (parent = commit->parents; parent; parent = parent->next) {
 981                if (!(parent->item->object.flags & UNINTERESTING)) {
 982                        ALLOC_GROW(ctx->oids.list, ctx->oids.nr + 1, ctx->oids.alloc);
 983                        oidcpy(&ctx->oids.list[ctx->oids.nr], &(parent->item->object.oid));
 984                        ctx->oids.nr++;
 985                        parent->item->object.flags |= UNINTERESTING;
 986                }
 987        }
 988}
 989
 990static void close_reachable(struct write_commit_graph_context *ctx)
 991{
 992        int i;
 993        struct commit *commit;
 994
 995        if (ctx->report_progress)
 996                ctx->progress = start_delayed_progress(
 997                                        _("Loading known commits in commit graph"),
 998                                        ctx->oids.nr);
 999        for (i = 0; i < ctx->oids.nr; i++) {
1000                display_progress(ctx->progress, i + 1);
1001                commit = lookup_commit(ctx->r, &ctx->oids.list[i]);
1002                if (commit)
1003                        commit->object.flags |= UNINTERESTING;
1004        }
1005        stop_progress(&ctx->progress);
1006
1007        /*
1008         * As this loop runs, ctx->oids.nr may grow, but not more
1009         * than the number of missing commits in the reachable
1010         * closure.
1011         */
1012        if (ctx->report_progress)
1013                ctx->progress = start_delayed_progress(
1014                                        _("Expanding reachable commits in commit graph"),
1015                                        ctx->oids.nr);
1016        for (i = 0; i < ctx->oids.nr; i++) {
1017                display_progress(ctx->progress, i + 1);
1018                commit = lookup_commit(ctx->r, &ctx->oids.list[i]);
1019
1020                if (!commit)
1021                        continue;
1022                if (ctx->split) {
1023                        if (!parse_commit(commit) &&
1024                            commit->graph_pos == COMMIT_NOT_FROM_GRAPH)
1025                                add_missing_parents(ctx, commit);
1026                } else if (!parse_commit_no_graph(commit))
1027                        add_missing_parents(ctx, commit);
1028        }
1029        stop_progress(&ctx->progress);
1030
1031        if (ctx->report_progress)
1032                ctx->progress = start_delayed_progress(
1033                                        _("Clearing commit marks in commit graph"),
1034                                        ctx->oids.nr);
1035        for (i = 0; i < ctx->oids.nr; i++) {
1036                display_progress(ctx->progress, i + 1);
1037                commit = lookup_commit(ctx->r, &ctx->oids.list[i]);
1038
1039                if (commit)
1040                        commit->object.flags &= ~UNINTERESTING;
1041        }
1042        stop_progress(&ctx->progress);
1043}
1044
1045static void compute_generation_numbers(struct write_commit_graph_context *ctx)
1046{
1047        int i;
1048        struct commit_list *list = NULL;
1049
1050        if (ctx->report_progress)
1051                ctx->progress = start_progress(
1052                                        _("Computing commit graph generation numbers"),
1053                                        ctx->commits.nr);
1054        for (i = 0; i < ctx->commits.nr; i++) {
1055                display_progress(ctx->progress, i + 1);
1056                if (ctx->commits.list[i]->generation != GENERATION_NUMBER_INFINITY &&
1057                    ctx->commits.list[i]->generation != GENERATION_NUMBER_ZERO)
1058                        continue;
1059
1060                commit_list_insert(ctx->commits.list[i], &list);
1061                while (list) {
1062                        struct commit *current = list->item;
1063                        struct commit_list *parent;
1064                        int all_parents_computed = 1;
1065                        uint32_t max_generation = 0;
1066
1067                        for (parent = current->parents; parent; parent = parent->next) {
1068                                if (parent->item->generation == GENERATION_NUMBER_INFINITY ||
1069                                    parent->item->generation == GENERATION_NUMBER_ZERO) {
1070                                        all_parents_computed = 0;
1071                                        commit_list_insert(parent->item, &list);
1072                                        break;
1073                                } else if (parent->item->generation > max_generation) {
1074                                        max_generation = parent->item->generation;
1075                                }
1076                        }
1077
1078                        if (all_parents_computed) {
1079                                current->generation = max_generation + 1;
1080                                pop_commit(&list);
1081
1082                                if (current->generation > GENERATION_NUMBER_MAX)
1083                                        current->generation = GENERATION_NUMBER_MAX;
1084                        }
1085                }
1086        }
1087        stop_progress(&ctx->progress);
1088}
1089
1090static int add_ref_to_list(const char *refname,
1091                           const struct object_id *oid,
1092                           int flags, void *cb_data)
1093{
1094        struct string_list *list = (struct string_list *)cb_data;
1095
1096        string_list_append(list, oid_to_hex(oid));
1097        return 0;
1098}
1099
1100int write_commit_graph_reachable(const char *obj_dir, unsigned int flags)
1101{
1102        struct string_list list = STRING_LIST_INIT_DUP;
1103        int result;
1104
1105        for_each_ref(add_ref_to_list, &list);
1106        result = write_commit_graph(obj_dir, NULL, &list,
1107                                    flags);
1108
1109        string_list_clear(&list, 0);
1110        return result;
1111}
1112
1113static int fill_oids_from_packs(struct write_commit_graph_context *ctx,
1114                                struct string_list *pack_indexes)
1115{
1116        uint32_t i;
1117        struct strbuf progress_title = STRBUF_INIT;
1118        struct strbuf packname = STRBUF_INIT;
1119        int dirlen;
1120
1121        strbuf_addf(&packname, "%s/pack/", ctx->obj_dir);
1122        dirlen = packname.len;
1123        if (ctx->report_progress) {
1124                strbuf_addf(&progress_title,
1125                            Q_("Finding commits for commit graph in %d pack",
1126                               "Finding commits for commit graph in %d packs",
1127                               pack_indexes->nr),
1128                            pack_indexes->nr);
1129                ctx->progress = start_delayed_progress(progress_title.buf, 0);
1130                ctx->progress_done = 0;
1131        }
1132        for (i = 0; i < pack_indexes->nr; i++) {
1133                struct packed_git *p;
1134                strbuf_setlen(&packname, dirlen);
1135                strbuf_addstr(&packname, pack_indexes->items[i].string);
1136                p = add_packed_git(packname.buf, packname.len, 1);
1137                if (!p) {
1138                        error(_("error adding pack %s"), packname.buf);
1139                        return -1;
1140                }
1141                if (open_pack_index(p)) {
1142                        error(_("error opening index for %s"), packname.buf);
1143                        return -1;
1144                }
1145                for_each_object_in_pack(p, add_packed_commits, ctx,
1146                                        FOR_EACH_OBJECT_PACK_ORDER);
1147                close_pack(p);
1148                free(p);
1149        }
1150
1151        stop_progress(&ctx->progress);
1152        strbuf_reset(&progress_title);
1153        strbuf_release(&packname);
1154
1155        return 0;
1156}
1157
1158static void fill_oids_from_commit_hex(struct write_commit_graph_context *ctx,
1159                                      struct string_list *commit_hex)
1160{
1161        uint32_t i;
1162        struct strbuf progress_title = STRBUF_INIT;
1163
1164        if (ctx->report_progress) {
1165                strbuf_addf(&progress_title,
1166                            Q_("Finding commits for commit graph from %d ref",
1167                               "Finding commits for commit graph from %d refs",
1168                               commit_hex->nr),
1169                            commit_hex->nr);
1170                ctx->progress = start_delayed_progress(
1171                                        progress_title.buf,
1172                                        commit_hex->nr);
1173        }
1174        for (i = 0; i < commit_hex->nr; i++) {
1175                const char *end;
1176                struct object_id oid;
1177                struct commit *result;
1178
1179                display_progress(ctx->progress, i + 1);
1180                if (commit_hex->items[i].string &&
1181                    parse_oid_hex(commit_hex->items[i].string, &oid, &end))
1182                        continue;
1183
1184                result = lookup_commit_reference_gently(ctx->r, &oid, 1);
1185
1186                if (result) {
1187                        ALLOC_GROW(ctx->oids.list, ctx->oids.nr + 1, ctx->oids.alloc);
1188                        oidcpy(&ctx->oids.list[ctx->oids.nr], &(result->object.oid));
1189                        ctx->oids.nr++;
1190                }
1191        }
1192        stop_progress(&ctx->progress);
1193        strbuf_release(&progress_title);
1194}
1195
1196static void fill_oids_from_all_packs(struct write_commit_graph_context *ctx)
1197{
1198        if (ctx->report_progress)
1199                ctx->progress = start_delayed_progress(
1200                        _("Finding commits for commit graph among packed objects"),
1201                        ctx->approx_nr_objects);
1202        for_each_packed_object(add_packed_commits, ctx,
1203                               FOR_EACH_OBJECT_PACK_ORDER);
1204        if (ctx->progress_done < ctx->approx_nr_objects)
1205                display_progress(ctx->progress, ctx->approx_nr_objects);
1206        stop_progress(&ctx->progress);
1207}
1208
1209static uint32_t count_distinct_commits(struct write_commit_graph_context *ctx)
1210{
1211        uint32_t i, count_distinct = 1;
1212
1213        if (ctx->report_progress)
1214                ctx->progress = start_delayed_progress(
1215                        _("Counting distinct commits in commit graph"),
1216                        ctx->oids.nr);
1217        display_progress(ctx->progress, 0); /* TODO: Measure QSORT() progress */
1218        QSORT(ctx->oids.list, ctx->oids.nr, oid_compare);
1219
1220        for (i = 1; i < ctx->oids.nr; i++) {
1221                display_progress(ctx->progress, i + 1);
1222                if (!oideq(&ctx->oids.list[i - 1], &ctx->oids.list[i])) {
1223                        if (ctx->split) {
1224                                struct commit *c = lookup_commit(ctx->r, &ctx->oids.list[i]);
1225
1226                                if (!c || c->graph_pos != COMMIT_NOT_FROM_GRAPH)
1227                                        continue;
1228                        }
1229
1230                        count_distinct++;
1231                }
1232        }
1233        stop_progress(&ctx->progress);
1234
1235        return count_distinct;
1236}
1237
1238static void copy_oids_to_commits(struct write_commit_graph_context *ctx)
1239{
1240        uint32_t i;
1241        struct commit_list *parent;
1242
1243        ctx->num_extra_edges = 0;
1244        if (ctx->report_progress)
1245                ctx->progress = start_delayed_progress(
1246                        _("Finding extra edges in commit graph"),
1247                        ctx->oids.nr);
1248        for (i = 0; i < ctx->oids.nr; i++) {
1249                int num_parents = 0;
1250                display_progress(ctx->progress, i + 1);
1251                if (i > 0 && oideq(&ctx->oids.list[i - 1], &ctx->oids.list[i]))
1252                        continue;
1253
1254                ALLOC_GROW(ctx->commits.list, ctx->commits.nr + 1, ctx->commits.alloc);
1255                ctx->commits.list[ctx->commits.nr] = lookup_commit(ctx->r, &ctx->oids.list[i]);
1256
1257                if (ctx->split &&
1258                    ctx->commits.list[ctx->commits.nr]->graph_pos != COMMIT_NOT_FROM_GRAPH)
1259                        continue;
1260
1261                parse_commit_no_graph(ctx->commits.list[ctx->commits.nr]);
1262
1263                for (parent = ctx->commits.list[ctx->commits.nr]->parents;
1264                     parent; parent = parent->next)
1265                        num_parents++;
1266
1267                if (num_parents > 2)
1268                        ctx->num_extra_edges += num_parents - 1;
1269
1270                ctx->commits.nr++;
1271        }
1272        stop_progress(&ctx->progress);
1273}
1274
1275static int write_graph_chunk_base_1(struct hashfile *f,
1276                                    struct commit_graph *g)
1277{
1278        int num = 0;
1279
1280        if (!g)
1281                return 0;
1282
1283        num = write_graph_chunk_base_1(f, g->base_graph);
1284        hashwrite(f, g->oid.hash, the_hash_algo->rawsz);
1285        return num + 1;
1286}
1287
1288static int write_graph_chunk_base(struct hashfile *f,
1289                                  struct write_commit_graph_context *ctx)
1290{
1291        int num = write_graph_chunk_base_1(f, ctx->new_base_graph);
1292
1293        if (num != ctx->num_commit_graphs_after - 1) {
1294                error(_("failed to write correct number of base graph ids"));
1295                return -1;
1296        }
1297
1298        return 0;
1299}
1300
1301static void init_commit_graph_chain(struct write_commit_graph_context *ctx)
1302{
1303        struct commit_graph *g = ctx->r->objects->commit_graph;
1304        uint32_t i;
1305
1306        ctx->new_base_graph = g;
1307        ctx->base_graph_name = xstrdup(g->filename);
1308        ctx->new_num_commits_in_base = g->num_commits + g->num_commits_in_base;
1309
1310        ctx->num_commit_graphs_after = ctx->num_commit_graphs_before + 1;
1311
1312        ALLOC_ARRAY(ctx->commit_graph_filenames_after, ctx->num_commit_graphs_after);
1313        ALLOC_ARRAY(ctx->commit_graph_hash_after, ctx->num_commit_graphs_after);
1314
1315        for (i = 0; i < ctx->num_commit_graphs_before - 1; i++)
1316                ctx->commit_graph_filenames_after[i] = xstrdup(ctx->commit_graph_filenames_before[i]);
1317
1318        if (ctx->num_commit_graphs_before)
1319                ctx->commit_graph_filenames_after[ctx->num_commit_graphs_before - 1] =
1320                        get_split_graph_filename(ctx->obj_dir, oid_to_hex(&g->oid));
1321
1322        i = ctx->num_commit_graphs_before - 1;
1323
1324        while (g) {
1325                ctx->commit_graph_hash_after[i] = xstrdup(oid_to_hex(&g->oid));
1326                i--;
1327                g = g->base_graph;
1328        }
1329}
1330
1331static int write_commit_graph_file(struct write_commit_graph_context *ctx)
1332{
1333        uint32_t i;
1334        int fd;
1335        struct hashfile *f;
1336        struct lock_file lk = LOCK_INIT;
1337        uint32_t chunk_ids[6];
1338        uint64_t chunk_offsets[6];
1339        const unsigned hashsz = the_hash_algo->rawsz;
1340        struct strbuf progress_title = STRBUF_INIT;
1341        int num_chunks = 3;
1342        struct object_id file_hash;
1343
1344        if (ctx->split) {
1345                struct strbuf tmp_file = STRBUF_INIT;
1346
1347                strbuf_addf(&tmp_file,
1348                            "%s/info/commit-graphs/tmp_graph_XXXXXX",
1349                            ctx->obj_dir);
1350                ctx->graph_name = strbuf_detach(&tmp_file, NULL);
1351        } else {
1352                ctx->graph_name = get_commit_graph_filename(ctx->obj_dir);
1353        }
1354
1355        if (safe_create_leading_directories(ctx->graph_name)) {
1356                UNLEAK(ctx->graph_name);
1357                error(_("unable to create leading directories of %s"),
1358                        ctx->graph_name);
1359                return -1;
1360        }
1361
1362        if (ctx->split) {
1363                char *lock_name = get_chain_filename(ctx->obj_dir);
1364
1365                hold_lock_file_for_update(&lk, lock_name, LOCK_DIE_ON_ERROR);
1366
1367                fd = git_mkstemp_mode(ctx->graph_name, 0444);
1368                if (fd < 0) {
1369                        error(_("unable to create '%s'"), ctx->graph_name);
1370                        return -1;
1371                }
1372
1373                f = hashfd(fd, ctx->graph_name);
1374        } else {
1375                hold_lock_file_for_update(&lk, ctx->graph_name, LOCK_DIE_ON_ERROR);
1376                fd = lk.tempfile->fd;
1377                f = hashfd(lk.tempfile->fd, lk.tempfile->filename.buf);
1378        }
1379
1380        chunk_ids[0] = GRAPH_CHUNKID_OIDFANOUT;
1381        chunk_ids[1] = GRAPH_CHUNKID_OIDLOOKUP;
1382        chunk_ids[2] = GRAPH_CHUNKID_DATA;
1383        if (ctx->num_extra_edges) {
1384                chunk_ids[num_chunks] = GRAPH_CHUNKID_EXTRAEDGES;
1385                num_chunks++;
1386        }
1387        if (ctx->num_commit_graphs_after > 1) {
1388                chunk_ids[num_chunks] = GRAPH_CHUNKID_BASE;
1389                num_chunks++;
1390        }
1391
1392        chunk_ids[num_chunks] = 0;
1393
1394        chunk_offsets[0] = 8 + (num_chunks + 1) * GRAPH_CHUNKLOOKUP_WIDTH;
1395        chunk_offsets[1] = chunk_offsets[0] + GRAPH_FANOUT_SIZE;
1396        chunk_offsets[2] = chunk_offsets[1] + hashsz * ctx->commits.nr;
1397        chunk_offsets[3] = chunk_offsets[2] + (hashsz + 16) * ctx->commits.nr;
1398
1399        num_chunks = 3;
1400        if (ctx->num_extra_edges) {
1401                chunk_offsets[num_chunks + 1] = chunk_offsets[num_chunks] +
1402                                                4 * ctx->num_extra_edges;
1403                num_chunks++;
1404        }
1405        if (ctx->num_commit_graphs_after > 1) {
1406                chunk_offsets[num_chunks + 1] = chunk_offsets[num_chunks] +
1407                                                hashsz * (ctx->num_commit_graphs_after - 1);
1408                num_chunks++;
1409        }
1410
1411        hashwrite_be32(f, GRAPH_SIGNATURE);
1412
1413        hashwrite_u8(f, GRAPH_VERSION);
1414        hashwrite_u8(f, oid_version());
1415        hashwrite_u8(f, num_chunks);
1416        hashwrite_u8(f, ctx->num_commit_graphs_after - 1);
1417
1418        for (i = 0; i <= num_chunks; i++) {
1419                uint32_t chunk_write[3];
1420
1421                chunk_write[0] = htonl(chunk_ids[i]);
1422                chunk_write[1] = htonl(chunk_offsets[i] >> 32);
1423                chunk_write[2] = htonl(chunk_offsets[i] & 0xffffffff);
1424                hashwrite(f, chunk_write, 12);
1425        }
1426
1427        if (ctx->report_progress) {
1428                strbuf_addf(&progress_title,
1429                            Q_("Writing out commit graph in %d pass",
1430                               "Writing out commit graph in %d passes",
1431                               num_chunks),
1432                            num_chunks);
1433                ctx->progress = start_delayed_progress(
1434                        progress_title.buf,
1435                        num_chunks * ctx->commits.nr);
1436        }
1437        write_graph_chunk_fanout(f, ctx);
1438        write_graph_chunk_oids(f, hashsz, ctx);
1439        write_graph_chunk_data(f, hashsz, ctx);
1440        if (ctx->num_extra_edges)
1441                write_graph_chunk_extra_edges(f, ctx);
1442        if (ctx->num_commit_graphs_after > 1 &&
1443            write_graph_chunk_base(f, ctx)) {
1444                return -1;
1445        }
1446        stop_progress(&ctx->progress);
1447        strbuf_release(&progress_title);
1448
1449        if (ctx->split && ctx->base_graph_name && ctx->num_commit_graphs_after > 1) {
1450                char *new_base_hash = xstrdup(oid_to_hex(&ctx->new_base_graph->oid));
1451                char *new_base_name = get_split_graph_filename(ctx->obj_dir, new_base_hash);
1452
1453                free(ctx->commit_graph_filenames_after[ctx->num_commit_graphs_after - 2]);
1454                free(ctx->commit_graph_hash_after[ctx->num_commit_graphs_after - 2]);
1455                ctx->commit_graph_filenames_after[ctx->num_commit_graphs_after - 2] = new_base_name;
1456                ctx->commit_graph_hash_after[ctx->num_commit_graphs_after - 2] = new_base_hash;
1457        }
1458
1459        close_commit_graph(ctx->r->objects);
1460        finalize_hashfile(f, file_hash.hash, CSUM_HASH_IN_STREAM | CSUM_FSYNC);
1461
1462        if (ctx->split) {
1463                FILE *chainf = fdopen_lock_file(&lk, "w");
1464                char *final_graph_name;
1465                int result;
1466
1467                close(fd);
1468
1469                if (!chainf) {
1470                        error(_("unable to open commit-graph chain file"));
1471                        return -1;
1472                }
1473
1474                if (ctx->base_graph_name) {
1475                        result = rename(ctx->base_graph_name,
1476                                        ctx->commit_graph_filenames_after[ctx->num_commit_graphs_after - 2]);
1477
1478                        if (result) {
1479                                error(_("failed to rename base commit-graph file"));
1480                                return -1;
1481                        }
1482                } else {
1483                        char *graph_name = get_commit_graph_filename(ctx->obj_dir);
1484                        unlink(graph_name);
1485                }
1486
1487                ctx->commit_graph_hash_after[ctx->num_commit_graphs_after - 1] = xstrdup(oid_to_hex(&file_hash));
1488                final_graph_name = get_split_graph_filename(ctx->obj_dir,
1489                                        ctx->commit_graph_hash_after[ctx->num_commit_graphs_after - 1]);
1490                ctx->commit_graph_filenames_after[ctx->num_commit_graphs_after - 1] = final_graph_name;
1491
1492                result = rename(ctx->graph_name, final_graph_name);
1493
1494                for (i = 0; i < ctx->num_commit_graphs_after; i++)
1495                        fprintf(lk.tempfile->fp, "%s\n", ctx->commit_graph_hash_after[i]);
1496
1497                if (result) {
1498                        error(_("failed to rename temporary commit-graph file"));
1499                        return -1;
1500                }
1501        }
1502
1503        commit_lock_file(&lk);
1504
1505        return 0;
1506}
1507
1508int write_commit_graph(const char *obj_dir,
1509                       struct string_list *pack_indexes,
1510                       struct string_list *commit_hex,
1511                       unsigned int flags)
1512{
1513        struct write_commit_graph_context *ctx;
1514        uint32_t i, count_distinct = 0;
1515        int res = 0;
1516
1517        if (!commit_graph_compatible(the_repository))
1518                return 0;
1519
1520        ctx = xcalloc(1, sizeof(struct write_commit_graph_context));
1521        ctx->r = the_repository;
1522        ctx->obj_dir = obj_dir;
1523        ctx->append = flags & COMMIT_GRAPH_APPEND ? 1 : 0;
1524        ctx->report_progress = flags & COMMIT_GRAPH_PROGRESS ? 1 : 0;
1525        ctx->split = flags & COMMIT_GRAPH_SPLIT ? 1 : 0;
1526
1527        if (ctx->split) {
1528                struct commit_graph *g;
1529                prepare_commit_graph(ctx->r);
1530
1531                g = ctx->r->objects->commit_graph;
1532
1533                while (g) {
1534                        ctx->num_commit_graphs_before++;
1535                        g = g->base_graph;
1536                }
1537
1538                if (ctx->num_commit_graphs_before) {
1539                        ALLOC_ARRAY(ctx->commit_graph_filenames_before, ctx->num_commit_graphs_before);
1540                        i = ctx->num_commit_graphs_before;
1541                        g = ctx->r->objects->commit_graph;
1542
1543                        while (g) {
1544                                ctx->commit_graph_filenames_before[--i] = xstrdup(g->filename);
1545                                g = g->base_graph;
1546                        }
1547                }
1548        }
1549
1550        ctx->approx_nr_objects = approximate_object_count();
1551        ctx->oids.alloc = ctx->approx_nr_objects / 32;
1552
1553        if (ctx->append) {
1554                prepare_commit_graph_one(ctx->r, ctx->obj_dir);
1555                if (ctx->r->objects->commit_graph)
1556                        ctx->oids.alloc += ctx->r->objects->commit_graph->num_commits;
1557        }
1558
1559        if (ctx->oids.alloc < 1024)
1560                ctx->oids.alloc = 1024;
1561        ALLOC_ARRAY(ctx->oids.list, ctx->oids.alloc);
1562
1563        if (ctx->append && ctx->r->objects->commit_graph) {
1564                struct commit_graph *g = ctx->r->objects->commit_graph;
1565                for (i = 0; i < g->num_commits; i++) {
1566                        const unsigned char *hash = g->chunk_oid_lookup + g->hash_len * i;
1567                        hashcpy(ctx->oids.list[ctx->oids.nr++].hash, hash);
1568                }
1569        }
1570
1571        if (pack_indexes) {
1572                if ((res = fill_oids_from_packs(ctx, pack_indexes)))
1573                        goto cleanup;
1574        }
1575
1576        if (commit_hex)
1577                fill_oids_from_commit_hex(ctx, commit_hex);
1578
1579        if (!pack_indexes && !commit_hex)
1580                fill_oids_from_all_packs(ctx);
1581
1582        close_reachable(ctx);
1583
1584        count_distinct = count_distinct_commits(ctx);
1585
1586        if (count_distinct >= GRAPH_EDGE_LAST_MASK) {
1587                error(_("the commit graph format cannot write %d commits"), count_distinct);
1588                res = -1;
1589                goto cleanup;
1590        }
1591
1592        ctx->commits.alloc = count_distinct;
1593        ALLOC_ARRAY(ctx->commits.list, ctx->commits.alloc);
1594
1595        copy_oids_to_commits(ctx);
1596
1597        if (ctx->commits.nr >= GRAPH_EDGE_LAST_MASK) {
1598                error(_("too many commits to write graph"));
1599                res = -1;
1600                goto cleanup;
1601        }
1602
1603        if (!ctx->commits.nr)
1604                goto cleanup;
1605
1606        if (ctx->split)
1607                init_commit_graph_chain(ctx);
1608        else
1609                ctx->num_commit_graphs_after = 1;
1610
1611        compute_generation_numbers(ctx);
1612
1613        res = write_commit_graph_file(ctx);
1614
1615cleanup:
1616        free(ctx->graph_name);
1617        free(ctx->commits.list);
1618        free(ctx->oids.list);
1619
1620        if (ctx->commit_graph_filenames_after) {
1621                for (i = 0; i < ctx->num_commit_graphs_after; i++) {
1622                        free(ctx->commit_graph_filenames_after[i]);
1623                        free(ctx->commit_graph_hash_after[i]);
1624                }
1625
1626                for (i = 0; i < ctx->num_commit_graphs_before; i++)
1627                        free(ctx->commit_graph_filenames_before[i]);
1628
1629                free(ctx->commit_graph_filenames_after);
1630                free(ctx->commit_graph_filenames_before);
1631                free(ctx->commit_graph_hash_after);
1632        }
1633
1634        free(ctx);
1635
1636        return res;
1637}
1638
1639#define VERIFY_COMMIT_GRAPH_ERROR_HASH 2
1640static int verify_commit_graph_error;
1641
1642static void graph_report(const char *fmt, ...)
1643{
1644        va_list ap;
1645
1646        verify_commit_graph_error = 1;
1647        va_start(ap, fmt);
1648        vfprintf(stderr, fmt, ap);
1649        fprintf(stderr, "\n");
1650        va_end(ap);
1651}
1652
1653#define GENERATION_ZERO_EXISTS 1
1654#define GENERATION_NUMBER_EXISTS 2
1655
1656int verify_commit_graph(struct repository *r, struct commit_graph *g)
1657{
1658        uint32_t i, cur_fanout_pos = 0;
1659        struct object_id prev_oid, cur_oid, checksum;
1660        int generation_zero = 0;
1661        struct hashfile *f;
1662        int devnull;
1663        struct progress *progress = NULL;
1664
1665        if (!g) {
1666                graph_report("no commit-graph file loaded");
1667                return 1;
1668        }
1669
1670        verify_commit_graph_error = verify_commit_graph_lite(g);
1671        if (verify_commit_graph_error)
1672                return verify_commit_graph_error;
1673
1674        devnull = open("/dev/null", O_WRONLY);
1675        f = hashfd(devnull, NULL);
1676        hashwrite(f, g->data, g->data_len - g->hash_len);
1677        finalize_hashfile(f, checksum.hash, CSUM_CLOSE);
1678        if (!hasheq(checksum.hash, g->data + g->data_len - g->hash_len)) {
1679                graph_report(_("the commit-graph file has incorrect checksum and is likely corrupt"));
1680                verify_commit_graph_error = VERIFY_COMMIT_GRAPH_ERROR_HASH;
1681        }
1682
1683        for (i = 0; i < g->num_commits; i++) {
1684                struct commit *graph_commit;
1685
1686                hashcpy(cur_oid.hash, g->chunk_oid_lookup + g->hash_len * i);
1687
1688                if (i && oidcmp(&prev_oid, &cur_oid) >= 0)
1689                        graph_report(_("commit-graph has incorrect OID order: %s then %s"),
1690                                     oid_to_hex(&prev_oid),
1691                                     oid_to_hex(&cur_oid));
1692
1693                oidcpy(&prev_oid, &cur_oid);
1694
1695                while (cur_oid.hash[0] > cur_fanout_pos) {
1696                        uint32_t fanout_value = get_be32(g->chunk_oid_fanout + cur_fanout_pos);
1697
1698                        if (i != fanout_value)
1699                                graph_report(_("commit-graph has incorrect fanout value: fanout[%d] = %u != %u"),
1700                                             cur_fanout_pos, fanout_value, i);
1701                        cur_fanout_pos++;
1702                }
1703
1704                graph_commit = lookup_commit(r, &cur_oid);
1705                if (!parse_commit_in_graph_one(r, g, graph_commit))
1706                        graph_report(_("failed to parse commit %s from commit-graph"),
1707                                     oid_to_hex(&cur_oid));
1708        }
1709
1710        while (cur_fanout_pos < 256) {
1711                uint32_t fanout_value = get_be32(g->chunk_oid_fanout + cur_fanout_pos);
1712
1713                if (g->num_commits != fanout_value)
1714                        graph_report(_("commit-graph has incorrect fanout value: fanout[%d] = %u != %u"),
1715                                     cur_fanout_pos, fanout_value, i);
1716
1717                cur_fanout_pos++;
1718        }
1719
1720        if (verify_commit_graph_error & ~VERIFY_COMMIT_GRAPH_ERROR_HASH)
1721                return verify_commit_graph_error;
1722
1723        progress = start_progress(_("Verifying commits in commit graph"),
1724                                  g->num_commits);
1725        for (i = 0; i < g->num_commits; i++) {
1726                struct commit *graph_commit, *odb_commit;
1727                struct commit_list *graph_parents, *odb_parents;
1728                uint32_t max_generation = 0;
1729
1730                display_progress(progress, i + 1);
1731                hashcpy(cur_oid.hash, g->chunk_oid_lookup + g->hash_len * i);
1732
1733                graph_commit = lookup_commit(r, &cur_oid);
1734                odb_commit = (struct commit *)create_object(r, cur_oid.hash, alloc_commit_node(r));
1735                if (parse_commit_internal(odb_commit, 0, 0)) {
1736                        graph_report(_("failed to parse commit %s from object database for commit-graph"),
1737                                     oid_to_hex(&cur_oid));
1738                        continue;
1739                }
1740
1741                if (!oideq(&get_commit_tree_in_graph_one(r, g, graph_commit)->object.oid,
1742                           get_commit_tree_oid(odb_commit)))
1743                        graph_report(_("root tree OID for commit %s in commit-graph is %s != %s"),
1744                                     oid_to_hex(&cur_oid),
1745                                     oid_to_hex(get_commit_tree_oid(graph_commit)),
1746                                     oid_to_hex(get_commit_tree_oid(odb_commit)));
1747
1748                graph_parents = graph_commit->parents;
1749                odb_parents = odb_commit->parents;
1750
1751                while (graph_parents) {
1752                        if (odb_parents == NULL) {
1753                                graph_report(_("commit-graph parent list for commit %s is too long"),
1754                                             oid_to_hex(&cur_oid));
1755                                break;
1756                        }
1757
1758                        if (!oideq(&graph_parents->item->object.oid, &odb_parents->item->object.oid))
1759                                graph_report(_("commit-graph parent for %s is %s != %s"),
1760                                             oid_to_hex(&cur_oid),
1761                                             oid_to_hex(&graph_parents->item->object.oid),
1762                                             oid_to_hex(&odb_parents->item->object.oid));
1763
1764                        if (graph_parents->item->generation > max_generation)
1765                                max_generation = graph_parents->item->generation;
1766
1767                        graph_parents = graph_parents->next;
1768                        odb_parents = odb_parents->next;
1769                }
1770
1771                if (odb_parents != NULL)
1772                        graph_report(_("commit-graph parent list for commit %s terminates early"),
1773                                     oid_to_hex(&cur_oid));
1774
1775                if (!graph_commit->generation) {
1776                        if (generation_zero == GENERATION_NUMBER_EXISTS)
1777                                graph_report(_("commit-graph has generation number zero for commit %s, but non-zero elsewhere"),
1778                                             oid_to_hex(&cur_oid));
1779                        generation_zero = GENERATION_ZERO_EXISTS;
1780                } else if (generation_zero == GENERATION_ZERO_EXISTS)
1781                        graph_report(_("commit-graph has non-zero generation number for commit %s, but zero elsewhere"),
1782                                     oid_to_hex(&cur_oid));
1783
1784                if (generation_zero == GENERATION_ZERO_EXISTS)
1785                        continue;
1786
1787                /*
1788                 * If one of our parents has generation GENERATION_NUMBER_MAX, then
1789                 * our generation is also GENERATION_NUMBER_MAX. Decrement to avoid
1790                 * extra logic in the following condition.
1791                 */
1792                if (max_generation == GENERATION_NUMBER_MAX)
1793                        max_generation--;
1794
1795                if (graph_commit->generation != max_generation + 1)
1796                        graph_report(_("commit-graph generation for commit %s is %u != %u"),
1797                                     oid_to_hex(&cur_oid),
1798                                     graph_commit->generation,
1799                                     max_generation + 1);
1800
1801                if (graph_commit->date != odb_commit->date)
1802                        graph_report(_("commit date for commit %s in commit-graph is %"PRItime" != %"PRItime),
1803                                     oid_to_hex(&cur_oid),
1804                                     graph_commit->date,
1805                                     odb_commit->date);
1806        }
1807        stop_progress(&progress);
1808
1809        return verify_commit_graph_error;
1810}
1811
1812void free_commit_graph(struct commit_graph *g)
1813{
1814        if (!g)
1815                return;
1816        if (g->graph_fd >= 0) {
1817                munmap((void *)g->data, g->data_len);
1818                g->data = NULL;
1819                close(g->graph_fd);
1820        }
1821        free(g->filename);
1822        free(g);
1823}