bisect.con commit pseudoref: check return values from read_ref() (2c3aed1)
   1#include "cache.h"
   2#include "commit.h"
   3#include "diff.h"
   4#include "revision.h"
   5#include "refs.h"
   6#include "list-objects.h"
   7#include "quote.h"
   8#include "sha1-lookup.h"
   9#include "run-command.h"
  10#include "log-tree.h"
  11#include "bisect.h"
  12#include "sha1-array.h"
  13#include "argv-array.h"
  14
  15static struct sha1_array good_revs;
  16static struct sha1_array skipped_revs;
  17
  18static struct object_id *current_bad_oid;
  19
  20static const char *argv_checkout[] = {"checkout", "-q", NULL, "--", NULL};
  21static const char *argv_show_branch[] = {"show-branch", NULL, NULL};
  22
  23/* Remember to update object flag allocation in object.h */
  24#define COUNTED         (1u<<16)
  25
  26/*
  27 * This is a truly stupid algorithm, but it's only
  28 * used for bisection, and we just don't care enough.
  29 *
  30 * We care just barely enough to avoid recursing for
  31 * non-merge entries.
  32 */
  33static int count_distance(struct commit_list *entry)
  34{
  35        int nr = 0;
  36
  37        while (entry) {
  38                struct commit *commit = entry->item;
  39                struct commit_list *p;
  40
  41                if (commit->object.flags & (UNINTERESTING | COUNTED))
  42                        break;
  43                if (!(commit->object.flags & TREESAME))
  44                        nr++;
  45                commit->object.flags |= COUNTED;
  46                p = commit->parents;
  47                entry = p;
  48                if (p) {
  49                        p = p->next;
  50                        while (p) {
  51                                nr += count_distance(p);
  52                                p = p->next;
  53                        }
  54                }
  55        }
  56
  57        return nr;
  58}
  59
  60static void clear_distance(struct commit_list *list)
  61{
  62        while (list) {
  63                struct commit *commit = list->item;
  64                commit->object.flags &= ~COUNTED;
  65                list = list->next;
  66        }
  67}
  68
  69#define DEBUG_BISECT 0
  70
  71static inline int weight(struct commit_list *elem)
  72{
  73        return *((int*)(elem->item->util));
  74}
  75
  76static inline void weight_set(struct commit_list *elem, int weight)
  77{
  78        *((int*)(elem->item->util)) = weight;
  79}
  80
  81static int count_interesting_parents(struct commit *commit)
  82{
  83        struct commit_list *p;
  84        int count;
  85
  86        for (count = 0, p = commit->parents; p; p = p->next) {
  87                if (p->item->object.flags & UNINTERESTING)
  88                        continue;
  89                count++;
  90        }
  91        return count;
  92}
  93
  94static inline int halfway(struct commit_list *p, int nr)
  95{
  96        /*
  97         * Don't short-cut something we are not going to return!
  98         */
  99        if (p->item->object.flags & TREESAME)
 100                return 0;
 101        if (DEBUG_BISECT)
 102                return 0;
 103        /*
 104         * 2 and 3 are halfway of 5.
 105         * 3 is halfway of 6 but 2 and 4 are not.
 106         */
 107        switch (2 * weight(p) - nr) {
 108        case -1: case 0: case 1:
 109                return 1;
 110        default:
 111                return 0;
 112        }
 113}
 114
 115#if !DEBUG_BISECT
 116#define show_list(a,b,c,d) do { ; } while (0)
 117#else
 118static void show_list(const char *debug, int counted, int nr,
 119                      struct commit_list *list)
 120{
 121        struct commit_list *p;
 122
 123        fprintf(stderr, "%s (%d/%d)\n", debug, counted, nr);
 124
 125        for (p = list; p; p = p->next) {
 126                struct commit_list *pp;
 127                struct commit *commit = p->item;
 128                unsigned flags = commit->object.flags;
 129                enum object_type type;
 130                unsigned long size;
 131                char *buf = read_sha1_file(commit->object.sha1, &type, &size);
 132                const char *subject_start;
 133                int subject_len;
 134
 135                fprintf(stderr, "%c%c%c ",
 136                        (flags & TREESAME) ? ' ' : 'T',
 137                        (flags & UNINTERESTING) ? 'U' : ' ',
 138                        (flags & COUNTED) ? 'C' : ' ');
 139                if (commit->util)
 140                        fprintf(stderr, "%3d", weight(p));
 141                else
 142                        fprintf(stderr, "---");
 143                fprintf(stderr, " %.*s", 8, sha1_to_hex(commit->object.sha1));
 144                for (pp = commit->parents; pp; pp = pp->next)
 145                        fprintf(stderr, " %.*s", 8,
 146                                sha1_to_hex(pp->item->object.sha1));
 147
 148                subject_len = find_commit_subject(buf, &subject_start);
 149                if (subject_len)
 150                        fprintf(stderr, " %.*s", subject_len, subject_start);
 151                fprintf(stderr, "\n");
 152        }
 153}
 154#endif /* DEBUG_BISECT */
 155
 156static struct commit_list *best_bisection(struct commit_list *list, int nr)
 157{
 158        struct commit_list *p, *best;
 159        int best_distance = -1;
 160
 161        best = list;
 162        for (p = list; p; p = p->next) {
 163                int distance;
 164                unsigned flags = p->item->object.flags;
 165
 166                if (flags & TREESAME)
 167                        continue;
 168                distance = weight(p);
 169                if (nr - distance < distance)
 170                        distance = nr - distance;
 171                if (distance > best_distance) {
 172                        best = p;
 173                        best_distance = distance;
 174                }
 175        }
 176
 177        return best;
 178}
 179
 180struct commit_dist {
 181        struct commit *commit;
 182        int distance;
 183};
 184
 185static int compare_commit_dist(const void *a_, const void *b_)
 186{
 187        struct commit_dist *a, *b;
 188
 189        a = (struct commit_dist *)a_;
 190        b = (struct commit_dist *)b_;
 191        if (a->distance != b->distance)
 192                return b->distance - a->distance; /* desc sort */
 193        return hashcmp(a->commit->object.sha1, b->commit->object.sha1);
 194}
 195
 196static struct commit_list *best_bisection_sorted(struct commit_list *list, int nr)
 197{
 198        struct commit_list *p;
 199        struct commit_dist *array = xcalloc(nr, sizeof(*array));
 200        int cnt, i;
 201
 202        for (p = list, cnt = 0; p; p = p->next) {
 203                int distance;
 204                unsigned flags = p->item->object.flags;
 205
 206                if (flags & TREESAME)
 207                        continue;
 208                distance = weight(p);
 209                if (nr - distance < distance)
 210                        distance = nr - distance;
 211                array[cnt].commit = p->item;
 212                array[cnt].distance = distance;
 213                cnt++;
 214        }
 215        qsort(array, cnt, sizeof(*array), compare_commit_dist);
 216        for (p = list, i = 0; i < cnt; i++) {
 217                char buf[100]; /* enough for dist=%d */
 218                struct object *obj = &(array[i].commit->object);
 219
 220                snprintf(buf, sizeof(buf), "dist=%d", array[i].distance);
 221                add_name_decoration(DECORATION_NONE, buf, obj);
 222
 223                p->item = array[i].commit;
 224                p = p->next;
 225        }
 226        if (p)
 227                p->next = NULL;
 228        free(array);
 229        return list;
 230}
 231
 232/*
 233 * zero or positive weight is the number of interesting commits it can
 234 * reach, including itself.  Especially, weight = 0 means it does not
 235 * reach any tree-changing commits (e.g. just above uninteresting one
 236 * but traversal is with pathspec).
 237 *
 238 * weight = -1 means it has one parent and its distance is yet to
 239 * be computed.
 240 *
 241 * weight = -2 means it has more than one parent and its distance is
 242 * unknown.  After running count_distance() first, they will get zero
 243 * or positive distance.
 244 */
 245static struct commit_list *do_find_bisection(struct commit_list *list,
 246                                             int nr, int *weights,
 247                                             int find_all)
 248{
 249        int n, counted;
 250        struct commit_list *p;
 251
 252        counted = 0;
 253
 254        for (n = 0, p = list; p; p = p->next) {
 255                struct commit *commit = p->item;
 256                unsigned flags = commit->object.flags;
 257
 258                p->item->util = &weights[n++];
 259                switch (count_interesting_parents(commit)) {
 260                case 0:
 261                        if (!(flags & TREESAME)) {
 262                                weight_set(p, 1);
 263                                counted++;
 264                                show_list("bisection 2 count one",
 265                                          counted, nr, list);
 266                        }
 267                        /*
 268                         * otherwise, it is known not to reach any
 269                         * tree-changing commit and gets weight 0.
 270                         */
 271                        break;
 272                case 1:
 273                        weight_set(p, -1);
 274                        break;
 275                default:
 276                        weight_set(p, -2);
 277                        break;
 278                }
 279        }
 280
 281        show_list("bisection 2 initialize", counted, nr, list);
 282
 283        /*
 284         * If you have only one parent in the resulting set
 285         * then you can reach one commit more than that parent
 286         * can reach.  So we do not have to run the expensive
 287         * count_distance() for single strand of pearls.
 288         *
 289         * However, if you have more than one parents, you cannot
 290         * just add their distance and one for yourself, since
 291         * they usually reach the same ancestor and you would
 292         * end up counting them twice that way.
 293         *
 294         * So we will first count distance of merges the usual
 295         * way, and then fill the blanks using cheaper algorithm.
 296         */
 297        for (p = list; p; p = p->next) {
 298                if (p->item->object.flags & UNINTERESTING)
 299                        continue;
 300                if (weight(p) != -2)
 301                        continue;
 302                weight_set(p, count_distance(p));
 303                clear_distance(list);
 304
 305                /* Does it happen to be at exactly half-way? */
 306                if (!find_all && halfway(p, nr))
 307                        return p;
 308                counted++;
 309        }
 310
 311        show_list("bisection 2 count_distance", counted, nr, list);
 312
 313        while (counted < nr) {
 314                for (p = list; p; p = p->next) {
 315                        struct commit_list *q;
 316                        unsigned flags = p->item->object.flags;
 317
 318                        if (0 <= weight(p))
 319                                continue;
 320                        for (q = p->item->parents; q; q = q->next) {
 321                                if (q->item->object.flags & UNINTERESTING)
 322                                        continue;
 323                                if (0 <= weight(q))
 324                                        break;
 325                        }
 326                        if (!q)
 327                                continue;
 328
 329                        /*
 330                         * weight for p is unknown but q is known.
 331                         * add one for p itself if p is to be counted,
 332                         * otherwise inherit it from q directly.
 333                         */
 334                        if (!(flags & TREESAME)) {
 335                                weight_set(p, weight(q)+1);
 336                                counted++;
 337                                show_list("bisection 2 count one",
 338                                          counted, nr, list);
 339                        }
 340                        else
 341                                weight_set(p, weight(q));
 342
 343                        /* Does it happen to be at exactly half-way? */
 344                        if (!find_all && halfway(p, nr))
 345                                return p;
 346                }
 347        }
 348
 349        show_list("bisection 2 counted all", counted, nr, list);
 350
 351        if (!find_all)
 352                return best_bisection(list, nr);
 353        else
 354                return best_bisection_sorted(list, nr);
 355}
 356
 357struct commit_list *find_bisection(struct commit_list *list,
 358                                          int *reaches, int *all,
 359                                          int find_all)
 360{
 361        int nr, on_list;
 362        struct commit_list *p, *best, *next, *last;
 363        int *weights;
 364
 365        show_list("bisection 2 entry", 0, 0, list);
 366
 367        /*
 368         * Count the number of total and tree-changing items on the
 369         * list, while reversing the list.
 370         */
 371        for (nr = on_list = 0, last = NULL, p = list;
 372             p;
 373             p = next) {
 374                unsigned flags = p->item->object.flags;
 375
 376                next = p->next;
 377                if (flags & UNINTERESTING)
 378                        continue;
 379                p->next = last;
 380                last = p;
 381                if (!(flags & TREESAME))
 382                        nr++;
 383                on_list++;
 384        }
 385        list = last;
 386        show_list("bisection 2 sorted", 0, nr, list);
 387
 388        *all = nr;
 389        weights = xcalloc(on_list, sizeof(*weights));
 390
 391        /* Do the real work of finding bisection commit. */
 392        best = do_find_bisection(list, nr, weights, find_all);
 393        if (best) {
 394                if (!find_all)
 395                        best->next = NULL;
 396                *reaches = weight(best);
 397        }
 398        free(weights);
 399        return best;
 400}
 401
 402static int register_ref(const char *refname, const struct object_id *oid,
 403                        int flags, void *cb_data)
 404{
 405        if (!strcmp(refname, "bad")) {
 406                current_bad_oid = xmalloc(sizeof(*current_bad_oid));
 407                oidcpy(current_bad_oid, oid);
 408        } else if (starts_with(refname, "good-")) {
 409                sha1_array_append(&good_revs, oid->hash);
 410        } else if (starts_with(refname, "skip-")) {
 411                sha1_array_append(&skipped_revs, oid->hash);
 412        }
 413
 414        return 0;
 415}
 416
 417static int read_bisect_refs(void)
 418{
 419        return for_each_ref_in("refs/bisect/", register_ref, NULL);
 420}
 421
 422static void read_bisect_paths(struct argv_array *array)
 423{
 424        struct strbuf str = STRBUF_INIT;
 425        const char *filename = git_path("BISECT_NAMES");
 426        FILE *fp = fopen(filename, "r");
 427
 428        if (!fp)
 429                die_errno("Could not open file '%s'", filename);
 430
 431        while (strbuf_getline(&str, fp, '\n') != EOF) {
 432                strbuf_trim(&str);
 433                if (sq_dequote_to_argv_array(str.buf, array))
 434                        die("Badly quoted content in file '%s': %s",
 435                            filename, str.buf);
 436        }
 437
 438        strbuf_release(&str);
 439        fclose(fp);
 440}
 441
 442static char *join_sha1_array_hex(struct sha1_array *array, char delim)
 443{
 444        struct strbuf joined_hexs = STRBUF_INIT;
 445        int i;
 446
 447        for (i = 0; i < array->nr; i++) {
 448                strbuf_addstr(&joined_hexs, sha1_to_hex(array->sha1[i]));
 449                if (i + 1 < array->nr)
 450                        strbuf_addch(&joined_hexs, delim);
 451        }
 452
 453        return strbuf_detach(&joined_hexs, NULL);
 454}
 455
 456/*
 457 * In this function, passing a not NULL skipped_first is very special.
 458 * It means that we want to know if the first commit in the list is
 459 * skipped because we will want to test a commit away from it if it is
 460 * indeed skipped.
 461 * So if the first commit is skipped, we cannot take the shortcut to
 462 * just "return list" when we find the first non skipped commit, we
 463 * have to return a fully filtered list.
 464 *
 465 * We use (*skipped_first == -1) to mean "it has been found that the
 466 * first commit is not skipped". In this case *skipped_first is set back
 467 * to 0 just before the function returns.
 468 */
 469struct commit_list *filter_skipped(struct commit_list *list,
 470                                   struct commit_list **tried,
 471                                   int show_all,
 472                                   int *count,
 473                                   int *skipped_first)
 474{
 475        struct commit_list *filtered = NULL, **f = &filtered;
 476
 477        *tried = NULL;
 478
 479        if (skipped_first)
 480                *skipped_first = 0;
 481        if (count)
 482                *count = 0;
 483
 484        if (!skipped_revs.nr)
 485                return list;
 486
 487        while (list) {
 488                struct commit_list *next = list->next;
 489                list->next = NULL;
 490                if (0 <= sha1_array_lookup(&skipped_revs,
 491                                           list->item->object.sha1)) {
 492                        if (skipped_first && !*skipped_first)
 493                                *skipped_first = 1;
 494                        /* Move current to tried list */
 495                        *tried = list;
 496                        tried = &list->next;
 497                } else {
 498                        if (!show_all) {
 499                                if (!skipped_first || !*skipped_first)
 500                                        return list;
 501                        } else if (skipped_first && !*skipped_first) {
 502                                /* This means we know it's not skipped */
 503                                *skipped_first = -1;
 504                        }
 505                        /* Move current to filtered list */
 506                        *f = list;
 507                        f = &list->next;
 508                        if (count)
 509                                (*count)++;
 510                }
 511                list = next;
 512        }
 513
 514        if (skipped_first && *skipped_first == -1)
 515                *skipped_first = 0;
 516
 517        return filtered;
 518}
 519
 520#define PRN_MODULO 32768
 521
 522/*
 523 * This is a pseudo random number generator based on "man 3 rand".
 524 * It is not used properly because the seed is the argument and it
 525 * is increased by one between each call, but that should not matter
 526 * for this application.
 527 */
 528static unsigned get_prn(unsigned count) {
 529        count = count * 1103515245 + 12345;
 530        return (count/65536) % PRN_MODULO;
 531}
 532
 533/*
 534 * Custom integer square root from
 535 * http://en.wikipedia.org/wiki/Integer_square_root
 536 */
 537static int sqrti(int val)
 538{
 539        float d, x = val;
 540
 541        if (val == 0)
 542                return 0;
 543
 544        do {
 545                float y = (x + (float)val / x) / 2;
 546                d = (y > x) ? y - x : x - y;
 547                x = y;
 548        } while (d >= 0.5);
 549
 550        return (int)x;
 551}
 552
 553static struct commit_list *skip_away(struct commit_list *list, int count)
 554{
 555        struct commit_list *cur, *previous;
 556        int prn, index, i;
 557
 558        prn = get_prn(count);
 559        index = (count * prn / PRN_MODULO) * sqrti(prn) / sqrti(PRN_MODULO);
 560
 561        cur = list;
 562        previous = NULL;
 563
 564        for (i = 0; cur; cur = cur->next, i++) {
 565                if (i == index) {
 566                        if (hashcmp(cur->item->object.sha1, current_bad_oid->hash))
 567                                return cur;
 568                        if (previous)
 569                                return previous;
 570                        return list;
 571                }
 572                previous = cur;
 573        }
 574
 575        return list;
 576}
 577
 578static struct commit_list *managed_skipped(struct commit_list *list,
 579                                           struct commit_list **tried)
 580{
 581        int count, skipped_first;
 582
 583        *tried = NULL;
 584
 585        if (!skipped_revs.nr)
 586                return list;
 587
 588        list = filter_skipped(list, tried, 0, &count, &skipped_first);
 589
 590        if (!skipped_first)
 591                return list;
 592
 593        return skip_away(list, count);
 594}
 595
 596static void bisect_rev_setup(struct rev_info *revs, const char *prefix,
 597                             const char *bad_format, const char *good_format,
 598                             int read_paths)
 599{
 600        struct argv_array rev_argv = ARGV_ARRAY_INIT;
 601        int i;
 602
 603        init_revisions(revs, prefix);
 604        revs->abbrev = 0;
 605        revs->commit_format = CMIT_FMT_UNSPECIFIED;
 606
 607        /* rev_argv.argv[0] will be ignored by setup_revisions */
 608        argv_array_push(&rev_argv, "bisect_rev_setup");
 609        argv_array_pushf(&rev_argv, bad_format, oid_to_hex(current_bad_oid));
 610        for (i = 0; i < good_revs.nr; i++)
 611                argv_array_pushf(&rev_argv, good_format,
 612                                 sha1_to_hex(good_revs.sha1[i]));
 613        argv_array_push(&rev_argv, "--");
 614        if (read_paths)
 615                read_bisect_paths(&rev_argv);
 616
 617        setup_revisions(rev_argv.argc, rev_argv.argv, revs, NULL);
 618        /* XXX leak rev_argv, as "revs" may still be pointing to it */
 619}
 620
 621static void bisect_common(struct rev_info *revs)
 622{
 623        if (prepare_revision_walk(revs))
 624                die("revision walk setup failed");
 625        if (revs->tree_objects)
 626                mark_edges_uninteresting(revs, NULL);
 627}
 628
 629static void exit_if_skipped_commits(struct commit_list *tried,
 630                                    const struct object_id *bad)
 631{
 632        if (!tried)
 633                return;
 634
 635        printf("There are only 'skip'ped commits left to test.\n"
 636               "The first bad commit could be any of:\n");
 637        print_commit_list(tried, "%s\n", "%s\n");
 638        if (bad)
 639                printf("%s\n", oid_to_hex(bad));
 640        printf("We cannot bisect more!\n");
 641        exit(2);
 642}
 643
 644static int is_expected_rev(const struct object_id *oid)
 645{
 646        const char *filename = git_path("BISECT_EXPECTED_REV");
 647        struct stat st;
 648        struct strbuf str = STRBUF_INIT;
 649        FILE *fp;
 650        int res = 0;
 651
 652        if (stat(filename, &st) || !S_ISREG(st.st_mode))
 653                return 0;
 654
 655        fp = fopen(filename, "r");
 656        if (!fp)
 657                return 0;
 658
 659        if (strbuf_getline(&str, fp, '\n') != EOF)
 660                res = !strcmp(str.buf, oid_to_hex(oid));
 661
 662        strbuf_release(&str);
 663        fclose(fp);
 664
 665        return res;
 666}
 667
 668static int bisect_checkout(const unsigned char *bisect_rev, int no_checkout)
 669{
 670        char bisect_rev_hex[GIT_SHA1_HEXSZ + 1];
 671
 672        memcpy(bisect_rev_hex, sha1_to_hex(bisect_rev), GIT_SHA1_HEXSZ + 1);
 673        update_ref(NULL, "BISECT_EXPECTED_REV", bisect_rev, NULL, 0, UPDATE_REFS_DIE_ON_ERR);
 674
 675        argv_checkout[2] = bisect_rev_hex;
 676        if (no_checkout) {
 677                update_ref(NULL, "BISECT_HEAD", bisect_rev, NULL, 0, UPDATE_REFS_DIE_ON_ERR);
 678        } else {
 679                int res;
 680                res = run_command_v_opt(argv_checkout, RUN_GIT_CMD);
 681                if (res)
 682                        exit(res);
 683        }
 684
 685        argv_show_branch[1] = bisect_rev_hex;
 686        return run_command_v_opt(argv_show_branch, RUN_GIT_CMD);
 687}
 688
 689static struct commit *get_commit_reference(const unsigned char *sha1)
 690{
 691        struct commit *r = lookup_commit_reference(sha1);
 692        if (!r)
 693                die("Not a valid commit name %s", sha1_to_hex(sha1));
 694        return r;
 695}
 696
 697static struct commit **get_bad_and_good_commits(int *rev_nr)
 698{
 699        int len = 1 + good_revs.nr;
 700        struct commit **rev = xmalloc(len * sizeof(*rev));
 701        int i, n = 0;
 702
 703        rev[n++] = get_commit_reference(current_bad_oid->hash);
 704        for (i = 0; i < good_revs.nr; i++)
 705                rev[n++] = get_commit_reference(good_revs.sha1[i]);
 706        *rev_nr = n;
 707
 708        return rev;
 709}
 710
 711static void handle_bad_merge_base(void)
 712{
 713        if (is_expected_rev(current_bad_oid)) {
 714                char *bad_hex = oid_to_hex(current_bad_oid);
 715                char *good_hex = join_sha1_array_hex(&good_revs, ' ');
 716
 717                fprintf(stderr, "The merge base %s is bad.\n"
 718                        "This means the bug has been fixed "
 719                        "between %s and [%s].\n",
 720                        bad_hex, bad_hex, good_hex);
 721
 722                exit(3);
 723        }
 724
 725        fprintf(stderr, "Some good revs are not ancestor of the bad rev.\n"
 726                "git bisect cannot work properly in this case.\n"
 727                "Maybe you mistake good and bad revs?\n");
 728        exit(1);
 729}
 730
 731static void handle_skipped_merge_base(const unsigned char *mb)
 732{
 733        char *mb_hex = sha1_to_hex(mb);
 734        char *bad_hex = sha1_to_hex(current_bad_oid->hash);
 735        char *good_hex = join_sha1_array_hex(&good_revs, ' ');
 736
 737        warning("the merge base between %s and [%s] "
 738                "must be skipped.\n"
 739                "So we cannot be sure the first bad commit is "
 740                "between %s and %s.\n"
 741                "We continue anyway.",
 742                bad_hex, good_hex, mb_hex, bad_hex);
 743        free(good_hex);
 744}
 745
 746/*
 747 * "check_merge_bases" checks that merge bases are not "bad".
 748 *
 749 * - If one is "bad", it means the user assumed something wrong
 750 * and we must exit with a non 0 error code.
 751 * - If one is "good", that's good, we have nothing to do.
 752 * - If one is "skipped", we can't know but we should warn.
 753 * - If we don't know, we should check it out and ask the user to test.
 754 */
 755static void check_merge_bases(int no_checkout)
 756{
 757        struct commit_list *result;
 758        int rev_nr;
 759        struct commit **rev = get_bad_and_good_commits(&rev_nr);
 760
 761        result = get_merge_bases_many(rev[0], rev_nr - 1, rev + 1);
 762
 763        for (; result; result = result->next) {
 764                const unsigned char *mb = result->item->object.sha1;
 765                if (!hashcmp(mb, current_bad_oid->hash)) {
 766                        handle_bad_merge_base();
 767                } else if (0 <= sha1_array_lookup(&good_revs, mb)) {
 768                        continue;
 769                } else if (0 <= sha1_array_lookup(&skipped_revs, mb)) {
 770                        handle_skipped_merge_base(mb);
 771                } else {
 772                        printf("Bisecting: a merge base must be tested\n");
 773                        exit(bisect_checkout(mb, no_checkout));
 774                }
 775        }
 776
 777        free(rev);
 778        free_commit_list(result);
 779}
 780
 781static int check_ancestors(const char *prefix)
 782{
 783        struct rev_info revs;
 784        struct object_array pending_copy;
 785        int res;
 786
 787        bisect_rev_setup(&revs, prefix, "^%s", "%s", 0);
 788
 789        /* Save pending objects, so they can be cleaned up later. */
 790        pending_copy = revs.pending;
 791        revs.leak_pending = 1;
 792
 793        /*
 794         * bisect_common calls prepare_revision_walk right away, which
 795         * (together with .leak_pending = 1) makes us the sole owner of
 796         * the list of pending objects.
 797         */
 798        bisect_common(&revs);
 799        res = (revs.commits != NULL);
 800
 801        /* Clean up objects used, as they will be reused. */
 802        clear_commit_marks_for_object_array(&pending_copy, ALL_REV_FLAGS);
 803        free(pending_copy.objects);
 804
 805        return res;
 806}
 807
 808/*
 809 * "check_good_are_ancestors_of_bad" checks that all "good" revs are
 810 * ancestor of the "bad" rev.
 811 *
 812 * If that's not the case, we need to check the merge bases.
 813 * If a merge base must be tested by the user, its source code will be
 814 * checked out to be tested by the user and we will exit.
 815 */
 816static void check_good_are_ancestors_of_bad(const char *prefix, int no_checkout)
 817{
 818        char *filename = git_pathdup("BISECT_ANCESTORS_OK");
 819        struct stat st;
 820        int fd;
 821
 822        if (!current_bad_oid)
 823                die("a bad revision is needed");
 824
 825        /* Check if file BISECT_ANCESTORS_OK exists. */
 826        if (!stat(filename, &st) && S_ISREG(st.st_mode))
 827                goto done;
 828
 829        /* Bisecting with no good rev is ok. */
 830        if (good_revs.nr == 0)
 831                goto done;
 832
 833        /* Check if all good revs are ancestor of the bad rev. */
 834        if (check_ancestors(prefix))
 835                check_merge_bases(no_checkout);
 836
 837        /* Create file BISECT_ANCESTORS_OK. */
 838        fd = open(filename, O_CREAT | O_TRUNC | O_WRONLY, 0600);
 839        if (fd < 0)
 840                warning("could not create file '%s': %s",
 841                        filename, strerror(errno));
 842        else
 843                close(fd);
 844 done:
 845        free(filename);
 846}
 847
 848/*
 849 * This does "git diff-tree --pretty COMMIT" without one fork+exec.
 850 */
 851static void show_diff_tree(const char *prefix, struct commit *commit)
 852{
 853        struct rev_info opt;
 854
 855        /* diff-tree init */
 856        init_revisions(&opt, prefix);
 857        git_config(git_diff_basic_config, NULL); /* no "diff" UI options */
 858        opt.abbrev = 0;
 859        opt.diff = 1;
 860
 861        /* This is what "--pretty" does */
 862        opt.verbose_header = 1;
 863        opt.use_terminator = 0;
 864        opt.commit_format = CMIT_FMT_DEFAULT;
 865
 866        /* diff-tree init */
 867        if (!opt.diffopt.output_format)
 868                opt.diffopt.output_format = DIFF_FORMAT_RAW;
 869
 870        log_tree_commit(&opt, commit);
 871}
 872
 873/*
 874 * We use the convention that exiting with an exit code 10 means that
 875 * the bisection process finished successfully.
 876 * In this case the calling shell script should exit 0.
 877 *
 878 * If no_checkout is non-zero, the bisection process does not
 879 * checkout the trial commit but instead simply updates BISECT_HEAD.
 880 */
 881int bisect_next_all(const char *prefix, int no_checkout)
 882{
 883        struct rev_info revs;
 884        struct commit_list *tried;
 885        int reaches = 0, all = 0, nr, steps;
 886        const unsigned char *bisect_rev;
 887
 888        if (read_bisect_refs())
 889                die("reading bisect refs failed");
 890
 891        check_good_are_ancestors_of_bad(prefix, no_checkout);
 892
 893        bisect_rev_setup(&revs, prefix, "%s", "^%s", 1);
 894        revs.limited = 1;
 895
 896        bisect_common(&revs);
 897
 898        revs.commits = find_bisection(revs.commits, &reaches, &all,
 899                                       !!skipped_revs.nr);
 900        revs.commits = managed_skipped(revs.commits, &tried);
 901
 902        if (!revs.commits) {
 903                /*
 904                 * We should exit here only if the "bad"
 905                 * commit is also a "skip" commit.
 906                 */
 907                exit_if_skipped_commits(tried, NULL);
 908
 909                printf("%s was both good and bad\n",
 910                       oid_to_hex(current_bad_oid));
 911                exit(1);
 912        }
 913
 914        if (!all) {
 915                fprintf(stderr, "No testable commit found.\n"
 916                        "Maybe you started with bad path parameters?\n");
 917                exit(4);
 918        }
 919
 920        bisect_rev = revs.commits->item->object.sha1;
 921
 922        if (!hashcmp(bisect_rev, current_bad_oid->hash)) {
 923                exit_if_skipped_commits(tried, current_bad_oid);
 924                printf("%s is the first bad commit\n", sha1_to_hex(bisect_rev));
 925                show_diff_tree(prefix, revs.commits->item);
 926                /* This means the bisection process succeeded. */
 927                exit(10);
 928        }
 929
 930        nr = all - reaches - 1;
 931        steps = estimate_bisect_steps(all);
 932        printf("Bisecting: %d revision%s left to test after this "
 933               "(roughly %d step%s)\n", nr, (nr == 1 ? "" : "s"),
 934               steps, (steps == 1 ? "" : "s"));
 935
 936        return bisect_checkout(bisect_rev, no_checkout);
 937}
 938
 939static inline int log2i(int n)
 940{
 941        int log2 = 0;
 942
 943        for (; n > 1; n >>= 1)
 944                log2++;
 945
 946        return log2;
 947}
 948
 949static inline int exp2i(int n)
 950{
 951        return 1 << n;
 952}
 953
 954/*
 955 * Estimate the number of bisect steps left (after the current step)
 956 *
 957 * For any x between 0 included and 2^n excluded, the probability for
 958 * n - 1 steps left looks like:
 959 *
 960 * P(2^n + x) == (2^n - x) / (2^n + x)
 961 *
 962 * and P(2^n + x) < 0.5 means 2^n < 3x
 963 */
 964int estimate_bisect_steps(int all)
 965{
 966        int n, x, e;
 967
 968        if (all < 3)
 969                return 0;
 970
 971        n = log2i(all);
 972        e = exp2i(n);
 973        x = all - e;
 974
 975        return (e < 3 * x) ? n : n - 1;
 976}