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