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