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