blame.con commit block alloc: add lifecycle APIs for cache_entry structs (a849735)
   1#include "cache.h"
   2#include "refs.h"
   3#include "cache-tree.h"
   4#include "mergesort.h"
   5#include "diff.h"
   6#include "diffcore.h"
   7#include "tag.h"
   8#include "blame.h"
   9
  10void blame_origin_decref(struct blame_origin *o)
  11{
  12        if (o && --o->refcnt <= 0) {
  13                struct blame_origin *p, *l = NULL;
  14                if (o->previous)
  15                        blame_origin_decref(o->previous);
  16                free(o->file.ptr);
  17                /* Should be present exactly once in commit chain */
  18                for (p = o->commit->util; p; l = p, p = p->next) {
  19                        if (p == o) {
  20                                if (l)
  21                                        l->next = p->next;
  22                                else
  23                                        o->commit->util = p->next;
  24                                free(o);
  25                                return;
  26                        }
  27                }
  28                die("internal error in blame_origin_decref");
  29        }
  30}
  31
  32/*
  33 * Given a commit and a path in it, create a new origin structure.
  34 * The callers that add blame to the scoreboard should use
  35 * get_origin() to obtain shared, refcounted copy instead of calling
  36 * this function directly.
  37 */
  38static struct blame_origin *make_origin(struct commit *commit, const char *path)
  39{
  40        struct blame_origin *o;
  41        FLEX_ALLOC_STR(o, path, path);
  42        o->commit = commit;
  43        o->refcnt = 1;
  44        o->next = commit->util;
  45        commit->util = o;
  46        return o;
  47}
  48
  49/*
  50 * Locate an existing origin or create a new one.
  51 * This moves the origin to front position in the commit util list.
  52 */
  53static struct blame_origin *get_origin(struct commit *commit, const char *path)
  54{
  55        struct blame_origin *o, *l;
  56
  57        for (o = commit->util, l = NULL; o; l = o, o = o->next) {
  58                if (!strcmp(o->path, path)) {
  59                        /* bump to front */
  60                        if (l) {
  61                                l->next = o->next;
  62                                o->next = commit->util;
  63                                commit->util = o;
  64                        }
  65                        return blame_origin_incref(o);
  66                }
  67        }
  68        return make_origin(commit, path);
  69}
  70
  71
  72
  73static void verify_working_tree_path(struct commit *work_tree, const char *path)
  74{
  75        struct commit_list *parents;
  76        int pos;
  77
  78        for (parents = work_tree->parents; parents; parents = parents->next) {
  79                const struct object_id *commit_oid = &parents->item->object.oid;
  80                struct object_id blob_oid;
  81                unsigned mode;
  82
  83                if (!get_tree_entry(commit_oid, path, &blob_oid, &mode) &&
  84                    oid_object_info(the_repository, &blob_oid, NULL) == OBJ_BLOB)
  85                        return;
  86        }
  87
  88        pos = cache_name_pos(path, strlen(path));
  89        if (pos >= 0)
  90                ; /* path is in the index */
  91        else if (-1 - pos < active_nr &&
  92                 !strcmp(active_cache[-1 - pos]->name, path))
  93                ; /* path is in the index, unmerged */
  94        else
  95                die("no such path '%s' in HEAD", path);
  96}
  97
  98static struct commit_list **append_parent(struct commit_list **tail, const struct object_id *oid)
  99{
 100        struct commit *parent;
 101
 102        parent = lookup_commit_reference(oid);
 103        if (!parent)
 104                die("no such commit %s", oid_to_hex(oid));
 105        return &commit_list_insert(parent, tail)->next;
 106}
 107
 108static void append_merge_parents(struct commit_list **tail)
 109{
 110        int merge_head;
 111        struct strbuf line = STRBUF_INIT;
 112
 113        merge_head = open(git_path_merge_head(), O_RDONLY);
 114        if (merge_head < 0) {
 115                if (errno == ENOENT)
 116                        return;
 117                die("cannot open '%s' for reading", git_path_merge_head());
 118        }
 119
 120        while (!strbuf_getwholeline_fd(&line, merge_head, '\n')) {
 121                struct object_id oid;
 122                if (line.len < GIT_SHA1_HEXSZ || get_oid_hex(line.buf, &oid))
 123                        die("unknown line in '%s': %s", git_path_merge_head(), line.buf);
 124                tail = append_parent(tail, &oid);
 125        }
 126        close(merge_head);
 127        strbuf_release(&line);
 128}
 129
 130/*
 131 * This isn't as simple as passing sb->buf and sb->len, because we
 132 * want to transfer ownership of the buffer to the commit (so we
 133 * must use detach).
 134 */
 135static void set_commit_buffer_from_strbuf(struct commit *c, struct strbuf *sb)
 136{
 137        size_t len;
 138        void *buf = strbuf_detach(sb, &len);
 139        set_commit_buffer(c, buf, len);
 140}
 141
 142/*
 143 * Prepare a dummy commit that represents the work tree (or staged) item.
 144 * Note that annotating work tree item never works in the reverse.
 145 */
 146static struct commit *fake_working_tree_commit(struct diff_options *opt,
 147                                               const char *path,
 148                                               const char *contents_from)
 149{
 150        struct commit *commit;
 151        struct blame_origin *origin;
 152        struct commit_list **parent_tail, *parent;
 153        struct object_id head_oid;
 154        struct strbuf buf = STRBUF_INIT;
 155        const char *ident;
 156        time_t now;
 157        int len;
 158        struct cache_entry *ce;
 159        unsigned mode;
 160        struct strbuf msg = STRBUF_INIT;
 161
 162        read_cache();
 163        time(&now);
 164        commit = alloc_commit_node();
 165        commit->object.parsed = 1;
 166        commit->date = now;
 167        parent_tail = &commit->parents;
 168
 169        if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
 170                die("no such ref: HEAD");
 171
 172        parent_tail = append_parent(parent_tail, &head_oid);
 173        append_merge_parents(parent_tail);
 174        verify_working_tree_path(commit, path);
 175
 176        origin = make_origin(commit, path);
 177
 178        ident = fmt_ident("Not Committed Yet", "not.committed.yet", NULL, 0);
 179        strbuf_addstr(&msg, "tree 0000000000000000000000000000000000000000\n");
 180        for (parent = commit->parents; parent; parent = parent->next)
 181                strbuf_addf(&msg, "parent %s\n",
 182                            oid_to_hex(&parent->item->object.oid));
 183        strbuf_addf(&msg,
 184                    "author %s\n"
 185                    "committer %s\n\n"
 186                    "Version of %s from %s\n",
 187                    ident, ident, path,
 188                    (!contents_from ? path :
 189                     (!strcmp(contents_from, "-") ? "standard input" : contents_from)));
 190        set_commit_buffer_from_strbuf(commit, &msg);
 191
 192        if (!contents_from || strcmp("-", contents_from)) {
 193                struct stat st;
 194                const char *read_from;
 195                char *buf_ptr;
 196                unsigned long buf_len;
 197
 198                if (contents_from) {
 199                        if (stat(contents_from, &st) < 0)
 200                                die_errno("Cannot stat '%s'", contents_from);
 201                        read_from = contents_from;
 202                }
 203                else {
 204                        if (lstat(path, &st) < 0)
 205                                die_errno("Cannot lstat '%s'", path);
 206                        read_from = path;
 207                }
 208                mode = canon_mode(st.st_mode);
 209
 210                switch (st.st_mode & S_IFMT) {
 211                case S_IFREG:
 212                        if (opt->flags.allow_textconv &&
 213                            textconv_object(read_from, mode, &null_oid, 0, &buf_ptr, &buf_len))
 214                                strbuf_attach(&buf, buf_ptr, buf_len, buf_len + 1);
 215                        else if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
 216                                die_errno("cannot open or read '%s'", read_from);
 217                        break;
 218                case S_IFLNK:
 219                        if (strbuf_readlink(&buf, read_from, st.st_size) < 0)
 220                                die_errno("cannot readlink '%s'", read_from);
 221                        break;
 222                default:
 223                        die("unsupported file type %s", read_from);
 224                }
 225        }
 226        else {
 227                /* Reading from stdin */
 228                mode = 0;
 229                if (strbuf_read(&buf, 0, 0) < 0)
 230                        die_errno("failed to read from stdin");
 231        }
 232        convert_to_git(&the_index, path, buf.buf, buf.len, &buf, 0);
 233        origin->file.ptr = buf.buf;
 234        origin->file.size = buf.len;
 235        pretend_object_file(buf.buf, buf.len, OBJ_BLOB, &origin->blob_oid);
 236
 237        /*
 238         * Read the current index, replace the path entry with
 239         * origin->blob_sha1 without mucking with its mode or type
 240         * bits; we are not going to write this index out -- we just
 241         * want to run "diff-index --cached".
 242         */
 243        discard_cache();
 244        read_cache();
 245
 246        len = strlen(path);
 247        if (!mode) {
 248                int pos = cache_name_pos(path, len);
 249                if (0 <= pos)
 250                        mode = active_cache[pos]->ce_mode;
 251                else
 252                        /* Let's not bother reading from HEAD tree */
 253                        mode = S_IFREG | 0644;
 254        }
 255        ce = make_empty_cache_entry(&the_index, len);
 256        oidcpy(&ce->oid, &origin->blob_oid);
 257        memcpy(ce->name, path, len);
 258        ce->ce_flags = create_ce_flags(0);
 259        ce->ce_namelen = len;
 260        ce->ce_mode = create_ce_mode(mode);
 261        add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
 262
 263        cache_tree_invalidate_path(&the_index, path);
 264
 265        return commit;
 266}
 267
 268
 269
 270static int diff_hunks(mmfile_t *file_a, mmfile_t *file_b,
 271                      xdl_emit_hunk_consume_func_t hunk_func, void *cb_data, int xdl_opts)
 272{
 273        xpparam_t xpp = {0};
 274        xdemitconf_t xecfg = {0};
 275        xdemitcb_t ecb = {NULL};
 276
 277        xpp.flags = xdl_opts;
 278        xecfg.hunk_func = hunk_func;
 279        ecb.priv = cb_data;
 280        return xdi_diff(file_a, file_b, &xpp, &xecfg, &ecb);
 281}
 282
 283/*
 284 * Given an origin, prepare mmfile_t structure to be used by the
 285 * diff machinery
 286 */
 287static void fill_origin_blob(struct diff_options *opt,
 288                             struct blame_origin *o, mmfile_t *file, int *num_read_blob)
 289{
 290        if (!o->file.ptr) {
 291                enum object_type type;
 292                unsigned long file_size;
 293
 294                (*num_read_blob)++;
 295                if (opt->flags.allow_textconv &&
 296                    textconv_object(o->path, o->mode, &o->blob_oid, 1, &file->ptr, &file_size))
 297                        ;
 298                else
 299                        file->ptr = read_object_file(&o->blob_oid, &type,
 300                                                     &file_size);
 301                file->size = file_size;
 302
 303                if (!file->ptr)
 304                        die("Cannot read blob %s for path %s",
 305                            oid_to_hex(&o->blob_oid),
 306                            o->path);
 307                o->file = *file;
 308        }
 309        else
 310                *file = o->file;
 311}
 312
 313static void drop_origin_blob(struct blame_origin *o)
 314{
 315        if (o->file.ptr) {
 316                FREE_AND_NULL(o->file.ptr);
 317        }
 318}
 319
 320/*
 321 * Any merge of blames happens on lists of blames that arrived via
 322 * different parents in a single suspect.  In this case, we want to
 323 * sort according to the suspect line numbers as opposed to the final
 324 * image line numbers.  The function body is somewhat longish because
 325 * it avoids unnecessary writes.
 326 */
 327
 328static struct blame_entry *blame_merge(struct blame_entry *list1,
 329                                       struct blame_entry *list2)
 330{
 331        struct blame_entry *p1 = list1, *p2 = list2,
 332                **tail = &list1;
 333
 334        if (!p1)
 335                return p2;
 336        if (!p2)
 337                return p1;
 338
 339        if (p1->s_lno <= p2->s_lno) {
 340                do {
 341                        tail = &p1->next;
 342                        if ((p1 = *tail) == NULL) {
 343                                *tail = p2;
 344                                return list1;
 345                        }
 346                } while (p1->s_lno <= p2->s_lno);
 347        }
 348        for (;;) {
 349                *tail = p2;
 350                do {
 351                        tail = &p2->next;
 352                        if ((p2 = *tail) == NULL)  {
 353                                *tail = p1;
 354                                return list1;
 355                        }
 356                } while (p1->s_lno > p2->s_lno);
 357                *tail = p1;
 358                do {
 359                        tail = &p1->next;
 360                        if ((p1 = *tail) == NULL) {
 361                                *tail = p2;
 362                                return list1;
 363                        }
 364                } while (p1->s_lno <= p2->s_lno);
 365        }
 366}
 367
 368static void *get_next_blame(const void *p)
 369{
 370        return ((struct blame_entry *)p)->next;
 371}
 372
 373static void set_next_blame(void *p1, void *p2)
 374{
 375        ((struct blame_entry *)p1)->next = p2;
 376}
 377
 378/*
 379 * Final image line numbers are all different, so we don't need a
 380 * three-way comparison here.
 381 */
 382
 383static int compare_blame_final(const void *p1, const void *p2)
 384{
 385        return ((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno
 386                ? 1 : -1;
 387}
 388
 389static int compare_blame_suspect(const void *p1, const void *p2)
 390{
 391        const struct blame_entry *s1 = p1, *s2 = p2;
 392        /*
 393         * to allow for collating suspects, we sort according to the
 394         * respective pointer value as the primary sorting criterion.
 395         * The actual relation is pretty unimportant as long as it
 396         * establishes a total order.  Comparing as integers gives us
 397         * that.
 398         */
 399        if (s1->suspect != s2->suspect)
 400                return (intptr_t)s1->suspect > (intptr_t)s2->suspect ? 1 : -1;
 401        if (s1->s_lno == s2->s_lno)
 402                return 0;
 403        return s1->s_lno > s2->s_lno ? 1 : -1;
 404}
 405
 406void blame_sort_final(struct blame_scoreboard *sb)
 407{
 408        sb->ent = llist_mergesort(sb->ent, get_next_blame, set_next_blame,
 409                                  compare_blame_final);
 410}
 411
 412static int compare_commits_by_reverse_commit_date(const void *a,
 413                                                  const void *b,
 414                                                  void *c)
 415{
 416        return -compare_commits_by_commit_date(a, b, c);
 417}
 418
 419/*
 420 * For debugging -- origin is refcounted, and this asserts that
 421 * we do not underflow.
 422 */
 423static void sanity_check_refcnt(struct blame_scoreboard *sb)
 424{
 425        int baa = 0;
 426        struct blame_entry *ent;
 427
 428        for (ent = sb->ent; ent; ent = ent->next) {
 429                /* Nobody should have zero or negative refcnt */
 430                if (ent->suspect->refcnt <= 0) {
 431                        fprintf(stderr, "%s in %s has negative refcnt %d\n",
 432                                ent->suspect->path,
 433                                oid_to_hex(&ent->suspect->commit->object.oid),
 434                                ent->suspect->refcnt);
 435                        baa = 1;
 436                }
 437        }
 438        if (baa)
 439                sb->on_sanity_fail(sb, baa);
 440}
 441
 442/*
 443 * If two blame entries that are next to each other came from
 444 * contiguous lines in the same origin (i.e. <commit, path> pair),
 445 * merge them together.
 446 */
 447void blame_coalesce(struct blame_scoreboard *sb)
 448{
 449        struct blame_entry *ent, *next;
 450
 451        for (ent = sb->ent; ent && (next = ent->next); ent = next) {
 452                if (ent->suspect == next->suspect &&
 453                    ent->s_lno + ent->num_lines == next->s_lno) {
 454                        ent->num_lines += next->num_lines;
 455                        ent->next = next->next;
 456                        blame_origin_decref(next->suspect);
 457                        free(next);
 458                        ent->score = 0;
 459                        next = ent; /* again */
 460                }
 461        }
 462
 463        if (sb->debug) /* sanity */
 464                sanity_check_refcnt(sb);
 465}
 466
 467/*
 468 * Merge the given sorted list of blames into a preexisting origin.
 469 * If there were no previous blames to that commit, it is entered into
 470 * the commit priority queue of the score board.
 471 */
 472
 473static void queue_blames(struct blame_scoreboard *sb, struct blame_origin *porigin,
 474                         struct blame_entry *sorted)
 475{
 476        if (porigin->suspects)
 477                porigin->suspects = blame_merge(porigin->suspects, sorted);
 478        else {
 479                struct blame_origin *o;
 480                for (o = porigin->commit->util; o; o = o->next) {
 481                        if (o->suspects) {
 482                                porigin->suspects = sorted;
 483                                return;
 484                        }
 485                }
 486                porigin->suspects = sorted;
 487                prio_queue_put(&sb->commits, porigin->commit);
 488        }
 489}
 490
 491/*
 492 * Fill the blob_sha1 field of an origin if it hasn't, so that later
 493 * call to fill_origin_blob() can use it to locate the data.  blob_sha1
 494 * for an origin is also used to pass the blame for the entire file to
 495 * the parent to detect the case where a child's blob is identical to
 496 * that of its parent's.
 497 *
 498 * This also fills origin->mode for corresponding tree path.
 499 */
 500static int fill_blob_sha1_and_mode(struct blame_origin *origin)
 501{
 502        if (!is_null_oid(&origin->blob_oid))
 503                return 0;
 504        if (get_tree_entry(&origin->commit->object.oid, origin->path, &origin->blob_oid, &origin->mode))
 505                goto error_out;
 506        if (oid_object_info(the_repository, &origin->blob_oid, NULL) != OBJ_BLOB)
 507                goto error_out;
 508        return 0;
 509 error_out:
 510        oidclr(&origin->blob_oid);
 511        origin->mode = S_IFINVALID;
 512        return -1;
 513}
 514
 515/*
 516 * We have an origin -- check if the same path exists in the
 517 * parent and return an origin structure to represent it.
 518 */
 519static struct blame_origin *find_origin(struct commit *parent,
 520                                  struct blame_origin *origin)
 521{
 522        struct blame_origin *porigin;
 523        struct diff_options diff_opts;
 524        const char *paths[2];
 525
 526        /* First check any existing origins */
 527        for (porigin = parent->util; porigin; porigin = porigin->next)
 528                if (!strcmp(porigin->path, origin->path)) {
 529                        /*
 530                         * The same path between origin and its parent
 531                         * without renaming -- the most common case.
 532                         */
 533                        return blame_origin_incref (porigin);
 534                }
 535
 536        /* See if the origin->path is different between parent
 537         * and origin first.  Most of the time they are the
 538         * same and diff-tree is fairly efficient about this.
 539         */
 540        diff_setup(&diff_opts);
 541        diff_opts.flags.recursive = 1;
 542        diff_opts.detect_rename = 0;
 543        diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
 544        paths[0] = origin->path;
 545        paths[1] = NULL;
 546
 547        parse_pathspec(&diff_opts.pathspec,
 548                       PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
 549                       PATHSPEC_LITERAL_PATH, "", paths);
 550        diff_setup_done(&diff_opts);
 551
 552        if (is_null_oid(&origin->commit->object.oid))
 553                do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
 554        else
 555                diff_tree_oid(get_commit_tree_oid(parent),
 556                              get_commit_tree_oid(origin->commit),
 557                              "", &diff_opts);
 558        diffcore_std(&diff_opts);
 559
 560        if (!diff_queued_diff.nr) {
 561                /* The path is the same as parent */
 562                porigin = get_origin(parent, origin->path);
 563                oidcpy(&porigin->blob_oid, &origin->blob_oid);
 564                porigin->mode = origin->mode;
 565        } else {
 566                /*
 567                 * Since origin->path is a pathspec, if the parent
 568                 * commit had it as a directory, we will see a whole
 569                 * bunch of deletion of files in the directory that we
 570                 * do not care about.
 571                 */
 572                int i;
 573                struct diff_filepair *p = NULL;
 574                for (i = 0; i < diff_queued_diff.nr; i++) {
 575                        const char *name;
 576                        p = diff_queued_diff.queue[i];
 577                        name = p->one->path ? p->one->path : p->two->path;
 578                        if (!strcmp(name, origin->path))
 579                                break;
 580                }
 581                if (!p)
 582                        die("internal error in blame::find_origin");
 583                switch (p->status) {
 584                default:
 585                        die("internal error in blame::find_origin (%c)",
 586                            p->status);
 587                case 'M':
 588                        porigin = get_origin(parent, origin->path);
 589                        oidcpy(&porigin->blob_oid, &p->one->oid);
 590                        porigin->mode = p->one->mode;
 591                        break;
 592                case 'A':
 593                case 'T':
 594                        /* Did not exist in parent, or type changed */
 595                        break;
 596                }
 597        }
 598        diff_flush(&diff_opts);
 599        clear_pathspec(&diff_opts.pathspec);
 600        return porigin;
 601}
 602
 603/*
 604 * We have an origin -- find the path that corresponds to it in its
 605 * parent and return an origin structure to represent it.
 606 */
 607static struct blame_origin *find_rename(struct commit *parent,
 608                                  struct blame_origin *origin)
 609{
 610        struct blame_origin *porigin = NULL;
 611        struct diff_options diff_opts;
 612        int i;
 613
 614        diff_setup(&diff_opts);
 615        diff_opts.flags.recursive = 1;
 616        diff_opts.detect_rename = DIFF_DETECT_RENAME;
 617        diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
 618        diff_opts.single_follow = origin->path;
 619        diff_setup_done(&diff_opts);
 620
 621        if (is_null_oid(&origin->commit->object.oid))
 622                do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
 623        else
 624                diff_tree_oid(get_commit_tree_oid(parent),
 625                              get_commit_tree_oid(origin->commit),
 626                              "", &diff_opts);
 627        diffcore_std(&diff_opts);
 628
 629        for (i = 0; i < diff_queued_diff.nr; i++) {
 630                struct diff_filepair *p = diff_queued_diff.queue[i];
 631                if ((p->status == 'R' || p->status == 'C') &&
 632                    !strcmp(p->two->path, origin->path)) {
 633                        porigin = get_origin(parent, p->one->path);
 634                        oidcpy(&porigin->blob_oid, &p->one->oid);
 635                        porigin->mode = p->one->mode;
 636                        break;
 637                }
 638        }
 639        diff_flush(&diff_opts);
 640        clear_pathspec(&diff_opts.pathspec);
 641        return porigin;
 642}
 643
 644/*
 645 * Append a new blame entry to a given output queue.
 646 */
 647static void add_blame_entry(struct blame_entry ***queue,
 648                            const struct blame_entry *src)
 649{
 650        struct blame_entry *e = xmalloc(sizeof(*e));
 651        memcpy(e, src, sizeof(*e));
 652        blame_origin_incref(e->suspect);
 653
 654        e->next = **queue;
 655        **queue = e;
 656        *queue = &e->next;
 657}
 658
 659/*
 660 * src typically is on-stack; we want to copy the information in it to
 661 * a malloced blame_entry that gets added to the given queue.  The
 662 * origin of dst loses a refcnt.
 663 */
 664static void dup_entry(struct blame_entry ***queue,
 665                      struct blame_entry *dst, struct blame_entry *src)
 666{
 667        blame_origin_incref(src->suspect);
 668        blame_origin_decref(dst->suspect);
 669        memcpy(dst, src, sizeof(*src));
 670        dst->next = **queue;
 671        **queue = dst;
 672        *queue = &dst->next;
 673}
 674
 675const char *blame_nth_line(struct blame_scoreboard *sb, long lno)
 676{
 677        return sb->final_buf + sb->lineno[lno];
 678}
 679
 680/*
 681 * It is known that lines between tlno to same came from parent, and e
 682 * has an overlap with that range.  it also is known that parent's
 683 * line plno corresponds to e's line tlno.
 684 *
 685 *                <---- e ----->
 686 *                   <------>
 687 *                   <------------>
 688 *             <------------>
 689 *             <------------------>
 690 *
 691 * Split e into potentially three parts; before this chunk, the chunk
 692 * to be blamed for the parent, and after that portion.
 693 */
 694static void split_overlap(struct blame_entry *split,
 695                          struct blame_entry *e,
 696                          int tlno, int plno, int same,
 697                          struct blame_origin *parent)
 698{
 699        int chunk_end_lno;
 700        memset(split, 0, sizeof(struct blame_entry [3]));
 701
 702        if (e->s_lno < tlno) {
 703                /* there is a pre-chunk part not blamed on parent */
 704                split[0].suspect = blame_origin_incref(e->suspect);
 705                split[0].lno = e->lno;
 706                split[0].s_lno = e->s_lno;
 707                split[0].num_lines = tlno - e->s_lno;
 708                split[1].lno = e->lno + tlno - e->s_lno;
 709                split[1].s_lno = plno;
 710        }
 711        else {
 712                split[1].lno = e->lno;
 713                split[1].s_lno = plno + (e->s_lno - tlno);
 714        }
 715
 716        if (same < e->s_lno + e->num_lines) {
 717                /* there is a post-chunk part not blamed on parent */
 718                split[2].suspect = blame_origin_incref(e->suspect);
 719                split[2].lno = e->lno + (same - e->s_lno);
 720                split[2].s_lno = e->s_lno + (same - e->s_lno);
 721                split[2].num_lines = e->s_lno + e->num_lines - same;
 722                chunk_end_lno = split[2].lno;
 723        }
 724        else
 725                chunk_end_lno = e->lno + e->num_lines;
 726        split[1].num_lines = chunk_end_lno - split[1].lno;
 727
 728        /*
 729         * if it turns out there is nothing to blame the parent for,
 730         * forget about the splitting.  !split[1].suspect signals this.
 731         */
 732        if (split[1].num_lines < 1)
 733                return;
 734        split[1].suspect = blame_origin_incref(parent);
 735}
 736
 737/*
 738 * split_overlap() divided an existing blame e into up to three parts
 739 * in split.  Any assigned blame is moved to queue to
 740 * reflect the split.
 741 */
 742static void split_blame(struct blame_entry ***blamed,
 743                        struct blame_entry ***unblamed,
 744                        struct blame_entry *split,
 745                        struct blame_entry *e)
 746{
 747        if (split[0].suspect && split[2].suspect) {
 748                /* The first part (reuse storage for the existing entry e) */
 749                dup_entry(unblamed, e, &split[0]);
 750
 751                /* The last part -- me */
 752                add_blame_entry(unblamed, &split[2]);
 753
 754                /* ... and the middle part -- parent */
 755                add_blame_entry(blamed, &split[1]);
 756        }
 757        else if (!split[0].suspect && !split[2].suspect)
 758                /*
 759                 * The parent covers the entire area; reuse storage for
 760                 * e and replace it with the parent.
 761                 */
 762                dup_entry(blamed, e, &split[1]);
 763        else if (split[0].suspect) {
 764                /* me and then parent */
 765                dup_entry(unblamed, e, &split[0]);
 766                add_blame_entry(blamed, &split[1]);
 767        }
 768        else {
 769                /* parent and then me */
 770                dup_entry(blamed, e, &split[1]);
 771                add_blame_entry(unblamed, &split[2]);
 772        }
 773}
 774
 775/*
 776 * After splitting the blame, the origins used by the
 777 * on-stack blame_entry should lose one refcnt each.
 778 */
 779static void decref_split(struct blame_entry *split)
 780{
 781        int i;
 782
 783        for (i = 0; i < 3; i++)
 784                blame_origin_decref(split[i].suspect);
 785}
 786
 787/*
 788 * reverse_blame reverses the list given in head, appending tail.
 789 * That allows us to build lists in reverse order, then reverse them
 790 * afterwards.  This can be faster than building the list in proper
 791 * order right away.  The reason is that building in proper order
 792 * requires writing a link in the _previous_ element, while building
 793 * in reverse order just requires placing the list head into the
 794 * _current_ element.
 795 */
 796
 797static struct blame_entry *reverse_blame(struct blame_entry *head,
 798                                         struct blame_entry *tail)
 799{
 800        while (head) {
 801                struct blame_entry *next = head->next;
 802                head->next = tail;
 803                tail = head;
 804                head = next;
 805        }
 806        return tail;
 807}
 808
 809/*
 810 * Process one hunk from the patch between the current suspect for
 811 * blame_entry e and its parent.  This first blames any unfinished
 812 * entries before the chunk (which is where target and parent start
 813 * differing) on the parent, and then splits blame entries at the
 814 * start and at the end of the difference region.  Since use of -M and
 815 * -C options may lead to overlapping/duplicate source line number
 816 * ranges, all we can rely on from sorting/merging is the order of the
 817 * first suspect line number.
 818 */
 819static void blame_chunk(struct blame_entry ***dstq, struct blame_entry ***srcq,
 820                        int tlno, int offset, int same,
 821                        struct blame_origin *parent)
 822{
 823        struct blame_entry *e = **srcq;
 824        struct blame_entry *samep = NULL, *diffp = NULL;
 825
 826        while (e && e->s_lno < tlno) {
 827                struct blame_entry *next = e->next;
 828                /*
 829                 * current record starts before differing portion.  If
 830                 * it reaches into it, we need to split it up and
 831                 * examine the second part separately.
 832                 */
 833                if (e->s_lno + e->num_lines > tlno) {
 834                        /* Move second half to a new record */
 835                        int len = tlno - e->s_lno;
 836                        struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry));
 837                        n->suspect = e->suspect;
 838                        n->lno = e->lno + len;
 839                        n->s_lno = e->s_lno + len;
 840                        n->num_lines = e->num_lines - len;
 841                        e->num_lines = len;
 842                        e->score = 0;
 843                        /* Push new record to diffp */
 844                        n->next = diffp;
 845                        diffp = n;
 846                } else
 847                        blame_origin_decref(e->suspect);
 848                /* Pass blame for everything before the differing
 849                 * chunk to the parent */
 850                e->suspect = blame_origin_incref(parent);
 851                e->s_lno += offset;
 852                e->next = samep;
 853                samep = e;
 854                e = next;
 855        }
 856        /*
 857         * As we don't know how much of a common stretch after this
 858         * diff will occur, the currently blamed parts are all that we
 859         * can assign to the parent for now.
 860         */
 861
 862        if (samep) {
 863                **dstq = reverse_blame(samep, **dstq);
 864                *dstq = &samep->next;
 865        }
 866        /*
 867         * Prepend the split off portions: everything after e starts
 868         * after the blameable portion.
 869         */
 870        e = reverse_blame(diffp, e);
 871
 872        /*
 873         * Now retain records on the target while parts are different
 874         * from the parent.
 875         */
 876        samep = NULL;
 877        diffp = NULL;
 878        while (e && e->s_lno < same) {
 879                struct blame_entry *next = e->next;
 880
 881                /*
 882                 * If current record extends into sameness, need to split.
 883                 */
 884                if (e->s_lno + e->num_lines > same) {
 885                        /*
 886                         * Move second half to a new record to be
 887                         * processed by later chunks
 888                         */
 889                        int len = same - e->s_lno;
 890                        struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry));
 891                        n->suspect = blame_origin_incref(e->suspect);
 892                        n->lno = e->lno + len;
 893                        n->s_lno = e->s_lno + len;
 894                        n->num_lines = e->num_lines - len;
 895                        e->num_lines = len;
 896                        e->score = 0;
 897                        /* Push new record to samep */
 898                        n->next = samep;
 899                        samep = n;
 900                }
 901                e->next = diffp;
 902                diffp = e;
 903                e = next;
 904        }
 905        **srcq = reverse_blame(diffp, reverse_blame(samep, e));
 906        /* Move across elements that are in the unblamable portion */
 907        if (diffp)
 908                *srcq = &diffp->next;
 909}
 910
 911struct blame_chunk_cb_data {
 912        struct blame_origin *parent;
 913        long offset;
 914        struct blame_entry **dstq;
 915        struct blame_entry **srcq;
 916};
 917
 918/* diff chunks are from parent to target */
 919static int blame_chunk_cb(long start_a, long count_a,
 920                          long start_b, long count_b, void *data)
 921{
 922        struct blame_chunk_cb_data *d = data;
 923        if (start_a - start_b != d->offset)
 924                die("internal error in blame::blame_chunk_cb");
 925        blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b,
 926                    start_b + count_b, d->parent);
 927        d->offset = start_a + count_a - (start_b + count_b);
 928        return 0;
 929}
 930
 931/*
 932 * We are looking at the origin 'target' and aiming to pass blame
 933 * for the lines it is suspected to its parent.  Run diff to find
 934 * which lines came from parent and pass blame for them.
 935 */
 936static void pass_blame_to_parent(struct blame_scoreboard *sb,
 937                                 struct blame_origin *target,
 938                                 struct blame_origin *parent)
 939{
 940        mmfile_t file_p, file_o;
 941        struct blame_chunk_cb_data d;
 942        struct blame_entry *newdest = NULL;
 943
 944        if (!target->suspects)
 945                return; /* nothing remains for this target */
 946
 947        d.parent = parent;
 948        d.offset = 0;
 949        d.dstq = &newdest; d.srcq = &target->suspects;
 950
 951        fill_origin_blob(&sb->revs->diffopt, parent, &file_p, &sb->num_read_blob);
 952        fill_origin_blob(&sb->revs->diffopt, target, &file_o, &sb->num_read_blob);
 953        sb->num_get_patch++;
 954
 955        if (diff_hunks(&file_p, &file_o, blame_chunk_cb, &d, sb->xdl_opts))
 956                die("unable to generate diff (%s -> %s)",
 957                    oid_to_hex(&parent->commit->object.oid),
 958                    oid_to_hex(&target->commit->object.oid));
 959        /* The rest are the same as the parent */
 960        blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, parent);
 961        *d.dstq = NULL;
 962        queue_blames(sb, parent, newdest);
 963
 964        return;
 965}
 966
 967/*
 968 * The lines in blame_entry after splitting blames many times can become
 969 * very small and trivial, and at some point it becomes pointless to
 970 * blame the parents.  E.g. "\t\t}\n\t}\n\n" appears everywhere in any
 971 * ordinary C program, and it is not worth to say it was copied from
 972 * totally unrelated file in the parent.
 973 *
 974 * Compute how trivial the lines in the blame_entry are.
 975 */
 976unsigned blame_entry_score(struct blame_scoreboard *sb, struct blame_entry *e)
 977{
 978        unsigned score;
 979        const char *cp, *ep;
 980
 981        if (e->score)
 982                return e->score;
 983
 984        score = 1;
 985        cp = blame_nth_line(sb, e->lno);
 986        ep = blame_nth_line(sb, e->lno + e->num_lines);
 987        while (cp < ep) {
 988                unsigned ch = *((unsigned char *)cp);
 989                if (isalnum(ch))
 990                        score++;
 991                cp++;
 992        }
 993        e->score = score;
 994        return score;
 995}
 996
 997/*
 998 * best_so_far[] and potential[] are both a split of an existing blame_entry
 999 * that passes blame to the parent.  Maintain best_so_far the best split so
1000 * far, by comparing potential and best_so_far and copying potential into
1001 * bst_so_far as needed.
1002 */
1003static void copy_split_if_better(struct blame_scoreboard *sb,
1004                                 struct blame_entry *best_so_far,
1005                                 struct blame_entry *potential)
1006{
1007        int i;
1008
1009        if (!potential[1].suspect)
1010                return;
1011        if (best_so_far[1].suspect) {
1012                if (blame_entry_score(sb, &potential[1]) <
1013                    blame_entry_score(sb, &best_so_far[1]))
1014                        return;
1015        }
1016
1017        for (i = 0; i < 3; i++)
1018                blame_origin_incref(potential[i].suspect);
1019        decref_split(best_so_far);
1020        memcpy(best_so_far, potential, sizeof(struct blame_entry[3]));
1021}
1022
1023/*
1024 * We are looking at a part of the final image represented by
1025 * ent (tlno and same are offset by ent->s_lno).
1026 * tlno is where we are looking at in the final image.
1027 * up to (but not including) same match preimage.
1028 * plno is where we are looking at in the preimage.
1029 *
1030 * <-------------- final image ---------------------->
1031 *       <------ent------>
1032 *         ^tlno ^same
1033 *    <---------preimage----->
1034 *         ^plno
1035 *
1036 * All line numbers are 0-based.
1037 */
1038static void handle_split(struct blame_scoreboard *sb,
1039                         struct blame_entry *ent,
1040                         int tlno, int plno, int same,
1041                         struct blame_origin *parent,
1042                         struct blame_entry *split)
1043{
1044        if (ent->num_lines <= tlno)
1045                return;
1046        if (tlno < same) {
1047                struct blame_entry potential[3];
1048                tlno += ent->s_lno;
1049                same += ent->s_lno;
1050                split_overlap(potential, ent, tlno, plno, same, parent);
1051                copy_split_if_better(sb, split, potential);
1052                decref_split(potential);
1053        }
1054}
1055
1056struct handle_split_cb_data {
1057        struct blame_scoreboard *sb;
1058        struct blame_entry *ent;
1059        struct blame_origin *parent;
1060        struct blame_entry *split;
1061        long plno;
1062        long tlno;
1063};
1064
1065static int handle_split_cb(long start_a, long count_a,
1066                           long start_b, long count_b, void *data)
1067{
1068        struct handle_split_cb_data *d = data;
1069        handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,
1070                     d->split);
1071        d->plno = start_a + count_a;
1072        d->tlno = start_b + count_b;
1073        return 0;
1074}
1075
1076/*
1077 * Find the lines from parent that are the same as ent so that
1078 * we can pass blames to it.  file_p has the blob contents for
1079 * the parent.
1080 */
1081static void find_copy_in_blob(struct blame_scoreboard *sb,
1082                              struct blame_entry *ent,
1083                              struct blame_origin *parent,
1084                              struct blame_entry *split,
1085                              mmfile_t *file_p)
1086{
1087        const char *cp;
1088        mmfile_t file_o;
1089        struct handle_split_cb_data d;
1090
1091        memset(&d, 0, sizeof(d));
1092        d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;
1093        /*
1094         * Prepare mmfile that contains only the lines in ent.
1095         */
1096        cp = blame_nth_line(sb, ent->lno);
1097        file_o.ptr = (char *) cp;
1098        file_o.size = blame_nth_line(sb, ent->lno + ent->num_lines) - cp;
1099
1100        /*
1101         * file_o is a part of final image we are annotating.
1102         * file_p partially may match that image.
1103         */
1104        memset(split, 0, sizeof(struct blame_entry [3]));
1105        if (diff_hunks(file_p, &file_o, handle_split_cb, &d, sb->xdl_opts))
1106                die("unable to generate diff (%s)",
1107                    oid_to_hex(&parent->commit->object.oid));
1108        /* remainder, if any, all match the preimage */
1109        handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);
1110}
1111
1112/* Move all blame entries from list *source that have a score smaller
1113 * than score_min to the front of list *small.
1114 * Returns a pointer to the link pointing to the old head of the small list.
1115 */
1116
1117static struct blame_entry **filter_small(struct blame_scoreboard *sb,
1118                                         struct blame_entry **small,
1119                                         struct blame_entry **source,
1120                                         unsigned score_min)
1121{
1122        struct blame_entry *p = *source;
1123        struct blame_entry *oldsmall = *small;
1124        while (p) {
1125                if (blame_entry_score(sb, p) <= score_min) {
1126                        *small = p;
1127                        small = &p->next;
1128                        p = *small;
1129                } else {
1130                        *source = p;
1131                        source = &p->next;
1132                        p = *source;
1133                }
1134        }
1135        *small = oldsmall;
1136        *source = NULL;
1137        return small;
1138}
1139
1140/*
1141 * See if lines currently target is suspected for can be attributed to
1142 * parent.
1143 */
1144static void find_move_in_parent(struct blame_scoreboard *sb,
1145                                struct blame_entry ***blamed,
1146                                struct blame_entry **toosmall,
1147                                struct blame_origin *target,
1148                                struct blame_origin *parent)
1149{
1150        struct blame_entry *e, split[3];
1151        struct blame_entry *unblamed = target->suspects;
1152        struct blame_entry *leftover = NULL;
1153        mmfile_t file_p;
1154
1155        if (!unblamed)
1156                return; /* nothing remains for this target */
1157
1158        fill_origin_blob(&sb->revs->diffopt, parent, &file_p, &sb->num_read_blob);
1159        if (!file_p.ptr)
1160                return;
1161
1162        /* At each iteration, unblamed has a NULL-terminated list of
1163         * entries that have not yet been tested for blame.  leftover
1164         * contains the reversed list of entries that have been tested
1165         * without being assignable to the parent.
1166         */
1167        do {
1168                struct blame_entry **unblamedtail = &unblamed;
1169                struct blame_entry *next;
1170                for (e = unblamed; e; e = next) {
1171                        next = e->next;
1172                        find_copy_in_blob(sb, e, parent, split, &file_p);
1173                        if (split[1].suspect &&
1174                            sb->move_score < blame_entry_score(sb, &split[1])) {
1175                                split_blame(blamed, &unblamedtail, split, e);
1176                        } else {
1177                                e->next = leftover;
1178                                leftover = e;
1179                        }
1180                        decref_split(split);
1181                }
1182                *unblamedtail = NULL;
1183                toosmall = filter_small(sb, toosmall, &unblamed, sb->move_score);
1184        } while (unblamed);
1185        target->suspects = reverse_blame(leftover, NULL);
1186}
1187
1188struct blame_list {
1189        struct blame_entry *ent;
1190        struct blame_entry split[3];
1191};
1192
1193/*
1194 * Count the number of entries the target is suspected for,
1195 * and prepare a list of entry and the best split.
1196 */
1197static struct blame_list *setup_blame_list(struct blame_entry *unblamed,
1198                                           int *num_ents_p)
1199{
1200        struct blame_entry *e;
1201        int num_ents, i;
1202        struct blame_list *blame_list = NULL;
1203
1204        for (e = unblamed, num_ents = 0; e; e = e->next)
1205                num_ents++;
1206        if (num_ents) {
1207                blame_list = xcalloc(num_ents, sizeof(struct blame_list));
1208                for (e = unblamed, i = 0; e; e = e->next)
1209                        blame_list[i++].ent = e;
1210        }
1211        *num_ents_p = num_ents;
1212        return blame_list;
1213}
1214
1215/*
1216 * For lines target is suspected for, see if we can find code movement
1217 * across file boundary from the parent commit.  porigin is the path
1218 * in the parent we already tried.
1219 */
1220static void find_copy_in_parent(struct blame_scoreboard *sb,
1221                                struct blame_entry ***blamed,
1222                                struct blame_entry **toosmall,
1223                                struct blame_origin *target,
1224                                struct commit *parent,
1225                                struct blame_origin *porigin,
1226                                int opt)
1227{
1228        struct diff_options diff_opts;
1229        int i, j;
1230        struct blame_list *blame_list;
1231        int num_ents;
1232        struct blame_entry *unblamed = target->suspects;
1233        struct blame_entry *leftover = NULL;
1234
1235        if (!unblamed)
1236                return; /* nothing remains for this target */
1237
1238        diff_setup(&diff_opts);
1239        diff_opts.flags.recursive = 1;
1240        diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1241
1242        diff_setup_done(&diff_opts);
1243
1244        /* Try "find copies harder" on new path if requested;
1245         * we do not want to use diffcore_rename() actually to
1246         * match things up; find_copies_harder is set only to
1247         * force diff_tree_oid() to feed all filepairs to diff_queue,
1248         * and this code needs to be after diff_setup_done(), which
1249         * usually makes find-copies-harder imply copy detection.
1250         */
1251        if ((opt & PICKAXE_BLAME_COPY_HARDEST)
1252            || ((opt & PICKAXE_BLAME_COPY_HARDER)
1253                && (!porigin || strcmp(target->path, porigin->path))))
1254                diff_opts.flags.find_copies_harder = 1;
1255
1256        if (is_null_oid(&target->commit->object.oid))
1257                do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
1258        else
1259                diff_tree_oid(get_commit_tree_oid(parent),
1260                              get_commit_tree_oid(target->commit),
1261                              "", &diff_opts);
1262
1263        if (!diff_opts.flags.find_copies_harder)
1264                diffcore_std(&diff_opts);
1265
1266        do {
1267                struct blame_entry **unblamedtail = &unblamed;
1268                blame_list = setup_blame_list(unblamed, &num_ents);
1269
1270                for (i = 0; i < diff_queued_diff.nr; i++) {
1271                        struct diff_filepair *p = diff_queued_diff.queue[i];
1272                        struct blame_origin *norigin;
1273                        mmfile_t file_p;
1274                        struct blame_entry potential[3];
1275
1276                        if (!DIFF_FILE_VALID(p->one))
1277                                continue; /* does not exist in parent */
1278                        if (S_ISGITLINK(p->one->mode))
1279                                continue; /* ignore git links */
1280                        if (porigin && !strcmp(p->one->path, porigin->path))
1281                                /* find_move already dealt with this path */
1282                                continue;
1283
1284                        norigin = get_origin(parent, p->one->path);
1285                        oidcpy(&norigin->blob_oid, &p->one->oid);
1286                        norigin->mode = p->one->mode;
1287                        fill_origin_blob(&sb->revs->diffopt, norigin, &file_p, &sb->num_read_blob);
1288                        if (!file_p.ptr)
1289                                continue;
1290
1291                        for (j = 0; j < num_ents; j++) {
1292                                find_copy_in_blob(sb, blame_list[j].ent,
1293                                                  norigin, potential, &file_p);
1294                                copy_split_if_better(sb, blame_list[j].split,
1295                                                     potential);
1296                                decref_split(potential);
1297                        }
1298                        blame_origin_decref(norigin);
1299                }
1300
1301                for (j = 0; j < num_ents; j++) {
1302                        struct blame_entry *split = blame_list[j].split;
1303                        if (split[1].suspect &&
1304                            sb->copy_score < blame_entry_score(sb, &split[1])) {
1305                                split_blame(blamed, &unblamedtail, split,
1306                                            blame_list[j].ent);
1307                        } else {
1308                                blame_list[j].ent->next = leftover;
1309                                leftover = blame_list[j].ent;
1310                        }
1311                        decref_split(split);
1312                }
1313                free(blame_list);
1314                *unblamedtail = NULL;
1315                toosmall = filter_small(sb, toosmall, &unblamed, sb->copy_score);
1316        } while (unblamed);
1317        target->suspects = reverse_blame(leftover, NULL);
1318        diff_flush(&diff_opts);
1319        clear_pathspec(&diff_opts.pathspec);
1320}
1321
1322/*
1323 * The blobs of origin and porigin exactly match, so everything
1324 * origin is suspected for can be blamed on the parent.
1325 */
1326static void pass_whole_blame(struct blame_scoreboard *sb,
1327                             struct blame_origin *origin, struct blame_origin *porigin)
1328{
1329        struct blame_entry *e, *suspects;
1330
1331        if (!porigin->file.ptr && origin->file.ptr) {
1332                /* Steal its file */
1333                porigin->file = origin->file;
1334                origin->file.ptr = NULL;
1335        }
1336        suspects = origin->suspects;
1337        origin->suspects = NULL;
1338        for (e = suspects; e; e = e->next) {
1339                blame_origin_incref(porigin);
1340                blame_origin_decref(e->suspect);
1341                e->suspect = porigin;
1342        }
1343        queue_blames(sb, porigin, suspects);
1344}
1345
1346/*
1347 * We pass blame from the current commit to its parents.  We keep saying
1348 * "parent" (and "porigin"), but what we mean is to find scapegoat to
1349 * exonerate ourselves.
1350 */
1351static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit,
1352                                        int reverse)
1353{
1354        if (!reverse) {
1355                if (revs->first_parent_only &&
1356                    commit->parents &&
1357                    commit->parents->next) {
1358                        free_commit_list(commit->parents->next);
1359                        commit->parents->next = NULL;
1360                }
1361                return commit->parents;
1362        }
1363        return lookup_decoration(&revs->children, &commit->object);
1364}
1365
1366static int num_scapegoats(struct rev_info *revs, struct commit *commit, int reverse)
1367{
1368        struct commit_list *l = first_scapegoat(revs, commit, reverse);
1369        return commit_list_count(l);
1370}
1371
1372/* Distribute collected unsorted blames to the respected sorted lists
1373 * in the various origins.
1374 */
1375static void distribute_blame(struct blame_scoreboard *sb, struct blame_entry *blamed)
1376{
1377        blamed = llist_mergesort(blamed, get_next_blame, set_next_blame,
1378                                 compare_blame_suspect);
1379        while (blamed)
1380        {
1381                struct blame_origin *porigin = blamed->suspect;
1382                struct blame_entry *suspects = NULL;
1383                do {
1384                        struct blame_entry *next = blamed->next;
1385                        blamed->next = suspects;
1386                        suspects = blamed;
1387                        blamed = next;
1388                } while (blamed && blamed->suspect == porigin);
1389                suspects = reverse_blame(suspects, NULL);
1390                queue_blames(sb, porigin, suspects);
1391        }
1392}
1393
1394#define MAXSG 16
1395
1396static void pass_blame(struct blame_scoreboard *sb, struct blame_origin *origin, int opt)
1397{
1398        struct rev_info *revs = sb->revs;
1399        int i, pass, num_sg;
1400        struct commit *commit = origin->commit;
1401        struct commit_list *sg;
1402        struct blame_origin *sg_buf[MAXSG];
1403        struct blame_origin *porigin, **sg_origin = sg_buf;
1404        struct blame_entry *toosmall = NULL;
1405        struct blame_entry *blames, **blametail = &blames;
1406
1407        num_sg = num_scapegoats(revs, commit, sb->reverse);
1408        if (!num_sg)
1409                goto finish;
1410        else if (num_sg < ARRAY_SIZE(sg_buf))
1411                memset(sg_buf, 0, sizeof(sg_buf));
1412        else
1413                sg_origin = xcalloc(num_sg, sizeof(*sg_origin));
1414
1415        /*
1416         * The first pass looks for unrenamed path to optimize for
1417         * common cases, then we look for renames in the second pass.
1418         */
1419        for (pass = 0; pass < 2 - sb->no_whole_file_rename; pass++) {
1420                struct blame_origin *(*find)(struct commit *, struct blame_origin *);
1421                find = pass ? find_rename : find_origin;
1422
1423                for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
1424                     i < num_sg && sg;
1425                     sg = sg->next, i++) {
1426                        struct commit *p = sg->item;
1427                        int j, same;
1428
1429                        if (sg_origin[i])
1430                                continue;
1431                        if (parse_commit(p))
1432                                continue;
1433                        porigin = find(p, origin);
1434                        if (!porigin)
1435                                continue;
1436                        if (!oidcmp(&porigin->blob_oid, &origin->blob_oid)) {
1437                                pass_whole_blame(sb, origin, porigin);
1438                                blame_origin_decref(porigin);
1439                                goto finish;
1440                        }
1441                        for (j = same = 0; j < i; j++)
1442                                if (sg_origin[j] &&
1443                                    !oidcmp(&sg_origin[j]->blob_oid, &porigin->blob_oid)) {
1444                                        same = 1;
1445                                        break;
1446                                }
1447                        if (!same)
1448                                sg_origin[i] = porigin;
1449                        else
1450                                blame_origin_decref(porigin);
1451                }
1452        }
1453
1454        sb->num_commits++;
1455        for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
1456             i < num_sg && sg;
1457             sg = sg->next, i++) {
1458                struct blame_origin *porigin = sg_origin[i];
1459                if (!porigin)
1460                        continue;
1461                if (!origin->previous) {
1462                        blame_origin_incref(porigin);
1463                        origin->previous = porigin;
1464                }
1465                pass_blame_to_parent(sb, origin, porigin);
1466                if (!origin->suspects)
1467                        goto finish;
1468        }
1469
1470        /*
1471         * Optionally find moves in parents' files.
1472         */
1473        if (opt & PICKAXE_BLAME_MOVE) {
1474                filter_small(sb, &toosmall, &origin->suspects, sb->move_score);
1475                if (origin->suspects) {
1476                        for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
1477                             i < num_sg && sg;
1478                             sg = sg->next, i++) {
1479                                struct blame_origin *porigin = sg_origin[i];
1480                                if (!porigin)
1481                                        continue;
1482                                find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);
1483                                if (!origin->suspects)
1484                                        break;
1485                        }
1486                }
1487        }
1488
1489        /*
1490         * Optionally find copies from parents' files.
1491         */
1492        if (opt & PICKAXE_BLAME_COPY) {
1493                if (sb->copy_score > sb->move_score)
1494                        filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);
1495                else if (sb->copy_score < sb->move_score) {
1496                        origin->suspects = blame_merge(origin->suspects, toosmall);
1497                        toosmall = NULL;
1498                        filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);
1499                }
1500                if (!origin->suspects)
1501                        goto finish;
1502
1503                for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
1504                     i < num_sg && sg;
1505                     sg = sg->next, i++) {
1506                        struct blame_origin *porigin = sg_origin[i];
1507                        find_copy_in_parent(sb, &blametail, &toosmall,
1508                                            origin, sg->item, porigin, opt);
1509                        if (!origin->suspects)
1510                                goto finish;
1511                }
1512        }
1513
1514finish:
1515        *blametail = NULL;
1516        distribute_blame(sb, blames);
1517        /*
1518         * prepend toosmall to origin->suspects
1519         *
1520         * There is no point in sorting: this ends up on a big
1521         * unsorted list in the caller anyway.
1522         */
1523        if (toosmall) {
1524                struct blame_entry **tail = &toosmall;
1525                while (*tail)
1526                        tail = &(*tail)->next;
1527                *tail = origin->suspects;
1528                origin->suspects = toosmall;
1529        }
1530        for (i = 0; i < num_sg; i++) {
1531                if (sg_origin[i]) {
1532                        drop_origin_blob(sg_origin[i]);
1533                        blame_origin_decref(sg_origin[i]);
1534                }
1535        }
1536        drop_origin_blob(origin);
1537        if (sg_buf != sg_origin)
1538                free(sg_origin);
1539}
1540
1541/*
1542 * The main loop -- while we have blobs with lines whose true origin
1543 * is still unknown, pick one blob, and allow its lines to pass blames
1544 * to its parents. */
1545void assign_blame(struct blame_scoreboard *sb, int opt)
1546{
1547        struct rev_info *revs = sb->revs;
1548        struct commit *commit = prio_queue_get(&sb->commits);
1549
1550        while (commit) {
1551                struct blame_entry *ent;
1552                struct blame_origin *suspect = commit->util;
1553
1554                /* find one suspect to break down */
1555                while (suspect && !suspect->suspects)
1556                        suspect = suspect->next;
1557
1558                if (!suspect) {
1559                        commit = prio_queue_get(&sb->commits);
1560                        continue;
1561                }
1562
1563                assert(commit == suspect->commit);
1564
1565                /*
1566                 * We will use this suspect later in the loop,
1567                 * so hold onto it in the meantime.
1568                 */
1569                blame_origin_incref(suspect);
1570                parse_commit(commit);
1571                if (sb->reverse ||
1572                    (!(commit->object.flags & UNINTERESTING) &&
1573                     !(revs->max_age != -1 && commit->date < revs->max_age)))
1574                        pass_blame(sb, suspect, opt);
1575                else {
1576                        commit->object.flags |= UNINTERESTING;
1577                        if (commit->object.parsed)
1578                                mark_parents_uninteresting(commit);
1579                }
1580                /* treat root commit as boundary */
1581                if (!commit->parents && !sb->show_root)
1582                        commit->object.flags |= UNINTERESTING;
1583
1584                /* Take responsibility for the remaining entries */
1585                ent = suspect->suspects;
1586                if (ent) {
1587                        suspect->guilty = 1;
1588                        for (;;) {
1589                                struct blame_entry *next = ent->next;
1590                                if (sb->found_guilty_entry)
1591                                        sb->found_guilty_entry(ent, sb->found_guilty_entry_data);
1592                                if (next) {
1593                                        ent = next;
1594                                        continue;
1595                                }
1596                                ent->next = sb->ent;
1597                                sb->ent = suspect->suspects;
1598                                suspect->suspects = NULL;
1599                                break;
1600                        }
1601                }
1602                blame_origin_decref(suspect);
1603
1604                if (sb->debug) /* sanity */
1605                        sanity_check_refcnt(sb);
1606        }
1607}
1608
1609static const char *get_next_line(const char *start, const char *end)
1610{
1611        const char *nl = memchr(start, '\n', end - start);
1612        return nl ? nl + 1 : end;
1613}
1614
1615/*
1616 * To allow quick access to the contents of nth line in the
1617 * final image, prepare an index in the scoreboard.
1618 */
1619static int prepare_lines(struct blame_scoreboard *sb)
1620{
1621        const char *buf = sb->final_buf;
1622        unsigned long len = sb->final_buf_size;
1623        const char *end = buf + len;
1624        const char *p;
1625        int *lineno;
1626        int num = 0;
1627
1628        for (p = buf; p < end; p = get_next_line(p, end))
1629                num++;
1630
1631        ALLOC_ARRAY(sb->lineno, num + 1);
1632        lineno = sb->lineno;
1633
1634        for (p = buf; p < end; p = get_next_line(p, end))
1635                *lineno++ = p - buf;
1636
1637        *lineno = len;
1638
1639        sb->num_lines = num;
1640        return sb->num_lines;
1641}
1642
1643static struct commit *find_single_final(struct rev_info *revs,
1644                                        const char **name_p)
1645{
1646        int i;
1647        struct commit *found = NULL;
1648        const char *name = NULL;
1649
1650        for (i = 0; i < revs->pending.nr; i++) {
1651                struct object *obj = revs->pending.objects[i].item;
1652                if (obj->flags & UNINTERESTING)
1653                        continue;
1654                obj = deref_tag(obj, NULL, 0);
1655                if (obj->type != OBJ_COMMIT)
1656                        die("Non commit %s?", revs->pending.objects[i].name);
1657                if (found)
1658                        die("More than one commit to dig from %s and %s?",
1659                            revs->pending.objects[i].name, name);
1660                found = (struct commit *)obj;
1661                name = revs->pending.objects[i].name;
1662        }
1663        if (name_p)
1664                *name_p = xstrdup_or_null(name);
1665        return found;
1666}
1667
1668static struct commit *dwim_reverse_initial(struct rev_info *revs,
1669                                           const char **name_p)
1670{
1671        /*
1672         * DWIM "git blame --reverse ONE -- PATH" as
1673         * "git blame --reverse ONE..HEAD -- PATH" but only do so
1674         * when it makes sense.
1675         */
1676        struct object *obj;
1677        struct commit *head_commit;
1678        struct object_id head_oid;
1679
1680        if (revs->pending.nr != 1)
1681                return NULL;
1682
1683        /* Is that sole rev a committish? */
1684        obj = revs->pending.objects[0].item;
1685        obj = deref_tag(obj, NULL, 0);
1686        if (obj->type != OBJ_COMMIT)
1687                return NULL;
1688
1689        /* Do we have HEAD? */
1690        if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
1691                return NULL;
1692        head_commit = lookup_commit_reference_gently(&head_oid, 1);
1693        if (!head_commit)
1694                return NULL;
1695
1696        /* Turn "ONE" into "ONE..HEAD" then */
1697        obj->flags |= UNINTERESTING;
1698        add_pending_object(revs, &head_commit->object, "HEAD");
1699
1700        if (name_p)
1701                *name_p = revs->pending.objects[0].name;
1702        return (struct commit *)obj;
1703}
1704
1705static struct commit *find_single_initial(struct rev_info *revs,
1706                                          const char **name_p)
1707{
1708        int i;
1709        struct commit *found = NULL;
1710        const char *name = NULL;
1711
1712        /*
1713         * There must be one and only one negative commit, and it must be
1714         * the boundary.
1715         */
1716        for (i = 0; i < revs->pending.nr; i++) {
1717                struct object *obj = revs->pending.objects[i].item;
1718                if (!(obj->flags & UNINTERESTING))
1719                        continue;
1720                obj = deref_tag(obj, NULL, 0);
1721                if (obj->type != OBJ_COMMIT)
1722                        die("Non commit %s?", revs->pending.objects[i].name);
1723                if (found)
1724                        die("More than one commit to dig up from, %s and %s?",
1725                            revs->pending.objects[i].name, name);
1726                found = (struct commit *) obj;
1727                name = revs->pending.objects[i].name;
1728        }
1729
1730        if (!name)
1731                found = dwim_reverse_initial(revs, &name);
1732        if (!name)
1733                die("No commit to dig up from?");
1734
1735        if (name_p)
1736                *name_p = xstrdup(name);
1737        return found;
1738}
1739
1740void init_scoreboard(struct blame_scoreboard *sb)
1741{
1742        memset(sb, 0, sizeof(struct blame_scoreboard));
1743        sb->move_score = BLAME_DEFAULT_MOVE_SCORE;
1744        sb->copy_score = BLAME_DEFAULT_COPY_SCORE;
1745}
1746
1747void setup_scoreboard(struct blame_scoreboard *sb, const char *path, struct blame_origin **orig)
1748{
1749        const char *final_commit_name = NULL;
1750        struct blame_origin *o;
1751        struct commit *final_commit = NULL;
1752        enum object_type type;
1753
1754        if (sb->reverse && sb->contents_from)
1755                die(_("--contents and --reverse do not blend well."));
1756
1757        if (!sb->reverse) {
1758                sb->final = find_single_final(sb->revs, &final_commit_name);
1759                sb->commits.compare = compare_commits_by_commit_date;
1760        } else {
1761                sb->final = find_single_initial(sb->revs, &final_commit_name);
1762                sb->commits.compare = compare_commits_by_reverse_commit_date;
1763        }
1764
1765        if (sb->final && sb->contents_from)
1766                die(_("cannot use --contents with final commit object name"));
1767
1768        if (sb->reverse && sb->revs->first_parent_only)
1769                sb->revs->children.name = NULL;
1770
1771        if (!sb->final) {
1772                /*
1773                 * "--not A B -- path" without anything positive;
1774                 * do not default to HEAD, but use the working tree
1775                 * or "--contents".
1776                 */
1777                setup_work_tree();
1778                sb->final = fake_working_tree_commit(&sb->revs->diffopt,
1779                                                     path, sb->contents_from);
1780                add_pending_object(sb->revs, &(sb->final->object), ":");
1781        }
1782
1783        if (sb->reverse && sb->revs->first_parent_only) {
1784                final_commit = find_single_final(sb->revs, NULL);
1785                if (!final_commit)
1786                        die(_("--reverse and --first-parent together require specified latest commit"));
1787        }
1788
1789        /*
1790         * If we have bottom, this will mark the ancestors of the
1791         * bottom commits we would reach while traversing as
1792         * uninteresting.
1793         */
1794        if (prepare_revision_walk(sb->revs))
1795                die(_("revision walk setup failed"));
1796
1797        if (sb->reverse && sb->revs->first_parent_only) {
1798                struct commit *c = final_commit;
1799
1800                sb->revs->children.name = "children";
1801                while (c->parents &&
1802                       oidcmp(&c->object.oid, &sb->final->object.oid)) {
1803                        struct commit_list *l = xcalloc(1, sizeof(*l));
1804
1805                        l->item = c;
1806                        if (add_decoration(&sb->revs->children,
1807                                           &c->parents->item->object, l))
1808                                BUG("not unique item in first-parent chain");
1809                        c = c->parents->item;
1810                }
1811
1812                if (oidcmp(&c->object.oid, &sb->final->object.oid))
1813                        die(_("--reverse --first-parent together require range along first-parent chain"));
1814        }
1815
1816        if (is_null_oid(&sb->final->object.oid)) {
1817                o = sb->final->util;
1818                sb->final_buf = xmemdupz(o->file.ptr, o->file.size);
1819                sb->final_buf_size = o->file.size;
1820        }
1821        else {
1822                o = get_origin(sb->final, path);
1823                if (fill_blob_sha1_and_mode(o))
1824                        die(_("no such path %s in %s"), path, final_commit_name);
1825
1826                if (sb->revs->diffopt.flags.allow_textconv &&
1827                    textconv_object(path, o->mode, &o->blob_oid, 1, (char **) &sb->final_buf,
1828                                    &sb->final_buf_size))
1829                        ;
1830                else
1831                        sb->final_buf = read_object_file(&o->blob_oid, &type,
1832                                                         &sb->final_buf_size);
1833
1834                if (!sb->final_buf)
1835                        die(_("cannot read blob %s for path %s"),
1836                            oid_to_hex(&o->blob_oid),
1837                            path);
1838        }
1839        sb->num_read_blob++;
1840        prepare_lines(sb);
1841
1842        if (orig)
1843                *orig = o;
1844
1845        free((char *)final_commit_name);
1846}
1847
1848
1849
1850struct blame_entry *blame_entry_prepend(struct blame_entry *head,
1851                                        long start, long end,
1852                                        struct blame_origin *o)
1853{
1854        struct blame_entry *new_head = xcalloc(1, sizeof(struct blame_entry));
1855        new_head->lno = start;
1856        new_head->num_lines = end - start;
1857        new_head->suspect = o;
1858        new_head->s_lno = start;
1859        new_head->next = head;
1860        blame_origin_incref(o);
1861        return new_head;
1862}