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