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