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