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