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