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