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