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