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