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