grep.con commit fetch: use heap buffer to format reflog (1412f76)
   1#include "cache.h"
   2#include "grep.h"
   3#include "userdiff.h"
   4#include "xdiff-interface.h"
   5#include "diff.h"
   6#include "diffcore.h"
   7#include "commit.h"
   8#include "quote.h"
   9
  10static int grep_source_load(struct grep_source *gs);
  11static int grep_source_is_binary(struct grep_source *gs);
  12
  13static struct grep_opt grep_defaults;
  14
  15static void std_output(struct grep_opt *opt, const void *buf, size_t size)
  16{
  17        fwrite(buf, size, 1, stdout);
  18}
  19
  20/*
  21 * Initialize the grep_defaults template with hardcoded defaults.
  22 * We could let the compiler do this, but without C99 initializers
  23 * the code gets unwieldy and unreadable, so...
  24 */
  25void init_grep_defaults(void)
  26{
  27        struct grep_opt *opt = &grep_defaults;
  28        static int run_once;
  29
  30        if (run_once)
  31                return;
  32        run_once++;
  33
  34        memset(opt, 0, sizeof(*opt));
  35        opt->relative = 1;
  36        opt->pathname = 1;
  37        opt->regflags = REG_NEWLINE;
  38        opt->max_depth = -1;
  39        opt->pattern_type_option = GREP_PATTERN_TYPE_UNSPECIFIED;
  40        opt->extended_regexp_option = 0;
  41        color_set(opt->color_context, "");
  42        color_set(opt->color_filename, "");
  43        color_set(opt->color_function, "");
  44        color_set(opt->color_lineno, "");
  45        color_set(opt->color_match_context, GIT_COLOR_BOLD_RED);
  46        color_set(opt->color_match_selected, GIT_COLOR_BOLD_RED);
  47        color_set(opt->color_selected, "");
  48        color_set(opt->color_sep, GIT_COLOR_CYAN);
  49        opt->color = -1;
  50        opt->output = std_output;
  51}
  52
  53static int parse_pattern_type_arg(const char *opt, const char *arg)
  54{
  55        if (!strcmp(arg, "default"))
  56                return GREP_PATTERN_TYPE_UNSPECIFIED;
  57        else if (!strcmp(arg, "basic"))
  58                return GREP_PATTERN_TYPE_BRE;
  59        else if (!strcmp(arg, "extended"))
  60                return GREP_PATTERN_TYPE_ERE;
  61        else if (!strcmp(arg, "fixed"))
  62                return GREP_PATTERN_TYPE_FIXED;
  63        else if (!strcmp(arg, "perl"))
  64                return GREP_PATTERN_TYPE_PCRE;
  65        die("bad %s argument: %s", opt, arg);
  66}
  67
  68/*
  69 * Read the configuration file once and store it in
  70 * the grep_defaults template.
  71 */
  72int grep_config(const char *var, const char *value, void *cb)
  73{
  74        struct grep_opt *opt = &grep_defaults;
  75        char *color = NULL;
  76
  77        if (userdiff_config(var, value) < 0)
  78                return -1;
  79
  80        if (!strcmp(var, "grep.extendedregexp")) {
  81                if (git_config_bool(var, value))
  82                        opt->extended_regexp_option = 1;
  83                else
  84                        opt->extended_regexp_option = 0;
  85                return 0;
  86        }
  87
  88        if (!strcmp(var, "grep.patterntype")) {
  89                opt->pattern_type_option = parse_pattern_type_arg(var, value);
  90                return 0;
  91        }
  92
  93        if (!strcmp(var, "grep.linenumber")) {
  94                opt->linenum = git_config_bool(var, value);
  95                return 0;
  96        }
  97
  98        if (!strcmp(var, "grep.fullname")) {
  99                opt->relative = !git_config_bool(var, value);
 100                return 0;
 101        }
 102
 103        if (!strcmp(var, "color.grep"))
 104                opt->color = git_config_colorbool(var, value);
 105        else if (!strcmp(var, "color.grep.context"))
 106                color = opt->color_context;
 107        else if (!strcmp(var, "color.grep.filename"))
 108                color = opt->color_filename;
 109        else if (!strcmp(var, "color.grep.function"))
 110                color = opt->color_function;
 111        else if (!strcmp(var, "color.grep.linenumber"))
 112                color = opt->color_lineno;
 113        else if (!strcmp(var, "color.grep.matchcontext"))
 114                color = opt->color_match_context;
 115        else if (!strcmp(var, "color.grep.matchselected"))
 116                color = opt->color_match_selected;
 117        else if (!strcmp(var, "color.grep.selected"))
 118                color = opt->color_selected;
 119        else if (!strcmp(var, "color.grep.separator"))
 120                color = opt->color_sep;
 121        else if (!strcmp(var, "color.grep.match")) {
 122                int rc = 0;
 123                if (!value)
 124                        return config_error_nonbool(var);
 125                rc |= color_parse(value, opt->color_match_context);
 126                rc |= color_parse(value, opt->color_match_selected);
 127                return rc;
 128        }
 129
 130        if (color) {
 131                if (!value)
 132                        return config_error_nonbool(var);
 133                return color_parse(value, color);
 134        }
 135        return 0;
 136}
 137
 138/*
 139 * Initialize one instance of grep_opt and copy the
 140 * default values from the template we read the configuration
 141 * information in an earlier call to git_config(grep_config).
 142 */
 143void grep_init(struct grep_opt *opt, const char *prefix)
 144{
 145        struct grep_opt *def = &grep_defaults;
 146
 147        memset(opt, 0, sizeof(*opt));
 148        opt->prefix = prefix;
 149        opt->prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
 150        opt->pattern_tail = &opt->pattern_list;
 151        opt->header_tail = &opt->header_list;
 152
 153        opt->color = def->color;
 154        opt->extended_regexp_option = def->extended_regexp_option;
 155        opt->pattern_type_option = def->pattern_type_option;
 156        opt->linenum = def->linenum;
 157        opt->max_depth = def->max_depth;
 158        opt->pathname = def->pathname;
 159        opt->regflags = def->regflags;
 160        opt->relative = def->relative;
 161        opt->output = def->output;
 162
 163        color_set(opt->color_context, def->color_context);
 164        color_set(opt->color_filename, def->color_filename);
 165        color_set(opt->color_function, def->color_function);
 166        color_set(opt->color_lineno, def->color_lineno);
 167        color_set(opt->color_match_context, def->color_match_context);
 168        color_set(opt->color_match_selected, def->color_match_selected);
 169        color_set(opt->color_selected, def->color_selected);
 170        color_set(opt->color_sep, def->color_sep);
 171}
 172
 173static void grep_set_pattern_type_option(enum grep_pattern_type pattern_type, struct grep_opt *opt)
 174{
 175        switch (pattern_type) {
 176        case GREP_PATTERN_TYPE_UNSPECIFIED:
 177                /* fall through */
 178
 179        case GREP_PATTERN_TYPE_BRE:
 180                opt->fixed = 0;
 181                opt->pcre = 0;
 182                opt->regflags &= ~REG_EXTENDED;
 183                break;
 184
 185        case GREP_PATTERN_TYPE_ERE:
 186                opt->fixed = 0;
 187                opt->pcre = 0;
 188                opt->regflags |= REG_EXTENDED;
 189                break;
 190
 191        case GREP_PATTERN_TYPE_FIXED:
 192                opt->fixed = 1;
 193                opt->pcre = 0;
 194                opt->regflags &= ~REG_EXTENDED;
 195                break;
 196
 197        case GREP_PATTERN_TYPE_PCRE:
 198                opt->fixed = 0;
 199                opt->pcre = 1;
 200                opt->regflags &= ~REG_EXTENDED;
 201                break;
 202        }
 203}
 204
 205void grep_commit_pattern_type(enum grep_pattern_type pattern_type, struct grep_opt *opt)
 206{
 207        if (pattern_type != GREP_PATTERN_TYPE_UNSPECIFIED)
 208                grep_set_pattern_type_option(pattern_type, opt);
 209        else if (opt->pattern_type_option != GREP_PATTERN_TYPE_UNSPECIFIED)
 210                grep_set_pattern_type_option(opt->pattern_type_option, opt);
 211        else if (opt->extended_regexp_option)
 212                grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, opt);
 213}
 214
 215static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
 216                                        const char *origin, int no,
 217                                        enum grep_pat_token t,
 218                                        enum grep_header_field field)
 219{
 220        struct grep_pat *p = xcalloc(1, sizeof(*p));
 221        p->pattern = xmemdupz(pat, patlen);
 222        p->patternlen = patlen;
 223        p->origin = origin;
 224        p->no = no;
 225        p->token = t;
 226        p->field = field;
 227        return p;
 228}
 229
 230static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
 231{
 232        **tail = p;
 233        *tail = &p->next;
 234        p->next = NULL;
 235
 236        switch (p->token) {
 237        case GREP_PATTERN: /* atom */
 238        case GREP_PATTERN_HEAD:
 239        case GREP_PATTERN_BODY:
 240                for (;;) {
 241                        struct grep_pat *new_pat;
 242                        size_t len = 0;
 243                        char *cp = p->pattern + p->patternlen, *nl = NULL;
 244                        while (++len <= p->patternlen) {
 245                                if (*(--cp) == '\n') {
 246                                        nl = cp;
 247                                        break;
 248                                }
 249                        }
 250                        if (!nl)
 251                                break;
 252                        new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
 253                                                  p->no, p->token, p->field);
 254                        new_pat->next = p->next;
 255                        if (!p->next)
 256                                *tail = &new_pat->next;
 257                        p->next = new_pat;
 258                        *nl = '\0';
 259                        p->patternlen -= len;
 260                }
 261                break;
 262        default:
 263                break;
 264        }
 265}
 266
 267void append_header_grep_pattern(struct grep_opt *opt,
 268                                enum grep_header_field field, const char *pat)
 269{
 270        struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
 271                                             GREP_PATTERN_HEAD, field);
 272        if (field == GREP_HEADER_REFLOG)
 273                opt->use_reflog_filter = 1;
 274        do_append_grep_pat(&opt->header_tail, p);
 275}
 276
 277void append_grep_pattern(struct grep_opt *opt, const char *pat,
 278                         const char *origin, int no, enum grep_pat_token t)
 279{
 280        append_grep_pat(opt, pat, strlen(pat), origin, no, t);
 281}
 282
 283void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
 284                     const char *origin, int no, enum grep_pat_token t)
 285{
 286        struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
 287        do_append_grep_pat(&opt->pattern_tail, p);
 288}
 289
 290struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
 291{
 292        struct grep_pat *pat;
 293        struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
 294        *ret = *opt;
 295
 296        ret->pattern_list = NULL;
 297        ret->pattern_tail = &ret->pattern_list;
 298
 299        for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
 300        {
 301                if(pat->token == GREP_PATTERN_HEAD)
 302                        append_header_grep_pattern(ret, pat->field,
 303                                                   pat->pattern);
 304                else
 305                        append_grep_pat(ret, pat->pattern, pat->patternlen,
 306                                        pat->origin, pat->no, pat->token);
 307        }
 308
 309        return ret;
 310}
 311
 312static NORETURN void compile_regexp_failed(const struct grep_pat *p,
 313                const char *error)
 314{
 315        char where[1024];
 316
 317        if (p->no)
 318                xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
 319        else if (p->origin)
 320                xsnprintf(where, sizeof(where), "%s, ", p->origin);
 321        else
 322                where[0] = 0;
 323
 324        die("%s'%s': %s", where, p->pattern, error);
 325}
 326
 327#ifdef USE_LIBPCRE
 328static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
 329{
 330        const char *error;
 331        int erroffset;
 332        int options = PCRE_MULTILINE;
 333
 334        if (opt->ignore_case) {
 335                if (has_non_ascii(p->pattern))
 336                        p->pcre_tables = pcre_maketables();
 337                options |= PCRE_CASELESS;
 338        }
 339        if (is_utf8_locale() && has_non_ascii(p->pattern))
 340                options |= PCRE_UTF8;
 341
 342        p->pcre_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
 343                                      p->pcre_tables);
 344        if (!p->pcre_regexp)
 345                compile_regexp_failed(p, error);
 346
 347        p->pcre_extra_info = pcre_study(p->pcre_regexp, 0, &error);
 348        if (!p->pcre_extra_info && error)
 349                die("%s", error);
 350}
 351
 352static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
 353                regmatch_t *match, int eflags)
 354{
 355        int ovector[30], ret, flags = 0;
 356
 357        if (eflags & REG_NOTBOL)
 358                flags |= PCRE_NOTBOL;
 359
 360        ret = pcre_exec(p->pcre_regexp, p->pcre_extra_info, line, eol - line,
 361                        0, flags, ovector, ARRAY_SIZE(ovector));
 362        if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
 363                die("pcre_exec failed with error code %d", ret);
 364        if (ret > 0) {
 365                ret = 0;
 366                match->rm_so = ovector[0];
 367                match->rm_eo = ovector[1];
 368        }
 369
 370        return ret;
 371}
 372
 373static void free_pcre_regexp(struct grep_pat *p)
 374{
 375        pcre_free(p->pcre_regexp);
 376        pcre_free(p->pcre_extra_info);
 377        pcre_free((void *)p->pcre_tables);
 378}
 379#else /* !USE_LIBPCRE */
 380static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
 381{
 382        die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
 383}
 384
 385static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
 386                regmatch_t *match, int eflags)
 387{
 388        return 1;
 389}
 390
 391static void free_pcre_regexp(struct grep_pat *p)
 392{
 393}
 394#endif /* !USE_LIBPCRE */
 395
 396static int is_fixed(const char *s, size_t len)
 397{
 398        size_t i;
 399
 400        /* regcomp cannot accept patterns with NULs so we
 401         * consider any pattern containing a NUL fixed.
 402         */
 403        if (memchr(s, 0, len))
 404                return 1;
 405
 406        for (i = 0; i < len; i++) {
 407                if (is_regex_special(s[i]))
 408                        return 0;
 409        }
 410
 411        return 1;
 412}
 413
 414static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
 415{
 416        struct strbuf sb = STRBUF_INIT;
 417        int err;
 418        int regflags;
 419
 420        basic_regex_quote_buf(&sb, p->pattern);
 421        regflags = opt->regflags & ~REG_EXTENDED;
 422        if (opt->ignore_case)
 423                regflags |= REG_ICASE;
 424        err = regcomp(&p->regexp, sb.buf, regflags);
 425        if (opt->debug)
 426                fprintf(stderr, "fixed %s\n", sb.buf);
 427        strbuf_release(&sb);
 428        if (err) {
 429                char errbuf[1024];
 430                regerror(err, &p->regexp, errbuf, sizeof(errbuf));
 431                regfree(&p->regexp);
 432                compile_regexp_failed(p, errbuf);
 433        }
 434}
 435
 436static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
 437{
 438        int icase, ascii_only;
 439        int err;
 440
 441        p->word_regexp = opt->word_regexp;
 442        p->ignore_case = opt->ignore_case;
 443        icase          = opt->regflags & REG_ICASE || p->ignore_case;
 444        ascii_only     = !has_non_ascii(p->pattern);
 445
 446        /*
 447         * Even when -F (fixed) asks us to do a non-regexp search, we
 448         * may not be able to correctly case-fold when -i
 449         * (ignore-case) is asked (in which case, we'll synthesize a
 450         * regexp to match the pattern that matches regexp special
 451         * characters literally, while ignoring case differences).  On
 452         * the other hand, even without -F, if the pattern does not
 453         * have any regexp special characters and there is no need for
 454         * case-folding search, we can internally turn it into a
 455         * simple string match using kws.  p->fixed tells us if we
 456         * want to use kws.
 457         */
 458        if (opt->fixed || is_fixed(p->pattern, p->patternlen))
 459                p->fixed = !icase || ascii_only;
 460        else
 461                p->fixed = 0;
 462
 463        if (p->fixed) {
 464                p->kws = kwsalloc(icase ? tolower_trans_tbl : NULL);
 465                kwsincr(p->kws, p->pattern, p->patternlen);
 466                kwsprep(p->kws);
 467                return;
 468        } else if (opt->fixed) {
 469                /*
 470                 * We come here when the pattern has the non-ascii
 471                 * characters we cannot case-fold, and asked to
 472                 * ignore-case.
 473                 */
 474                compile_fixed_regexp(p, opt);
 475                return;
 476        }
 477
 478        if (opt->pcre) {
 479                compile_pcre_regexp(p, opt);
 480                return;
 481        }
 482
 483        err = regcomp(&p->regexp, p->pattern, opt->regflags);
 484        if (err) {
 485                char errbuf[1024];
 486                regerror(err, &p->regexp, errbuf, 1024);
 487                regfree(&p->regexp);
 488                compile_regexp_failed(p, errbuf);
 489        }
 490}
 491
 492static struct grep_expr *compile_pattern_or(struct grep_pat **);
 493static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
 494{
 495        struct grep_pat *p;
 496        struct grep_expr *x;
 497
 498        p = *list;
 499        if (!p)
 500                return NULL;
 501        switch (p->token) {
 502        case GREP_PATTERN: /* atom */
 503        case GREP_PATTERN_HEAD:
 504        case GREP_PATTERN_BODY:
 505                x = xcalloc(1, sizeof (struct grep_expr));
 506                x->node = GREP_NODE_ATOM;
 507                x->u.atom = p;
 508                *list = p->next;
 509                return x;
 510        case GREP_OPEN_PAREN:
 511                *list = p->next;
 512                x = compile_pattern_or(list);
 513                if (!*list || (*list)->token != GREP_CLOSE_PAREN)
 514                        die("unmatched parenthesis");
 515                *list = (*list)->next;
 516                return x;
 517        default:
 518                return NULL;
 519        }
 520}
 521
 522static struct grep_expr *compile_pattern_not(struct grep_pat **list)
 523{
 524        struct grep_pat *p;
 525        struct grep_expr *x;
 526
 527        p = *list;
 528        if (!p)
 529                return NULL;
 530        switch (p->token) {
 531        case GREP_NOT:
 532                if (!p->next)
 533                        die("--not not followed by pattern expression");
 534                *list = p->next;
 535                x = xcalloc(1, sizeof (struct grep_expr));
 536                x->node = GREP_NODE_NOT;
 537                x->u.unary = compile_pattern_not(list);
 538                if (!x->u.unary)
 539                        die("--not followed by non pattern expression");
 540                return x;
 541        default:
 542                return compile_pattern_atom(list);
 543        }
 544}
 545
 546static struct grep_expr *compile_pattern_and(struct grep_pat **list)
 547{
 548        struct grep_pat *p;
 549        struct grep_expr *x, *y, *z;
 550
 551        x = compile_pattern_not(list);
 552        p = *list;
 553        if (p && p->token == GREP_AND) {
 554                if (!p->next)
 555                        die("--and not followed by pattern expression");
 556                *list = p->next;
 557                y = compile_pattern_and(list);
 558                if (!y)
 559                        die("--and not followed by pattern expression");
 560                z = xcalloc(1, sizeof (struct grep_expr));
 561                z->node = GREP_NODE_AND;
 562                z->u.binary.left = x;
 563                z->u.binary.right = y;
 564                return z;
 565        }
 566        return x;
 567}
 568
 569static struct grep_expr *compile_pattern_or(struct grep_pat **list)
 570{
 571        struct grep_pat *p;
 572        struct grep_expr *x, *y, *z;
 573
 574        x = compile_pattern_and(list);
 575        p = *list;
 576        if (x && p && p->token != GREP_CLOSE_PAREN) {
 577                y = compile_pattern_or(list);
 578                if (!y)
 579                        die("not a pattern expression %s", p->pattern);
 580                z = xcalloc(1, sizeof (struct grep_expr));
 581                z->node = GREP_NODE_OR;
 582                z->u.binary.left = x;
 583                z->u.binary.right = y;
 584                return z;
 585        }
 586        return x;
 587}
 588
 589static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
 590{
 591        return compile_pattern_or(list);
 592}
 593
 594static void indent(int in)
 595{
 596        while (in-- > 0)
 597                fputc(' ', stderr);
 598}
 599
 600static void dump_grep_pat(struct grep_pat *p)
 601{
 602        switch (p->token) {
 603        case GREP_AND: fprintf(stderr, "*and*"); break;
 604        case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
 605        case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
 606        case GREP_NOT: fprintf(stderr, "*not*"); break;
 607        case GREP_OR: fprintf(stderr, "*or*"); break;
 608
 609        case GREP_PATTERN: fprintf(stderr, "pattern"); break;
 610        case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
 611        case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
 612        }
 613
 614        switch (p->token) {
 615        default: break;
 616        case GREP_PATTERN_HEAD:
 617                fprintf(stderr, "<head %d>", p->field); break;
 618        case GREP_PATTERN_BODY:
 619                fprintf(stderr, "<body>"); break;
 620        }
 621        switch (p->token) {
 622        default: break;
 623        case GREP_PATTERN_HEAD:
 624        case GREP_PATTERN_BODY:
 625        case GREP_PATTERN:
 626                fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
 627                break;
 628        }
 629        fputc('\n', stderr);
 630}
 631
 632static void dump_grep_expression_1(struct grep_expr *x, int in)
 633{
 634        indent(in);
 635        switch (x->node) {
 636        case GREP_NODE_TRUE:
 637                fprintf(stderr, "true\n");
 638                break;
 639        case GREP_NODE_ATOM:
 640                dump_grep_pat(x->u.atom);
 641                break;
 642        case GREP_NODE_NOT:
 643                fprintf(stderr, "(not\n");
 644                dump_grep_expression_1(x->u.unary, in+1);
 645                indent(in);
 646                fprintf(stderr, ")\n");
 647                break;
 648        case GREP_NODE_AND:
 649                fprintf(stderr, "(and\n");
 650                dump_grep_expression_1(x->u.binary.left, in+1);
 651                dump_grep_expression_1(x->u.binary.right, in+1);
 652                indent(in);
 653                fprintf(stderr, ")\n");
 654                break;
 655        case GREP_NODE_OR:
 656                fprintf(stderr, "(or\n");
 657                dump_grep_expression_1(x->u.binary.left, in+1);
 658                dump_grep_expression_1(x->u.binary.right, in+1);
 659                indent(in);
 660                fprintf(stderr, ")\n");
 661                break;
 662        }
 663}
 664
 665static void dump_grep_expression(struct grep_opt *opt)
 666{
 667        struct grep_expr *x = opt->pattern_expression;
 668
 669        if (opt->all_match)
 670                fprintf(stderr, "[all-match]\n");
 671        dump_grep_expression_1(x, 0);
 672        fflush(NULL);
 673}
 674
 675static struct grep_expr *grep_true_expr(void)
 676{
 677        struct grep_expr *z = xcalloc(1, sizeof(*z));
 678        z->node = GREP_NODE_TRUE;
 679        return z;
 680}
 681
 682static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
 683{
 684        struct grep_expr *z = xcalloc(1, sizeof(*z));
 685        z->node = GREP_NODE_OR;
 686        z->u.binary.left = left;
 687        z->u.binary.right = right;
 688        return z;
 689}
 690
 691static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
 692{
 693        struct grep_pat *p;
 694        struct grep_expr *header_expr;
 695        struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
 696        enum grep_header_field fld;
 697
 698        if (!opt->header_list)
 699                return NULL;
 700
 701        for (p = opt->header_list; p; p = p->next) {
 702                if (p->token != GREP_PATTERN_HEAD)
 703                        die("BUG: a non-header pattern in grep header list.");
 704                if (p->field < GREP_HEADER_FIELD_MIN ||
 705                    GREP_HEADER_FIELD_MAX <= p->field)
 706                        die("BUG: unknown header field %d", p->field);
 707                compile_regexp(p, opt);
 708        }
 709
 710        for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
 711                header_group[fld] = NULL;
 712
 713        for (p = opt->header_list; p; p = p->next) {
 714                struct grep_expr *h;
 715                struct grep_pat *pp = p;
 716
 717                h = compile_pattern_atom(&pp);
 718                if (!h || pp != p->next)
 719                        die("BUG: malformed header expr");
 720                if (!header_group[p->field]) {
 721                        header_group[p->field] = h;
 722                        continue;
 723                }
 724                header_group[p->field] = grep_or_expr(h, header_group[p->field]);
 725        }
 726
 727        header_expr = NULL;
 728
 729        for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
 730                if (!header_group[fld])
 731                        continue;
 732                if (!header_expr)
 733                        header_expr = grep_true_expr();
 734                header_expr = grep_or_expr(header_group[fld], header_expr);
 735        }
 736        return header_expr;
 737}
 738
 739static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
 740{
 741        struct grep_expr *z = x;
 742
 743        while (x) {
 744                assert(x->node == GREP_NODE_OR);
 745                if (x->u.binary.right &&
 746                    x->u.binary.right->node == GREP_NODE_TRUE) {
 747                        x->u.binary.right = y;
 748                        break;
 749                }
 750                x = x->u.binary.right;
 751        }
 752        return z;
 753}
 754
 755static void compile_grep_patterns_real(struct grep_opt *opt)
 756{
 757        struct grep_pat *p;
 758        struct grep_expr *header_expr = prep_header_patterns(opt);
 759
 760        for (p = opt->pattern_list; p; p = p->next) {
 761                switch (p->token) {
 762                case GREP_PATTERN: /* atom */
 763                case GREP_PATTERN_HEAD:
 764                case GREP_PATTERN_BODY:
 765                        compile_regexp(p, opt);
 766                        break;
 767                default:
 768                        opt->extended = 1;
 769                        break;
 770                }
 771        }
 772
 773        if (opt->all_match || header_expr)
 774                opt->extended = 1;
 775        else if (!opt->extended && !opt->debug)
 776                return;
 777
 778        p = opt->pattern_list;
 779        if (p)
 780                opt->pattern_expression = compile_pattern_expr(&p);
 781        if (p)
 782                die("incomplete pattern expression: %s", p->pattern);
 783
 784        if (!header_expr)
 785                return;
 786
 787        if (!opt->pattern_expression)
 788                opt->pattern_expression = header_expr;
 789        else if (opt->all_match)
 790                opt->pattern_expression = grep_splice_or(header_expr,
 791                                                         opt->pattern_expression);
 792        else
 793                opt->pattern_expression = grep_or_expr(opt->pattern_expression,
 794                                                       header_expr);
 795        opt->all_match = 1;
 796}
 797
 798void compile_grep_patterns(struct grep_opt *opt)
 799{
 800        compile_grep_patterns_real(opt);
 801        if (opt->debug)
 802                dump_grep_expression(opt);
 803}
 804
 805static void free_pattern_expr(struct grep_expr *x)
 806{
 807        switch (x->node) {
 808        case GREP_NODE_TRUE:
 809        case GREP_NODE_ATOM:
 810                break;
 811        case GREP_NODE_NOT:
 812                free_pattern_expr(x->u.unary);
 813                break;
 814        case GREP_NODE_AND:
 815        case GREP_NODE_OR:
 816                free_pattern_expr(x->u.binary.left);
 817                free_pattern_expr(x->u.binary.right);
 818                break;
 819        }
 820        free(x);
 821}
 822
 823void free_grep_patterns(struct grep_opt *opt)
 824{
 825        struct grep_pat *p, *n;
 826
 827        for (p = opt->pattern_list; p; p = n) {
 828                n = p->next;
 829                switch (p->token) {
 830                case GREP_PATTERN: /* atom */
 831                case GREP_PATTERN_HEAD:
 832                case GREP_PATTERN_BODY:
 833                        if (p->kws)
 834                                kwsfree(p->kws);
 835                        else if (p->pcre_regexp)
 836                                free_pcre_regexp(p);
 837                        else
 838                                regfree(&p->regexp);
 839                        free(p->pattern);
 840                        break;
 841                default:
 842                        break;
 843                }
 844                free(p);
 845        }
 846
 847        if (!opt->extended)
 848                return;
 849        free_pattern_expr(opt->pattern_expression);
 850}
 851
 852static char *end_of_line(char *cp, unsigned long *left)
 853{
 854        unsigned long l = *left;
 855        while (l && *cp != '\n') {
 856                l--;
 857                cp++;
 858        }
 859        *left = l;
 860        return cp;
 861}
 862
 863static int word_char(char ch)
 864{
 865        return isalnum(ch) || ch == '_';
 866}
 867
 868static void output_color(struct grep_opt *opt, const void *data, size_t size,
 869                         const char *color)
 870{
 871        if (want_color(opt->color) && color && color[0]) {
 872                opt->output(opt, color, strlen(color));
 873                opt->output(opt, data, size);
 874                opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
 875        } else
 876                opt->output(opt, data, size);
 877}
 878
 879static void output_sep(struct grep_opt *opt, char sign)
 880{
 881        if (opt->null_following_name)
 882                opt->output(opt, "\0", 1);
 883        else
 884                output_color(opt, &sign, 1, opt->color_sep);
 885}
 886
 887static void show_name(struct grep_opt *opt, const char *name)
 888{
 889        output_color(opt, name, strlen(name), opt->color_filename);
 890        opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
 891}
 892
 893static int fixmatch(struct grep_pat *p, char *line, char *eol,
 894                    regmatch_t *match)
 895{
 896        struct kwsmatch kwsm;
 897        size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
 898        if (offset == -1) {
 899                match->rm_so = match->rm_eo = -1;
 900                return REG_NOMATCH;
 901        } else {
 902                match->rm_so = offset;
 903                match->rm_eo = match->rm_so + kwsm.size[0];
 904                return 0;
 905        }
 906}
 907
 908static int patmatch(struct grep_pat *p, char *line, char *eol,
 909                    regmatch_t *match, int eflags)
 910{
 911        int hit;
 912
 913        if (p->fixed)
 914                hit = !fixmatch(p, line, eol, match);
 915        else if (p->pcre_regexp)
 916                hit = !pcrematch(p, line, eol, match, eflags);
 917        else
 918                hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
 919                                   eflags);
 920
 921        return hit;
 922}
 923
 924static int strip_timestamp(char *bol, char **eol_p)
 925{
 926        char *eol = *eol_p;
 927        int ch;
 928
 929        while (bol < --eol) {
 930                if (*eol != '>')
 931                        continue;
 932                *eol_p = ++eol;
 933                ch = *eol;
 934                *eol = '\0';
 935                return ch;
 936        }
 937        return 0;
 938}
 939
 940static struct {
 941        const char *field;
 942        size_t len;
 943} header_field[] = {
 944        { "author ", 7 },
 945        { "committer ", 10 },
 946        { "reflog ", 7 },
 947};
 948
 949static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
 950                             enum grep_context ctx,
 951                             regmatch_t *pmatch, int eflags)
 952{
 953        int hit = 0;
 954        int saved_ch = 0;
 955        const char *start = bol;
 956
 957        if ((p->token != GREP_PATTERN) &&
 958            ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
 959                return 0;
 960
 961        if (p->token == GREP_PATTERN_HEAD) {
 962                const char *field;
 963                size_t len;
 964                assert(p->field < ARRAY_SIZE(header_field));
 965                field = header_field[p->field].field;
 966                len = header_field[p->field].len;
 967                if (strncmp(bol, field, len))
 968                        return 0;
 969                bol += len;
 970                switch (p->field) {
 971                case GREP_HEADER_AUTHOR:
 972                case GREP_HEADER_COMMITTER:
 973                        saved_ch = strip_timestamp(bol, &eol);
 974                        break;
 975                default:
 976                        break;
 977                }
 978        }
 979
 980 again:
 981        hit = patmatch(p, bol, eol, pmatch, eflags);
 982
 983        if (hit && p->word_regexp) {
 984                if ((pmatch[0].rm_so < 0) ||
 985                    (eol - bol) < pmatch[0].rm_so ||
 986                    (pmatch[0].rm_eo < 0) ||
 987                    (eol - bol) < pmatch[0].rm_eo)
 988                        die("regexp returned nonsense");
 989
 990                /* Match beginning must be either beginning of the
 991                 * line, or at word boundary (i.e. the last char must
 992                 * not be a word char).  Similarly, match end must be
 993                 * either end of the line, or at word boundary
 994                 * (i.e. the next char must not be a word char).
 995                 */
 996                if ( ((pmatch[0].rm_so == 0) ||
 997                      !word_char(bol[pmatch[0].rm_so-1])) &&
 998                     ((pmatch[0].rm_eo == (eol-bol)) ||
 999                      !word_char(bol[pmatch[0].rm_eo])) )
1000                        ;
1001                else
1002                        hit = 0;
1003
1004                /* Words consist of at least one character. */
1005                if (pmatch->rm_so == pmatch->rm_eo)
1006                        hit = 0;
1007
1008                if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
1009                        /* There could be more than one match on the
1010                         * line, and the first match might not be
1011                         * strict word match.  But later ones could be!
1012                         * Forward to the next possible start, i.e. the
1013                         * next position following a non-word char.
1014                         */
1015                        bol = pmatch[0].rm_so + bol + 1;
1016                        while (word_char(bol[-1]) && bol < eol)
1017                                bol++;
1018                        eflags |= REG_NOTBOL;
1019                        if (bol < eol)
1020                                goto again;
1021                }
1022        }
1023        if (p->token == GREP_PATTERN_HEAD && saved_ch)
1024                *eol = saved_ch;
1025        if (hit) {
1026                pmatch[0].rm_so += bol - start;
1027                pmatch[0].rm_eo += bol - start;
1028        }
1029        return hit;
1030}
1031
1032static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
1033                           enum grep_context ctx, int collect_hits)
1034{
1035        int h = 0;
1036        regmatch_t match;
1037
1038        if (!x)
1039                die("Not a valid grep expression");
1040        switch (x->node) {
1041        case GREP_NODE_TRUE:
1042                h = 1;
1043                break;
1044        case GREP_NODE_ATOM:
1045                h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
1046                break;
1047        case GREP_NODE_NOT:
1048                h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
1049                break;
1050        case GREP_NODE_AND:
1051                if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
1052                        return 0;
1053                h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
1054                break;
1055        case GREP_NODE_OR:
1056                if (!collect_hits)
1057                        return (match_expr_eval(x->u.binary.left,
1058                                                bol, eol, ctx, 0) ||
1059                                match_expr_eval(x->u.binary.right,
1060                                                bol, eol, ctx, 0));
1061                h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
1062                x->u.binary.left->hit |= h;
1063                h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
1064                break;
1065        default:
1066                die("Unexpected node type (internal error) %d", x->node);
1067        }
1068        if (collect_hits)
1069                x->hit |= h;
1070        return h;
1071}
1072
1073static int match_expr(struct grep_opt *opt, char *bol, char *eol,
1074                      enum grep_context ctx, int collect_hits)
1075{
1076        struct grep_expr *x = opt->pattern_expression;
1077        return match_expr_eval(x, bol, eol, ctx, collect_hits);
1078}
1079
1080static int match_line(struct grep_opt *opt, char *bol, char *eol,
1081                      enum grep_context ctx, int collect_hits)
1082{
1083        struct grep_pat *p;
1084        regmatch_t match;
1085
1086        if (opt->extended)
1087                return match_expr(opt, bol, eol, ctx, collect_hits);
1088
1089        /* we do not call with collect_hits without being extended */
1090        for (p = opt->pattern_list; p; p = p->next) {
1091                if (match_one_pattern(p, bol, eol, ctx, &match, 0))
1092                        return 1;
1093        }
1094        return 0;
1095}
1096
1097static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
1098                              enum grep_context ctx,
1099                              regmatch_t *pmatch, int eflags)
1100{
1101        regmatch_t match;
1102
1103        if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
1104                return 0;
1105        if (match.rm_so < 0 || match.rm_eo < 0)
1106                return 0;
1107        if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1108                if (match.rm_so > pmatch->rm_so)
1109                        return 1;
1110                if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1111                        return 1;
1112        }
1113        pmatch->rm_so = match.rm_so;
1114        pmatch->rm_eo = match.rm_eo;
1115        return 1;
1116}
1117
1118static int next_match(struct grep_opt *opt, char *bol, char *eol,
1119                      enum grep_context ctx, regmatch_t *pmatch, int eflags)
1120{
1121        struct grep_pat *p;
1122        int hit = 0;
1123
1124        pmatch->rm_so = pmatch->rm_eo = -1;
1125        if (bol < eol) {
1126                for (p = opt->pattern_list; p; p = p->next) {
1127                        switch (p->token) {
1128                        case GREP_PATTERN: /* atom */
1129                        case GREP_PATTERN_HEAD:
1130                        case GREP_PATTERN_BODY:
1131                                hit |= match_next_pattern(p, bol, eol, ctx,
1132                                                          pmatch, eflags);
1133                                break;
1134                        default:
1135                                break;
1136                        }
1137                }
1138        }
1139        return hit;
1140}
1141
1142static void show_line(struct grep_opt *opt, char *bol, char *eol,
1143                      const char *name, unsigned lno, char sign)
1144{
1145        int rest = eol - bol;
1146        const char *match_color, *line_color = NULL;
1147
1148        if (opt->file_break && opt->last_shown == 0) {
1149                if (opt->show_hunk_mark)
1150                        opt->output(opt, "\n", 1);
1151        } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1152                if (opt->last_shown == 0) {
1153                        if (opt->show_hunk_mark) {
1154                                output_color(opt, "--", 2, opt->color_sep);
1155                                opt->output(opt, "\n", 1);
1156                        }
1157                } else if (lno > opt->last_shown + 1) {
1158                        output_color(opt, "--", 2, opt->color_sep);
1159                        opt->output(opt, "\n", 1);
1160                }
1161        }
1162        if (opt->heading && opt->last_shown == 0) {
1163                output_color(opt, name, strlen(name), opt->color_filename);
1164                opt->output(opt, "\n", 1);
1165        }
1166        opt->last_shown = lno;
1167
1168        if (!opt->heading && opt->pathname) {
1169                output_color(opt, name, strlen(name), opt->color_filename);
1170                output_sep(opt, sign);
1171        }
1172        if (opt->linenum) {
1173                char buf[32];
1174                snprintf(buf, sizeof(buf), "%d", lno);
1175                output_color(opt, buf, strlen(buf), opt->color_lineno);
1176                output_sep(opt, sign);
1177        }
1178        if (opt->color) {
1179                regmatch_t match;
1180                enum grep_context ctx = GREP_CONTEXT_BODY;
1181                int ch = *eol;
1182                int eflags = 0;
1183
1184                if (sign == ':')
1185                        match_color = opt->color_match_selected;
1186                else
1187                        match_color = opt->color_match_context;
1188                if (sign == ':')
1189                        line_color = opt->color_selected;
1190                else if (sign == '-')
1191                        line_color = opt->color_context;
1192                else if (sign == '=')
1193                        line_color = opt->color_function;
1194                *eol = '\0';
1195                while (next_match(opt, bol, eol, ctx, &match, eflags)) {
1196                        if (match.rm_so == match.rm_eo)
1197                                break;
1198
1199                        output_color(opt, bol, match.rm_so, line_color);
1200                        output_color(opt, bol + match.rm_so,
1201                                     match.rm_eo - match.rm_so, match_color);
1202                        bol += match.rm_eo;
1203                        rest -= match.rm_eo;
1204                        eflags = REG_NOTBOL;
1205                }
1206                *eol = ch;
1207        }
1208        output_color(opt, bol, rest, line_color);
1209        opt->output(opt, "\n", 1);
1210}
1211
1212#ifndef NO_PTHREADS
1213int grep_use_locks;
1214
1215/*
1216 * This lock protects access to the gitattributes machinery, which is
1217 * not thread-safe.
1218 */
1219pthread_mutex_t grep_attr_mutex;
1220
1221static inline void grep_attr_lock(void)
1222{
1223        if (grep_use_locks)
1224                pthread_mutex_lock(&grep_attr_mutex);
1225}
1226
1227static inline void grep_attr_unlock(void)
1228{
1229        if (grep_use_locks)
1230                pthread_mutex_unlock(&grep_attr_mutex);
1231}
1232
1233/*
1234 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
1235 */
1236pthread_mutex_t grep_read_mutex;
1237
1238#else
1239#define grep_attr_lock()
1240#define grep_attr_unlock()
1241#endif
1242
1243static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
1244{
1245        xdemitconf_t *xecfg = opt->priv;
1246        if (xecfg && !xecfg->find_func) {
1247                grep_source_load_driver(gs);
1248                if (gs->driver->funcname.pattern) {
1249                        const struct userdiff_funcname *pe = &gs->driver->funcname;
1250                        xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1251                } else {
1252                        xecfg = opt->priv = NULL;
1253                }
1254        }
1255
1256        if (xecfg) {
1257                char buf[1];
1258                return xecfg->find_func(bol, eol - bol, buf, 1,
1259                                        xecfg->find_func_priv) >= 0;
1260        }
1261
1262        if (bol == eol)
1263                return 0;
1264        if (isalpha(*bol) || *bol == '_' || *bol == '$')
1265                return 1;
1266        return 0;
1267}
1268
1269static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1270                               char *bol, unsigned lno)
1271{
1272        while (bol > gs->buf) {
1273                char *eol = --bol;
1274
1275                while (bol > gs->buf && bol[-1] != '\n')
1276                        bol--;
1277                lno--;
1278
1279                if (lno <= opt->last_shown)
1280                        break;
1281
1282                if (match_funcname(opt, gs, bol, eol)) {
1283                        show_line(opt, bol, eol, gs->name, lno, '=');
1284                        break;
1285                }
1286        }
1287}
1288
1289static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1290                             char *bol, char *end, unsigned lno)
1291{
1292        unsigned cur = lno, from = 1, funcname_lno = 0;
1293        int funcname_needed = !!opt->funcname;
1294
1295        if (opt->funcbody && !match_funcname(opt, gs, bol, end))
1296                funcname_needed = 2;
1297
1298        if (opt->pre_context < lno)
1299                from = lno - opt->pre_context;
1300        if (from <= opt->last_shown)
1301                from = opt->last_shown + 1;
1302
1303        /* Rewind. */
1304        while (bol > gs->buf &&
1305               cur > (funcname_needed == 2 ? opt->last_shown + 1 : from)) {
1306                char *eol = --bol;
1307
1308                while (bol > gs->buf && bol[-1] != '\n')
1309                        bol--;
1310                cur--;
1311                if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1312                        funcname_lno = cur;
1313                        funcname_needed = 0;
1314                }
1315        }
1316
1317        /* We need to look even further back to find a function signature. */
1318        if (opt->funcname && funcname_needed)
1319                show_funcname_line(opt, gs, bol, cur);
1320
1321        /* Back forward. */
1322        while (cur < lno) {
1323                char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1324
1325                while (*eol != '\n')
1326                        eol++;
1327                show_line(opt, bol, eol, gs->name, cur, sign);
1328                bol = eol + 1;
1329                cur++;
1330        }
1331}
1332
1333static int should_lookahead(struct grep_opt *opt)
1334{
1335        struct grep_pat *p;
1336
1337        if (opt->extended)
1338                return 0; /* punt for too complex stuff */
1339        if (opt->invert)
1340                return 0;
1341        for (p = opt->pattern_list; p; p = p->next) {
1342                if (p->token != GREP_PATTERN)
1343                        return 0; /* punt for "header only" and stuff */
1344        }
1345        return 1;
1346}
1347
1348static int look_ahead(struct grep_opt *opt,
1349                      unsigned long *left_p,
1350                      unsigned *lno_p,
1351                      char **bol_p)
1352{
1353        unsigned lno = *lno_p;
1354        char *bol = *bol_p;
1355        struct grep_pat *p;
1356        char *sp, *last_bol;
1357        regoff_t earliest = -1;
1358
1359        for (p = opt->pattern_list; p; p = p->next) {
1360                int hit;
1361                regmatch_t m;
1362
1363                hit = patmatch(p, bol, bol + *left_p, &m, 0);
1364                if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1365                        continue;
1366                if (earliest < 0 || m.rm_so < earliest)
1367                        earliest = m.rm_so;
1368        }
1369
1370        if (earliest < 0) {
1371                *bol_p = bol + *left_p;
1372                *left_p = 0;
1373                return 1;
1374        }
1375        for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1376                ; /* find the beginning of the line */
1377        last_bol = sp;
1378
1379        for (sp = bol; sp < last_bol; sp++) {
1380                if (*sp == '\n')
1381                        lno++;
1382        }
1383        *left_p -= last_bol - bol;
1384        *bol_p = last_bol;
1385        *lno_p = lno;
1386        return 0;
1387}
1388
1389static int fill_textconv_grep(struct userdiff_driver *driver,
1390                              struct grep_source *gs)
1391{
1392        struct diff_filespec *df;
1393        char *buf;
1394        size_t size;
1395
1396        if (!driver || !driver->textconv)
1397                return grep_source_load(gs);
1398
1399        /*
1400         * The textconv interface is intimately tied to diff_filespecs, so we
1401         * have to pretend to be one. If we could unify the grep_source
1402         * and diff_filespec structs, this mess could just go away.
1403         */
1404        df = alloc_filespec(gs->path);
1405        switch (gs->type) {
1406        case GREP_SOURCE_SHA1:
1407                fill_filespec(df, gs->identifier, 1, 0100644);
1408                break;
1409        case GREP_SOURCE_FILE:
1410                fill_filespec(df, null_sha1, 0, 0100644);
1411                break;
1412        default:
1413                die("BUG: attempt to textconv something without a path?");
1414        }
1415
1416        /*
1417         * fill_textconv is not remotely thread-safe; it may load objects
1418         * behind the scenes, and it modifies the global diff tempfile
1419         * structure.
1420         */
1421        grep_read_lock();
1422        size = fill_textconv(driver, df, &buf);
1423        grep_read_unlock();
1424        free_filespec(df);
1425
1426        /*
1427         * The normal fill_textconv usage by the diff machinery would just keep
1428         * the textconv'd buf separate from the diff_filespec. But much of the
1429         * grep code passes around a grep_source and assumes that its "buf"
1430         * pointer is the beginning of the thing we are searching. So let's
1431         * install our textconv'd version into the grep_source, taking care not
1432         * to leak any existing buffer.
1433         */
1434        grep_source_clear_data(gs);
1435        gs->buf = buf;
1436        gs->size = size;
1437
1438        return 0;
1439}
1440
1441static int is_empty_line(const char *bol, const char *eol)
1442{
1443        while (bol < eol && isspace(*bol))
1444                bol++;
1445        return bol == eol;
1446}
1447
1448static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1449{
1450        char *bol;
1451        char *peek_bol = NULL;
1452        unsigned long left;
1453        unsigned lno = 1;
1454        unsigned last_hit = 0;
1455        int binary_match_only = 0;
1456        unsigned count = 0;
1457        int try_lookahead = 0;
1458        int show_function = 0;
1459        struct userdiff_driver *textconv = NULL;
1460        enum grep_context ctx = GREP_CONTEXT_HEAD;
1461        xdemitconf_t xecfg;
1462
1463        if (!opt->output)
1464                opt->output = std_output;
1465
1466        if (opt->pre_context || opt->post_context || opt->file_break ||
1467            opt->funcbody) {
1468                /* Show hunk marks, except for the first file. */
1469                if (opt->last_shown)
1470                        opt->show_hunk_mark = 1;
1471                /*
1472                 * If we're using threads then we can't easily identify
1473                 * the first file.  Always put hunk marks in that case
1474                 * and skip the very first one later in work_done().
1475                 */
1476                if (opt->output != std_output)
1477                        opt->show_hunk_mark = 1;
1478        }
1479        opt->last_shown = 0;
1480
1481        if (opt->allow_textconv) {
1482                grep_source_load_driver(gs);
1483                /*
1484                 * We might set up the shared textconv cache data here, which
1485                 * is not thread-safe.
1486                 */
1487                grep_attr_lock();
1488                textconv = userdiff_get_textconv(gs->driver);
1489                grep_attr_unlock();
1490        }
1491
1492        /*
1493         * We know the result of a textconv is text, so we only have to care
1494         * about binary handling if we are not using it.
1495         */
1496        if (!textconv) {
1497                switch (opt->binary) {
1498                case GREP_BINARY_DEFAULT:
1499                        if (grep_source_is_binary(gs))
1500                                binary_match_only = 1;
1501                        break;
1502                case GREP_BINARY_NOMATCH:
1503                        if (grep_source_is_binary(gs))
1504                                return 0; /* Assume unmatch */
1505                        break;
1506                case GREP_BINARY_TEXT:
1507                        break;
1508                default:
1509                        die("BUG: unknown binary handling mode");
1510                }
1511        }
1512
1513        memset(&xecfg, 0, sizeof(xecfg));
1514        opt->priv = &xecfg;
1515
1516        try_lookahead = should_lookahead(opt);
1517
1518        if (fill_textconv_grep(textconv, gs) < 0)
1519                return 0;
1520
1521        bol = gs->buf;
1522        left = gs->size;
1523        while (left) {
1524                char *eol, ch;
1525                int hit;
1526
1527                /*
1528                 * look_ahead() skips quickly to the line that possibly
1529                 * has the next hit; don't call it if we need to do
1530                 * something more than just skipping the current line
1531                 * in response to an unmatch for the current line.  E.g.
1532                 * inside a post-context window, we will show the current
1533                 * line as a context around the previous hit when it
1534                 * doesn't hit.
1535                 */
1536                if (try_lookahead
1537                    && !(last_hit
1538                         && (show_function ||
1539                             lno <= last_hit + opt->post_context))
1540                    && look_ahead(opt, &left, &lno, &bol))
1541                        break;
1542                eol = end_of_line(bol, &left);
1543                ch = *eol;
1544                *eol = 0;
1545
1546                if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1547                        ctx = GREP_CONTEXT_BODY;
1548
1549                hit = match_line(opt, bol, eol, ctx, collect_hits);
1550                *eol = ch;
1551
1552                if (collect_hits)
1553                        goto next_line;
1554
1555                /* "grep -v -e foo -e bla" should list lines
1556                 * that do not have either, so inversion should
1557                 * be done outside.
1558                 */
1559                if (opt->invert)
1560                        hit = !hit;
1561                if (opt->unmatch_name_only) {
1562                        if (hit)
1563                                return 0;
1564                        goto next_line;
1565                }
1566                if (hit) {
1567                        count++;
1568                        if (opt->status_only)
1569                                return 1;
1570                        if (opt->name_only) {
1571                                show_name(opt, gs->name);
1572                                return 1;
1573                        }
1574                        if (opt->count)
1575                                goto next_line;
1576                        if (binary_match_only) {
1577                                opt->output(opt, "Binary file ", 12);
1578                                output_color(opt, gs->name, strlen(gs->name),
1579                                             opt->color_filename);
1580                                opt->output(opt, " matches\n", 9);
1581                                return 1;
1582                        }
1583                        /* Hit at this line.  If we haven't shown the
1584                         * pre-context lines, we would need to show them.
1585                         */
1586                        if (opt->pre_context || opt->funcbody)
1587                                show_pre_context(opt, gs, bol, eol, lno);
1588                        else if (opt->funcname)
1589                                show_funcname_line(opt, gs, bol, lno);
1590                        show_line(opt, bol, eol, gs->name, lno, ':');
1591                        last_hit = lno;
1592                        if (opt->funcbody)
1593                                show_function = 1;
1594                        goto next_line;
1595                }
1596                if (show_function && (!peek_bol || peek_bol < bol)) {
1597                        unsigned long peek_left = left;
1598                        char *peek_eol = eol;
1599
1600                        /*
1601                         * Trailing empty lines are not interesting.
1602                         * Peek past them to see if they belong to the
1603                         * body of the current function.
1604                         */
1605                        peek_bol = bol;
1606                        while (is_empty_line(peek_bol, peek_eol)) {
1607                                peek_bol = peek_eol + 1;
1608                                peek_eol = end_of_line(peek_bol, &peek_left);
1609                        }
1610
1611                        if (match_funcname(opt, gs, peek_bol, peek_eol))
1612                                show_function = 0;
1613                }
1614                if (show_function ||
1615                    (last_hit && lno <= last_hit + opt->post_context)) {
1616                        /* If the last hit is within the post context,
1617                         * we need to show this line.
1618                         */
1619                        show_line(opt, bol, eol, gs->name, lno, '-');
1620                }
1621
1622        next_line:
1623                bol = eol + 1;
1624                if (!left)
1625                        break;
1626                left--;
1627                lno++;
1628        }
1629
1630        if (collect_hits)
1631                return 0;
1632
1633        if (opt->status_only)
1634                return 0;
1635        if (opt->unmatch_name_only) {
1636                /* We did not see any hit, so we want to show this */
1637                show_name(opt, gs->name);
1638                return 1;
1639        }
1640
1641        xdiff_clear_find_func(&xecfg);
1642        opt->priv = NULL;
1643
1644        /* NEEDSWORK:
1645         * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1646         * which feels mostly useless but sometimes useful.  Maybe
1647         * make it another option?  For now suppress them.
1648         */
1649        if (opt->count && count) {
1650                char buf[32];
1651                if (opt->pathname) {
1652                        output_color(opt, gs->name, strlen(gs->name),
1653                                     opt->color_filename);
1654                        output_sep(opt, ':');
1655                }
1656                snprintf(buf, sizeof(buf), "%u\n", count);
1657                opt->output(opt, buf, strlen(buf));
1658                return 1;
1659        }
1660        return !!last_hit;
1661}
1662
1663static void clr_hit_marker(struct grep_expr *x)
1664{
1665        /* All-hit markers are meaningful only at the very top level
1666         * OR node.
1667         */
1668        while (1) {
1669                x->hit = 0;
1670                if (x->node != GREP_NODE_OR)
1671                        return;
1672                x->u.binary.left->hit = 0;
1673                x = x->u.binary.right;
1674        }
1675}
1676
1677static int chk_hit_marker(struct grep_expr *x)
1678{
1679        /* Top level nodes have hit markers.  See if they all are hits */
1680        while (1) {
1681                if (x->node != GREP_NODE_OR)
1682                        return x->hit;
1683                if (!x->u.binary.left->hit)
1684                        return 0;
1685                x = x->u.binary.right;
1686        }
1687}
1688
1689int grep_source(struct grep_opt *opt, struct grep_source *gs)
1690{
1691        /*
1692         * we do not have to do the two-pass grep when we do not check
1693         * buffer-wide "all-match".
1694         */
1695        if (!opt->all_match)
1696                return grep_source_1(opt, gs, 0);
1697
1698        /* Otherwise the toplevel "or" terms hit a bit differently.
1699         * We first clear hit markers from them.
1700         */
1701        clr_hit_marker(opt->pattern_expression);
1702        grep_source_1(opt, gs, 1);
1703
1704        if (!chk_hit_marker(opt->pattern_expression))
1705                return 0;
1706
1707        return grep_source_1(opt, gs, 0);
1708}
1709
1710int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
1711{
1712        struct grep_source gs;
1713        int r;
1714
1715        grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
1716        gs.buf = buf;
1717        gs.size = size;
1718
1719        r = grep_source(opt, &gs);
1720
1721        grep_source_clear(&gs);
1722        return r;
1723}
1724
1725void grep_source_init(struct grep_source *gs, enum grep_source_type type,
1726                      const char *name, const char *path,
1727                      const void *identifier)
1728{
1729        gs->type = type;
1730        gs->name = xstrdup_or_null(name);
1731        gs->path = xstrdup_or_null(path);
1732        gs->buf = NULL;
1733        gs->size = 0;
1734        gs->driver = NULL;
1735
1736        switch (type) {
1737        case GREP_SOURCE_FILE:
1738                gs->identifier = xstrdup(identifier);
1739                break;
1740        case GREP_SOURCE_SUBMODULE:
1741                if (!identifier) {
1742                        gs->identifier = NULL;
1743                        break;
1744                }
1745                /*
1746                 * FALL THROUGH
1747                 * If the identifier is non-NULL (in the submodule case) it
1748                 * will be a SHA1 that needs to be copied.
1749                 */
1750        case GREP_SOURCE_SHA1:
1751                gs->identifier = xmalloc(20);
1752                hashcpy(gs->identifier, identifier);
1753                break;
1754        case GREP_SOURCE_BUF:
1755                gs->identifier = NULL;
1756                break;
1757        }
1758}
1759
1760void grep_source_clear(struct grep_source *gs)
1761{
1762        free(gs->name);
1763        gs->name = NULL;
1764        free(gs->path);
1765        gs->path = NULL;
1766        free(gs->identifier);
1767        gs->identifier = NULL;
1768        grep_source_clear_data(gs);
1769}
1770
1771void grep_source_clear_data(struct grep_source *gs)
1772{
1773        switch (gs->type) {
1774        case GREP_SOURCE_FILE:
1775        case GREP_SOURCE_SHA1:
1776        case GREP_SOURCE_SUBMODULE:
1777                free(gs->buf);
1778                gs->buf = NULL;
1779                gs->size = 0;
1780                break;
1781        case GREP_SOURCE_BUF:
1782                /* leave user-provided buf intact */
1783                break;
1784        }
1785}
1786
1787static int grep_source_load_sha1(struct grep_source *gs)
1788{
1789        enum object_type type;
1790
1791        grep_read_lock();
1792        gs->buf = read_sha1_file(gs->identifier, &type, &gs->size);
1793        grep_read_unlock();
1794
1795        if (!gs->buf)
1796                return error(_("'%s': unable to read %s"),
1797                             gs->name,
1798                             sha1_to_hex(gs->identifier));
1799        return 0;
1800}
1801
1802static int grep_source_load_file(struct grep_source *gs)
1803{
1804        const char *filename = gs->identifier;
1805        struct stat st;
1806        char *data;
1807        size_t size;
1808        int i;
1809
1810        if (lstat(filename, &st) < 0) {
1811        err_ret:
1812                if (errno != ENOENT)
1813                        error_errno(_("failed to stat '%s'"), filename);
1814                return -1;
1815        }
1816        if (!S_ISREG(st.st_mode))
1817                return -1;
1818        size = xsize_t(st.st_size);
1819        i = open(filename, O_RDONLY);
1820        if (i < 0)
1821                goto err_ret;
1822        data = xmallocz(size);
1823        if (st.st_size != read_in_full(i, data, size)) {
1824                error_errno(_("'%s': short read"), filename);
1825                close(i);
1826                free(data);
1827                return -1;
1828        }
1829        close(i);
1830
1831        gs->buf = data;
1832        gs->size = size;
1833        return 0;
1834}
1835
1836static int grep_source_load(struct grep_source *gs)
1837{
1838        if (gs->buf)
1839                return 0;
1840
1841        switch (gs->type) {
1842        case GREP_SOURCE_FILE:
1843                return grep_source_load_file(gs);
1844        case GREP_SOURCE_SHA1:
1845                return grep_source_load_sha1(gs);
1846        case GREP_SOURCE_BUF:
1847                return gs->buf ? 0 : -1;
1848        case GREP_SOURCE_SUBMODULE:
1849                break;
1850        }
1851        die("BUG: invalid grep_source type to load");
1852}
1853
1854void grep_source_load_driver(struct grep_source *gs)
1855{
1856        if (gs->driver)
1857                return;
1858
1859        grep_attr_lock();
1860        if (gs->path)
1861                gs->driver = userdiff_find_by_path(gs->path);
1862        if (!gs->driver)
1863                gs->driver = userdiff_find_by_name("default");
1864        grep_attr_unlock();
1865}
1866
1867static int grep_source_is_binary(struct grep_source *gs)
1868{
1869        grep_source_load_driver(gs);
1870        if (gs->driver->binary != -1)
1871                return gs->driver->binary;
1872
1873        if (!grep_source_load(gs))
1874                return buffer_is_binary(gs->buf, gs->size);
1875
1876        return 0;
1877}