git-submodule.txt: fix AsciiDoc formatting error
[git] / blame.c
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
13 define_commit_slab(blame_suspects, struct blame_origin *);
14 static struct blame_suspects blame_suspects;
15
16 struct 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
25 static void set_blame_suspects(struct commit *commit, struct blame_origin *origin)
26 {
27         *blame_suspects_at(&blame_suspects, commit) = origin;
28 }
29
30 void 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  */
58 static 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  */
73 static 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
93 static 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
119 static 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
131 static 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  */
161 static 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  */
174 static 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         repo_read_index(r);
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         repo_read_index(r);
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
300 static 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  */
317 static 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
344 static 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
357 static 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
397 static void *get_next_blame(const void *p)
398 {
399         return ((struct blame_entry *)p)->next;
400 }
401
402 static 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
412 static 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
418 static 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
435 void 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
441 static 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  */
452 static 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  */
476 void 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
502 static 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  */
529 static 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  */
549 static 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  */
638 static 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  */
679 static 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  */
696 static 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
707 const 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  */
726 static 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  */
774 static 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  */
811 static 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
829 static 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  * Process one hunk from the patch between the current suspect for
843  * blame_entry e and its parent.  This first blames any unfinished
844  * entries before the chunk (which is where target and parent start
845  * differing) on the parent, and then splits blame entries at the
846  * start and at the end of the difference region.  Since use of -M and
847  * -C options may lead to overlapping/duplicate source line number
848  * ranges, all we can rely on from sorting/merging is the order of the
849  * first suspect line number.
850  */
851 static void blame_chunk(struct blame_entry ***dstq, struct blame_entry ***srcq,
852                         int tlno, int offset, int same,
853                         struct blame_origin *parent)
854 {
855         struct blame_entry *e = **srcq;
856         struct blame_entry *samep = NULL, *diffp = NULL;
857
858         while (e && e->s_lno < tlno) {
859                 struct blame_entry *next = e->next;
860                 /*
861                  * current record starts before differing portion.  If
862                  * it reaches into it, we need to split it up and
863                  * examine the second part separately.
864                  */
865                 if (e->s_lno + e->num_lines > tlno) {
866                         /* Move second half to a new record */
867                         int len = tlno - e->s_lno;
868                         struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry));
869                         n->suspect = e->suspect;
870                         n->lno = e->lno + len;
871                         n->s_lno = e->s_lno + len;
872                         n->num_lines = e->num_lines - len;
873                         e->num_lines = len;
874                         e->score = 0;
875                         /* Push new record to diffp */
876                         n->next = diffp;
877                         diffp = n;
878                 } else
879                         blame_origin_decref(e->suspect);
880                 /* Pass blame for everything before the differing
881                  * chunk to the parent */
882                 e->suspect = blame_origin_incref(parent);
883                 e->s_lno += offset;
884                 e->next = samep;
885                 samep = e;
886                 e = next;
887         }
888         /*
889          * As we don't know how much of a common stretch after this
890          * diff will occur, the currently blamed parts are all that we
891          * can assign to the parent for now.
892          */
893
894         if (samep) {
895                 **dstq = reverse_blame(samep, **dstq);
896                 *dstq = &samep->next;
897         }
898         /*
899          * Prepend the split off portions: everything after e starts
900          * after the blameable portion.
901          */
902         e = reverse_blame(diffp, e);
903
904         /*
905          * Now retain records on the target while parts are different
906          * from the parent.
907          */
908         samep = NULL;
909         diffp = NULL;
910         while (e && e->s_lno < same) {
911                 struct blame_entry *next = e->next;
912
913                 /*
914                  * If current record extends into sameness, need to split.
915                  */
916                 if (e->s_lno + e->num_lines > same) {
917                         /*
918                          * Move second half to a new record to be
919                          * processed by later chunks
920                          */
921                         int len = same - e->s_lno;
922                         struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry));
923                         n->suspect = blame_origin_incref(e->suspect);
924                         n->lno = e->lno + len;
925                         n->s_lno = e->s_lno + len;
926                         n->num_lines = e->num_lines - len;
927                         e->num_lines = len;
928                         e->score = 0;
929                         /* Push new record to samep */
930                         n->next = samep;
931                         samep = n;
932                 }
933                 e->next = diffp;
934                 diffp = e;
935                 e = next;
936         }
937         **srcq = reverse_blame(diffp, reverse_blame(samep, e));
938         /* Move across elements that are in the unblamable portion */
939         if (diffp)
940                 *srcq = &diffp->next;
941 }
942
943 struct blame_chunk_cb_data {
944         struct blame_origin *parent;
945         long offset;
946         struct blame_entry **dstq;
947         struct blame_entry **srcq;
948 };
949
950 /* diff chunks are from parent to target */
951 static int blame_chunk_cb(long start_a, long count_a,
952                           long start_b, long count_b, void *data)
953 {
954         struct blame_chunk_cb_data *d = data;
955         if (start_a - start_b != d->offset)
956                 die("internal error in blame::blame_chunk_cb");
957         blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b,
958                     start_b + count_b, d->parent);
959         d->offset = start_a + count_a - (start_b + count_b);
960         return 0;
961 }
962
963 /*
964  * We are looking at the origin 'target' and aiming to pass blame
965  * for the lines it is suspected to its parent.  Run diff to find
966  * which lines came from parent and pass blame for them.
967  */
968 static void pass_blame_to_parent(struct blame_scoreboard *sb,
969                                  struct blame_origin *target,
970                                  struct blame_origin *parent)
971 {
972         mmfile_t file_p, file_o;
973         struct blame_chunk_cb_data d;
974         struct blame_entry *newdest = NULL;
975
976         if (!target->suspects)
977                 return; /* nothing remains for this target */
978
979         d.parent = parent;
980         d.offset = 0;
981         d.dstq = &newdest; d.srcq = &target->suspects;
982
983         fill_origin_blob(&sb->revs->diffopt, parent, &file_p, &sb->num_read_blob);
984         fill_origin_blob(&sb->revs->diffopt, target, &file_o, &sb->num_read_blob);
985         sb->num_get_patch++;
986
987         if (diff_hunks(&file_p, &file_o, blame_chunk_cb, &d, sb->xdl_opts))
988                 die("unable to generate diff (%s -> %s)",
989                     oid_to_hex(&parent->commit->object.oid),
990                     oid_to_hex(&target->commit->object.oid));
991         /* The rest are the same as the parent */
992         blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, parent);
993         *d.dstq = NULL;
994         queue_blames(sb, parent, newdest);
995
996         return;
997 }
998
999 /*
1000  * The lines in blame_entry after splitting blames many times can become
1001  * very small and trivial, and at some point it becomes pointless to
1002  * blame the parents.  E.g. "\t\t}\n\t}\n\n" appears everywhere in any
1003  * ordinary C program, and it is not worth to say it was copied from
1004  * totally unrelated file in the parent.
1005  *
1006  * Compute how trivial the lines in the blame_entry are.
1007  */
1008 unsigned blame_entry_score(struct blame_scoreboard *sb, struct blame_entry *e)
1009 {
1010         unsigned score;
1011         const char *cp, *ep;
1012
1013         if (e->score)
1014                 return e->score;
1015
1016         score = 1;
1017         cp = blame_nth_line(sb, e->lno);
1018         ep = blame_nth_line(sb, e->lno + e->num_lines);
1019         while (cp < ep) {
1020                 unsigned ch = *((unsigned char *)cp);
1021                 if (isalnum(ch))
1022                         score++;
1023                 cp++;
1024         }
1025         e->score = score;
1026         return score;
1027 }
1028
1029 /*
1030  * best_so_far[] and potential[] are both a split of an existing blame_entry
1031  * that passes blame to the parent.  Maintain best_so_far the best split so
1032  * far, by comparing potential and best_so_far and copying potential into
1033  * bst_so_far as needed.
1034  */
1035 static void copy_split_if_better(struct blame_scoreboard *sb,
1036                                  struct blame_entry *best_so_far,
1037                                  struct blame_entry *potential)
1038 {
1039         int i;
1040
1041         if (!potential[1].suspect)
1042                 return;
1043         if (best_so_far[1].suspect) {
1044                 if (blame_entry_score(sb, &potential[1]) <
1045                     blame_entry_score(sb, &best_so_far[1]))
1046                         return;
1047         }
1048
1049         for (i = 0; i < 3; i++)
1050                 blame_origin_incref(potential[i].suspect);
1051         decref_split(best_so_far);
1052         memcpy(best_so_far, potential, sizeof(struct blame_entry[3]));
1053 }
1054
1055 /*
1056  * We are looking at a part of the final image represented by
1057  * ent (tlno and same are offset by ent->s_lno).
1058  * tlno is where we are looking at in the final image.
1059  * up to (but not including) same match preimage.
1060  * plno is where we are looking at in the preimage.
1061  *
1062  * <-------------- final image ---------------------->
1063  *       <------ent------>
1064  *         ^tlno ^same
1065  *    <---------preimage----->
1066  *         ^plno
1067  *
1068  * All line numbers are 0-based.
1069  */
1070 static void handle_split(struct blame_scoreboard *sb,
1071                          struct blame_entry *ent,
1072                          int tlno, int plno, int same,
1073                          struct blame_origin *parent,
1074                          struct blame_entry *split)
1075 {
1076         if (ent->num_lines <= tlno)
1077                 return;
1078         if (tlno < same) {
1079                 struct blame_entry potential[3];
1080                 tlno += ent->s_lno;
1081                 same += ent->s_lno;
1082                 split_overlap(potential, ent, tlno, plno, same, parent);
1083                 copy_split_if_better(sb, split, potential);
1084                 decref_split(potential);
1085         }
1086 }
1087
1088 struct handle_split_cb_data {
1089         struct blame_scoreboard *sb;
1090         struct blame_entry *ent;
1091         struct blame_origin *parent;
1092         struct blame_entry *split;
1093         long plno;
1094         long tlno;
1095 };
1096
1097 static int handle_split_cb(long start_a, long count_a,
1098                            long start_b, long count_b, void *data)
1099 {
1100         struct handle_split_cb_data *d = data;
1101         handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,
1102                      d->split);
1103         d->plno = start_a + count_a;
1104         d->tlno = start_b + count_b;
1105         return 0;
1106 }
1107
1108 /*
1109  * Find the lines from parent that are the same as ent so that
1110  * we can pass blames to it.  file_p has the blob contents for
1111  * the parent.
1112  */
1113 static void find_copy_in_blob(struct blame_scoreboard *sb,
1114                               struct blame_entry *ent,
1115                               struct blame_origin *parent,
1116                               struct blame_entry *split,
1117                               mmfile_t *file_p)
1118 {
1119         const char *cp;
1120         mmfile_t file_o;
1121         struct handle_split_cb_data d;
1122
1123         memset(&d, 0, sizeof(d));
1124         d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;
1125         /*
1126          * Prepare mmfile that contains only the lines in ent.
1127          */
1128         cp = blame_nth_line(sb, ent->lno);
1129         file_o.ptr = (char *) cp;
1130         file_o.size = blame_nth_line(sb, ent->lno + ent->num_lines) - cp;
1131
1132         /*
1133          * file_o is a part of final image we are annotating.
1134          * file_p partially may match that image.
1135          */
1136         memset(split, 0, sizeof(struct blame_entry [3]));
1137         if (diff_hunks(file_p, &file_o, handle_split_cb, &d, sb->xdl_opts))
1138                 die("unable to generate diff (%s)",
1139                     oid_to_hex(&parent->commit->object.oid));
1140         /* remainder, if any, all match the preimage */
1141         handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);
1142 }
1143
1144 /* Move all blame entries from list *source that have a score smaller
1145  * than score_min to the front of list *small.
1146  * Returns a pointer to the link pointing to the old head of the small list.
1147  */
1148
1149 static struct blame_entry **filter_small(struct blame_scoreboard *sb,
1150                                          struct blame_entry **small,
1151                                          struct blame_entry **source,
1152                                          unsigned score_min)
1153 {
1154         struct blame_entry *p = *source;
1155         struct blame_entry *oldsmall = *small;
1156         while (p) {
1157                 if (blame_entry_score(sb, p) <= score_min) {
1158                         *small = p;
1159                         small = &p->next;
1160                         p = *small;
1161                 } else {
1162                         *source = p;
1163                         source = &p->next;
1164                         p = *source;
1165                 }
1166         }
1167         *small = oldsmall;
1168         *source = NULL;
1169         return small;
1170 }
1171
1172 /*
1173  * See if lines currently target is suspected for can be attributed to
1174  * parent.
1175  */
1176 static void find_move_in_parent(struct blame_scoreboard *sb,
1177                                 struct blame_entry ***blamed,
1178                                 struct blame_entry **toosmall,
1179                                 struct blame_origin *target,
1180                                 struct blame_origin *parent)
1181 {
1182         struct blame_entry *e, split[3];
1183         struct blame_entry *unblamed = target->suspects;
1184         struct blame_entry *leftover = NULL;
1185         mmfile_t file_p;
1186
1187         if (!unblamed)
1188                 return; /* nothing remains for this target */
1189
1190         fill_origin_blob(&sb->revs->diffopt, parent, &file_p, &sb->num_read_blob);
1191         if (!file_p.ptr)
1192                 return;
1193
1194         /* At each iteration, unblamed has a NULL-terminated list of
1195          * entries that have not yet been tested for blame.  leftover
1196          * contains the reversed list of entries that have been tested
1197          * without being assignable to the parent.
1198          */
1199         do {
1200                 struct blame_entry **unblamedtail = &unblamed;
1201                 struct blame_entry *next;
1202                 for (e = unblamed; e; e = next) {
1203                         next = e->next;
1204                         find_copy_in_blob(sb, e, parent, split, &file_p);
1205                         if (split[1].suspect &&
1206                             sb->move_score < blame_entry_score(sb, &split[1])) {
1207                                 split_blame(blamed, &unblamedtail, split, e);
1208                         } else {
1209                                 e->next = leftover;
1210                                 leftover = e;
1211                         }
1212                         decref_split(split);
1213                 }
1214                 *unblamedtail = NULL;
1215                 toosmall = filter_small(sb, toosmall, &unblamed, sb->move_score);
1216         } while (unblamed);
1217         target->suspects = reverse_blame(leftover, NULL);
1218 }
1219
1220 struct blame_list {
1221         struct blame_entry *ent;
1222         struct blame_entry split[3];
1223 };
1224
1225 /*
1226  * Count the number of entries the target is suspected for,
1227  * and prepare a list of entry and the best split.
1228  */
1229 static struct blame_list *setup_blame_list(struct blame_entry *unblamed,
1230                                            int *num_ents_p)
1231 {
1232         struct blame_entry *e;
1233         int num_ents, i;
1234         struct blame_list *blame_list = NULL;
1235
1236         for (e = unblamed, num_ents = 0; e; e = e->next)
1237                 num_ents++;
1238         if (num_ents) {
1239                 blame_list = xcalloc(num_ents, sizeof(struct blame_list));
1240                 for (e = unblamed, i = 0; e; e = e->next)
1241                         blame_list[i++].ent = e;
1242         }
1243         *num_ents_p = num_ents;
1244         return blame_list;
1245 }
1246
1247 /*
1248  * For lines target is suspected for, see if we can find code movement
1249  * across file boundary from the parent commit.  porigin is the path
1250  * in the parent we already tried.
1251  */
1252 static void find_copy_in_parent(struct blame_scoreboard *sb,
1253                                 struct blame_entry ***blamed,
1254                                 struct blame_entry **toosmall,
1255                                 struct blame_origin *target,
1256                                 struct commit *parent,
1257                                 struct blame_origin *porigin,
1258                                 int opt)
1259 {
1260         struct diff_options diff_opts;
1261         int i, j;
1262         struct blame_list *blame_list;
1263         int num_ents;
1264         struct blame_entry *unblamed = target->suspects;
1265         struct blame_entry *leftover = NULL;
1266
1267         if (!unblamed)
1268                 return; /* nothing remains for this target */
1269
1270         repo_diff_setup(sb->repo, &diff_opts);
1271         diff_opts.flags.recursive = 1;
1272         diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1273
1274         diff_setup_done(&diff_opts);
1275
1276         /* Try "find copies harder" on new path if requested;
1277          * we do not want to use diffcore_rename() actually to
1278          * match things up; find_copies_harder is set only to
1279          * force diff_tree_oid() to feed all filepairs to diff_queue,
1280          * and this code needs to be after diff_setup_done(), which
1281          * usually makes find-copies-harder imply copy detection.
1282          */
1283         if ((opt & PICKAXE_BLAME_COPY_HARDEST)
1284             || ((opt & PICKAXE_BLAME_COPY_HARDER)
1285                 && (!porigin || strcmp(target->path, porigin->path))))
1286                 diff_opts.flags.find_copies_harder = 1;
1287
1288         if (is_null_oid(&target->commit->object.oid))
1289                 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
1290         else
1291                 diff_tree_oid(get_commit_tree_oid(parent),
1292                               get_commit_tree_oid(target->commit),
1293                               "", &diff_opts);
1294
1295         if (!diff_opts.flags.find_copies_harder)
1296                 diffcore_std(&diff_opts);
1297
1298         do {
1299                 struct blame_entry **unblamedtail = &unblamed;
1300                 blame_list = setup_blame_list(unblamed, &num_ents);
1301
1302                 for (i = 0; i < diff_queued_diff.nr; i++) {
1303                         struct diff_filepair *p = diff_queued_diff.queue[i];
1304                         struct blame_origin *norigin;
1305                         mmfile_t file_p;
1306                         struct blame_entry potential[3];
1307
1308                         if (!DIFF_FILE_VALID(p->one))
1309                                 continue; /* does not exist in parent */
1310                         if (S_ISGITLINK(p->one->mode))
1311                                 continue; /* ignore git links */
1312                         if (porigin && !strcmp(p->one->path, porigin->path))
1313                                 /* find_move already dealt with this path */
1314                                 continue;
1315
1316                         norigin = get_origin(parent, p->one->path);
1317                         oidcpy(&norigin->blob_oid, &p->one->oid);
1318                         norigin->mode = p->one->mode;
1319                         fill_origin_blob(&sb->revs->diffopt, norigin, &file_p, &sb->num_read_blob);
1320                         if (!file_p.ptr)
1321                                 continue;
1322
1323                         for (j = 0; j < num_ents; j++) {
1324                                 find_copy_in_blob(sb, blame_list[j].ent,
1325                                                   norigin, potential, &file_p);
1326                                 copy_split_if_better(sb, blame_list[j].split,
1327                                                      potential);
1328                                 decref_split(potential);
1329                         }
1330                         blame_origin_decref(norigin);
1331                 }
1332
1333                 for (j = 0; j < num_ents; j++) {
1334                         struct blame_entry *split = blame_list[j].split;
1335                         if (split[1].suspect &&
1336                             sb->copy_score < blame_entry_score(sb, &split[1])) {
1337                                 split_blame(blamed, &unblamedtail, split,
1338                                             blame_list[j].ent);
1339                         } else {
1340                                 blame_list[j].ent->next = leftover;
1341                                 leftover = blame_list[j].ent;
1342                         }
1343                         decref_split(split);
1344                 }
1345                 free(blame_list);
1346                 *unblamedtail = NULL;
1347                 toosmall = filter_small(sb, toosmall, &unblamed, sb->copy_score);
1348         } while (unblamed);
1349         target->suspects = reverse_blame(leftover, NULL);
1350         diff_flush(&diff_opts);
1351         clear_pathspec(&diff_opts.pathspec);
1352 }
1353
1354 /*
1355  * The blobs of origin and porigin exactly match, so everything
1356  * origin is suspected for can be blamed on the parent.
1357  */
1358 static void pass_whole_blame(struct blame_scoreboard *sb,
1359                              struct blame_origin *origin, struct blame_origin *porigin)
1360 {
1361         struct blame_entry *e, *suspects;
1362
1363         if (!porigin->file.ptr && origin->file.ptr) {
1364                 /* Steal its file */
1365                 porigin->file = origin->file;
1366                 origin->file.ptr = NULL;
1367         }
1368         suspects = origin->suspects;
1369         origin->suspects = NULL;
1370         for (e = suspects; e; e = e->next) {
1371                 blame_origin_incref(porigin);
1372                 blame_origin_decref(e->suspect);
1373                 e->suspect = porigin;
1374         }
1375         queue_blames(sb, porigin, suspects);
1376 }
1377
1378 /*
1379  * We pass blame from the current commit to its parents.  We keep saying
1380  * "parent" (and "porigin"), but what we mean is to find scapegoat to
1381  * exonerate ourselves.
1382  */
1383 static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit,
1384                                         int reverse)
1385 {
1386         if (!reverse) {
1387                 if (revs->first_parent_only &&
1388                     commit->parents &&
1389                     commit->parents->next) {
1390                         free_commit_list(commit->parents->next);
1391                         commit->parents->next = NULL;
1392                 }
1393                 return commit->parents;
1394         }
1395         return lookup_decoration(&revs->children, &commit->object);
1396 }
1397
1398 static int num_scapegoats(struct rev_info *revs, struct commit *commit, int reverse)
1399 {
1400         struct commit_list *l = first_scapegoat(revs, commit, reverse);
1401         return commit_list_count(l);
1402 }
1403
1404 /* Distribute collected unsorted blames to the respected sorted lists
1405  * in the various origins.
1406  */
1407 static void distribute_blame(struct blame_scoreboard *sb, struct blame_entry *blamed)
1408 {
1409         blamed = llist_mergesort(blamed, get_next_blame, set_next_blame,
1410                                  compare_blame_suspect);
1411         while (blamed)
1412         {
1413                 struct blame_origin *porigin = blamed->suspect;
1414                 struct blame_entry *suspects = NULL;
1415                 do {
1416                         struct blame_entry *next = blamed->next;
1417                         blamed->next = suspects;
1418                         suspects = blamed;
1419                         blamed = next;
1420                 } while (blamed && blamed->suspect == porigin);
1421                 suspects = reverse_blame(suspects, NULL);
1422                 queue_blames(sb, porigin, suspects);
1423         }
1424 }
1425
1426 #define MAXSG 16
1427
1428 static void pass_blame(struct blame_scoreboard *sb, struct blame_origin *origin, int opt)
1429 {
1430         struct rev_info *revs = sb->revs;
1431         int i, pass, num_sg;
1432         struct commit *commit = origin->commit;
1433         struct commit_list *sg;
1434         struct blame_origin *sg_buf[MAXSG];
1435         struct blame_origin *porigin, **sg_origin = sg_buf;
1436         struct blame_entry *toosmall = NULL;
1437         struct blame_entry *blames, **blametail = &blames;
1438
1439         num_sg = num_scapegoats(revs, commit, sb->reverse);
1440         if (!num_sg)
1441                 goto finish;
1442         else if (num_sg < ARRAY_SIZE(sg_buf))
1443                 memset(sg_buf, 0, sizeof(sg_buf));
1444         else
1445                 sg_origin = xcalloc(num_sg, sizeof(*sg_origin));
1446
1447         /*
1448          * The first pass looks for unrenamed path to optimize for
1449          * common cases, then we look for renames in the second pass.
1450          */
1451         for (pass = 0; pass < 2 - sb->no_whole_file_rename; pass++) {
1452                 struct blame_origin *(*find)(struct repository *, struct commit *, struct blame_origin *);
1453                 find = pass ? find_rename : find_origin;
1454
1455                 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
1456                      i < num_sg && sg;
1457                      sg = sg->next, i++) {
1458                         struct commit *p = sg->item;
1459                         int j, same;
1460
1461                         if (sg_origin[i])
1462                                 continue;
1463                         if (parse_commit(p))
1464                                 continue;
1465                         porigin = find(sb->repo, p, origin);
1466                         if (!porigin)
1467                                 continue;
1468                         if (oideq(&porigin->blob_oid, &origin->blob_oid)) {
1469                                 pass_whole_blame(sb, origin, porigin);
1470                                 blame_origin_decref(porigin);
1471                                 goto finish;
1472                         }
1473                         for (j = same = 0; j < i; j++)
1474                                 if (sg_origin[j] &&
1475                                     oideq(&sg_origin[j]->blob_oid, &porigin->blob_oid)) {
1476                                         same = 1;
1477                                         break;
1478                                 }
1479                         if (!same)
1480                                 sg_origin[i] = porigin;
1481                         else
1482                                 blame_origin_decref(porigin);
1483                 }
1484         }
1485
1486         sb->num_commits++;
1487         for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
1488              i < num_sg && sg;
1489              sg = sg->next, i++) {
1490                 struct blame_origin *porigin = sg_origin[i];
1491                 if (!porigin)
1492                         continue;
1493                 if (!origin->previous) {
1494                         blame_origin_incref(porigin);
1495                         origin->previous = porigin;
1496                 }
1497                 pass_blame_to_parent(sb, origin, porigin);
1498                 if (!origin->suspects)
1499                         goto finish;
1500         }
1501
1502         /*
1503          * Optionally find moves in parents' files.
1504          */
1505         if (opt & PICKAXE_BLAME_MOVE) {
1506                 filter_small(sb, &toosmall, &origin->suspects, sb->move_score);
1507                 if (origin->suspects) {
1508                         for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
1509                              i < num_sg && sg;
1510                              sg = sg->next, i++) {
1511                                 struct blame_origin *porigin = sg_origin[i];
1512                                 if (!porigin)
1513                                         continue;
1514                                 find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);
1515                                 if (!origin->suspects)
1516                                         break;
1517                         }
1518                 }
1519         }
1520
1521         /*
1522          * Optionally find copies from parents' files.
1523          */
1524         if (opt & PICKAXE_BLAME_COPY) {
1525                 if (sb->copy_score > sb->move_score)
1526                         filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);
1527                 else if (sb->copy_score < sb->move_score) {
1528                         origin->suspects = blame_merge(origin->suspects, toosmall);
1529                         toosmall = NULL;
1530                         filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);
1531                 }
1532                 if (!origin->suspects)
1533                         goto finish;
1534
1535                 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
1536                      i < num_sg && sg;
1537                      sg = sg->next, i++) {
1538                         struct blame_origin *porigin = sg_origin[i];
1539                         find_copy_in_parent(sb, &blametail, &toosmall,
1540                                             origin, sg->item, porigin, opt);
1541                         if (!origin->suspects)
1542                                 goto finish;
1543                 }
1544         }
1545
1546 finish:
1547         *blametail = NULL;
1548         distribute_blame(sb, blames);
1549         /*
1550          * prepend toosmall to origin->suspects
1551          *
1552          * There is no point in sorting: this ends up on a big
1553          * unsorted list in the caller anyway.
1554          */
1555         if (toosmall) {
1556                 struct blame_entry **tail = &toosmall;
1557                 while (*tail)
1558                         tail = &(*tail)->next;
1559                 *tail = origin->suspects;
1560                 origin->suspects = toosmall;
1561         }
1562         for (i = 0; i < num_sg; i++) {
1563                 if (sg_origin[i]) {
1564                         drop_origin_blob(sg_origin[i]);
1565                         blame_origin_decref(sg_origin[i]);
1566                 }
1567         }
1568         drop_origin_blob(origin);
1569         if (sg_buf != sg_origin)
1570                 free(sg_origin);
1571 }
1572
1573 /*
1574  * The main loop -- while we have blobs with lines whose true origin
1575  * is still unknown, pick one blob, and allow its lines to pass blames
1576  * to its parents. */
1577 void assign_blame(struct blame_scoreboard *sb, int opt)
1578 {
1579         struct rev_info *revs = sb->revs;
1580         struct commit *commit = prio_queue_get(&sb->commits);
1581
1582         while (commit) {
1583                 struct blame_entry *ent;
1584                 struct blame_origin *suspect = get_blame_suspects(commit);
1585
1586                 /* find one suspect to break down */
1587                 while (suspect && !suspect->suspects)
1588                         suspect = suspect->next;
1589
1590                 if (!suspect) {
1591                         commit = prio_queue_get(&sb->commits);
1592                         continue;
1593                 }
1594
1595                 assert(commit == suspect->commit);
1596
1597                 /*
1598                  * We will use this suspect later in the loop,
1599                  * so hold onto it in the meantime.
1600                  */
1601                 blame_origin_incref(suspect);
1602                 parse_commit(commit);
1603                 if (sb->reverse ||
1604                     (!(commit->object.flags & UNINTERESTING) &&
1605                      !(revs->max_age != -1 && commit->date < revs->max_age)))
1606                         pass_blame(sb, suspect, opt);
1607                 else {
1608                         commit->object.flags |= UNINTERESTING;
1609                         if (commit->object.parsed)
1610                                 mark_parents_uninteresting(commit);
1611                 }
1612                 /* treat root commit as boundary */
1613                 if (!commit->parents && !sb->show_root)
1614                         commit->object.flags |= UNINTERESTING;
1615
1616                 /* Take responsibility for the remaining entries */
1617                 ent = suspect->suspects;
1618                 if (ent) {
1619                         suspect->guilty = 1;
1620                         for (;;) {
1621                                 struct blame_entry *next = ent->next;
1622                                 if (sb->found_guilty_entry)
1623                                         sb->found_guilty_entry(ent, sb->found_guilty_entry_data);
1624                                 if (next) {
1625                                         ent = next;
1626                                         continue;
1627                                 }
1628                                 ent->next = sb->ent;
1629                                 sb->ent = suspect->suspects;
1630                                 suspect->suspects = NULL;
1631                                 break;
1632                         }
1633                 }
1634                 blame_origin_decref(suspect);
1635
1636                 if (sb->debug) /* sanity */
1637                         sanity_check_refcnt(sb);
1638         }
1639 }
1640
1641 static const char *get_next_line(const char *start, const char *end)
1642 {
1643         const char *nl = memchr(start, '\n', end - start);
1644         return nl ? nl + 1 : end;
1645 }
1646
1647 /*
1648  * To allow quick access to the contents of nth line in the
1649  * final image, prepare an index in the scoreboard.
1650  */
1651 static int prepare_lines(struct blame_scoreboard *sb)
1652 {
1653         const char *buf = sb->final_buf;
1654         unsigned long len = sb->final_buf_size;
1655         const char *end = buf + len;
1656         const char *p;
1657         int *lineno;
1658         int num = 0;
1659
1660         for (p = buf; p < end; p = get_next_line(p, end))
1661                 num++;
1662
1663         ALLOC_ARRAY(sb->lineno, num + 1);
1664         lineno = sb->lineno;
1665
1666         for (p = buf; p < end; p = get_next_line(p, end))
1667                 *lineno++ = p - buf;
1668
1669         *lineno = len;
1670
1671         sb->num_lines = num;
1672         return sb->num_lines;
1673 }
1674
1675 static struct commit *find_single_final(struct rev_info *revs,
1676                                         const char **name_p)
1677 {
1678         int i;
1679         struct commit *found = NULL;
1680         const char *name = NULL;
1681
1682         for (i = 0; i < revs->pending.nr; i++) {
1683                 struct object *obj = revs->pending.objects[i].item;
1684                 if (obj->flags & UNINTERESTING)
1685                         continue;
1686                 obj = deref_tag(revs->repo, obj, NULL, 0);
1687                 if (obj->type != OBJ_COMMIT)
1688                         die("Non commit %s?", revs->pending.objects[i].name);
1689                 if (found)
1690                         die("More than one commit to dig from %s and %s?",
1691                             revs->pending.objects[i].name, name);
1692                 found = (struct commit *)obj;
1693                 name = revs->pending.objects[i].name;
1694         }
1695         if (name_p)
1696                 *name_p = xstrdup_or_null(name);
1697         return found;
1698 }
1699
1700 static struct commit *dwim_reverse_initial(struct rev_info *revs,
1701                                            const char **name_p)
1702 {
1703         /*
1704          * DWIM "git blame --reverse ONE -- PATH" as
1705          * "git blame --reverse ONE..HEAD -- PATH" but only do so
1706          * when it makes sense.
1707          */
1708         struct object *obj;
1709         struct commit *head_commit;
1710         struct object_id head_oid;
1711
1712         if (revs->pending.nr != 1)
1713                 return NULL;
1714
1715         /* Is that sole rev a committish? */
1716         obj = revs->pending.objects[0].item;
1717         obj = deref_tag(revs->repo, obj, NULL, 0);
1718         if (obj->type != OBJ_COMMIT)
1719                 return NULL;
1720
1721         /* Do we have HEAD? */
1722         if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
1723                 return NULL;
1724         head_commit = lookup_commit_reference_gently(revs->repo,
1725                                                      &head_oid, 1);
1726         if (!head_commit)
1727                 return NULL;
1728
1729         /* Turn "ONE" into "ONE..HEAD" then */
1730         obj->flags |= UNINTERESTING;
1731         add_pending_object(revs, &head_commit->object, "HEAD");
1732
1733         if (name_p)
1734                 *name_p = revs->pending.objects[0].name;
1735         return (struct commit *)obj;
1736 }
1737
1738 static struct commit *find_single_initial(struct rev_info *revs,
1739                                           const char **name_p)
1740 {
1741         int i;
1742         struct commit *found = NULL;
1743         const char *name = NULL;
1744
1745         /*
1746          * There must be one and only one negative commit, and it must be
1747          * the boundary.
1748          */
1749         for (i = 0; i < revs->pending.nr; i++) {
1750                 struct object *obj = revs->pending.objects[i].item;
1751                 if (!(obj->flags & UNINTERESTING))
1752                         continue;
1753                 obj = deref_tag(revs->repo, obj, NULL, 0);
1754                 if (obj->type != OBJ_COMMIT)
1755                         die("Non commit %s?", revs->pending.objects[i].name);
1756                 if (found)
1757                         die("More than one commit to dig up from, %s and %s?",
1758                             revs->pending.objects[i].name, name);
1759                 found = (struct commit *) obj;
1760                 name = revs->pending.objects[i].name;
1761         }
1762
1763         if (!name)
1764                 found = dwim_reverse_initial(revs, &name);
1765         if (!name)
1766                 die("No commit to dig up from?");
1767
1768         if (name_p)
1769                 *name_p = xstrdup(name);
1770         return found;
1771 }
1772
1773 void init_scoreboard(struct blame_scoreboard *sb)
1774 {
1775         memset(sb, 0, sizeof(struct blame_scoreboard));
1776         sb->move_score = BLAME_DEFAULT_MOVE_SCORE;
1777         sb->copy_score = BLAME_DEFAULT_COPY_SCORE;
1778 }
1779
1780 void setup_scoreboard(struct blame_scoreboard *sb,
1781                       const char *path,
1782                       struct blame_origin **orig)
1783 {
1784         const char *final_commit_name = NULL;
1785         struct blame_origin *o;
1786         struct commit *final_commit = NULL;
1787         enum object_type type;
1788
1789         init_blame_suspects(&blame_suspects);
1790
1791         if (sb->reverse && sb->contents_from)
1792                 die(_("--contents and --reverse do not blend well."));
1793
1794         if (!sb->repo)
1795                 BUG("repo is NULL");
1796
1797         if (!sb->reverse) {
1798                 sb->final = find_single_final(sb->revs, &final_commit_name);
1799                 sb->commits.compare = compare_commits_by_commit_date;
1800         } else {
1801                 sb->final = find_single_initial(sb->revs, &final_commit_name);
1802                 sb->commits.compare = compare_commits_by_reverse_commit_date;
1803         }
1804
1805         if (sb->final && sb->contents_from)
1806                 die(_("cannot use --contents with final commit object name"));
1807
1808         if (sb->reverse && sb->revs->first_parent_only)
1809                 sb->revs->children.name = NULL;
1810
1811         if (!sb->final) {
1812                 /*
1813                  * "--not A B -- path" without anything positive;
1814                  * do not default to HEAD, but use the working tree
1815                  * or "--contents".
1816                  */
1817                 setup_work_tree();
1818                 sb->final = fake_working_tree_commit(sb->repo,
1819                                                      &sb->revs->diffopt,
1820                                                      path, sb->contents_from);
1821                 add_pending_object(sb->revs, &(sb->final->object), ":");
1822         }
1823
1824         if (sb->reverse && sb->revs->first_parent_only) {
1825                 final_commit = find_single_final(sb->revs, NULL);
1826                 if (!final_commit)
1827                         die(_("--reverse and --first-parent together require specified latest commit"));
1828         }
1829
1830         /*
1831          * If we have bottom, this will mark the ancestors of the
1832          * bottom commits we would reach while traversing as
1833          * uninteresting.
1834          */
1835         if (prepare_revision_walk(sb->revs))
1836                 die(_("revision walk setup failed"));
1837
1838         if (sb->reverse && sb->revs->first_parent_only) {
1839                 struct commit *c = final_commit;
1840
1841                 sb->revs->children.name = "children";
1842                 while (c->parents &&
1843                        !oideq(&c->object.oid, &sb->final->object.oid)) {
1844                         struct commit_list *l = xcalloc(1, sizeof(*l));
1845
1846                         l->item = c;
1847                         if (add_decoration(&sb->revs->children,
1848                                            &c->parents->item->object, l))
1849                                 BUG("not unique item in first-parent chain");
1850                         c = c->parents->item;
1851                 }
1852
1853                 if (!oideq(&c->object.oid, &sb->final->object.oid))
1854                         die(_("--reverse --first-parent together require range along first-parent chain"));
1855         }
1856
1857         if (is_null_oid(&sb->final->object.oid)) {
1858                 o = get_blame_suspects(sb->final);
1859                 sb->final_buf = xmemdupz(o->file.ptr, o->file.size);
1860                 sb->final_buf_size = o->file.size;
1861         }
1862         else {
1863                 o = get_origin(sb->final, path);
1864                 if (fill_blob_sha1_and_mode(sb->repo, o))
1865                         die(_("no such path %s in %s"), path, final_commit_name);
1866
1867                 if (sb->revs->diffopt.flags.allow_textconv &&
1868                     textconv_object(sb->repo, path, o->mode, &o->blob_oid, 1, (char **) &sb->final_buf,
1869                                     &sb->final_buf_size))
1870                         ;
1871                 else
1872                         sb->final_buf = read_object_file(&o->blob_oid, &type,
1873                                                          &sb->final_buf_size);
1874
1875                 if (!sb->final_buf)
1876                         die(_("cannot read blob %s for path %s"),
1877                             oid_to_hex(&o->blob_oid),
1878                             path);
1879         }
1880         sb->num_read_blob++;
1881         prepare_lines(sb);
1882
1883         if (orig)
1884                 *orig = o;
1885
1886         free((char *)final_commit_name);
1887 }
1888
1889
1890
1891 struct blame_entry *blame_entry_prepend(struct blame_entry *head,
1892                                         long start, long end,
1893                                         struct blame_origin *o)
1894 {
1895         struct blame_entry *new_head = xcalloc(1, sizeof(struct blame_entry));
1896         new_head->lno = start;
1897         new_head->num_lines = end - start;
1898         new_head->suspect = o;
1899         new_head->s_lno = start;
1900         new_head->next = head;
1901         blame_origin_incref(o);
1902         return new_head;
1903 }