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