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