]> git.ipfire.org Git - thirdparty/git.git/blame - grep.c
gettext: add is_utf8_locale()
[thirdparty/git.git] / grep.c
CommitLineData
83b5d2f5 1#include "cache.h"
83b5d2f5 2#include "grep.h"
60ecac98 3#include "userdiff.h"
6bfce93e 4#include "xdiff-interface.h"
335ec3bf
JK
5#include "diff.h"
6#include "diffcore.h"
5c1ebcca 7#include "commit.h"
793dc676 8#include "quote.h"
83b5d2f5 9
07a7d656
JH
10static int grep_source_load(struct grep_source *gs);
11static int grep_source_is_binary(struct grep_source *gs);
12
7687a054
JH
13static struct grep_opt grep_defaults;
14
15/*
16 * Initialize the grep_defaults template with hardcoded defaults.
17 * We could let the compiler do this, but without C99 initializers
18 * the code gets unwieldy and unreadable, so...
19 */
20void init_grep_defaults(void)
21{
22 struct grep_opt *opt = &grep_defaults;
918d4e1c
JH
23 static int run_once;
24
25 if (run_once)
26 return;
27 run_once++;
7687a054
JH
28
29 memset(opt, 0, sizeof(*opt));
30 opt->relative = 1;
31 opt->pathname = 1;
32 opt->regflags = REG_NEWLINE;
33 opt->max_depth = -1;
34 opt->pattern_type_option = GREP_PATTERN_TYPE_UNSPECIFIED;
35 opt->extended_regexp_option = 0;
7ce4fb94
JK
36 color_set(opt->color_context, "");
37 color_set(opt->color_filename, "");
38 color_set(opt->color_function, "");
39 color_set(opt->color_lineno, "");
40 color_set(opt->color_match_context, GIT_COLOR_BOLD_RED);
41 color_set(opt->color_match_selected, GIT_COLOR_BOLD_RED);
42 color_set(opt->color_selected, "");
43 color_set(opt->color_sep, GIT_COLOR_CYAN);
7687a054
JH
44 opt->color = -1;
45}
46
47static int parse_pattern_type_arg(const char *opt, const char *arg)
48{
49 if (!strcmp(arg, "default"))
50 return GREP_PATTERN_TYPE_UNSPECIFIED;
51 else if (!strcmp(arg, "basic"))
52 return GREP_PATTERN_TYPE_BRE;
53 else if (!strcmp(arg, "extended"))
54 return GREP_PATTERN_TYPE_ERE;
55 else if (!strcmp(arg, "fixed"))
56 return GREP_PATTERN_TYPE_FIXED;
57 else if (!strcmp(arg, "perl"))
58 return GREP_PATTERN_TYPE_PCRE;
59 die("bad %s argument: %s", opt, arg);
60}
61
62/*
63 * Read the configuration file once and store it in
64 * the grep_defaults template.
65 */
66int grep_config(const char *var, const char *value, void *cb)
67{
68 struct grep_opt *opt = &grep_defaults;
69 char *color = NULL;
70
71 if (userdiff_config(var, value) < 0)
72 return -1;
73
74 if (!strcmp(var, "grep.extendedregexp")) {
75 if (git_config_bool(var, value))
76 opt->extended_regexp_option = 1;
77 else
78 opt->extended_regexp_option = 0;
79 return 0;
80 }
81
82 if (!strcmp(var, "grep.patterntype")) {
83 opt->pattern_type_option = parse_pattern_type_arg(var, value);
84 return 0;
85 }
86
87 if (!strcmp(var, "grep.linenumber")) {
88 opt->linenum = git_config_bool(var, value);
89 return 0;
90 }
91
6453f7b3
AS
92 if (!strcmp(var, "grep.fullname")) {
93 opt->relative = !git_config_bool(var, value);
94 return 0;
95 }
96
7687a054
JH
97 if (!strcmp(var, "color.grep"))
98 opt->color = git_config_colorbool(var, value);
99 else if (!strcmp(var, "color.grep.context"))
100 color = opt->color_context;
101 else if (!strcmp(var, "color.grep.filename"))
102 color = opt->color_filename;
103 else if (!strcmp(var, "color.grep.function"))
104 color = opt->color_function;
105 else if (!strcmp(var, "color.grep.linenumber"))
106 color = opt->color_lineno;
79a77109
RS
107 else if (!strcmp(var, "color.grep.matchcontext"))
108 color = opt->color_match_context;
109 else if (!strcmp(var, "color.grep.matchselected"))
110 color = opt->color_match_selected;
7687a054
JH
111 else if (!strcmp(var, "color.grep.selected"))
112 color = opt->color_selected;
113 else if (!strcmp(var, "color.grep.separator"))
114 color = opt->color_sep;
79a77109
RS
115 else if (!strcmp(var, "color.grep.match")) {
116 int rc = 0;
117 if (!value)
118 return config_error_nonbool(var);
bf1f639e
JH
119 rc |= color_parse(value, opt->color_match_context);
120 rc |= color_parse(value, opt->color_match_selected);
79a77109
RS
121 return rc;
122 }
7687a054
JH
123
124 if (color) {
125 if (!value)
126 return config_error_nonbool(var);
f6c5a296 127 return color_parse(value, color);
7687a054
JH
128 }
129 return 0;
130}
131
132/*
133 * Initialize one instance of grep_opt and copy the
134 * default values from the template we read the configuration
135 * information in an earlier call to git_config(grep_config).
136 */
137void grep_init(struct grep_opt *opt, const char *prefix)
138{
139 struct grep_opt *def = &grep_defaults;
140
141 memset(opt, 0, sizeof(*opt));
142 opt->prefix = prefix;
143 opt->prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
144 opt->pattern_tail = &opt->pattern_list;
145 opt->header_tail = &opt->header_list;
146
147 opt->color = def->color;
148 opt->extended_regexp_option = def->extended_regexp_option;
149 opt->pattern_type_option = def->pattern_type_option;
150 opt->linenum = def->linenum;
151 opt->max_depth = def->max_depth;
152 opt->pathname = def->pathname;
153 opt->regflags = def->regflags;
154 opt->relative = def->relative;
155
7ce4fb94
JK
156 color_set(opt->color_context, def->color_context);
157 color_set(opt->color_filename, def->color_filename);
158 color_set(opt->color_function, def->color_function);
159 color_set(opt->color_lineno, def->color_lineno);
160 color_set(opt->color_match_context, def->color_match_context);
161 color_set(opt->color_match_selected, def->color_match_selected);
162 color_set(opt->color_selected, def->color_selected);
163 color_set(opt->color_sep, def->color_sep);
7687a054 164}
07a7d656 165
c5c31d33
JH
166void grep_commit_pattern_type(enum grep_pattern_type pattern_type, struct grep_opt *opt)
167{
168 if (pattern_type != GREP_PATTERN_TYPE_UNSPECIFIED)
169 grep_set_pattern_type_option(pattern_type, opt);
170 else if (opt->pattern_type_option != GREP_PATTERN_TYPE_UNSPECIFIED)
171 grep_set_pattern_type_option(opt->pattern_type_option, opt);
172 else if (opt->extended_regexp_option)
173 grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, opt);
174}
175
176void grep_set_pattern_type_option(enum grep_pattern_type pattern_type, struct grep_opt *opt)
177{
178 switch (pattern_type) {
179 case GREP_PATTERN_TYPE_UNSPECIFIED:
180 /* fall through */
181
182 case GREP_PATTERN_TYPE_BRE:
183 opt->fixed = 0;
184 opt->pcre = 0;
185 opt->regflags &= ~REG_EXTENDED;
186 break;
187
188 case GREP_PATTERN_TYPE_ERE:
189 opt->fixed = 0;
190 opt->pcre = 0;
191 opt->regflags |= REG_EXTENDED;
192 break;
193
194 case GREP_PATTERN_TYPE_FIXED:
195 opt->fixed = 1;
196 opt->pcre = 0;
197 opt->regflags &= ~REG_EXTENDED;
198 break;
199
200 case GREP_PATTERN_TYPE_PCRE:
201 opt->fixed = 0;
202 opt->pcre = 1;
203 opt->regflags &= ~REG_EXTENDED;
204 break;
205 }
206}
207
fc456751
RS
208static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
209 const char *origin, int no,
210 enum grep_pat_token t,
211 enum grep_header_field field)
a4d7d2c6
JH
212{
213 struct grep_pat *p = xcalloc(1, sizeof(*p));
526a858a 214 p->pattern = xmemdupz(pat, patlen);
fc456751
RS
215 p->patternlen = patlen;
216 p->origin = origin;
217 p->no = no;
218 p->token = t;
a4d7d2c6 219 p->field = field;
fc456751
RS
220 return p;
221}
222
2b3873ff
RS
223static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
224{
225 **tail = p;
226 *tail = &p->next;
a4d7d2c6 227 p->next = NULL;
526a858a
RS
228
229 switch (p->token) {
230 case GREP_PATTERN: /* atom */
231 case GREP_PATTERN_HEAD:
232 case GREP_PATTERN_BODY:
233 for (;;) {
234 struct grep_pat *new_pat;
235 size_t len = 0;
236 char *cp = p->pattern + p->patternlen, *nl = NULL;
237 while (++len <= p->patternlen) {
238 if (*(--cp) == '\n') {
239 nl = cp;
240 break;
241 }
242 }
243 if (!nl)
244 break;
245 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
246 p->no, p->token, p->field);
247 new_pat->next = p->next;
248 if (!p->next)
249 *tail = &new_pat->next;
250 p->next = new_pat;
251 *nl = '\0';
252 p->patternlen -= len;
253 }
254 break;
255 default:
256 break;
257 }
2b3873ff
RS
258}
259
fc456751
RS
260void append_header_grep_pattern(struct grep_opt *opt,
261 enum grep_header_field field, const char *pat)
262{
263 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
264 GREP_PATTERN_HEAD, field);
baa6378f
JH
265 if (field == GREP_HEADER_REFLOG)
266 opt->use_reflog_filter = 1;
2b3873ff 267 do_append_grep_pat(&opt->header_tail, p);
a4d7d2c6
JH
268}
269
83b5d2f5
JH
270void append_grep_pattern(struct grep_opt *opt, const char *pat,
271 const char *origin, int no, enum grep_pat_token t)
ed40a095
RS
272{
273 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
274}
275
276void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
277 const char *origin, int no, enum grep_pat_token t)
83b5d2f5 278{
fc456751 279 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
2b3873ff 280 do_append_grep_pat(&opt->pattern_tail, p);
83b5d2f5
JH
281}
282
5b594f45
FK
283struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
284{
285 struct grep_pat *pat;
286 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
287 *ret = *opt;
288
289 ret->pattern_list = NULL;
290 ret->pattern_tail = &ret->pattern_list;
291
292 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
293 {
294 if(pat->token == GREP_PATTERN_HEAD)
295 append_header_grep_pattern(ret, pat->field,
296 pat->pattern);
297 else
ed40a095
RS
298 append_grep_pat(ret, pat->pattern, pat->patternlen,
299 pat->origin, pat->no, pat->token);
5b594f45
FK
300 }
301
302 return ret;
303}
304
a30c148a
MK
305static NORETURN void compile_regexp_failed(const struct grep_pat *p,
306 const char *error)
307{
308 char where[1024];
309
310 if (p->no)
19bdd3e7 311 xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
a30c148a 312 else if (p->origin)
19bdd3e7 313 xsnprintf(where, sizeof(where), "%s, ", p->origin);
a30c148a
MK
314 else
315 where[0] = 0;
316
317 die("%s'%s': %s", where, p->pattern, error);
318}
319
63e7e9d8
MK
320#ifdef USE_LIBPCRE
321static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
322{
323 const char *error;
324 int erroffset;
fba4f125 325 int options = PCRE_MULTILINE;
63e7e9d8 326
9d9babb8
NTND
327 if (opt->ignore_case) {
328 if (has_non_ascii(p->pattern))
329 p->pcre_tables = pcre_maketables();
63e7e9d8 330 options |= PCRE_CASELESS;
9d9babb8 331 }
63e7e9d8
MK
332
333 p->pcre_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
9d9babb8 334 p->pcre_tables);
63e7e9d8
MK
335 if (!p->pcre_regexp)
336 compile_regexp_failed(p, error);
337
338 p->pcre_extra_info = pcre_study(p->pcre_regexp, 0, &error);
339 if (!p->pcre_extra_info && error)
340 die("%s", error);
341}
342
343static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
344 regmatch_t *match, int eflags)
345{
346 int ovector[30], ret, flags = 0;
347
348 if (eflags & REG_NOTBOL)
349 flags |= PCRE_NOTBOL;
350
351 ret = pcre_exec(p->pcre_regexp, p->pcre_extra_info, line, eol - line,
352 0, flags, ovector, ARRAY_SIZE(ovector));
353 if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
354 die("pcre_exec failed with error code %d", ret);
355 if (ret > 0) {
356 ret = 0;
357 match->rm_so = ovector[0];
358 match->rm_eo = ovector[1];
359 }
360
361 return ret;
362}
363
364static void free_pcre_regexp(struct grep_pat *p)
365{
366 pcre_free(p->pcre_regexp);
367 pcre_free(p->pcre_extra_info);
9d9babb8 368 pcre_free((void *)p->pcre_tables);
63e7e9d8
MK
369}
370#else /* !USE_LIBPCRE */
371static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
372{
373 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
374}
375
376static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
377 regmatch_t *match, int eflags)
378{
379 return 1;
380}
381
382static void free_pcre_regexp(struct grep_pat *p)
383{
384}
385#endif /* !USE_LIBPCRE */
386
9eceddee
FK
387static int is_fixed(const char *s, size_t len)
388{
389 size_t i;
390
391 /* regcomp cannot accept patterns with NULs so we
392 * consider any pattern containing a NUL fixed.
393 */
394 if (memchr(s, 0, len))
395 return 1;
396
397 for (i = 0; i < len; i++) {
398 if (is_regex_special(s[i]))
399 return 0;
400 }
401
402 return 1;
403}
404
793dc676
NTND
405static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
406{
407 struct strbuf sb = STRBUF_INIT;
408 int err;
409 int regflags;
410
411 basic_regex_quote_buf(&sb, p->pattern);
412 regflags = opt->regflags & ~REG_EXTENDED;
413 if (opt->ignore_case)
414 regflags |= REG_ICASE;
415 err = regcomp(&p->regexp, sb.buf, regflags);
416 if (opt->debug)
417 fprintf(stderr, "fixed %s\n", sb.buf);
418 strbuf_release(&sb);
419 if (err) {
420 char errbuf[1024];
421 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
422 regfree(&p->regexp);
423 compile_regexp_failed(p, errbuf);
424 }
425}
426
83b5d2f5
JH
427static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
428{
5c1ebcca 429 int icase, ascii_only;
c822255c
RS
430 int err;
431
d7eb527d 432 p->word_regexp = opt->word_regexp;
5183bf67 433 p->ignore_case = opt->ignore_case;
5c1ebcca
NTND
434 icase = opt->regflags & REG_ICASE || p->ignore_case;
435 ascii_only = !has_non_ascii(p->pattern);
d7eb527d 436
793dc676
NTND
437 /*
438 * Even when -F (fixed) asks us to do a non-regexp search, we
439 * may not be able to correctly case-fold when -i
440 * (ignore-case) is asked (in which case, we'll synthesize a
441 * regexp to match the pattern that matches regexp special
442 * characters literally, while ignoring case differences). On
443 * the other hand, even without -F, if the pattern does not
444 * have any regexp special characters and there is no need for
445 * case-folding search, we can internally turn it into a
446 * simple string match using kws. p->fixed tells us if we
447 * want to use kws.
448 */
e944d9d9 449 if (opt->fixed || is_fixed(p->pattern, p->patternlen))
793dc676 450 p->fixed = !icase || ascii_only;
9eceddee
FK
451 else
452 p->fixed = 0;
453
454 if (p->fixed) {
0f871cf5
JH
455 if (opt->regflags & REG_ICASE || p->ignore_case)
456 p->kws = kwsalloc(tolower_trans_tbl);
457 else
9eceddee 458 p->kws = kwsalloc(NULL);
9eceddee
FK
459 kwsincr(p->kws, p->pattern, p->patternlen);
460 kwsprep(p->kws);
c822255c 461 return;
793dc676
NTND
462 } else if (opt->fixed) {
463 /*
464 * We come here when the pattern has the non-ascii
465 * characters we cannot case-fold, and asked to
466 * ignore-case.
467 */
468 compile_fixed_regexp(p, opt);
469 return;
9eceddee 470 }
c822255c 471
63e7e9d8
MK
472 if (opt->pcre) {
473 compile_pcre_regexp(p, opt);
474 return;
475 }
476
c822255c 477 err = regcomp(&p->regexp, p->pattern, opt->regflags);
83b5d2f5
JH
478 if (err) {
479 char errbuf[1024];
83b5d2f5
JH
480 regerror(err, &p->regexp, errbuf, 1024);
481 regfree(&p->regexp);
a30c148a 482 compile_regexp_failed(p, errbuf);
83b5d2f5
JH
483 }
484}
485
0ab7befa 486static struct grep_expr *compile_pattern_or(struct grep_pat **);
83b5d2f5
JH
487static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
488{
489 struct grep_pat *p;
490 struct grep_expr *x;
491
492 p = *list;
c922b01f
LT
493 if (!p)
494 return NULL;
83b5d2f5
JH
495 switch (p->token) {
496 case GREP_PATTERN: /* atom */
480c1ca6
JH
497 case GREP_PATTERN_HEAD:
498 case GREP_PATTERN_BODY:
83b5d2f5
JH
499 x = xcalloc(1, sizeof (struct grep_expr));
500 x->node = GREP_NODE_ATOM;
501 x->u.atom = p;
502 *list = p->next;
503 return x;
504 case GREP_OPEN_PAREN:
505 *list = p->next;
0ab7befa 506 x = compile_pattern_or(list);
83b5d2f5
JH
507 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
508 die("unmatched parenthesis");
509 *list = (*list)->next;
510 return x;
511 default:
512 return NULL;
513 }
514}
515
516static struct grep_expr *compile_pattern_not(struct grep_pat **list)
517{
518 struct grep_pat *p;
519 struct grep_expr *x;
520
521 p = *list;
c922b01f
LT
522 if (!p)
523 return NULL;
83b5d2f5
JH
524 switch (p->token) {
525 case GREP_NOT:
526 if (!p->next)
527 die("--not not followed by pattern expression");
528 *list = p->next;
529 x = xcalloc(1, sizeof (struct grep_expr));
530 x->node = GREP_NODE_NOT;
531 x->u.unary = compile_pattern_not(list);
532 if (!x->u.unary)
533 die("--not followed by non pattern expression");
534 return x;
535 default:
536 return compile_pattern_atom(list);
537 }
538}
539
540static struct grep_expr *compile_pattern_and(struct grep_pat **list)
541{
542 struct grep_pat *p;
543 struct grep_expr *x, *y, *z;
544
545 x = compile_pattern_not(list);
546 p = *list;
547 if (p && p->token == GREP_AND) {
548 if (!p->next)
549 die("--and not followed by pattern expression");
550 *list = p->next;
551 y = compile_pattern_and(list);
552 if (!y)
553 die("--and not followed by pattern expression");
554 z = xcalloc(1, sizeof (struct grep_expr));
555 z->node = GREP_NODE_AND;
556 z->u.binary.left = x;
557 z->u.binary.right = y;
558 return z;
559 }
560 return x;
561}
562
563static struct grep_expr *compile_pattern_or(struct grep_pat **list)
564{
565 struct grep_pat *p;
566 struct grep_expr *x, *y, *z;
567
568 x = compile_pattern_and(list);
569 p = *list;
570 if (x && p && p->token != GREP_CLOSE_PAREN) {
571 y = compile_pattern_or(list);
572 if (!y)
573 die("not a pattern expression %s", p->pattern);
574 z = xcalloc(1, sizeof (struct grep_expr));
575 z->node = GREP_NODE_OR;
576 z->u.binary.left = x;
577 z->u.binary.right = y;
578 return z;
579 }
580 return x;
581}
582
583static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
584{
585 return compile_pattern_or(list);
586}
587
17bf35a3
JH
588static void indent(int in)
589{
590 while (in-- > 0)
591 fputc(' ', stderr);
592}
593
594static void dump_grep_pat(struct grep_pat *p)
595{
596 switch (p->token) {
597 case GREP_AND: fprintf(stderr, "*and*"); break;
598 case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
599 case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
600 case GREP_NOT: fprintf(stderr, "*not*"); break;
601 case GREP_OR: fprintf(stderr, "*or*"); break;
602
603 case GREP_PATTERN: fprintf(stderr, "pattern"); break;
604 case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
605 case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
606 }
607
608 switch (p->token) {
609 default: break;
610 case GREP_PATTERN_HEAD:
611 fprintf(stderr, "<head %d>", p->field); break;
612 case GREP_PATTERN_BODY:
613 fprintf(stderr, "<body>"); break;
614 }
615 switch (p->token) {
616 default: break;
617 case GREP_PATTERN_HEAD:
618 case GREP_PATTERN_BODY:
619 case GREP_PATTERN:
620 fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
621 break;
622 }
623 fputc('\n', stderr);
624}
625
626static void dump_grep_expression_1(struct grep_expr *x, int in)
627{
628 indent(in);
629 switch (x->node) {
630 case GREP_NODE_TRUE:
631 fprintf(stderr, "true\n");
632 break;
633 case GREP_NODE_ATOM:
634 dump_grep_pat(x->u.atom);
635 break;
636 case GREP_NODE_NOT:
637 fprintf(stderr, "(not\n");
638 dump_grep_expression_1(x->u.unary, in+1);
639 indent(in);
640 fprintf(stderr, ")\n");
641 break;
642 case GREP_NODE_AND:
643 fprintf(stderr, "(and\n");
644 dump_grep_expression_1(x->u.binary.left, in+1);
645 dump_grep_expression_1(x->u.binary.right, in+1);
646 indent(in);
647 fprintf(stderr, ")\n");
648 break;
649 case GREP_NODE_OR:
650 fprintf(stderr, "(or\n");
651 dump_grep_expression_1(x->u.binary.left, in+1);
652 dump_grep_expression_1(x->u.binary.right, in+1);
653 indent(in);
654 fprintf(stderr, ")\n");
655 break;
656 }
657}
658
07a7d656 659static void dump_grep_expression(struct grep_opt *opt)
17bf35a3
JH
660{
661 struct grep_expr *x = opt->pattern_expression;
662
663 if (opt->all_match)
664 fprintf(stderr, "[all-match]\n");
665 dump_grep_expression_1(x, 0);
666 fflush(NULL);
667}
668
5aaeb733
JH
669static struct grep_expr *grep_true_expr(void)
670{
671 struct grep_expr *z = xcalloc(1, sizeof(*z));
672 z->node = GREP_NODE_TRUE;
673 return z;
674}
675
676static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
677{
678 struct grep_expr *z = xcalloc(1, sizeof(*z));
679 z->node = GREP_NODE_OR;
680 z->u.binary.left = left;
681 z->u.binary.right = right;
682 return z;
683}
684
95ce9ce2 685static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
83b5d2f5
JH
686{
687 struct grep_pat *p;
95ce9ce2 688 struct grep_expr *header_expr;
5aaeb733
JH
689 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
690 enum grep_header_field fld;
83b5d2f5 691
95ce9ce2
JH
692 if (!opt->header_list)
693 return NULL;
2385f246 694
95ce9ce2
JH
695 for (p = opt->header_list; p; p = p->next) {
696 if (p->token != GREP_PATTERN_HEAD)
697 die("bug: a non-header pattern in grep header list.");
3ce3ffb8
AP
698 if (p->field < GREP_HEADER_FIELD_MIN ||
699 GREP_HEADER_FIELD_MAX <= p->field)
95ce9ce2
JH
700 die("bug: unknown header field %d", p->field);
701 compile_regexp(p, opt);
80235ba7 702 }
5aaeb733
JH
703
704 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
705 header_group[fld] = NULL;
706
707 for (p = opt->header_list; p; p = p->next) {
708 struct grep_expr *h;
709 struct grep_pat *pp = p;
710
711 h = compile_pattern_atom(&pp);
712 if (!h || pp != p->next)
713 die("bug: malformed header expr");
714 if (!header_group[p->field]) {
715 header_group[p->field] = h;
716 continue;
717 }
718 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
719 }
720
721 header_expr = NULL;
722
723 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
724 if (!header_group[fld])
725 continue;
726 if (!header_expr)
727 header_expr = grep_true_expr();
728 header_expr = grep_or_expr(header_group[fld], header_expr);
729 }
95ce9ce2
JH
730 return header_expr;
731}
732
13e4fc7e
JH
733static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
734{
735 struct grep_expr *z = x;
736
737 while (x) {
738 assert(x->node == GREP_NODE_OR);
739 if (x->u.binary.right &&
740 x->u.binary.right->node == GREP_NODE_TRUE) {
741 x->u.binary.right = y;
742 break;
743 }
744 x = x->u.binary.right;
745 }
746 return z;
747}
748
17bf35a3 749static void compile_grep_patterns_real(struct grep_opt *opt)
95ce9ce2
JH
750{
751 struct grep_pat *p;
752 struct grep_expr *header_expr = prep_header_patterns(opt);
0ab7befa 753
83b5d2f5 754 for (p = opt->pattern_list; p; p = p->next) {
480c1ca6
JH
755 switch (p->token) {
756 case GREP_PATTERN: /* atom */
757 case GREP_PATTERN_HEAD:
758 case GREP_PATTERN_BODY:
c822255c 759 compile_regexp(p, opt);
480c1ca6
JH
760 break;
761 default:
83b5d2f5 762 opt->extended = 1;
480c1ca6
JH
763 break;
764 }
83b5d2f5
JH
765 }
766
80235ba7
JH
767 if (opt->all_match || header_expr)
768 opt->extended = 1;
17bf35a3 769 else if (!opt->extended && !opt->debug)
83b5d2f5
JH
770 return;
771
83b5d2f5 772 p = opt->pattern_list;
ba150a3f
MB
773 if (p)
774 opt->pattern_expression = compile_pattern_expr(&p);
83b5d2f5
JH
775 if (p)
776 die("incomplete pattern expression: %s", p->pattern);
80235ba7
JH
777
778 if (!header_expr)
779 return;
780
5aaeb733 781 if (!opt->pattern_expression)
80235ba7 782 opt->pattern_expression = header_expr;
13e4fc7e
JH
783 else if (opt->all_match)
784 opt->pattern_expression = grep_splice_or(header_expr,
785 opt->pattern_expression);
5aaeb733
JH
786 else
787 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
788 header_expr);
80235ba7 789 opt->all_match = 1;
83b5d2f5
JH
790}
791
17bf35a3
JH
792void compile_grep_patterns(struct grep_opt *opt)
793{
794 compile_grep_patterns_real(opt);
795 if (opt->debug)
796 dump_grep_expression(opt);
797}
798
b48fb5b6
JH
799static void free_pattern_expr(struct grep_expr *x)
800{
801 switch (x->node) {
5aaeb733 802 case GREP_NODE_TRUE:
b48fb5b6
JH
803 case GREP_NODE_ATOM:
804 break;
805 case GREP_NODE_NOT:
806 free_pattern_expr(x->u.unary);
807 break;
808 case GREP_NODE_AND:
809 case GREP_NODE_OR:
810 free_pattern_expr(x->u.binary.left);
811 free_pattern_expr(x->u.binary.right);
812 break;
813 }
814 free(x);
815}
816
817void free_grep_patterns(struct grep_opt *opt)
818{
819 struct grep_pat *p, *n;
820
821 for (p = opt->pattern_list; p; p = n) {
822 n = p->next;
823 switch (p->token) {
824 case GREP_PATTERN: /* atom */
825 case GREP_PATTERN_HEAD:
826 case GREP_PATTERN_BODY:
9eceddee
FK
827 if (p->kws)
828 kwsfree(p->kws);
829 else if (p->pcre_regexp)
63e7e9d8
MK
830 free_pcre_regexp(p);
831 else
832 regfree(&p->regexp);
526a858a 833 free(p->pattern);
b48fb5b6
JH
834 break;
835 default:
836 break;
837 }
838 free(p);
839 }
840
841 if (!opt->extended)
842 return;
843 free_pattern_expr(opt->pattern_expression);
844}
845
83b5d2f5
JH
846static char *end_of_line(char *cp, unsigned long *left)
847{
848 unsigned long l = *left;
849 while (l && *cp != '\n') {
850 l--;
851 cp++;
852 }
853 *left = l;
854 return cp;
855}
856
857static int word_char(char ch)
858{
859 return isalnum(ch) || ch == '_';
860}
861
55f638bd
ML
862static void output_color(struct grep_opt *opt, const void *data, size_t size,
863 const char *color)
864{
daa0c3d9 865 if (want_color(opt->color) && color && color[0]) {
55f638bd
ML
866 opt->output(opt, color, strlen(color));
867 opt->output(opt, data, size);
868 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
869 } else
870 opt->output(opt, data, size);
871}
872
873static void output_sep(struct grep_opt *opt, char sign)
874{
875 if (opt->null_following_name)
876 opt->output(opt, "\0", 1);
877 else
878 output_color(opt, &sign, 1, opt->color_sep);
879}
880
83caecca
RZ
881static void show_name(struct grep_opt *opt, const char *name)
882{
55f638bd 883 output_color(opt, name, strlen(name), opt->color_filename);
5b594f45 884 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
83caecca
RZ
885}
886
ed40a095
RS
887static int fixmatch(struct grep_pat *p, char *line, char *eol,
888 regmatch_t *match)
83b5d2f5 889{
9eceddee
FK
890 struct kwsmatch kwsm;
891 size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
892 if (offset == -1) {
83b5d2f5
JH
893 match->rm_so = match->rm_eo = -1;
894 return REG_NOMATCH;
9eceddee
FK
895 } else {
896 match->rm_so = offset;
897 match->rm_eo = match->rm_so + kwsm.size[0];
83b5d2f5
JH
898 return 0;
899 }
900}
901
f96e5673
RS
902static int regmatch(const regex_t *preg, char *line, char *eol,
903 regmatch_t *match, int eflags)
904{
905#ifdef REG_STARTEND
906 match->rm_so = 0;
907 match->rm_eo = eol - line;
908 eflags |= REG_STARTEND;
909#endif
910 return regexec(preg, line, 1, match, eflags);
911}
912
97e77784
MK
913static int patmatch(struct grep_pat *p, char *line, char *eol,
914 regmatch_t *match, int eflags)
915{
916 int hit;
917
918 if (p->fixed)
919 hit = !fixmatch(p, line, eol, match);
63e7e9d8
MK
920 else if (p->pcre_regexp)
921 hit = !pcrematch(p, line, eol, match, eflags);
97e77784
MK
922 else
923 hit = !regmatch(&p->regexp, line, eol, match, eflags);
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];
1178 snprintf(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
5b594f45
FK
1393static void std_output(struct grep_opt *opt, const void *buf, size_t size)
1394{
1395 fwrite(buf, size, 1, stdout);
1396}
1397
335ec3bf
JK
1398static int fill_textconv_grep(struct userdiff_driver *driver,
1399 struct grep_source *gs)
1400{
1401 struct diff_filespec *df;
1402 char *buf;
1403 size_t size;
1404
1405 if (!driver || !driver->textconv)
1406 return grep_source_load(gs);
1407
1408 /*
1409 * The textconv interface is intimately tied to diff_filespecs, so we
1410 * have to pretend to be one. If we could unify the grep_source
1411 * and diff_filespec structs, this mess could just go away.
1412 */
1413 df = alloc_filespec(gs->path);
1414 switch (gs->type) {
1415 case GREP_SOURCE_SHA1:
1416 fill_filespec(df, gs->identifier, 1, 0100644);
1417 break;
1418 case GREP_SOURCE_FILE:
1419 fill_filespec(df, null_sha1, 0, 0100644);
1420 break;
1421 default:
1422 die("BUG: attempt to textconv something without a path?");
1423 }
1424
1425 /*
1426 * fill_textconv is not remotely thread-safe; it may load objects
1427 * behind the scenes, and it modifies the global diff tempfile
1428 * structure.
1429 */
1430 grep_read_lock();
1431 size = fill_textconv(driver, df, &buf);
1432 grep_read_unlock();
1433 free_filespec(df);
1434
1435 /*
1436 * The normal fill_textconv usage by the diff machinery would just keep
1437 * the textconv'd buf separate from the diff_filespec. But much of the
1438 * grep code passes around a grep_source and assumes that its "buf"
1439 * pointer is the beginning of the thing we are searching. So let's
1440 * install our textconv'd version into the grep_source, taking care not
1441 * to leak any existing buffer.
1442 */
1443 grep_source_clear_data(gs);
1444 gs->buf = buf;
1445 gs->size = size;
1446
1447 return 0;
1448}
1449
e1327023 1450static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
83b5d2f5 1451{
e1327023
JK
1452 char *bol;
1453 unsigned long left;
83b5d2f5 1454 unsigned lno = 1;
83b5d2f5 1455 unsigned last_hit = 0;
83b5d2f5 1456 int binary_match_only = 0;
83b5d2f5 1457 unsigned count = 0;
a26345b6 1458 int try_lookahead = 0;
ba8ea749 1459 int show_function = 0;
335ec3bf 1460 struct userdiff_driver *textconv = NULL;
480c1ca6 1461 enum grep_context ctx = GREP_CONTEXT_HEAD;
60ecac98 1462 xdemitconf_t xecfg;
83b5d2f5 1463
5b594f45
FK
1464 if (!opt->output)
1465 opt->output = std_output;
1466
ba8ea749
RS
1467 if (opt->pre_context || opt->post_context || opt->file_break ||
1468 opt->funcbody) {
08303c36
RS
1469 /* Show hunk marks, except for the first file. */
1470 if (opt->last_shown)
1471 opt->show_hunk_mark = 1;
1472 /*
1473 * If we're using threads then we can't easily identify
1474 * the first file. Always put hunk marks in that case
1475 * and skip the very first one later in work_done().
1476 */
1477 if (opt->output != std_output)
1478 opt->show_hunk_mark = 1;
1479 }
431d6e7b
RS
1480 opt->last_shown = 0;
1481
335ec3bf
JK
1482 if (opt->allow_textconv) {
1483 grep_source_load_driver(gs);
1484 /*
1485 * We might set up the shared textconv cache data here, which
1486 * is not thread-safe.
1487 */
1488 grep_attr_lock();
1489 textconv = userdiff_get_textconv(gs->driver);
1490 grep_attr_unlock();
1491 }
1492
1493 /*
1494 * We know the result of a textconv is text, so we only have to care
1495 * about binary handling if we are not using it.
1496 */
1497 if (!textconv) {
1498 switch (opt->binary) {
1499 case GREP_BINARY_DEFAULT:
1500 if (grep_source_is_binary(gs))
1501 binary_match_only = 1;
1502 break;
1503 case GREP_BINARY_NOMATCH:
1504 if (grep_source_is_binary(gs))
1505 return 0; /* Assume unmatch */
1506 break;
1507 case GREP_BINARY_TEXT:
1508 break;
1509 default:
1510 die("bug: unknown binary handling mode");
1511 }
83b5d2f5
JH
1512 }
1513
60ecac98 1514 memset(&xecfg, 0, sizeof(xecfg));
0579f91d
TR
1515 opt->priv = &xecfg;
1516
a26345b6 1517 try_lookahead = should_lookahead(opt);
60ecac98 1518
335ec3bf 1519 if (fill_textconv_grep(textconv, gs) < 0)
08265798
JK
1520 return 0;
1521
e1327023
JK
1522 bol = gs->buf;
1523 left = gs->size;
83b5d2f5
JH
1524 while (left) {
1525 char *eol, ch;
0ab7befa 1526 int hit;
83b5d2f5 1527
a26345b6 1528 /*
8997da38 1529 * look_ahead() skips quickly to the line that possibly
a26345b6
JH
1530 * has the next hit; don't call it if we need to do
1531 * something more than just skipping the current line
1532 * in response to an unmatch for the current line. E.g.
1533 * inside a post-context window, we will show the current
1534 * line as a context around the previous hit when it
1535 * doesn't hit.
1536 */
1537 if (try_lookahead
1538 && !(last_hit
ba8ea749
RS
1539 && (show_function ||
1540 lno <= last_hit + opt->post_context))
a26345b6
JH
1541 && look_ahead(opt, &left, &lno, &bol))
1542 break;
83b5d2f5
JH
1543 eol = end_of_line(bol, &left);
1544 ch = *eol;
1545 *eol = 0;
1546
480c1ca6
JH
1547 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1548 ctx = GREP_CONTEXT_BODY;
1549
0ab7befa 1550 hit = match_line(opt, bol, eol, ctx, collect_hits);
83b5d2f5
JH
1551 *eol = ch;
1552
0ab7befa
JH
1553 if (collect_hits)
1554 goto next_line;
1555
83b5d2f5
JH
1556 /* "grep -v -e foo -e bla" should list lines
1557 * that do not have either, so inversion should
1558 * be done outside.
1559 */
1560 if (opt->invert)
1561 hit = !hit;
1562 if (opt->unmatch_name_only) {
1563 if (hit)
1564 return 0;
1565 goto next_line;
1566 }
1567 if (hit) {
1568 count++;
1569 if (opt->status_only)
1570 return 1;
321ffcc0 1571 if (opt->name_only) {
e1327023 1572 show_name(opt, gs->name);
321ffcc0
RS
1573 return 1;
1574 }
c30c10cf
RS
1575 if (opt->count)
1576 goto next_line;
83b5d2f5 1577 if (binary_match_only) {
5b594f45 1578 opt->output(opt, "Binary file ", 12);
e1327023 1579 output_color(opt, gs->name, strlen(gs->name),
55f638bd 1580 opt->color_filename);
5b594f45 1581 opt->output(opt, " matches\n", 9);
83b5d2f5
JH
1582 return 1;
1583 }
83b5d2f5
JH
1584 /* Hit at this line. If we haven't shown the
1585 * pre-context lines, we would need to show them.
83b5d2f5 1586 */
ba8ea749 1587 if (opt->pre_context || opt->funcbody)
e1327023 1588 show_pre_context(opt, gs, bol, eol, lno);
2944e4e6 1589 else if (opt->funcname)
e1327023
JK
1590 show_funcname_line(opt, gs, bol, lno);
1591 show_line(opt, bol, eol, gs->name, lno, ':');
5dd06d38 1592 last_hit = lno;
ba8ea749
RS
1593 if (opt->funcbody)
1594 show_function = 1;
1595 goto next_line;
83b5d2f5 1596 }
e1327023 1597 if (show_function && match_funcname(opt, gs, bol, eol))
ba8ea749
RS
1598 show_function = 0;
1599 if (show_function ||
1600 (last_hit && lno <= last_hit + opt->post_context)) {
83b5d2f5
JH
1601 /* If the last hit is within the post context,
1602 * we need to show this line.
1603 */
e1327023 1604 show_line(opt, bol, eol, gs->name, lno, '-');
83b5d2f5 1605 }
83b5d2f5
JH
1606
1607 next_line:
1608 bol = eol + 1;
1609 if (!left)
1610 break;
1611 left--;
1612 lno++;
1613 }
1614
0ab7befa
JH
1615 if (collect_hits)
1616 return 0;
b48fb5b6 1617
83b5d2f5
JH
1618 if (opt->status_only)
1619 return 0;
1620 if (opt->unmatch_name_only) {
1621 /* We did not see any hit, so we want to show this */
e1327023 1622 show_name(opt, gs->name);
83b5d2f5
JH
1623 return 1;
1624 }
1625
60ecac98
RS
1626 xdiff_clear_find_func(&xecfg);
1627 opt->priv = NULL;
1628
83b5d2f5
JH
1629 /* NEEDSWORK:
1630 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1631 * which feels mostly useless but sometimes useful. Maybe
1632 * make it another option? For now suppress them.
1633 */
5b594f45
FK
1634 if (opt->count && count) {
1635 char buf[32];
f76d947a
RS
1636 if (opt->pathname) {
1637 output_color(opt, gs->name, strlen(gs->name),
1638 opt->color_filename);
1639 output_sep(opt, ':');
1640 }
55f638bd 1641 snprintf(buf, sizeof(buf), "%u\n", count);
5b594f45 1642 opt->output(opt, buf, strlen(buf));
c30c10cf 1643 return 1;
5b594f45 1644 }
83b5d2f5
JH
1645 return !!last_hit;
1646}
1647
0ab7befa
JH
1648static void clr_hit_marker(struct grep_expr *x)
1649{
1650 /* All-hit markers are meaningful only at the very top level
1651 * OR node.
1652 */
1653 while (1) {
1654 x->hit = 0;
1655 if (x->node != GREP_NODE_OR)
1656 return;
1657 x->u.binary.left->hit = 0;
1658 x = x->u.binary.right;
1659 }
1660}
1661
1662static int chk_hit_marker(struct grep_expr *x)
1663{
1664 /* Top level nodes have hit markers. See if they all are hits */
1665 while (1) {
1666 if (x->node != GREP_NODE_OR)
1667 return x->hit;
1668 if (!x->u.binary.left->hit)
1669 return 0;
1670 x = x->u.binary.right;
1671 }
1672}
1673
e1327023 1674int grep_source(struct grep_opt *opt, struct grep_source *gs)
0ab7befa
JH
1675{
1676 /*
1677 * we do not have to do the two-pass grep when we do not check
1678 * buffer-wide "all-match".
1679 */
1680 if (!opt->all_match)
e1327023 1681 return grep_source_1(opt, gs, 0);
0ab7befa
JH
1682
1683 /* Otherwise the toplevel "or" terms hit a bit differently.
1684 * We first clear hit markers from them.
1685 */
1686 clr_hit_marker(opt->pattern_expression);
e1327023 1687 grep_source_1(opt, gs, 1);
0ab7befa
JH
1688
1689 if (!chk_hit_marker(opt->pattern_expression))
1690 return 0;
1691
e1327023
JK
1692 return grep_source_1(opt, gs, 0);
1693}
1694
c876d6da 1695int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
e1327023
JK
1696{
1697 struct grep_source gs;
1698 int r;
1699
55c61688 1700 grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
e1327023
JK
1701 gs.buf = buf;
1702 gs.size = size;
1703
1704 r = grep_source(opt, &gs);
1705
1706 grep_source_clear(&gs);
1707 return r;
1708}
1709
1710void grep_source_init(struct grep_source *gs, enum grep_source_type type,
55c61688
NTND
1711 const char *name, const char *path,
1712 const void *identifier)
e1327023
JK
1713{
1714 gs->type = type;
8c53f071
JK
1715 gs->name = xstrdup_or_null(name);
1716 gs->path = xstrdup_or_null(path);
e1327023
JK
1717 gs->buf = NULL;
1718 gs->size = 0;
94ad9d9e 1719 gs->driver = NULL;
e1327023
JK
1720
1721 switch (type) {
1722 case GREP_SOURCE_FILE:
1723 gs->identifier = xstrdup(identifier);
1724 break;
1725 case GREP_SOURCE_SHA1:
1726 gs->identifier = xmalloc(20);
50546b15 1727 hashcpy(gs->identifier, identifier);
e1327023
JK
1728 break;
1729 case GREP_SOURCE_BUF:
1730 gs->identifier = NULL;
1731 }
1732}
1733
1734void grep_source_clear(struct grep_source *gs)
1735{
1736 free(gs->name);
1737 gs->name = NULL;
55c61688
NTND
1738 free(gs->path);
1739 gs->path = NULL;
e1327023
JK
1740 free(gs->identifier);
1741 gs->identifier = NULL;
1742 grep_source_clear_data(gs);
1743}
1744
1745void grep_source_clear_data(struct grep_source *gs)
1746{
1747 switch (gs->type) {
1748 case GREP_SOURCE_FILE:
1749 case GREP_SOURCE_SHA1:
1750 free(gs->buf);
1751 gs->buf = NULL;
1752 gs->size = 0;
1753 break;
1754 case GREP_SOURCE_BUF:
1755 /* leave user-provided buf intact */
1756 break;
1757 }
1758}
1759
1760static int grep_source_load_sha1(struct grep_source *gs)
1761{
1762 enum object_type type;
1763
1764 grep_read_lock();
1765 gs->buf = read_sha1_file(gs->identifier, &type, &gs->size);
1766 grep_read_unlock();
1767
1768 if (!gs->buf)
1769 return error(_("'%s': unable to read %s"),
1770 gs->name,
1771 sha1_to_hex(gs->identifier));
1772 return 0;
1773}
1774
1775static int grep_source_load_file(struct grep_source *gs)
1776{
1777 const char *filename = gs->identifier;
1778 struct stat st;
1779 char *data;
1780 size_t size;
1781 int i;
1782
1783 if (lstat(filename, &st) < 0) {
1784 err_ret:
1785 if (errno != ENOENT)
1786 error(_("'%s': %s"), filename, strerror(errno));
1787 return -1;
1788 }
1789 if (!S_ISREG(st.st_mode))
1790 return -1;
1791 size = xsize_t(st.st_size);
1792 i = open(filename, O_RDONLY);
1793 if (i < 0)
1794 goto err_ret;
1795 data = xmalloc(size + 1);
1796 if (st.st_size != read_in_full(i, data, size)) {
1797 error(_("'%s': short read %s"), filename, strerror(errno));
1798 close(i);
1799 free(data);
1800 return -1;
1801 }
1802 close(i);
1803 data[size] = 0;
1804
1805 gs->buf = data;
1806 gs->size = size;
1807 return 0;
1808}
1809
3083301e 1810static int grep_source_load(struct grep_source *gs)
e1327023
JK
1811{
1812 if (gs->buf)
1813 return 0;
1814
1815 switch (gs->type) {
1816 case GREP_SOURCE_FILE:
1817 return grep_source_load_file(gs);
1818 case GREP_SOURCE_SHA1:
1819 return grep_source_load_sha1(gs);
1820 case GREP_SOURCE_BUF:
1821 return gs->buf ? 0 : -1;
1822 }
1823 die("BUG: invalid grep_source type");
0ab7befa 1824}
94ad9d9e
JK
1825
1826void grep_source_load_driver(struct grep_source *gs)
1827{
1828 if (gs->driver)
1829 return;
1830
1831 grep_attr_lock();
55c61688
NTND
1832 if (gs->path)
1833 gs->driver = userdiff_find_by_path(gs->path);
94ad9d9e
JK
1834 if (!gs->driver)
1835 gs->driver = userdiff_find_by_name("default");
1836 grep_attr_unlock();
1837}
41b59bfc 1838
3083301e 1839static int grep_source_is_binary(struct grep_source *gs)
41b59bfc
JK
1840{
1841 grep_source_load_driver(gs);
1842 if (gs->driver->binary != -1)
1843 return gs->driver->binary;
1844
1845 if (!grep_source_load(gs))
1846 return buffer_is_binary(gs->buf, gs->size);
1847
1848 return 0;
1849}