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