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