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