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