Merge branch 'tz/lib-gpg-prereq-fix'
[alt-git.git] / grep.c
blobf00986c451a99502a9dbe5bc1feeca6c486f0065
1 #include "git-compat-util.h"
2 #include "config.h"
3 #include "gettext.h"
4 #include "grep.h"
5 #include "hex.h"
6 #include "object-store.h"
7 #include "pretty.h"
8 #include "userdiff.h"
9 #include "xdiff-interface.h"
10 #include "diff.h"
11 #include "diffcore.h"
12 #include "commit.h"
13 #include "quote.h"
14 #include "help.h"
15 #include "wrapper.h"
17 static int grep_source_load(struct grep_source *gs);
18 static int grep_source_is_binary(struct grep_source *gs,
19 struct index_state *istate);
21 static void std_output(struct grep_opt *opt, const void *buf, size_t size)
23 fwrite(buf, size, 1, stdout);
26 static const char *color_grep_slots[] = {
27 [GREP_COLOR_CONTEXT] = "context",
28 [GREP_COLOR_FILENAME] = "filename",
29 [GREP_COLOR_FUNCTION] = "function",
30 [GREP_COLOR_LINENO] = "lineNumber",
31 [GREP_COLOR_COLUMNNO] = "column",
32 [GREP_COLOR_MATCH_CONTEXT] = "matchContext",
33 [GREP_COLOR_MATCH_SELECTED] = "matchSelected",
34 [GREP_COLOR_SELECTED] = "selected",
35 [GREP_COLOR_SEP] = "separator",
38 static int parse_pattern_type_arg(const char *opt, const char *arg)
40 if (!strcmp(arg, "default"))
41 return GREP_PATTERN_TYPE_UNSPECIFIED;
42 else if (!strcmp(arg, "basic"))
43 return GREP_PATTERN_TYPE_BRE;
44 else if (!strcmp(arg, "extended"))
45 return GREP_PATTERN_TYPE_ERE;
46 else if (!strcmp(arg, "fixed"))
47 return GREP_PATTERN_TYPE_FIXED;
48 else if (!strcmp(arg, "perl"))
49 return GREP_PATTERN_TYPE_PCRE;
50 die("bad %s argument: %s", opt, arg);
53 define_list_config_array_extra(color_grep_slots, {"match"});
56 * Read the configuration file once and store it in
57 * the grep_defaults template.
59 int grep_config(const char *var, const char *value, void *cb)
61 struct grep_opt *opt = cb;
62 const char *slot;
64 if (userdiff_config(var, value) < 0)
65 return -1;
67 if (!strcmp(var, "grep.extendedregexp")) {
68 opt->extended_regexp_option = git_config_bool(var, value);
69 return 0;
72 if (!strcmp(var, "grep.patterntype")) {
73 opt->pattern_type_option = parse_pattern_type_arg(var, value);
74 return 0;
77 if (!strcmp(var, "grep.linenumber")) {
78 opt->linenum = git_config_bool(var, value);
79 return 0;
81 if (!strcmp(var, "grep.column")) {
82 opt->columnnum = git_config_bool(var, value);
83 return 0;
86 if (!strcmp(var, "grep.fullname")) {
87 opt->relative = !git_config_bool(var, value);
88 return 0;
91 if (!strcmp(var, "color.grep"))
92 opt->color = git_config_colorbool(var, value);
93 if (!strcmp(var, "color.grep.match")) {
94 if (grep_config("color.grep.matchcontext", value, cb) < 0)
95 return -1;
96 if (grep_config("color.grep.matchselected", value, cb) < 0)
97 return -1;
98 } else if (skip_prefix(var, "color.grep.", &slot)) {
99 int i = LOOKUP_CONFIG(color_grep_slots, slot);
100 char *color;
102 if (i < 0)
103 return -1;
104 color = opt->colors[i];
105 if (!value)
106 return config_error_nonbool(var);
107 return color_parse(value, color);
109 return 0;
112 void grep_init(struct grep_opt *opt, struct repository *repo)
114 struct grep_opt blank = GREP_OPT_INIT;
115 memcpy(opt, &blank, sizeof(*opt));
117 opt->repo = repo;
118 opt->pattern_tail = &opt->pattern_list;
119 opt->header_tail = &opt->header_list;
122 static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
123 const char *origin, int no,
124 enum grep_pat_token t,
125 enum grep_header_field field)
127 struct grep_pat *p = xcalloc(1, sizeof(*p));
128 p->pattern = xmemdupz(pat, patlen);
129 p->patternlen = patlen;
130 p->origin = origin;
131 p->no = no;
132 p->token = t;
133 p->field = field;
134 return p;
137 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
139 **tail = p;
140 *tail = &p->next;
141 p->next = NULL;
143 switch (p->token) {
144 case GREP_PATTERN: /* atom */
145 case GREP_PATTERN_HEAD:
146 case GREP_PATTERN_BODY:
147 for (;;) {
148 struct grep_pat *new_pat;
149 size_t len = 0;
150 char *cp = p->pattern + p->patternlen, *nl = NULL;
151 while (++len <= p->patternlen) {
152 if (*(--cp) == '\n') {
153 nl = cp;
154 break;
157 if (!nl)
158 break;
159 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
160 p->no, p->token, p->field);
161 new_pat->next = p->next;
162 if (!p->next)
163 *tail = &new_pat->next;
164 p->next = new_pat;
165 *nl = '\0';
166 p->patternlen -= len;
168 break;
169 default:
170 break;
174 void append_header_grep_pattern(struct grep_opt *opt,
175 enum grep_header_field field, const char *pat)
177 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
178 GREP_PATTERN_HEAD, field);
179 if (field == GREP_HEADER_REFLOG)
180 opt->use_reflog_filter = 1;
181 do_append_grep_pat(&opt->header_tail, p);
184 void append_grep_pattern(struct grep_opt *opt, const char *pat,
185 const char *origin, int no, enum grep_pat_token t)
187 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
190 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
191 const char *origin, int no, enum grep_pat_token t)
193 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
194 do_append_grep_pat(&opt->pattern_tail, p);
197 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
199 struct grep_pat *pat;
200 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
201 *ret = *opt;
203 ret->pattern_list = NULL;
204 ret->pattern_tail = &ret->pattern_list;
206 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
208 if(pat->token == GREP_PATTERN_HEAD)
209 append_header_grep_pattern(ret, pat->field,
210 pat->pattern);
211 else
212 append_grep_pat(ret, pat->pattern, pat->patternlen,
213 pat->origin, pat->no, pat->token);
216 return ret;
219 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
220 const char *error)
222 char where[1024];
224 if (p->no)
225 xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
226 else if (p->origin)
227 xsnprintf(where, sizeof(where), "%s, ", p->origin);
228 else
229 where[0] = 0;
231 die("%s'%s': %s", where, p->pattern, error);
234 static int is_fixed(const char *s, size_t len)
236 size_t i;
238 for (i = 0; i < len; i++) {
239 if (is_regex_special(s[i]))
240 return 0;
243 return 1;
246 #ifdef USE_LIBPCRE2
247 #define GREP_PCRE2_DEBUG_MALLOC 0
249 static void *pcre2_malloc(PCRE2_SIZE size, MAYBE_UNUSED void *memory_data)
251 void *pointer = malloc(size);
252 #if GREP_PCRE2_DEBUG_MALLOC
253 static int count = 1;
254 fprintf(stderr, "PCRE2:%p -> #%02d: alloc(%lu)\n", pointer, count++, size);
255 #endif
256 return pointer;
259 static void pcre2_free(void *pointer, MAYBE_UNUSED void *memory_data)
261 #if GREP_PCRE2_DEBUG_MALLOC
262 static int count = 1;
263 if (pointer)
264 fprintf(stderr, "PCRE2:%p -> #%02d: free()\n", pointer, count++);
265 #endif
266 free(pointer);
269 static int pcre2_jit_functional(void)
271 static int jit_working = -1;
272 pcre2_code *code;
273 size_t off;
274 int err;
276 if (jit_working != -1)
277 return jit_working;
280 * Try to JIT compile a simple pattern to probe if the JIT is
281 * working in general. It might fail for systems where creating
282 * memory mappings for runtime code generation is restricted.
284 code = pcre2_compile((PCRE2_SPTR)".", 1, 0, &err, &off, NULL);
285 if (!code)
286 return 0;
288 jit_working = pcre2_jit_compile(code, PCRE2_JIT_COMPLETE) == 0;
289 pcre2_code_free(code);
291 return jit_working;
294 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
296 int error;
297 PCRE2_UCHAR errbuf[256];
298 PCRE2_SIZE erroffset;
299 int options = PCRE2_MULTILINE;
300 int jitret;
301 int patinforet;
302 size_t jitsizearg;
303 int literal = !opt->ignore_case && (p->fixed || p->is_fixed);
306 * Call pcre2_general_context_create() before calling any
307 * other pcre2_*(). It sets up our malloc()/free() functions
308 * with which everything else is allocated.
310 p->pcre2_general_context = pcre2_general_context_create(
311 pcre2_malloc, pcre2_free, NULL);
312 if (!p->pcre2_general_context)
313 die("Couldn't allocate PCRE2 general context");
315 if (opt->ignore_case) {
316 if (!opt->ignore_locale && has_non_ascii(p->pattern)) {
317 p->pcre2_tables = pcre2_maketables(p->pcre2_general_context);
318 p->pcre2_compile_context = pcre2_compile_context_create(p->pcre2_general_context);
319 pcre2_set_character_tables(p->pcre2_compile_context,
320 p->pcre2_tables);
322 options |= PCRE2_CASELESS;
324 if (!opt->ignore_locale && is_utf8_locale() && !literal)
325 options |= (PCRE2_UTF | PCRE2_UCP | PCRE2_MATCH_INVALID_UTF);
327 #ifndef GIT_PCRE2_VERSION_10_35_OR_HIGHER
329 * Work around a JIT bug related to invalid Unicode character handling
330 * fixed in 10.35:
331 * https://github.com/PCRE2Project/pcre2/commit/c21bd977547d
333 options &= ~PCRE2_UCP;
334 #endif
336 #ifndef GIT_PCRE2_VERSION_10_36_OR_HIGHER
337 /* Work around https://bugs.exim.org/show_bug.cgi?id=2642 fixed in 10.36 */
338 if (PCRE2_MATCH_INVALID_UTF && options & (PCRE2_UTF | PCRE2_CASELESS))
339 options |= PCRE2_NO_START_OPTIMIZE;
340 #endif
342 p->pcre2_pattern = pcre2_compile((PCRE2_SPTR)p->pattern,
343 p->patternlen, options, &error, &erroffset,
344 p->pcre2_compile_context);
346 if (p->pcre2_pattern) {
347 p->pcre2_match_data = pcre2_match_data_create_from_pattern(p->pcre2_pattern, p->pcre2_general_context);
348 if (!p->pcre2_match_data)
349 die("Couldn't allocate PCRE2 match data");
350 } else {
351 pcre2_get_error_message(error, errbuf, sizeof(errbuf));
352 compile_regexp_failed(p, (const char *)&errbuf);
355 pcre2_config(PCRE2_CONFIG_JIT, &p->pcre2_jit_on);
356 if (p->pcre2_jit_on) {
357 jitret = pcre2_jit_compile(p->pcre2_pattern, PCRE2_JIT_COMPLETE);
358 if (jitret == PCRE2_ERROR_NOMEMORY && !pcre2_jit_functional()) {
360 * Even though pcre2_config(PCRE2_CONFIG_JIT, ...)
361 * indicated JIT support, the library might still
362 * fail to generate JIT code for various reasons,
363 * e.g. when SELinux's 'deny_execmem' or PaX's
364 * MPROTECT prevent creating W|X memory mappings.
366 * Instead of faling hard, fall back to interpreter
367 * mode, just as if the pattern was prefixed with
368 * '(*NO_JIT)'.
370 p->pcre2_jit_on = 0;
371 return;
372 } else if (jitret) {
373 int need_clip = p->patternlen > 64;
374 int clip_len = need_clip ? 64 : p->patternlen;
375 die("Couldn't JIT the PCRE2 pattern '%.*s'%s, got '%d'%s",
376 clip_len, p->pattern, need_clip ? "..." : "", jitret,
377 pcre2_jit_functional()
378 ? "\nPerhaps prefix (*NO_JIT) to your pattern?"
379 : "");
383 * The pcre2_config(PCRE2_CONFIG_JIT, ...) call just
384 * tells us whether the library itself supports JIT,
385 * but to see whether we're going to be actually using
386 * JIT we need to extract PCRE2_INFO_JITSIZE from the
387 * pattern *after* we do pcre2_jit_compile() above.
389 * This is because if the pattern contains the
390 * (*NO_JIT) verb (see pcre2syntax(3))
391 * pcre2_jit_compile() will exit early with 0. If we
392 * then proceed to call pcre2_jit_match() further down
393 * the line instead of pcre2_match() we'll either
394 * segfault (pre PCRE 10.31) or run into a fatal error
395 * (post PCRE2 10.31)
397 patinforet = pcre2_pattern_info(p->pcre2_pattern, PCRE2_INFO_JITSIZE, &jitsizearg);
398 if (patinforet)
399 BUG("pcre2_pattern_info() failed: %d", patinforet);
400 if (jitsizearg == 0) {
401 p->pcre2_jit_on = 0;
402 return;
407 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
408 regmatch_t *match, int eflags)
410 int ret, flags = 0;
411 PCRE2_SIZE *ovector;
412 PCRE2_UCHAR errbuf[256];
414 if (eflags & REG_NOTBOL)
415 flags |= PCRE2_NOTBOL;
417 if (p->pcre2_jit_on)
418 ret = pcre2_jit_match(p->pcre2_pattern, (unsigned char *)line,
419 eol - line, 0, flags, p->pcre2_match_data,
420 NULL);
421 else
422 ret = pcre2_match(p->pcre2_pattern, (unsigned char *)line,
423 eol - line, 0, flags, p->pcre2_match_data,
424 NULL);
426 if (ret < 0 && ret != PCRE2_ERROR_NOMATCH) {
427 pcre2_get_error_message(ret, errbuf, sizeof(errbuf));
428 die("%s failed with error code %d: %s",
429 (p->pcre2_jit_on ? "pcre2_jit_match" : "pcre2_match"), ret,
430 errbuf);
432 if (ret > 0) {
433 ovector = pcre2_get_ovector_pointer(p->pcre2_match_data);
434 ret = 0;
435 match->rm_so = (int)ovector[0];
436 match->rm_eo = (int)ovector[1];
439 return ret;
442 static void free_pcre2_pattern(struct grep_pat *p)
444 pcre2_compile_context_free(p->pcre2_compile_context);
445 pcre2_code_free(p->pcre2_pattern);
446 pcre2_match_data_free(p->pcre2_match_data);
447 #ifdef GIT_PCRE2_VERSION_10_34_OR_HIGHER
448 pcre2_maketables_free(p->pcre2_general_context, p->pcre2_tables);
449 #else
450 free((void *)p->pcre2_tables);
451 #endif
452 pcre2_general_context_free(p->pcre2_general_context);
454 #else /* !USE_LIBPCRE2 */
455 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
457 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
460 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
461 regmatch_t *match, int eflags)
463 return 1;
466 static void free_pcre2_pattern(struct grep_pat *p)
470 static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
472 struct strbuf sb = STRBUF_INIT;
473 int err;
474 int regflags = 0;
476 basic_regex_quote_buf(&sb, p->pattern);
477 if (opt->ignore_case)
478 regflags |= REG_ICASE;
479 err = regcomp(&p->regexp, sb.buf, regflags);
480 strbuf_release(&sb);
481 if (err) {
482 char errbuf[1024];
483 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
484 compile_regexp_failed(p, errbuf);
487 #endif /* !USE_LIBPCRE2 */
489 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
491 int err;
492 int regflags = REG_NEWLINE;
494 if (opt->pattern_type_option == GREP_PATTERN_TYPE_UNSPECIFIED)
495 opt->pattern_type_option = (opt->extended_regexp_option
496 ? GREP_PATTERN_TYPE_ERE
497 : GREP_PATTERN_TYPE_BRE);
499 p->word_regexp = opt->word_regexp;
500 p->ignore_case = opt->ignore_case;
501 p->fixed = opt->pattern_type_option == GREP_PATTERN_TYPE_FIXED;
503 if (opt->pattern_type_option != GREP_PATTERN_TYPE_PCRE &&
504 memchr(p->pattern, 0, p->patternlen))
505 die(_("given pattern contains NULL byte (via -f <file>). This is only supported with -P under PCRE v2"));
507 p->is_fixed = is_fixed(p->pattern, p->patternlen);
508 #ifdef USE_LIBPCRE2
509 if (!p->fixed && !p->is_fixed) {
510 const char *no_jit = "(*NO_JIT)";
511 const int no_jit_len = strlen(no_jit);
512 if (starts_with(p->pattern, no_jit) &&
513 is_fixed(p->pattern + no_jit_len,
514 p->patternlen - no_jit_len))
515 p->is_fixed = 1;
517 #endif
518 if (p->fixed || p->is_fixed) {
519 #ifdef USE_LIBPCRE2
520 if (p->is_fixed) {
521 compile_pcre2_pattern(p, opt);
522 } else {
524 * E.g. t7811-grep-open.sh relies on the
525 * pattern being restored.
527 char *old_pattern = p->pattern;
528 size_t old_patternlen = p->patternlen;
529 struct strbuf sb = STRBUF_INIT;
532 * There is the PCRE2_LITERAL flag, but it's
533 * only in PCRE v2 10.30 and later. Needing to
534 * ifdef our way around that and dealing with
535 * it + PCRE2_MULTILINE being an error is more
536 * complex than just quoting this ourselves.
538 strbuf_add(&sb, "\\Q", 2);
539 strbuf_add(&sb, p->pattern, p->patternlen);
540 strbuf_add(&sb, "\\E", 2);
542 p->pattern = sb.buf;
543 p->patternlen = sb.len;
544 compile_pcre2_pattern(p, opt);
545 p->pattern = old_pattern;
546 p->patternlen = old_patternlen;
547 strbuf_release(&sb);
549 #else /* !USE_LIBPCRE2 */
550 compile_fixed_regexp(p, opt);
551 #endif /* !USE_LIBPCRE2 */
552 return;
555 if (opt->pattern_type_option == GREP_PATTERN_TYPE_PCRE) {
556 compile_pcre2_pattern(p, opt);
557 return;
560 if (p->ignore_case)
561 regflags |= REG_ICASE;
562 if (opt->pattern_type_option == GREP_PATTERN_TYPE_ERE)
563 regflags |= REG_EXTENDED;
564 err = regcomp(&p->regexp, p->pattern, regflags);
565 if (err) {
566 char errbuf[1024];
567 regerror(err, &p->regexp, errbuf, 1024);
568 compile_regexp_failed(p, errbuf);
572 static struct grep_expr *grep_not_expr(struct grep_expr *expr)
574 struct grep_expr *z = xcalloc(1, sizeof(*z));
575 z->node = GREP_NODE_NOT;
576 z->u.unary = expr;
577 return z;
580 static struct grep_expr *grep_binexp(enum grep_expr_node kind,
581 struct grep_expr *left,
582 struct grep_expr *right)
584 struct grep_expr *z = xcalloc(1, sizeof(*z));
585 z->node = kind;
586 z->u.binary.left = left;
587 z->u.binary.right = right;
588 return z;
591 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
593 return grep_binexp(GREP_NODE_OR, left, right);
596 static struct grep_expr *grep_and_expr(struct grep_expr *left, struct grep_expr *right)
598 return grep_binexp(GREP_NODE_AND, left, right);
601 static struct grep_expr *compile_pattern_or(struct grep_pat **);
602 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
604 struct grep_pat *p;
605 struct grep_expr *x;
607 p = *list;
608 if (!p)
609 return NULL;
610 switch (p->token) {
611 case GREP_PATTERN: /* atom */
612 case GREP_PATTERN_HEAD:
613 case GREP_PATTERN_BODY:
614 CALLOC_ARRAY(x, 1);
615 x->node = GREP_NODE_ATOM;
616 x->u.atom = p;
617 *list = p->next;
618 return x;
619 case GREP_OPEN_PAREN:
620 *list = p->next;
621 x = compile_pattern_or(list);
622 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
623 die("unmatched parenthesis");
624 *list = (*list)->next;
625 return x;
626 default:
627 return NULL;
631 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
633 struct grep_pat *p;
634 struct grep_expr *x;
636 p = *list;
637 if (!p)
638 return NULL;
639 switch (p->token) {
640 case GREP_NOT:
641 if (!p->next)
642 die("--not not followed by pattern expression");
643 *list = p->next;
644 x = compile_pattern_not(list);
645 if (!x)
646 die("--not followed by non pattern expression");
647 return grep_not_expr(x);
648 default:
649 return compile_pattern_atom(list);
653 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
655 struct grep_pat *p;
656 struct grep_expr *x, *y;
658 x = compile_pattern_not(list);
659 p = *list;
660 if (p && p->token == GREP_AND) {
661 if (!x)
662 die("--and not preceded by pattern expression");
663 if (!p->next)
664 die("--and not followed by pattern expression");
665 *list = p->next;
666 y = compile_pattern_and(list);
667 if (!y)
668 die("--and not followed by pattern expression");
669 return grep_and_expr(x, y);
671 return x;
674 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
676 struct grep_pat *p;
677 struct grep_expr *x, *y;
679 x = compile_pattern_and(list);
680 p = *list;
681 if (x && p && p->token != GREP_CLOSE_PAREN) {
682 y = compile_pattern_or(list);
683 if (!y)
684 die("not a pattern expression %s", p->pattern);
685 return grep_or_expr(x, y);
687 return x;
690 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
692 return compile_pattern_or(list);
695 static struct grep_expr *grep_true_expr(void)
697 struct grep_expr *z = xcalloc(1, sizeof(*z));
698 z->node = GREP_NODE_TRUE;
699 return z;
702 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
704 struct grep_pat *p;
705 struct grep_expr *header_expr;
706 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
707 enum grep_header_field fld;
709 if (!opt->header_list)
710 return NULL;
712 for (p = opt->header_list; p; p = p->next) {
713 if (p->token != GREP_PATTERN_HEAD)
714 BUG("a non-header pattern in grep header list.");
715 if (p->field < GREP_HEADER_FIELD_MIN ||
716 GREP_HEADER_FIELD_MAX <= p->field)
717 BUG("unknown header field %d", p->field);
718 compile_regexp(p, opt);
721 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
722 header_group[fld] = NULL;
724 for (p = opt->header_list; p; p = p->next) {
725 struct grep_expr *h;
726 struct grep_pat *pp = p;
728 h = compile_pattern_atom(&pp);
729 if (!h || pp != p->next)
730 BUG("malformed header expr");
731 if (!header_group[p->field]) {
732 header_group[p->field] = h;
733 continue;
735 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
738 header_expr = NULL;
740 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
741 if (!header_group[fld])
742 continue;
743 if (!header_expr)
744 header_expr = grep_true_expr();
745 header_expr = grep_or_expr(header_group[fld], header_expr);
747 return header_expr;
750 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
752 struct grep_expr *z = x;
754 while (x) {
755 assert(x->node == GREP_NODE_OR);
756 if (x->u.binary.right &&
757 x->u.binary.right->node == GREP_NODE_TRUE) {
758 x->u.binary.right = y;
759 break;
761 x = x->u.binary.right;
763 return z;
766 void compile_grep_patterns(struct grep_opt *opt)
768 struct grep_pat *p;
769 struct grep_expr *header_expr = prep_header_patterns(opt);
770 int extended = 0;
772 for (p = opt->pattern_list; p; p = p->next) {
773 switch (p->token) {
774 case GREP_PATTERN: /* atom */
775 case GREP_PATTERN_HEAD:
776 case GREP_PATTERN_BODY:
777 compile_regexp(p, opt);
778 break;
779 default:
780 extended = 1;
781 break;
785 if (opt->all_match || opt->no_body_match || header_expr)
786 extended = 1;
787 else if (!extended)
788 return;
790 p = opt->pattern_list;
791 if (p)
792 opt->pattern_expression = compile_pattern_expr(&p);
793 if (p)
794 die("incomplete pattern expression: %s", p->pattern);
796 if (opt->no_body_match && opt->pattern_expression)
797 opt->pattern_expression = grep_not_expr(opt->pattern_expression);
799 if (!header_expr)
800 return;
802 if (!opt->pattern_expression)
803 opt->pattern_expression = header_expr;
804 else if (opt->all_match)
805 opt->pattern_expression = grep_splice_or(header_expr,
806 opt->pattern_expression);
807 else
808 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
809 header_expr);
810 opt->all_match = 1;
813 static void free_pattern_expr(struct grep_expr *x)
815 switch (x->node) {
816 case GREP_NODE_TRUE:
817 case GREP_NODE_ATOM:
818 break;
819 case GREP_NODE_NOT:
820 free_pattern_expr(x->u.unary);
821 break;
822 case GREP_NODE_AND:
823 case GREP_NODE_OR:
824 free_pattern_expr(x->u.binary.left);
825 free_pattern_expr(x->u.binary.right);
826 break;
828 free(x);
831 static void free_grep_pat(struct grep_pat *pattern)
833 struct grep_pat *p, *n;
835 for (p = pattern; p; p = n) {
836 n = p->next;
837 switch (p->token) {
838 case GREP_PATTERN: /* atom */
839 case GREP_PATTERN_HEAD:
840 case GREP_PATTERN_BODY:
841 if (p->pcre2_pattern)
842 free_pcre2_pattern(p);
843 else
844 regfree(&p->regexp);
845 free(p->pattern);
846 break;
847 default:
848 break;
850 free(p);
854 void free_grep_patterns(struct grep_opt *opt)
856 free_grep_pat(opt->pattern_list);
857 free_grep_pat(opt->header_list);
859 if (opt->pattern_expression)
860 free_pattern_expr(opt->pattern_expression);
863 static const char *end_of_line(const char *cp, unsigned long *left)
865 unsigned long l = *left;
866 while (l && *cp != '\n') {
867 l--;
868 cp++;
870 *left = l;
871 return cp;
874 static int word_char(char ch)
876 return isalnum(ch) || ch == '_';
879 static void output_color(struct grep_opt *opt, const void *data, size_t size,
880 const char *color)
882 if (want_color(opt->color) && color && color[0]) {
883 opt->output(opt, color, strlen(color));
884 opt->output(opt, data, size);
885 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
886 } else
887 opt->output(opt, data, size);
890 static void output_sep(struct grep_opt *opt, char sign)
892 if (opt->null_following_name)
893 opt->output(opt, "\0", 1);
894 else
895 output_color(opt, &sign, 1, opt->colors[GREP_COLOR_SEP]);
898 static void show_name(struct grep_opt *opt, const char *name)
900 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
901 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
904 static int patmatch(struct grep_pat *p,
905 const char *line, const char *eol,
906 regmatch_t *match, int eflags)
908 int hit;
910 if (p->pcre2_pattern)
911 hit = !pcre2match(p, line, eol, match, eflags);
912 else
913 hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
914 eflags);
916 return hit;
919 static void strip_timestamp(const char *bol, const char **eol_p)
921 const char *eol = *eol_p;
923 while (bol < --eol) {
924 if (*eol != '>')
925 continue;
926 *eol_p = ++eol;
927 break;
931 static struct {
932 const char *field;
933 size_t len;
934 } header_field[] = {
935 { "author ", 7 },
936 { "committer ", 10 },
937 { "reflog ", 7 },
940 static int headerless_match_one_pattern(struct grep_pat *p,
941 const char *bol, const char *eol,
942 enum grep_context ctx,
943 regmatch_t *pmatch, int eflags)
945 int hit = 0;
946 const char *start = bol;
948 if ((p->token != GREP_PATTERN) &&
949 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
950 return 0;
952 again:
953 hit = patmatch(p, bol, eol, pmatch, eflags);
955 if (hit && p->word_regexp) {
956 if ((pmatch[0].rm_so < 0) ||
957 (eol - bol) < pmatch[0].rm_so ||
958 (pmatch[0].rm_eo < 0) ||
959 (eol - bol) < pmatch[0].rm_eo)
960 die("regexp returned nonsense");
962 /* Match beginning must be either beginning of the
963 * line, or at word boundary (i.e. the last char must
964 * not be a word char). Similarly, match end must be
965 * either end of the line, or at word boundary
966 * (i.e. the next char must not be a word char).
968 if ( ((pmatch[0].rm_so == 0) ||
969 !word_char(bol[pmatch[0].rm_so-1])) &&
970 ((pmatch[0].rm_eo == (eol-bol)) ||
971 !word_char(bol[pmatch[0].rm_eo])) )
973 else
974 hit = 0;
976 /* Words consist of at least one character. */
977 if (pmatch->rm_so == pmatch->rm_eo)
978 hit = 0;
980 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
981 /* There could be more than one match on the
982 * line, and the first match might not be
983 * strict word match. But later ones could be!
984 * Forward to the next possible start, i.e. the
985 * next position following a non-word char.
987 bol = pmatch[0].rm_so + bol + 1;
988 while (word_char(bol[-1]) && bol < eol)
989 bol++;
990 eflags |= REG_NOTBOL;
991 if (bol < eol)
992 goto again;
995 if (hit) {
996 pmatch[0].rm_so += bol - start;
997 pmatch[0].rm_eo += bol - start;
999 return hit;
1002 static int match_one_pattern(struct grep_pat *p,
1003 const char *bol, const char *eol,
1004 enum grep_context ctx, regmatch_t *pmatch,
1005 int eflags)
1007 const char *field;
1008 size_t len;
1010 if (p->token == GREP_PATTERN_HEAD) {
1011 assert(p->field < ARRAY_SIZE(header_field));
1012 field = header_field[p->field].field;
1013 len = header_field[p->field].len;
1014 if (strncmp(bol, field, len))
1015 return 0;
1016 bol += len;
1018 switch (p->field) {
1019 case GREP_HEADER_AUTHOR:
1020 case GREP_HEADER_COMMITTER:
1021 strip_timestamp(bol, &eol);
1022 break;
1023 default:
1024 break;
1028 return headerless_match_one_pattern(p, bol, eol, ctx, pmatch, eflags);
1032 static int match_expr_eval(struct grep_opt *opt, struct grep_expr *x,
1033 const char *bol, const char *eol,
1034 enum grep_context ctx, ssize_t *col,
1035 ssize_t *icol, int collect_hits)
1037 int h = 0;
1039 switch (x->node) {
1040 case GREP_NODE_TRUE:
1041 h = 1;
1042 break;
1043 case GREP_NODE_ATOM:
1045 regmatch_t tmp;
1046 h = match_one_pattern(x->u.atom, bol, eol, ctx,
1047 &tmp, 0);
1048 if (h && (*col < 0 || tmp.rm_so < *col))
1049 *col = tmp.rm_so;
1051 if (x->u.atom->token == GREP_PATTERN_BODY)
1052 opt->body_hit |= h;
1053 break;
1054 case GREP_NODE_NOT:
1056 * Upon visiting a GREP_NODE_NOT, col and icol become swapped.
1058 h = !match_expr_eval(opt, x->u.unary, bol, eol, ctx, icol, col,
1060 break;
1061 case GREP_NODE_AND:
1062 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1063 icol, 0);
1064 if (h || opt->columnnum) {
1066 * Don't short-circuit AND when given --column, since a
1067 * NOT earlier in the tree may turn this into an OR. In
1068 * this case, see the below comment.
1070 h &= match_expr_eval(opt, x->u.binary.right, bol, eol,
1071 ctx, col, icol, 0);
1073 break;
1074 case GREP_NODE_OR:
1075 if (!(collect_hits || opt->columnnum)) {
1077 * Don't short-circuit OR when given --column (or
1078 * collecting hits) to ensure we don't skip a later
1079 * child that would produce an earlier match.
1081 return (match_expr_eval(opt, x->u.binary.left, bol, eol,
1082 ctx, col, icol, 0) ||
1083 match_expr_eval(opt, x->u.binary.right, bol,
1084 eol, ctx, col, icol, 0));
1086 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1087 icol, 0);
1088 if (collect_hits)
1089 x->u.binary.left->hit |= h;
1090 h |= match_expr_eval(opt, x->u.binary.right, bol, eol, ctx, col,
1091 icol, collect_hits);
1092 break;
1093 default:
1094 die("Unexpected node type (internal error) %d", x->node);
1096 if (collect_hits)
1097 x->hit |= h;
1098 return h;
1101 static int match_expr(struct grep_opt *opt,
1102 const char *bol, const char *eol,
1103 enum grep_context ctx, ssize_t *col,
1104 ssize_t *icol, int collect_hits)
1106 struct grep_expr *x = opt->pattern_expression;
1107 return match_expr_eval(opt, x, bol, eol, ctx, col, icol, collect_hits);
1110 static int match_line(struct grep_opt *opt,
1111 const char *bol, const char *eol,
1112 ssize_t *col, ssize_t *icol,
1113 enum grep_context ctx, int collect_hits)
1115 struct grep_pat *p;
1116 int hit = 0;
1118 if (opt->pattern_expression)
1119 return match_expr(opt, bol, eol, ctx, col, icol,
1120 collect_hits);
1122 /* we do not call with collect_hits without being extended */
1123 for (p = opt->pattern_list; p; p = p->next) {
1124 regmatch_t tmp;
1125 if (match_one_pattern(p, bol, eol, ctx, &tmp, 0)) {
1126 hit |= 1;
1127 if (!opt->columnnum) {
1129 * Without --column, any single match on a line
1130 * is enough to know that it needs to be
1131 * printed. With --column, scan _all_ patterns
1132 * to find the earliest.
1134 break;
1136 if (*col < 0 || tmp.rm_so < *col)
1137 *col = tmp.rm_so;
1140 return hit;
1143 static int match_next_pattern(struct grep_pat *p,
1144 const char *bol, const char *eol,
1145 enum grep_context ctx,
1146 regmatch_t *pmatch, int eflags)
1148 regmatch_t match;
1150 if (!headerless_match_one_pattern(p, bol, eol, ctx, &match, eflags))
1151 return 0;
1152 if (match.rm_so < 0 || match.rm_eo < 0)
1153 return 0;
1154 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1155 if (match.rm_so > pmatch->rm_so)
1156 return 1;
1157 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1158 return 1;
1160 pmatch->rm_so = match.rm_so;
1161 pmatch->rm_eo = match.rm_eo;
1162 return 1;
1165 int grep_next_match(struct grep_opt *opt,
1166 const char *bol, const char *eol,
1167 enum grep_context ctx, regmatch_t *pmatch,
1168 enum grep_header_field field, int eflags)
1170 struct grep_pat *p;
1171 int hit = 0;
1173 pmatch->rm_so = pmatch->rm_eo = -1;
1174 if (bol < eol) {
1175 for (p = ((ctx == GREP_CONTEXT_HEAD)
1176 ? opt->header_list : opt->pattern_list);
1177 p; p = p->next) {
1178 switch (p->token) {
1179 case GREP_PATTERN_HEAD:
1180 if ((field != GREP_HEADER_FIELD_MAX) &&
1181 (p->field != field))
1182 continue;
1183 /* fall thru */
1184 case GREP_PATTERN: /* atom */
1185 case GREP_PATTERN_BODY:
1186 hit |= match_next_pattern(p, bol, eol, ctx,
1187 pmatch, eflags);
1188 break;
1189 default:
1190 break;
1194 return hit;
1197 static void show_line_header(struct grep_opt *opt, const char *name,
1198 unsigned lno, ssize_t cno, char sign)
1200 if (opt->heading && opt->last_shown == 0) {
1201 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1202 opt->output(opt, "\n", 1);
1204 opt->last_shown = lno;
1206 if (!opt->heading && opt->pathname) {
1207 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1208 output_sep(opt, sign);
1210 if (opt->linenum) {
1211 char buf[32];
1212 xsnprintf(buf, sizeof(buf), "%d", lno);
1213 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_LINENO]);
1214 output_sep(opt, sign);
1217 * Treat 'cno' as the 1-indexed offset from the start of a non-context
1218 * line to its first match. Otherwise, 'cno' is 0 indicating that we are
1219 * being called with a context line.
1221 if (opt->columnnum && cno) {
1222 char buf[32];
1223 xsnprintf(buf, sizeof(buf), "%"PRIuMAX, (uintmax_t)cno);
1224 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_COLUMNNO]);
1225 output_sep(opt, sign);
1229 static void show_line(struct grep_opt *opt,
1230 const char *bol, const char *eol,
1231 const char *name, unsigned lno, ssize_t cno, char sign)
1233 int rest = eol - bol;
1234 const char *match_color = NULL;
1235 const char *line_color = NULL;
1237 if (opt->file_break && opt->last_shown == 0) {
1238 if (opt->show_hunk_mark)
1239 opt->output(opt, "\n", 1);
1240 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1241 if (opt->last_shown == 0) {
1242 if (opt->show_hunk_mark) {
1243 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1244 opt->output(opt, "\n", 1);
1246 } else if (lno > opt->last_shown + 1) {
1247 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1248 opt->output(opt, "\n", 1);
1251 if (!opt->only_matching) {
1253 * In case the line we're being called with contains more than
1254 * one match, leave printing each header to the loop below.
1256 show_line_header(opt, name, lno, cno, sign);
1258 if (opt->color || opt->only_matching) {
1259 regmatch_t match;
1260 enum grep_context ctx = GREP_CONTEXT_BODY;
1261 int eflags = 0;
1263 if (opt->color) {
1264 if (sign == ':')
1265 match_color = opt->colors[GREP_COLOR_MATCH_SELECTED];
1266 else
1267 match_color = opt->colors[GREP_COLOR_MATCH_CONTEXT];
1268 if (sign == ':')
1269 line_color = opt->colors[GREP_COLOR_SELECTED];
1270 else if (sign == '-')
1271 line_color = opt->colors[GREP_COLOR_CONTEXT];
1272 else if (sign == '=')
1273 line_color = opt->colors[GREP_COLOR_FUNCTION];
1275 while (grep_next_match(opt, bol, eol, ctx, &match,
1276 GREP_HEADER_FIELD_MAX, eflags)) {
1277 if (match.rm_so == match.rm_eo)
1278 break;
1280 if (opt->only_matching)
1281 show_line_header(opt, name, lno, cno, sign);
1282 else
1283 output_color(opt, bol, match.rm_so, line_color);
1284 output_color(opt, bol + match.rm_so,
1285 match.rm_eo - match.rm_so, match_color);
1286 if (opt->only_matching)
1287 opt->output(opt, "\n", 1);
1288 bol += match.rm_eo;
1289 cno += match.rm_eo;
1290 rest -= match.rm_eo;
1291 eflags = REG_NOTBOL;
1294 if (!opt->only_matching) {
1295 output_color(opt, bol, rest, line_color);
1296 opt->output(opt, "\n", 1);
1300 int grep_use_locks;
1303 * This lock protects access to the gitattributes machinery, which is
1304 * not thread-safe.
1306 pthread_mutex_t grep_attr_mutex;
1308 static inline void grep_attr_lock(void)
1310 if (grep_use_locks)
1311 pthread_mutex_lock(&grep_attr_mutex);
1314 static inline void grep_attr_unlock(void)
1316 if (grep_use_locks)
1317 pthread_mutex_unlock(&grep_attr_mutex);
1320 static int match_funcname(struct grep_opt *opt, struct grep_source *gs,
1321 const char *bol, const char *eol)
1323 xdemitconf_t *xecfg = opt->priv;
1324 if (xecfg && !xecfg->find_func) {
1325 grep_source_load_driver(gs, opt->repo->index);
1326 if (gs->driver->funcname.pattern) {
1327 const struct userdiff_funcname *pe = &gs->driver->funcname;
1328 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1329 } else {
1330 xecfg = opt->priv = NULL;
1334 if (xecfg) {
1335 char buf[1];
1336 return xecfg->find_func(bol, eol - bol, buf, 1,
1337 xecfg->find_func_priv) >= 0;
1340 if (bol == eol)
1341 return 0;
1342 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1343 return 1;
1344 return 0;
1347 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1348 const char *bol, unsigned lno)
1350 while (bol > gs->buf) {
1351 const char *eol = --bol;
1353 while (bol > gs->buf && bol[-1] != '\n')
1354 bol--;
1355 lno--;
1357 if (lno <= opt->last_shown)
1358 break;
1360 if (match_funcname(opt, gs, bol, eol)) {
1361 show_line(opt, bol, eol, gs->name, lno, 0, '=');
1362 break;
1367 static int is_empty_line(const char *bol, const char *eol);
1369 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1370 const char *bol, const char *end, unsigned lno)
1372 unsigned cur = lno, from = 1, funcname_lno = 0, orig_from;
1373 int funcname_needed = !!opt->funcname, comment_needed = 0;
1375 if (opt->pre_context < lno)
1376 from = lno - opt->pre_context;
1377 if (from <= opt->last_shown)
1378 from = opt->last_shown + 1;
1379 orig_from = from;
1380 if (opt->funcbody) {
1381 if (match_funcname(opt, gs, bol, end))
1382 comment_needed = 1;
1383 else
1384 funcname_needed = 1;
1385 from = opt->last_shown + 1;
1388 /* Rewind. */
1389 while (bol > gs->buf && cur > from) {
1390 const char *next_bol = bol;
1391 const char *eol = --bol;
1393 while (bol > gs->buf && bol[-1] != '\n')
1394 bol--;
1395 cur--;
1396 if (comment_needed && (is_empty_line(bol, eol) ||
1397 match_funcname(opt, gs, bol, eol))) {
1398 comment_needed = 0;
1399 from = orig_from;
1400 if (cur < from) {
1401 cur++;
1402 bol = next_bol;
1403 break;
1406 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1407 funcname_lno = cur;
1408 funcname_needed = 0;
1409 if (opt->funcbody)
1410 comment_needed = 1;
1411 else
1412 from = orig_from;
1416 /* We need to look even further back to find a function signature. */
1417 if (opt->funcname && funcname_needed)
1418 show_funcname_line(opt, gs, bol, cur);
1420 /* Back forward. */
1421 while (cur < lno) {
1422 const char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1424 while (*eol != '\n')
1425 eol++;
1426 show_line(opt, bol, eol, gs->name, cur, 0, sign);
1427 bol = eol + 1;
1428 cur++;
1432 static int should_lookahead(struct grep_opt *opt)
1434 struct grep_pat *p;
1436 if (opt->pattern_expression)
1437 return 0; /* punt for too complex stuff */
1438 if (opt->invert)
1439 return 0;
1440 for (p = opt->pattern_list; p; p = p->next) {
1441 if (p->token != GREP_PATTERN)
1442 return 0; /* punt for "header only" and stuff */
1444 return 1;
1447 static int look_ahead(struct grep_opt *opt,
1448 unsigned long *left_p,
1449 unsigned *lno_p,
1450 const char **bol_p)
1452 unsigned lno = *lno_p;
1453 const char *bol = *bol_p;
1454 struct grep_pat *p;
1455 const char *sp, *last_bol;
1456 regoff_t earliest = -1;
1458 for (p = opt->pattern_list; p; p = p->next) {
1459 int hit;
1460 regmatch_t m;
1462 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1463 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1464 continue;
1465 if (earliest < 0 || m.rm_so < earliest)
1466 earliest = m.rm_so;
1469 if (earliest < 0) {
1470 *bol_p = bol + *left_p;
1471 *left_p = 0;
1472 return 1;
1474 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1475 ; /* find the beginning of the line */
1476 last_bol = sp;
1478 for (sp = bol; sp < last_bol; sp++) {
1479 if (*sp == '\n')
1480 lno++;
1482 *left_p -= last_bol - bol;
1483 *bol_p = last_bol;
1484 *lno_p = lno;
1485 return 0;
1488 static int fill_textconv_grep(struct repository *r,
1489 struct userdiff_driver *driver,
1490 struct grep_source *gs)
1492 struct diff_filespec *df;
1493 char *buf;
1494 size_t size;
1496 if (!driver || !driver->textconv)
1497 return grep_source_load(gs);
1500 * The textconv interface is intimately tied to diff_filespecs, so we
1501 * have to pretend to be one. If we could unify the grep_source
1502 * and diff_filespec structs, this mess could just go away.
1504 df = alloc_filespec(gs->path);
1505 switch (gs->type) {
1506 case GREP_SOURCE_OID:
1507 fill_filespec(df, gs->identifier, 1, 0100644);
1508 break;
1509 case GREP_SOURCE_FILE:
1510 fill_filespec(df, null_oid(), 0, 0100644);
1511 break;
1512 default:
1513 BUG("attempt to textconv something without a path?");
1517 * fill_textconv is not remotely thread-safe; it modifies the global
1518 * diff tempfile structure, writes to the_repo's odb and might
1519 * internally call thread-unsafe functions such as the
1520 * prepare_packed_git() lazy-initializator. Because of the last two, we
1521 * must ensure mutual exclusion between this call and the object reading
1522 * API, thus we use obj_read_lock() here.
1524 * TODO: allowing text conversion to run in parallel with object
1525 * reading operations might increase performance in the multithreaded
1526 * non-worktreee git-grep with --textconv.
1528 obj_read_lock();
1529 size = fill_textconv(r, driver, df, &buf);
1530 obj_read_unlock();
1531 free_filespec(df);
1534 * The normal fill_textconv usage by the diff machinery would just keep
1535 * the textconv'd buf separate from the diff_filespec. But much of the
1536 * grep code passes around a grep_source and assumes that its "buf"
1537 * pointer is the beginning of the thing we are searching. So let's
1538 * install our textconv'd version into the grep_source, taking care not
1539 * to leak any existing buffer.
1541 grep_source_clear_data(gs);
1542 gs->buf = buf;
1543 gs->size = size;
1545 return 0;
1548 static int is_empty_line(const char *bol, const char *eol)
1550 while (bol < eol && isspace(*bol))
1551 bol++;
1552 return bol == eol;
1555 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1557 const char *bol;
1558 const char *peek_bol = NULL;
1559 unsigned long left;
1560 unsigned lno = 1;
1561 unsigned last_hit = 0;
1562 int binary_match_only = 0;
1563 unsigned count = 0;
1564 int try_lookahead = 0;
1565 int show_function = 0;
1566 struct userdiff_driver *textconv = NULL;
1567 enum grep_context ctx = GREP_CONTEXT_HEAD;
1568 xdemitconf_t xecfg;
1570 if (!opt->status_only && gs->name == NULL)
1571 BUG("grep call which could print a name requires "
1572 "grep_source.name be non-NULL");
1574 if (!opt->output)
1575 opt->output = std_output;
1577 if (opt->pre_context || opt->post_context || opt->file_break ||
1578 opt->funcbody) {
1579 /* Show hunk marks, except for the first file. */
1580 if (opt->last_shown)
1581 opt->show_hunk_mark = 1;
1583 * If we're using threads then we can't easily identify
1584 * the first file. Always put hunk marks in that case
1585 * and skip the very first one later in work_done().
1587 if (opt->output != std_output)
1588 opt->show_hunk_mark = 1;
1590 opt->last_shown = 0;
1592 if (opt->allow_textconv) {
1593 grep_source_load_driver(gs, opt->repo->index);
1595 * We might set up the shared textconv cache data here, which
1596 * is not thread-safe. Also, get_oid_with_context() and
1597 * parse_object() might be internally called. As they are not
1598 * currently thread-safe and might be racy with object reading,
1599 * obj_read_lock() must be called.
1601 grep_attr_lock();
1602 obj_read_lock();
1603 textconv = userdiff_get_textconv(opt->repo, gs->driver);
1604 obj_read_unlock();
1605 grep_attr_unlock();
1609 * We know the result of a textconv is text, so we only have to care
1610 * about binary handling if we are not using it.
1612 if (!textconv) {
1613 switch (opt->binary) {
1614 case GREP_BINARY_DEFAULT:
1615 if (grep_source_is_binary(gs, opt->repo->index))
1616 binary_match_only = 1;
1617 break;
1618 case GREP_BINARY_NOMATCH:
1619 if (grep_source_is_binary(gs, opt->repo->index))
1620 return 0; /* Assume unmatch */
1621 break;
1622 case GREP_BINARY_TEXT:
1623 break;
1624 default:
1625 BUG("unknown binary handling mode");
1629 memset(&xecfg, 0, sizeof(xecfg));
1630 opt->priv = &xecfg;
1632 try_lookahead = should_lookahead(opt);
1634 if (fill_textconv_grep(opt->repo, textconv, gs) < 0)
1635 return 0;
1637 bol = gs->buf;
1638 left = gs->size;
1639 while (left) {
1640 const char *eol;
1641 int hit;
1642 ssize_t cno;
1643 ssize_t col = -1, icol = -1;
1646 * look_ahead() skips quickly to the line that possibly
1647 * has the next hit; don't call it if we need to do
1648 * something more than just skipping the current line
1649 * in response to an unmatch for the current line. E.g.
1650 * inside a post-context window, we will show the current
1651 * line as a context around the previous hit when it
1652 * doesn't hit.
1654 if (try_lookahead
1655 && !(last_hit
1656 && (show_function ||
1657 lno <= last_hit + opt->post_context))
1658 && look_ahead(opt, &left, &lno, &bol))
1659 break;
1660 eol = end_of_line(bol, &left);
1662 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1663 ctx = GREP_CONTEXT_BODY;
1665 hit = match_line(opt, bol, eol, &col, &icol, ctx, collect_hits);
1667 if (collect_hits)
1668 goto next_line;
1670 /* "grep -v -e foo -e bla" should list lines
1671 * that do not have either, so inversion should
1672 * be done outside.
1674 if (opt->invert)
1675 hit = !hit;
1676 if (opt->unmatch_name_only) {
1677 if (hit)
1678 return 0;
1679 goto next_line;
1681 if (hit && (opt->max_count < 0 || count < opt->max_count)) {
1682 count++;
1683 if (opt->status_only)
1684 return 1;
1685 if (opt->name_only) {
1686 show_name(opt, gs->name);
1687 return 1;
1689 if (opt->count)
1690 goto next_line;
1691 if (binary_match_only) {
1692 opt->output(opt, "Binary file ", 12);
1693 output_color(opt, gs->name, strlen(gs->name),
1694 opt->colors[GREP_COLOR_FILENAME]);
1695 opt->output(opt, " matches\n", 9);
1696 return 1;
1698 /* Hit at this line. If we haven't shown the
1699 * pre-context lines, we would need to show them.
1701 if (opt->pre_context || opt->funcbody)
1702 show_pre_context(opt, gs, bol, eol, lno);
1703 else if (opt->funcname)
1704 show_funcname_line(opt, gs, bol, lno);
1705 cno = opt->invert ? icol : col;
1706 if (cno < 0) {
1708 * A negative cno indicates that there was no
1709 * match on the line. We are thus inverted and
1710 * being asked to show all lines that _don't_
1711 * match a given expression. Therefore, set cno
1712 * to 0 to suggest the whole line matches.
1714 cno = 0;
1716 show_line(opt, bol, eol, gs->name, lno, cno + 1, ':');
1717 last_hit = lno;
1718 if (opt->funcbody)
1719 show_function = 1;
1720 goto next_line;
1722 if (show_function && (!peek_bol || peek_bol < bol)) {
1723 unsigned long peek_left = left;
1724 const char *peek_eol = eol;
1727 * Trailing empty lines are not interesting.
1728 * Peek past them to see if they belong to the
1729 * body of the current function.
1731 peek_bol = bol;
1732 while (is_empty_line(peek_bol, peek_eol)) {
1733 peek_bol = peek_eol + 1;
1734 peek_eol = end_of_line(peek_bol, &peek_left);
1737 if (match_funcname(opt, gs, peek_bol, peek_eol))
1738 show_function = 0;
1740 if (show_function ||
1741 (last_hit && lno <= last_hit + opt->post_context)) {
1742 /* If the last hit is within the post context,
1743 * we need to show this line.
1745 show_line(opt, bol, eol, gs->name, lno, col + 1, '-');
1748 next_line:
1749 bol = eol + 1;
1750 if (!left)
1751 break;
1752 left--;
1753 lno++;
1756 if (collect_hits)
1757 return 0;
1759 if (opt->status_only)
1760 return opt->unmatch_name_only;
1761 if (opt->unmatch_name_only) {
1762 /* We did not see any hit, so we want to show this */
1763 show_name(opt, gs->name);
1764 return 1;
1767 xdiff_clear_find_func(&xecfg);
1768 opt->priv = NULL;
1770 /* NEEDSWORK:
1771 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1772 * which feels mostly useless but sometimes useful. Maybe
1773 * make it another option? For now suppress them.
1775 if (opt->count && count) {
1776 char buf[32];
1777 if (opt->pathname) {
1778 output_color(opt, gs->name, strlen(gs->name),
1779 opt->colors[GREP_COLOR_FILENAME]);
1780 output_sep(opt, ':');
1782 xsnprintf(buf, sizeof(buf), "%u\n", count);
1783 opt->output(opt, buf, strlen(buf));
1784 return 1;
1786 return !!last_hit;
1789 static void clr_hit_marker(struct grep_expr *x)
1791 /* All-hit markers are meaningful only at the very top level
1792 * OR node.
1794 while (1) {
1795 x->hit = 0;
1796 if (x->node != GREP_NODE_OR)
1797 return;
1798 x->u.binary.left->hit = 0;
1799 x = x->u.binary.right;
1803 static int chk_hit_marker(struct grep_expr *x)
1805 /* Top level nodes have hit markers. See if they all are hits */
1806 while (1) {
1807 if (x->node != GREP_NODE_OR)
1808 return x->hit;
1809 if (!x->u.binary.left->hit)
1810 return 0;
1811 x = x->u.binary.right;
1815 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1818 * we do not have to do the two-pass grep when we do not check
1819 * buffer-wide "all-match".
1821 if (!opt->all_match && !opt->no_body_match)
1822 return grep_source_1(opt, gs, 0);
1824 /* Otherwise the toplevel "or" terms hit a bit differently.
1825 * We first clear hit markers from them.
1827 clr_hit_marker(opt->pattern_expression);
1828 opt->body_hit = 0;
1829 grep_source_1(opt, gs, 1);
1831 if (opt->all_match && !chk_hit_marker(opt->pattern_expression))
1832 return 0;
1833 if (opt->no_body_match && opt->body_hit)
1834 return 0;
1836 return grep_source_1(opt, gs, 0);
1839 static void grep_source_init_buf(struct grep_source *gs,
1840 const char *buf,
1841 unsigned long size)
1843 gs->type = GREP_SOURCE_BUF;
1844 gs->name = NULL;
1845 gs->path = NULL;
1846 gs->buf = buf;
1847 gs->size = size;
1848 gs->driver = NULL;
1849 gs->identifier = NULL;
1852 int grep_buffer(struct grep_opt *opt, const char *buf, unsigned long size)
1854 struct grep_source gs;
1855 int r;
1857 grep_source_init_buf(&gs, buf, size);
1859 r = grep_source(opt, &gs);
1861 grep_source_clear(&gs);
1862 return r;
1865 void grep_source_init_file(struct grep_source *gs, const char *name,
1866 const char *path)
1868 gs->type = GREP_SOURCE_FILE;
1869 gs->name = xstrdup_or_null(name);
1870 gs->path = xstrdup_or_null(path);
1871 gs->buf = NULL;
1872 gs->size = 0;
1873 gs->driver = NULL;
1874 gs->identifier = xstrdup(path);
1877 void grep_source_init_oid(struct grep_source *gs, const char *name,
1878 const char *path, const struct object_id *oid,
1879 struct repository *repo)
1881 gs->type = GREP_SOURCE_OID;
1882 gs->name = xstrdup_or_null(name);
1883 gs->path = xstrdup_or_null(path);
1884 gs->buf = NULL;
1885 gs->size = 0;
1886 gs->driver = NULL;
1887 gs->identifier = oiddup(oid);
1888 gs->repo = repo;
1891 void grep_source_clear(struct grep_source *gs)
1893 FREE_AND_NULL(gs->name);
1894 FREE_AND_NULL(gs->path);
1895 FREE_AND_NULL(gs->identifier);
1896 grep_source_clear_data(gs);
1899 void grep_source_clear_data(struct grep_source *gs)
1901 switch (gs->type) {
1902 case GREP_SOURCE_FILE:
1903 case GREP_SOURCE_OID:
1904 /* these types own the buffer */
1905 free((char *)gs->buf);
1906 gs->buf = NULL;
1907 gs->size = 0;
1908 break;
1909 case GREP_SOURCE_BUF:
1910 /* leave user-provided buf intact */
1911 break;
1915 static int grep_source_load_oid(struct grep_source *gs)
1917 enum object_type type;
1919 gs->buf = repo_read_object_file(gs->repo, gs->identifier, &type,
1920 &gs->size);
1921 if (!gs->buf)
1922 return error(_("'%s': unable to read %s"),
1923 gs->name,
1924 oid_to_hex(gs->identifier));
1925 return 0;
1928 static int grep_source_load_file(struct grep_source *gs)
1930 const char *filename = gs->identifier;
1931 struct stat st;
1932 char *data;
1933 size_t size;
1934 int i;
1936 if (lstat(filename, &st) < 0) {
1937 err_ret:
1938 if (errno != ENOENT)
1939 error_errno(_("failed to stat '%s'"), filename);
1940 return -1;
1942 if (!S_ISREG(st.st_mode))
1943 return -1;
1944 size = xsize_t(st.st_size);
1945 i = open(filename, O_RDONLY);
1946 if (i < 0)
1947 goto err_ret;
1948 data = xmallocz(size);
1949 if (st.st_size != read_in_full(i, data, size)) {
1950 error_errno(_("'%s': short read"), filename);
1951 close(i);
1952 free(data);
1953 return -1;
1955 close(i);
1957 gs->buf = data;
1958 gs->size = size;
1959 return 0;
1962 static int grep_source_load(struct grep_source *gs)
1964 if (gs->buf)
1965 return 0;
1967 switch (gs->type) {
1968 case GREP_SOURCE_FILE:
1969 return grep_source_load_file(gs);
1970 case GREP_SOURCE_OID:
1971 return grep_source_load_oid(gs);
1972 case GREP_SOURCE_BUF:
1973 return gs->buf ? 0 : -1;
1975 BUG("invalid grep_source type to load");
1978 void grep_source_load_driver(struct grep_source *gs,
1979 struct index_state *istate)
1981 if (gs->driver)
1982 return;
1984 grep_attr_lock();
1985 if (gs->path)
1986 gs->driver = userdiff_find_by_path(istate, gs->path);
1987 if (!gs->driver)
1988 gs->driver = userdiff_find_by_name("default");
1989 grep_attr_unlock();
1992 static int grep_source_is_binary(struct grep_source *gs,
1993 struct index_state *istate)
1995 grep_source_load_driver(gs, istate);
1996 if (gs->driver->binary != -1)
1997 return gs->driver->binary;
1999 if (!grep_source_load(gs))
2000 return buffer_is_binary(gs->buf, gs->size);
2002 return 0;