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