unicode: update the width tables to Unicode 15
[git.git] / grep.c
blobcee44a78d044dad174f5560b14432b396d6fdfb4
1 #include "cache.h"
2 #include "config.h"
3 #include "grep.h"
4 #include "object-store.h"
5 #include "userdiff.h"
6 #include "xdiff-interface.h"
7 #include "diff.h"
8 #include "diffcore.h"
9 #include "commit.h"
10 #include "quote.h"
11 #include "help.h"
13 static int grep_source_load(struct grep_source *gs);
14 static int grep_source_is_binary(struct grep_source *gs,
15 struct index_state *istate);
17 static void std_output(struct grep_opt *opt, const void *buf, size_t size)
19 fwrite(buf, size, 1, stdout);
22 static const char *color_grep_slots[] = {
23 [GREP_COLOR_CONTEXT] = "context",
24 [GREP_COLOR_FILENAME] = "filename",
25 [GREP_COLOR_FUNCTION] = "function",
26 [GREP_COLOR_LINENO] = "lineNumber",
27 [GREP_COLOR_COLUMNNO] = "column",
28 [GREP_COLOR_MATCH_CONTEXT] = "matchContext",
29 [GREP_COLOR_MATCH_SELECTED] = "matchSelected",
30 [GREP_COLOR_SELECTED] = "selected",
31 [GREP_COLOR_SEP] = "separator",
34 static int parse_pattern_type_arg(const char *opt, const char *arg)
36 if (!strcmp(arg, "default"))
37 return GREP_PATTERN_TYPE_UNSPECIFIED;
38 else if (!strcmp(arg, "basic"))
39 return GREP_PATTERN_TYPE_BRE;
40 else if (!strcmp(arg, "extended"))
41 return GREP_PATTERN_TYPE_ERE;
42 else if (!strcmp(arg, "fixed"))
43 return GREP_PATTERN_TYPE_FIXED;
44 else if (!strcmp(arg, "perl"))
45 return GREP_PATTERN_TYPE_PCRE;
46 die("bad %s argument: %s", opt, arg);
49 define_list_config_array_extra(color_grep_slots, {"match"});
52 * Read the configuration file once and store it in
53 * the grep_defaults template.
55 int grep_config(const char *var, const char *value, void *cb)
57 struct grep_opt *opt = cb;
58 const char *slot;
60 if (userdiff_config(var, value) < 0)
61 return -1;
63 if (!strcmp(var, "grep.extendedregexp")) {
64 opt->extended_regexp_option = git_config_bool(var, value);
65 return 0;
68 if (!strcmp(var, "grep.patterntype")) {
69 opt->pattern_type_option = parse_pattern_type_arg(var, value);
70 return 0;
73 if (!strcmp(var, "grep.linenumber")) {
74 opt->linenum = git_config_bool(var, value);
75 return 0;
77 if (!strcmp(var, "grep.column")) {
78 opt->columnnum = git_config_bool(var, value);
79 return 0;
82 if (!strcmp(var, "grep.fullname")) {
83 opt->relative = !git_config_bool(var, value);
84 return 0;
87 if (!strcmp(var, "color.grep"))
88 opt->color = git_config_colorbool(var, value);
89 if (!strcmp(var, "color.grep.match")) {
90 if (grep_config("color.grep.matchcontext", value, cb) < 0)
91 return -1;
92 if (grep_config("color.grep.matchselected", value, cb) < 0)
93 return -1;
94 } else if (skip_prefix(var, "color.grep.", &slot)) {
95 int i = LOOKUP_CONFIG(color_grep_slots, slot);
96 char *color;
98 if (i < 0)
99 return -1;
100 color = opt->colors[i];
101 if (!value)
102 return config_error_nonbool(var);
103 return color_parse(value, color);
105 return 0;
108 void grep_init(struct grep_opt *opt, struct repository *repo)
110 struct grep_opt blank = GREP_OPT_INIT;
111 memcpy(opt, &blank, sizeof(*opt));
113 opt->repo = repo;
114 opt->pattern_tail = &opt->pattern_list;
115 opt->header_tail = &opt->header_list;
118 static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
119 const char *origin, int no,
120 enum grep_pat_token t,
121 enum grep_header_field field)
123 struct grep_pat *p = xcalloc(1, sizeof(*p));
124 p->pattern = xmemdupz(pat, patlen);
125 p->patternlen = patlen;
126 p->origin = origin;
127 p->no = no;
128 p->token = t;
129 p->field = field;
130 return p;
133 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
135 **tail = p;
136 *tail = &p->next;
137 p->next = NULL;
139 switch (p->token) {
140 case GREP_PATTERN: /* atom */
141 case GREP_PATTERN_HEAD:
142 case GREP_PATTERN_BODY:
143 for (;;) {
144 struct grep_pat *new_pat;
145 size_t len = 0;
146 char *cp = p->pattern + p->patternlen, *nl = NULL;
147 while (++len <= p->patternlen) {
148 if (*(--cp) == '\n') {
149 nl = cp;
150 break;
153 if (!nl)
154 break;
155 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
156 p->no, p->token, p->field);
157 new_pat->next = p->next;
158 if (!p->next)
159 *tail = &new_pat->next;
160 p->next = new_pat;
161 *nl = '\0';
162 p->patternlen -= len;
164 break;
165 default:
166 break;
170 void append_header_grep_pattern(struct grep_opt *opt,
171 enum grep_header_field field, const char *pat)
173 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
174 GREP_PATTERN_HEAD, field);
175 if (field == GREP_HEADER_REFLOG)
176 opt->use_reflog_filter = 1;
177 do_append_grep_pat(&opt->header_tail, p);
180 void append_grep_pattern(struct grep_opt *opt, const char *pat,
181 const char *origin, int no, enum grep_pat_token t)
183 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
186 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
187 const char *origin, int no, enum grep_pat_token t)
189 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
190 do_append_grep_pat(&opt->pattern_tail, p);
193 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
195 struct grep_pat *pat;
196 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
197 *ret = *opt;
199 ret->pattern_list = NULL;
200 ret->pattern_tail = &ret->pattern_list;
202 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
204 if(pat->token == GREP_PATTERN_HEAD)
205 append_header_grep_pattern(ret, pat->field,
206 pat->pattern);
207 else
208 append_grep_pat(ret, pat->pattern, pat->patternlen,
209 pat->origin, pat->no, pat->token);
212 return ret;
215 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
216 const char *error)
218 char where[1024];
220 if (p->no)
221 xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
222 else if (p->origin)
223 xsnprintf(where, sizeof(where), "%s, ", p->origin);
224 else
225 where[0] = 0;
227 die("%s'%s': %s", where, p->pattern, error);
230 static int is_fixed(const char *s, size_t len)
232 size_t i;
234 for (i = 0; i < len; i++) {
235 if (is_regex_special(s[i]))
236 return 0;
239 return 1;
242 #ifdef USE_LIBPCRE2
243 #define GREP_PCRE2_DEBUG_MALLOC 0
245 static void *pcre2_malloc(PCRE2_SIZE size, MAYBE_UNUSED void *memory_data)
247 void *pointer = malloc(size);
248 #if GREP_PCRE2_DEBUG_MALLOC
249 static int count = 1;
250 fprintf(stderr, "PCRE2:%p -> #%02d: alloc(%lu)\n", pointer, count++, size);
251 #endif
252 return pointer;
255 static void pcre2_free(void *pointer, MAYBE_UNUSED void *memory_data)
257 #if GREP_PCRE2_DEBUG_MALLOC
258 static int count = 1;
259 if (pointer)
260 fprintf(stderr, "PCRE2:%p -> #%02d: free()\n", pointer, count++);
261 #endif
262 free(pointer);
265 static int pcre2_jit_functional(void)
267 static int jit_working = -1;
268 pcre2_code *code;
269 size_t off;
270 int err;
272 if (jit_working != -1)
273 return jit_working;
276 * Try to JIT compile a simple pattern to probe if the JIT is
277 * working in general. It might fail for systems where creating
278 * memory mappings for runtime code generation is restricted.
280 code = pcre2_compile((PCRE2_SPTR)".", 1, 0, &err, &off, NULL);
281 if (!code)
282 return 0;
284 jit_working = pcre2_jit_compile(code, PCRE2_JIT_COMPLETE) == 0;
285 pcre2_code_free(code);
287 return jit_working;
290 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
292 int error;
293 PCRE2_UCHAR errbuf[256];
294 PCRE2_SIZE erroffset;
295 int options = PCRE2_MULTILINE;
296 int jitret;
297 int patinforet;
298 size_t jitsizearg;
299 int literal = !opt->ignore_case && (p->fixed || p->is_fixed);
302 * Call pcre2_general_context_create() before calling any
303 * other pcre2_*(). It sets up our malloc()/free() functions
304 * with which everything else is allocated.
306 p->pcre2_general_context = pcre2_general_context_create(
307 pcre2_malloc, pcre2_free, NULL);
308 if (!p->pcre2_general_context)
309 die("Couldn't allocate PCRE2 general context");
311 if (opt->ignore_case) {
312 if (!opt->ignore_locale && has_non_ascii(p->pattern)) {
313 p->pcre2_tables = pcre2_maketables(p->pcre2_general_context);
314 p->pcre2_compile_context = pcre2_compile_context_create(p->pcre2_general_context);
315 pcre2_set_character_tables(p->pcre2_compile_context,
316 p->pcre2_tables);
318 options |= PCRE2_CASELESS;
320 if (!opt->ignore_locale && is_utf8_locale() && !literal)
321 options |= (PCRE2_UTF | PCRE2_UCP | PCRE2_MATCH_INVALID_UTF);
323 #ifndef GIT_PCRE2_VERSION_10_36_OR_HIGHER
324 /* Work around https://bugs.exim.org/show_bug.cgi?id=2642 fixed in 10.36 */
325 if (PCRE2_MATCH_INVALID_UTF && options & (PCRE2_UTF | PCRE2_CASELESS))
326 options |= PCRE2_NO_START_OPTIMIZE;
327 #endif
329 p->pcre2_pattern = pcre2_compile((PCRE2_SPTR)p->pattern,
330 p->patternlen, options, &error, &erroffset,
331 p->pcre2_compile_context);
333 if (p->pcre2_pattern) {
334 p->pcre2_match_data = pcre2_match_data_create_from_pattern(p->pcre2_pattern, p->pcre2_general_context);
335 if (!p->pcre2_match_data)
336 die("Couldn't allocate PCRE2 match data");
337 } else {
338 pcre2_get_error_message(error, errbuf, sizeof(errbuf));
339 compile_regexp_failed(p, (const char *)&errbuf);
342 pcre2_config(PCRE2_CONFIG_JIT, &p->pcre2_jit_on);
343 if (p->pcre2_jit_on) {
344 jitret = pcre2_jit_compile(p->pcre2_pattern, PCRE2_JIT_COMPLETE);
345 if (jitret == PCRE2_ERROR_NOMEMORY && !pcre2_jit_functional()) {
347 * Even though pcre2_config(PCRE2_CONFIG_JIT, ...)
348 * indicated JIT support, the library might still
349 * fail to generate JIT code for various reasons,
350 * e.g. when SELinux's 'deny_execmem' or PaX's
351 * MPROTECT prevent creating W|X memory mappings.
353 * Instead of faling hard, fall back to interpreter
354 * mode, just as if the pattern was prefixed with
355 * '(*NO_JIT)'.
357 p->pcre2_jit_on = 0;
358 return;
359 } else if (jitret) {
360 int need_clip = p->patternlen > 64;
361 int clip_len = need_clip ? 64 : p->patternlen;
362 die("Couldn't JIT the PCRE2 pattern '%.*s'%s, got '%d'%s",
363 clip_len, p->pattern, need_clip ? "..." : "", jitret,
364 pcre2_jit_functional()
365 ? "\nPerhaps prefix (*NO_JIT) to your pattern?"
366 : "");
370 * The pcre2_config(PCRE2_CONFIG_JIT, ...) call just
371 * tells us whether the library itself supports JIT,
372 * but to see whether we're going to be actually using
373 * JIT we need to extract PCRE2_INFO_JITSIZE from the
374 * pattern *after* we do pcre2_jit_compile() above.
376 * This is because if the pattern contains the
377 * (*NO_JIT) verb (see pcre2syntax(3))
378 * pcre2_jit_compile() will exit early with 0. If we
379 * then proceed to call pcre2_jit_match() further down
380 * the line instead of pcre2_match() we'll either
381 * segfault (pre PCRE 10.31) or run into a fatal error
382 * (post PCRE2 10.31)
384 patinforet = pcre2_pattern_info(p->pcre2_pattern, PCRE2_INFO_JITSIZE, &jitsizearg);
385 if (patinforet)
386 BUG("pcre2_pattern_info() failed: %d", patinforet);
387 if (jitsizearg == 0) {
388 p->pcre2_jit_on = 0;
389 return;
394 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
395 regmatch_t *match, int eflags)
397 int ret, flags = 0;
398 PCRE2_SIZE *ovector;
399 PCRE2_UCHAR errbuf[256];
401 if (eflags & REG_NOTBOL)
402 flags |= PCRE2_NOTBOL;
404 if (p->pcre2_jit_on)
405 ret = pcre2_jit_match(p->pcre2_pattern, (unsigned char *)line,
406 eol - line, 0, flags, p->pcre2_match_data,
407 NULL);
408 else
409 ret = pcre2_match(p->pcre2_pattern, (unsigned char *)line,
410 eol - line, 0, flags, p->pcre2_match_data,
411 NULL);
413 if (ret < 0 && ret != PCRE2_ERROR_NOMATCH) {
414 pcre2_get_error_message(ret, errbuf, sizeof(errbuf));
415 die("%s failed with error code %d: %s",
416 (p->pcre2_jit_on ? "pcre2_jit_match" : "pcre2_match"), ret,
417 errbuf);
419 if (ret > 0) {
420 ovector = pcre2_get_ovector_pointer(p->pcre2_match_data);
421 ret = 0;
422 match->rm_so = (int)ovector[0];
423 match->rm_eo = (int)ovector[1];
426 return ret;
429 static void free_pcre2_pattern(struct grep_pat *p)
431 pcre2_compile_context_free(p->pcre2_compile_context);
432 pcre2_code_free(p->pcre2_pattern);
433 pcre2_match_data_free(p->pcre2_match_data);
434 #ifdef GIT_PCRE2_VERSION_10_34_OR_HIGHER
435 pcre2_maketables_free(p->pcre2_general_context, p->pcre2_tables);
436 #else
437 free((void *)p->pcre2_tables);
438 #endif
439 pcre2_general_context_free(p->pcre2_general_context);
441 #else /* !USE_LIBPCRE2 */
442 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
444 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
447 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
448 regmatch_t *match, int eflags)
450 return 1;
453 static void free_pcre2_pattern(struct grep_pat *p)
457 static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
459 struct strbuf sb = STRBUF_INIT;
460 int err;
461 int regflags = 0;
463 basic_regex_quote_buf(&sb, p->pattern);
464 if (opt->ignore_case)
465 regflags |= REG_ICASE;
466 err = regcomp(&p->regexp, sb.buf, regflags);
467 strbuf_release(&sb);
468 if (err) {
469 char errbuf[1024];
470 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
471 compile_regexp_failed(p, errbuf);
474 #endif /* !USE_LIBPCRE2 */
476 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
478 int err;
479 int regflags = REG_NEWLINE;
481 if (opt->pattern_type_option == GREP_PATTERN_TYPE_UNSPECIFIED)
482 opt->pattern_type_option = (opt->extended_regexp_option
483 ? GREP_PATTERN_TYPE_ERE
484 : GREP_PATTERN_TYPE_BRE);
486 p->word_regexp = opt->word_regexp;
487 p->ignore_case = opt->ignore_case;
488 p->fixed = opt->pattern_type_option == GREP_PATTERN_TYPE_FIXED;
490 if (opt->pattern_type_option != GREP_PATTERN_TYPE_PCRE &&
491 memchr(p->pattern, 0, p->patternlen))
492 die(_("given pattern contains NULL byte (via -f <file>). This is only supported with -P under PCRE v2"));
494 p->is_fixed = is_fixed(p->pattern, p->patternlen);
495 #ifdef USE_LIBPCRE2
496 if (!p->fixed && !p->is_fixed) {
497 const char *no_jit = "(*NO_JIT)";
498 const int no_jit_len = strlen(no_jit);
499 if (starts_with(p->pattern, no_jit) &&
500 is_fixed(p->pattern + no_jit_len,
501 p->patternlen - no_jit_len))
502 p->is_fixed = 1;
504 #endif
505 if (p->fixed || p->is_fixed) {
506 #ifdef USE_LIBPCRE2
507 if (p->is_fixed) {
508 compile_pcre2_pattern(p, opt);
509 } else {
511 * E.g. t7811-grep-open.sh relies on the
512 * pattern being restored.
514 char *old_pattern = p->pattern;
515 size_t old_patternlen = p->patternlen;
516 struct strbuf sb = STRBUF_INIT;
519 * There is the PCRE2_LITERAL flag, but it's
520 * only in PCRE v2 10.30 and later. Needing to
521 * ifdef our way around that and dealing with
522 * it + PCRE2_MULTILINE being an error is more
523 * complex than just quoting this ourselves.
525 strbuf_add(&sb, "\\Q", 2);
526 strbuf_add(&sb, p->pattern, p->patternlen);
527 strbuf_add(&sb, "\\E", 2);
529 p->pattern = sb.buf;
530 p->patternlen = sb.len;
531 compile_pcre2_pattern(p, opt);
532 p->pattern = old_pattern;
533 p->patternlen = old_patternlen;
534 strbuf_release(&sb);
536 #else /* !USE_LIBPCRE2 */
537 compile_fixed_regexp(p, opt);
538 #endif /* !USE_LIBPCRE2 */
539 return;
542 if (opt->pattern_type_option == GREP_PATTERN_TYPE_PCRE) {
543 compile_pcre2_pattern(p, opt);
544 return;
547 if (p->ignore_case)
548 regflags |= REG_ICASE;
549 if (opt->pattern_type_option == GREP_PATTERN_TYPE_ERE)
550 regflags |= REG_EXTENDED;
551 err = regcomp(&p->regexp, p->pattern, regflags);
552 if (err) {
553 char errbuf[1024];
554 regerror(err, &p->regexp, errbuf, 1024);
555 compile_regexp_failed(p, errbuf);
559 static struct grep_expr *grep_not_expr(struct grep_expr *expr)
561 struct grep_expr *z = xcalloc(1, sizeof(*z));
562 z->node = GREP_NODE_NOT;
563 z->u.unary = expr;
564 return z;
567 static struct grep_expr *grep_binexp(enum grep_expr_node kind,
568 struct grep_expr *left,
569 struct grep_expr *right)
571 struct grep_expr *z = xcalloc(1, sizeof(*z));
572 z->node = kind;
573 z->u.binary.left = left;
574 z->u.binary.right = right;
575 return z;
578 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
580 return grep_binexp(GREP_NODE_OR, left, right);
583 static struct grep_expr *grep_and_expr(struct grep_expr *left, struct grep_expr *right)
585 return grep_binexp(GREP_NODE_AND, left, right);
588 static struct grep_expr *compile_pattern_or(struct grep_pat **);
589 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
591 struct grep_pat *p;
592 struct grep_expr *x;
594 p = *list;
595 if (!p)
596 return NULL;
597 switch (p->token) {
598 case GREP_PATTERN: /* atom */
599 case GREP_PATTERN_HEAD:
600 case GREP_PATTERN_BODY:
601 CALLOC_ARRAY(x, 1);
602 x->node = GREP_NODE_ATOM;
603 x->u.atom = p;
604 *list = p->next;
605 return x;
606 case GREP_OPEN_PAREN:
607 *list = p->next;
608 x = compile_pattern_or(list);
609 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
610 die("unmatched parenthesis");
611 *list = (*list)->next;
612 return x;
613 default:
614 return NULL;
618 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
620 struct grep_pat *p;
621 struct grep_expr *x;
623 p = *list;
624 if (!p)
625 return NULL;
626 switch (p->token) {
627 case GREP_NOT:
628 if (!p->next)
629 die("--not not followed by pattern expression");
630 *list = p->next;
631 x = compile_pattern_not(list);
632 if (!x)
633 die("--not followed by non pattern expression");
634 return grep_not_expr(x);
635 default:
636 return compile_pattern_atom(list);
640 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
642 struct grep_pat *p;
643 struct grep_expr *x, *y;
645 x = compile_pattern_not(list);
646 p = *list;
647 if (p && p->token == GREP_AND) {
648 if (!x)
649 die("--and not preceded by pattern expression");
650 if (!p->next)
651 die("--and not followed by pattern expression");
652 *list = p->next;
653 y = compile_pattern_and(list);
654 if (!y)
655 die("--and not followed by pattern expression");
656 return grep_and_expr(x, y);
658 return x;
661 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
663 struct grep_pat *p;
664 struct grep_expr *x, *y;
666 x = compile_pattern_and(list);
667 p = *list;
668 if (x && p && p->token != GREP_CLOSE_PAREN) {
669 y = compile_pattern_or(list);
670 if (!y)
671 die("not a pattern expression %s", p->pattern);
672 return grep_or_expr(x, y);
674 return x;
677 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
679 return compile_pattern_or(list);
682 static struct grep_expr *grep_true_expr(void)
684 struct grep_expr *z = xcalloc(1, sizeof(*z));
685 z->node = GREP_NODE_TRUE;
686 return z;
689 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
691 struct grep_pat *p;
692 struct grep_expr *header_expr;
693 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
694 enum grep_header_field fld;
696 if (!opt->header_list)
697 return NULL;
699 for (p = opt->header_list; p; p = p->next) {
700 if (p->token != GREP_PATTERN_HEAD)
701 BUG("a non-header pattern in grep header list.");
702 if (p->field < GREP_HEADER_FIELD_MIN ||
703 GREP_HEADER_FIELD_MAX <= p->field)
704 BUG("unknown header field %d", p->field);
705 compile_regexp(p, opt);
708 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
709 header_group[fld] = NULL;
711 for (p = opt->header_list; p; p = p->next) {
712 struct grep_expr *h;
713 struct grep_pat *pp = p;
715 h = compile_pattern_atom(&pp);
716 if (!h || pp != p->next)
717 BUG("malformed header expr");
718 if (!header_group[p->field]) {
719 header_group[p->field] = h;
720 continue;
722 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
725 header_expr = NULL;
727 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
728 if (!header_group[fld])
729 continue;
730 if (!header_expr)
731 header_expr = grep_true_expr();
732 header_expr = grep_or_expr(header_group[fld], header_expr);
734 return header_expr;
737 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
739 struct grep_expr *z = x;
741 while (x) {
742 assert(x->node == GREP_NODE_OR);
743 if (x->u.binary.right &&
744 x->u.binary.right->node == GREP_NODE_TRUE) {
745 x->u.binary.right = y;
746 break;
748 x = x->u.binary.right;
750 return z;
753 void compile_grep_patterns(struct grep_opt *opt)
755 struct grep_pat *p;
756 struct grep_expr *header_expr = prep_header_patterns(opt);
757 int extended = 0;
759 for (p = opt->pattern_list; p; p = p->next) {
760 switch (p->token) {
761 case GREP_PATTERN: /* atom */
762 case GREP_PATTERN_HEAD:
763 case GREP_PATTERN_BODY:
764 compile_regexp(p, opt);
765 break;
766 default:
767 extended = 1;
768 break;
772 if (opt->all_match || opt->no_body_match || header_expr)
773 extended = 1;
774 else if (!extended)
775 return;
777 p = opt->pattern_list;
778 if (p)
779 opt->pattern_expression = compile_pattern_expr(&p);
780 if (p)
781 die("incomplete pattern expression: %s", p->pattern);
783 if (opt->no_body_match && opt->pattern_expression)
784 opt->pattern_expression = grep_not_expr(opt->pattern_expression);
786 if (!header_expr)
787 return;
789 if (!opt->pattern_expression)
790 opt->pattern_expression = header_expr;
791 else if (opt->all_match)
792 opt->pattern_expression = grep_splice_or(header_expr,
793 opt->pattern_expression);
794 else
795 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
796 header_expr);
797 opt->all_match = 1;
800 static void free_pattern_expr(struct grep_expr *x)
802 switch (x->node) {
803 case GREP_NODE_TRUE:
804 case GREP_NODE_ATOM:
805 break;
806 case GREP_NODE_NOT:
807 free_pattern_expr(x->u.unary);
808 break;
809 case GREP_NODE_AND:
810 case GREP_NODE_OR:
811 free_pattern_expr(x->u.binary.left);
812 free_pattern_expr(x->u.binary.right);
813 break;
815 free(x);
818 static void free_grep_pat(struct grep_pat *pattern)
820 struct grep_pat *p, *n;
822 for (p = pattern; p; p = n) {
823 n = p->next;
824 switch (p->token) {
825 case GREP_PATTERN: /* atom */
826 case GREP_PATTERN_HEAD:
827 case GREP_PATTERN_BODY:
828 if (p->pcre2_pattern)
829 free_pcre2_pattern(p);
830 else
831 regfree(&p->regexp);
832 free(p->pattern);
833 break;
834 default:
835 break;
837 free(p);
841 void free_grep_patterns(struct grep_opt *opt)
843 free_grep_pat(opt->pattern_list);
844 free_grep_pat(opt->header_list);
846 if (opt->pattern_expression)
847 free_pattern_expr(opt->pattern_expression);
850 static const char *end_of_line(const char *cp, unsigned long *left)
852 unsigned long l = *left;
853 while (l && *cp != '\n') {
854 l--;
855 cp++;
857 *left = l;
858 return cp;
861 static int word_char(char ch)
863 return isalnum(ch) || ch == '_';
866 static void output_color(struct grep_opt *opt, const void *data, size_t size,
867 const char *color)
869 if (want_color(opt->color) && color && color[0]) {
870 opt->output(opt, color, strlen(color));
871 opt->output(opt, data, size);
872 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
873 } else
874 opt->output(opt, data, size);
877 static void output_sep(struct grep_opt *opt, char sign)
879 if (opt->null_following_name)
880 opt->output(opt, "\0", 1);
881 else
882 output_color(opt, &sign, 1, opt->colors[GREP_COLOR_SEP]);
885 static void show_name(struct grep_opt *opt, const char *name)
887 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
888 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
891 static int patmatch(struct grep_pat *p,
892 const char *line, const char *eol,
893 regmatch_t *match, int eflags)
895 int hit;
897 if (p->pcre2_pattern)
898 hit = !pcre2match(p, line, eol, match, eflags);
899 else
900 hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
901 eflags);
903 return hit;
906 static void strip_timestamp(const char *bol, const char **eol_p)
908 const char *eol = *eol_p;
910 while (bol < --eol) {
911 if (*eol != '>')
912 continue;
913 *eol_p = ++eol;
914 break;
918 static struct {
919 const char *field;
920 size_t len;
921 } header_field[] = {
922 { "author ", 7 },
923 { "committer ", 10 },
924 { "reflog ", 7 },
927 static int headerless_match_one_pattern(struct grep_pat *p,
928 const char *bol, const char *eol,
929 enum grep_context ctx,
930 regmatch_t *pmatch, int eflags)
932 int hit = 0;
933 const char *start = bol;
935 if ((p->token != GREP_PATTERN) &&
936 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
937 return 0;
939 again:
940 hit = patmatch(p, bol, eol, pmatch, eflags);
942 if (hit && p->word_regexp) {
943 if ((pmatch[0].rm_so < 0) ||
944 (eol - bol) < pmatch[0].rm_so ||
945 (pmatch[0].rm_eo < 0) ||
946 (eol - bol) < pmatch[0].rm_eo)
947 die("regexp returned nonsense");
949 /* Match beginning must be either beginning of the
950 * line, or at word boundary (i.e. the last char must
951 * not be a word char). Similarly, match end must be
952 * either end of the line, or at word boundary
953 * (i.e. the next char must not be a word char).
955 if ( ((pmatch[0].rm_so == 0) ||
956 !word_char(bol[pmatch[0].rm_so-1])) &&
957 ((pmatch[0].rm_eo == (eol-bol)) ||
958 !word_char(bol[pmatch[0].rm_eo])) )
960 else
961 hit = 0;
963 /* Words consist of at least one character. */
964 if (pmatch->rm_so == pmatch->rm_eo)
965 hit = 0;
967 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
968 /* There could be more than one match on the
969 * line, and the first match might not be
970 * strict word match. But later ones could be!
971 * Forward to the next possible start, i.e. the
972 * next position following a non-word char.
974 bol = pmatch[0].rm_so + bol + 1;
975 while (word_char(bol[-1]) && bol < eol)
976 bol++;
977 eflags |= REG_NOTBOL;
978 if (bol < eol)
979 goto again;
982 if (hit) {
983 pmatch[0].rm_so += bol - start;
984 pmatch[0].rm_eo += bol - start;
986 return hit;
989 static int match_one_pattern(struct grep_pat *p,
990 const char *bol, const char *eol,
991 enum grep_context ctx, regmatch_t *pmatch,
992 int eflags)
994 const char *field;
995 size_t len;
997 if (p->token == GREP_PATTERN_HEAD) {
998 assert(p->field < ARRAY_SIZE(header_field));
999 field = header_field[p->field].field;
1000 len = header_field[p->field].len;
1001 if (strncmp(bol, field, len))
1002 return 0;
1003 bol += len;
1005 switch (p->field) {
1006 case GREP_HEADER_AUTHOR:
1007 case GREP_HEADER_COMMITTER:
1008 strip_timestamp(bol, &eol);
1009 break;
1010 default:
1011 break;
1015 return headerless_match_one_pattern(p, bol, eol, ctx, pmatch, eflags);
1019 static int match_expr_eval(struct grep_opt *opt, struct grep_expr *x,
1020 const char *bol, const char *eol,
1021 enum grep_context ctx, ssize_t *col,
1022 ssize_t *icol, int collect_hits)
1024 int h = 0;
1026 switch (x->node) {
1027 case GREP_NODE_TRUE:
1028 h = 1;
1029 break;
1030 case GREP_NODE_ATOM:
1032 regmatch_t tmp;
1033 h = match_one_pattern(x->u.atom, bol, eol, ctx,
1034 &tmp, 0);
1035 if (h && (*col < 0 || tmp.rm_so < *col))
1036 *col = tmp.rm_so;
1038 if (x->u.atom->token == GREP_PATTERN_BODY)
1039 opt->body_hit |= h;
1040 break;
1041 case GREP_NODE_NOT:
1043 * Upon visiting a GREP_NODE_NOT, col and icol become swapped.
1045 h = !match_expr_eval(opt, x->u.unary, bol, eol, ctx, icol, col,
1047 break;
1048 case GREP_NODE_AND:
1049 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1050 icol, 0);
1051 if (h || opt->columnnum) {
1053 * Don't short-circuit AND when given --column, since a
1054 * NOT earlier in the tree may turn this into an OR. In
1055 * this case, see the below comment.
1057 h &= match_expr_eval(opt, x->u.binary.right, bol, eol,
1058 ctx, col, icol, 0);
1060 break;
1061 case GREP_NODE_OR:
1062 if (!(collect_hits || opt->columnnum)) {
1064 * Don't short-circuit OR when given --column (or
1065 * collecting hits) to ensure we don't skip a later
1066 * child that would produce an earlier match.
1068 return (match_expr_eval(opt, x->u.binary.left, bol, eol,
1069 ctx, col, icol, 0) ||
1070 match_expr_eval(opt, x->u.binary.right, bol,
1071 eol, ctx, col, icol, 0));
1073 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1074 icol, 0);
1075 if (collect_hits)
1076 x->u.binary.left->hit |= h;
1077 h |= match_expr_eval(opt, x->u.binary.right, bol, eol, ctx, col,
1078 icol, collect_hits);
1079 break;
1080 default:
1081 die("Unexpected node type (internal error) %d", x->node);
1083 if (collect_hits)
1084 x->hit |= h;
1085 return h;
1088 static int match_expr(struct grep_opt *opt,
1089 const char *bol, const char *eol,
1090 enum grep_context ctx, ssize_t *col,
1091 ssize_t *icol, int collect_hits)
1093 struct grep_expr *x = opt->pattern_expression;
1094 return match_expr_eval(opt, x, bol, eol, ctx, col, icol, collect_hits);
1097 static int match_line(struct grep_opt *opt,
1098 const char *bol, const char *eol,
1099 ssize_t *col, ssize_t *icol,
1100 enum grep_context ctx, int collect_hits)
1102 struct grep_pat *p;
1103 int hit = 0;
1105 if (opt->pattern_expression)
1106 return match_expr(opt, bol, eol, ctx, col, icol,
1107 collect_hits);
1109 /* we do not call with collect_hits without being extended */
1110 for (p = opt->pattern_list; p; p = p->next) {
1111 regmatch_t tmp;
1112 if (match_one_pattern(p, bol, eol, ctx, &tmp, 0)) {
1113 hit |= 1;
1114 if (!opt->columnnum) {
1116 * Without --column, any single match on a line
1117 * is enough to know that it needs to be
1118 * printed. With --column, scan _all_ patterns
1119 * to find the earliest.
1121 break;
1123 if (*col < 0 || tmp.rm_so < *col)
1124 *col = tmp.rm_so;
1127 return hit;
1130 static int match_next_pattern(struct grep_pat *p,
1131 const char *bol, const char *eol,
1132 enum grep_context ctx,
1133 regmatch_t *pmatch, int eflags)
1135 regmatch_t match;
1137 if (!headerless_match_one_pattern(p, bol, eol, ctx, &match, eflags))
1138 return 0;
1139 if (match.rm_so < 0 || match.rm_eo < 0)
1140 return 0;
1141 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1142 if (match.rm_so > pmatch->rm_so)
1143 return 1;
1144 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1145 return 1;
1147 pmatch->rm_so = match.rm_so;
1148 pmatch->rm_eo = match.rm_eo;
1149 return 1;
1152 int grep_next_match(struct grep_opt *opt,
1153 const char *bol, const char *eol,
1154 enum grep_context ctx, regmatch_t *pmatch,
1155 enum grep_header_field field, int eflags)
1157 struct grep_pat *p;
1158 int hit = 0;
1160 pmatch->rm_so = pmatch->rm_eo = -1;
1161 if (bol < eol) {
1162 for (p = ((ctx == GREP_CONTEXT_HEAD)
1163 ? opt->header_list : opt->pattern_list);
1164 p; p = p->next) {
1165 switch (p->token) {
1166 case GREP_PATTERN_HEAD:
1167 if ((field != GREP_HEADER_FIELD_MAX) &&
1168 (p->field != field))
1169 continue;
1170 /* fall thru */
1171 case GREP_PATTERN: /* atom */
1172 case GREP_PATTERN_BODY:
1173 hit |= match_next_pattern(p, bol, eol, ctx,
1174 pmatch, eflags);
1175 break;
1176 default:
1177 break;
1181 return hit;
1184 static void show_line_header(struct grep_opt *opt, const char *name,
1185 unsigned lno, ssize_t cno, char sign)
1187 if (opt->heading && opt->last_shown == 0) {
1188 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1189 opt->output(opt, "\n", 1);
1191 opt->last_shown = lno;
1193 if (!opt->heading && opt->pathname) {
1194 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1195 output_sep(opt, sign);
1197 if (opt->linenum) {
1198 char buf[32];
1199 xsnprintf(buf, sizeof(buf), "%d", lno);
1200 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_LINENO]);
1201 output_sep(opt, sign);
1204 * Treat 'cno' as the 1-indexed offset from the start of a non-context
1205 * line to its first match. Otherwise, 'cno' is 0 indicating that we are
1206 * being called with a context line.
1208 if (opt->columnnum && cno) {
1209 char buf[32];
1210 xsnprintf(buf, sizeof(buf), "%"PRIuMAX, (uintmax_t)cno);
1211 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_COLUMNNO]);
1212 output_sep(opt, sign);
1216 static void show_line(struct grep_opt *opt,
1217 const char *bol, const char *eol,
1218 const char *name, unsigned lno, ssize_t cno, char sign)
1220 int rest = eol - bol;
1221 const char *match_color = NULL;
1222 const char *line_color = NULL;
1224 if (opt->file_break && opt->last_shown == 0) {
1225 if (opt->show_hunk_mark)
1226 opt->output(opt, "\n", 1);
1227 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1228 if (opt->last_shown == 0) {
1229 if (opt->show_hunk_mark) {
1230 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1231 opt->output(opt, "\n", 1);
1233 } else if (lno > opt->last_shown + 1) {
1234 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1235 opt->output(opt, "\n", 1);
1238 if (!opt->only_matching) {
1240 * In case the line we're being called with contains more than
1241 * one match, leave printing each header to the loop below.
1243 show_line_header(opt, name, lno, cno, sign);
1245 if (opt->color || opt->only_matching) {
1246 regmatch_t match;
1247 enum grep_context ctx = GREP_CONTEXT_BODY;
1248 int eflags = 0;
1250 if (opt->color) {
1251 if (sign == ':')
1252 match_color = opt->colors[GREP_COLOR_MATCH_SELECTED];
1253 else
1254 match_color = opt->colors[GREP_COLOR_MATCH_CONTEXT];
1255 if (sign == ':')
1256 line_color = opt->colors[GREP_COLOR_SELECTED];
1257 else if (sign == '-')
1258 line_color = opt->colors[GREP_COLOR_CONTEXT];
1259 else if (sign == '=')
1260 line_color = opt->colors[GREP_COLOR_FUNCTION];
1262 while (grep_next_match(opt, bol, eol, ctx, &match,
1263 GREP_HEADER_FIELD_MAX, eflags)) {
1264 if (match.rm_so == match.rm_eo)
1265 break;
1267 if (opt->only_matching)
1268 show_line_header(opt, name, lno, cno, sign);
1269 else
1270 output_color(opt, bol, match.rm_so, line_color);
1271 output_color(opt, bol + match.rm_so,
1272 match.rm_eo - match.rm_so, match_color);
1273 if (opt->only_matching)
1274 opt->output(opt, "\n", 1);
1275 bol += match.rm_eo;
1276 cno += match.rm_eo;
1277 rest -= match.rm_eo;
1278 eflags = REG_NOTBOL;
1281 if (!opt->only_matching) {
1282 output_color(opt, bol, rest, line_color);
1283 opt->output(opt, "\n", 1);
1287 int grep_use_locks;
1290 * This lock protects access to the gitattributes machinery, which is
1291 * not thread-safe.
1293 pthread_mutex_t grep_attr_mutex;
1295 static inline void grep_attr_lock(void)
1297 if (grep_use_locks)
1298 pthread_mutex_lock(&grep_attr_mutex);
1301 static inline void grep_attr_unlock(void)
1303 if (grep_use_locks)
1304 pthread_mutex_unlock(&grep_attr_mutex);
1307 static int match_funcname(struct grep_opt *opt, struct grep_source *gs,
1308 const char *bol, const char *eol)
1310 xdemitconf_t *xecfg = opt->priv;
1311 if (xecfg && !xecfg->find_func) {
1312 grep_source_load_driver(gs, opt->repo->index);
1313 if (gs->driver->funcname.pattern) {
1314 const struct userdiff_funcname *pe = &gs->driver->funcname;
1315 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1316 } else {
1317 xecfg = opt->priv = NULL;
1321 if (xecfg) {
1322 char buf[1];
1323 return xecfg->find_func(bol, eol - bol, buf, 1,
1324 xecfg->find_func_priv) >= 0;
1327 if (bol == eol)
1328 return 0;
1329 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1330 return 1;
1331 return 0;
1334 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1335 const char *bol, unsigned lno)
1337 while (bol > gs->buf) {
1338 const char *eol = --bol;
1340 while (bol > gs->buf && bol[-1] != '\n')
1341 bol--;
1342 lno--;
1344 if (lno <= opt->last_shown)
1345 break;
1347 if (match_funcname(opt, gs, bol, eol)) {
1348 show_line(opt, bol, eol, gs->name, lno, 0, '=');
1349 break;
1354 static int is_empty_line(const char *bol, const char *eol);
1356 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1357 const char *bol, const char *end, unsigned lno)
1359 unsigned cur = lno, from = 1, funcname_lno = 0, orig_from;
1360 int funcname_needed = !!opt->funcname, comment_needed = 0;
1362 if (opt->pre_context < lno)
1363 from = lno - opt->pre_context;
1364 if (from <= opt->last_shown)
1365 from = opt->last_shown + 1;
1366 orig_from = from;
1367 if (opt->funcbody) {
1368 if (match_funcname(opt, gs, bol, end))
1369 comment_needed = 1;
1370 else
1371 funcname_needed = 1;
1372 from = opt->last_shown + 1;
1375 /* Rewind. */
1376 while (bol > gs->buf && cur > from) {
1377 const char *next_bol = bol;
1378 const char *eol = --bol;
1380 while (bol > gs->buf && bol[-1] != '\n')
1381 bol--;
1382 cur--;
1383 if (comment_needed && (is_empty_line(bol, eol) ||
1384 match_funcname(opt, gs, bol, eol))) {
1385 comment_needed = 0;
1386 from = orig_from;
1387 if (cur < from) {
1388 cur++;
1389 bol = next_bol;
1390 break;
1393 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1394 funcname_lno = cur;
1395 funcname_needed = 0;
1396 if (opt->funcbody)
1397 comment_needed = 1;
1398 else
1399 from = orig_from;
1403 /* We need to look even further back to find a function signature. */
1404 if (opt->funcname && funcname_needed)
1405 show_funcname_line(opt, gs, bol, cur);
1407 /* Back forward. */
1408 while (cur < lno) {
1409 const char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1411 while (*eol != '\n')
1412 eol++;
1413 show_line(opt, bol, eol, gs->name, cur, 0, sign);
1414 bol = eol + 1;
1415 cur++;
1419 static int should_lookahead(struct grep_opt *opt)
1421 struct grep_pat *p;
1423 if (opt->pattern_expression)
1424 return 0; /* punt for too complex stuff */
1425 if (opt->invert)
1426 return 0;
1427 for (p = opt->pattern_list; p; p = p->next) {
1428 if (p->token != GREP_PATTERN)
1429 return 0; /* punt for "header only" and stuff */
1431 return 1;
1434 static int look_ahead(struct grep_opt *opt,
1435 unsigned long *left_p,
1436 unsigned *lno_p,
1437 const char **bol_p)
1439 unsigned lno = *lno_p;
1440 const char *bol = *bol_p;
1441 struct grep_pat *p;
1442 const char *sp, *last_bol;
1443 regoff_t earliest = -1;
1445 for (p = opt->pattern_list; p; p = p->next) {
1446 int hit;
1447 regmatch_t m;
1449 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1450 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1451 continue;
1452 if (earliest < 0 || m.rm_so < earliest)
1453 earliest = m.rm_so;
1456 if (earliest < 0) {
1457 *bol_p = bol + *left_p;
1458 *left_p = 0;
1459 return 1;
1461 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1462 ; /* find the beginning of the line */
1463 last_bol = sp;
1465 for (sp = bol; sp < last_bol; sp++) {
1466 if (*sp == '\n')
1467 lno++;
1469 *left_p -= last_bol - bol;
1470 *bol_p = last_bol;
1471 *lno_p = lno;
1472 return 0;
1475 static int fill_textconv_grep(struct repository *r,
1476 struct userdiff_driver *driver,
1477 struct grep_source *gs)
1479 struct diff_filespec *df;
1480 char *buf;
1481 size_t size;
1483 if (!driver || !driver->textconv)
1484 return grep_source_load(gs);
1487 * The textconv interface is intimately tied to diff_filespecs, so we
1488 * have to pretend to be one. If we could unify the grep_source
1489 * and diff_filespec structs, this mess could just go away.
1491 df = alloc_filespec(gs->path);
1492 switch (gs->type) {
1493 case GREP_SOURCE_OID:
1494 fill_filespec(df, gs->identifier, 1, 0100644);
1495 break;
1496 case GREP_SOURCE_FILE:
1497 fill_filespec(df, null_oid(), 0, 0100644);
1498 break;
1499 default:
1500 BUG("attempt to textconv something without a path?");
1504 * fill_textconv is not remotely thread-safe; it modifies the global
1505 * diff tempfile structure, writes to the_repo's odb and might
1506 * internally call thread-unsafe functions such as the
1507 * prepare_packed_git() lazy-initializator. Because of the last two, we
1508 * must ensure mutual exclusion between this call and the object reading
1509 * API, thus we use obj_read_lock() here.
1511 * TODO: allowing text conversion to run in parallel with object
1512 * reading operations might increase performance in the multithreaded
1513 * non-worktreee git-grep with --textconv.
1515 obj_read_lock();
1516 size = fill_textconv(r, driver, df, &buf);
1517 obj_read_unlock();
1518 free_filespec(df);
1521 * The normal fill_textconv usage by the diff machinery would just keep
1522 * the textconv'd buf separate from the diff_filespec. But much of the
1523 * grep code passes around a grep_source and assumes that its "buf"
1524 * pointer is the beginning of the thing we are searching. So let's
1525 * install our textconv'd version into the grep_source, taking care not
1526 * to leak any existing buffer.
1528 grep_source_clear_data(gs);
1529 gs->buf = buf;
1530 gs->size = size;
1532 return 0;
1535 static int is_empty_line(const char *bol, const char *eol)
1537 while (bol < eol && isspace(*bol))
1538 bol++;
1539 return bol == eol;
1542 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1544 const char *bol;
1545 const char *peek_bol = NULL;
1546 unsigned long left;
1547 unsigned lno = 1;
1548 unsigned last_hit = 0;
1549 int binary_match_only = 0;
1550 unsigned count = 0;
1551 int try_lookahead = 0;
1552 int show_function = 0;
1553 struct userdiff_driver *textconv = NULL;
1554 enum grep_context ctx = GREP_CONTEXT_HEAD;
1555 xdemitconf_t xecfg;
1557 if (!opt->status_only && gs->name == NULL)
1558 BUG("grep call which could print a name requires "
1559 "grep_source.name be non-NULL");
1561 if (!opt->output)
1562 opt->output = std_output;
1564 if (opt->pre_context || opt->post_context || opt->file_break ||
1565 opt->funcbody) {
1566 /* Show hunk marks, except for the first file. */
1567 if (opt->last_shown)
1568 opt->show_hunk_mark = 1;
1570 * If we're using threads then we can't easily identify
1571 * the first file. Always put hunk marks in that case
1572 * and skip the very first one later in work_done().
1574 if (opt->output != std_output)
1575 opt->show_hunk_mark = 1;
1577 opt->last_shown = 0;
1579 if (opt->allow_textconv) {
1580 grep_source_load_driver(gs, opt->repo->index);
1582 * We might set up the shared textconv cache data here, which
1583 * is not thread-safe. Also, get_oid_with_context() and
1584 * parse_object() might be internally called. As they are not
1585 * currently thread-safe and might be racy with object reading,
1586 * obj_read_lock() must be called.
1588 grep_attr_lock();
1589 obj_read_lock();
1590 textconv = userdiff_get_textconv(opt->repo, gs->driver);
1591 obj_read_unlock();
1592 grep_attr_unlock();
1596 * We know the result of a textconv is text, so we only have to care
1597 * about binary handling if we are not using it.
1599 if (!textconv) {
1600 switch (opt->binary) {
1601 case GREP_BINARY_DEFAULT:
1602 if (grep_source_is_binary(gs, opt->repo->index))
1603 binary_match_only = 1;
1604 break;
1605 case GREP_BINARY_NOMATCH:
1606 if (grep_source_is_binary(gs, opt->repo->index))
1607 return 0; /* Assume unmatch */
1608 break;
1609 case GREP_BINARY_TEXT:
1610 break;
1611 default:
1612 BUG("unknown binary handling mode");
1616 memset(&xecfg, 0, sizeof(xecfg));
1617 opt->priv = &xecfg;
1619 try_lookahead = should_lookahead(opt);
1621 if (fill_textconv_grep(opt->repo, textconv, gs) < 0)
1622 return 0;
1624 bol = gs->buf;
1625 left = gs->size;
1626 while (left) {
1627 const char *eol;
1628 int hit;
1629 ssize_t cno;
1630 ssize_t col = -1, icol = -1;
1633 * look_ahead() skips quickly to the line that possibly
1634 * has the next hit; don't call it if we need to do
1635 * something more than just skipping the current line
1636 * in response to an unmatch for the current line. E.g.
1637 * inside a post-context window, we will show the current
1638 * line as a context around the previous hit when it
1639 * doesn't hit.
1641 if (try_lookahead
1642 && !(last_hit
1643 && (show_function ||
1644 lno <= last_hit + opt->post_context))
1645 && look_ahead(opt, &left, &lno, &bol))
1646 break;
1647 eol = end_of_line(bol, &left);
1649 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1650 ctx = GREP_CONTEXT_BODY;
1652 hit = match_line(opt, bol, eol, &col, &icol, ctx, collect_hits);
1654 if (collect_hits)
1655 goto next_line;
1657 /* "grep -v -e foo -e bla" should list lines
1658 * that do not have either, so inversion should
1659 * be done outside.
1661 if (opt->invert)
1662 hit = !hit;
1663 if (opt->unmatch_name_only) {
1664 if (hit)
1665 return 0;
1666 goto next_line;
1668 if (hit && (opt->max_count < 0 || count < opt->max_count)) {
1669 count++;
1670 if (opt->status_only)
1671 return 1;
1672 if (opt->name_only) {
1673 show_name(opt, gs->name);
1674 return 1;
1676 if (opt->count)
1677 goto next_line;
1678 if (binary_match_only) {
1679 opt->output(opt, "Binary file ", 12);
1680 output_color(opt, gs->name, strlen(gs->name),
1681 opt->colors[GREP_COLOR_FILENAME]);
1682 opt->output(opt, " matches\n", 9);
1683 return 1;
1685 /* Hit at this line. If we haven't shown the
1686 * pre-context lines, we would need to show them.
1688 if (opt->pre_context || opt->funcbody)
1689 show_pre_context(opt, gs, bol, eol, lno);
1690 else if (opt->funcname)
1691 show_funcname_line(opt, gs, bol, lno);
1692 cno = opt->invert ? icol : col;
1693 if (cno < 0) {
1695 * A negative cno indicates that there was no
1696 * match on the line. We are thus inverted and
1697 * being asked to show all lines that _don't_
1698 * match a given expression. Therefore, set cno
1699 * to 0 to suggest the whole line matches.
1701 cno = 0;
1703 show_line(opt, bol, eol, gs->name, lno, cno + 1, ':');
1704 last_hit = lno;
1705 if (opt->funcbody)
1706 show_function = 1;
1707 goto next_line;
1709 if (show_function && (!peek_bol || peek_bol < bol)) {
1710 unsigned long peek_left = left;
1711 const char *peek_eol = eol;
1714 * Trailing empty lines are not interesting.
1715 * Peek past them to see if they belong to the
1716 * body of the current function.
1718 peek_bol = bol;
1719 while (is_empty_line(peek_bol, peek_eol)) {
1720 peek_bol = peek_eol + 1;
1721 peek_eol = end_of_line(peek_bol, &peek_left);
1724 if (match_funcname(opt, gs, peek_bol, peek_eol))
1725 show_function = 0;
1727 if (show_function ||
1728 (last_hit && lno <= last_hit + opt->post_context)) {
1729 /* If the last hit is within the post context,
1730 * we need to show this line.
1732 show_line(opt, bol, eol, gs->name, lno, col + 1, '-');
1735 next_line:
1736 bol = eol + 1;
1737 if (!left)
1738 break;
1739 left--;
1740 lno++;
1743 if (collect_hits)
1744 return 0;
1746 if (opt->status_only)
1747 return opt->unmatch_name_only;
1748 if (opt->unmatch_name_only) {
1749 /* We did not see any hit, so we want to show this */
1750 show_name(opt, gs->name);
1751 return 1;
1754 xdiff_clear_find_func(&xecfg);
1755 opt->priv = NULL;
1757 /* NEEDSWORK:
1758 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1759 * which feels mostly useless but sometimes useful. Maybe
1760 * make it another option? For now suppress them.
1762 if (opt->count && count) {
1763 char buf[32];
1764 if (opt->pathname) {
1765 output_color(opt, gs->name, strlen(gs->name),
1766 opt->colors[GREP_COLOR_FILENAME]);
1767 output_sep(opt, ':');
1769 xsnprintf(buf, sizeof(buf), "%u\n", count);
1770 opt->output(opt, buf, strlen(buf));
1771 return 1;
1773 return !!last_hit;
1776 static void clr_hit_marker(struct grep_expr *x)
1778 /* All-hit markers are meaningful only at the very top level
1779 * OR node.
1781 while (1) {
1782 x->hit = 0;
1783 if (x->node != GREP_NODE_OR)
1784 return;
1785 x->u.binary.left->hit = 0;
1786 x = x->u.binary.right;
1790 static int chk_hit_marker(struct grep_expr *x)
1792 /* Top level nodes have hit markers. See if they all are hits */
1793 while (1) {
1794 if (x->node != GREP_NODE_OR)
1795 return x->hit;
1796 if (!x->u.binary.left->hit)
1797 return 0;
1798 x = x->u.binary.right;
1802 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1805 * we do not have to do the two-pass grep when we do not check
1806 * buffer-wide "all-match".
1808 if (!opt->all_match && !opt->no_body_match)
1809 return grep_source_1(opt, gs, 0);
1811 /* Otherwise the toplevel "or" terms hit a bit differently.
1812 * We first clear hit markers from them.
1814 clr_hit_marker(opt->pattern_expression);
1815 opt->body_hit = 0;
1816 grep_source_1(opt, gs, 1);
1818 if (opt->all_match && !chk_hit_marker(opt->pattern_expression))
1819 return 0;
1820 if (opt->no_body_match && opt->body_hit)
1821 return 0;
1823 return grep_source_1(opt, gs, 0);
1826 static void grep_source_init_buf(struct grep_source *gs,
1827 const char *buf,
1828 unsigned long size)
1830 gs->type = GREP_SOURCE_BUF;
1831 gs->name = NULL;
1832 gs->path = NULL;
1833 gs->buf = buf;
1834 gs->size = size;
1835 gs->driver = NULL;
1836 gs->identifier = NULL;
1839 int grep_buffer(struct grep_opt *opt, const char *buf, unsigned long size)
1841 struct grep_source gs;
1842 int r;
1844 grep_source_init_buf(&gs, buf, size);
1846 r = grep_source(opt, &gs);
1848 grep_source_clear(&gs);
1849 return r;
1852 void grep_source_init_file(struct grep_source *gs, const char *name,
1853 const char *path)
1855 gs->type = GREP_SOURCE_FILE;
1856 gs->name = xstrdup_or_null(name);
1857 gs->path = xstrdup_or_null(path);
1858 gs->buf = NULL;
1859 gs->size = 0;
1860 gs->driver = NULL;
1861 gs->identifier = xstrdup(path);
1864 void grep_source_init_oid(struct grep_source *gs, const char *name,
1865 const char *path, const struct object_id *oid,
1866 struct repository *repo)
1868 gs->type = GREP_SOURCE_OID;
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 = oiddup(oid);
1875 gs->repo = repo;
1878 void grep_source_clear(struct grep_source *gs)
1880 FREE_AND_NULL(gs->name);
1881 FREE_AND_NULL(gs->path);
1882 FREE_AND_NULL(gs->identifier);
1883 grep_source_clear_data(gs);
1886 void grep_source_clear_data(struct grep_source *gs)
1888 switch (gs->type) {
1889 case GREP_SOURCE_FILE:
1890 case GREP_SOURCE_OID:
1891 /* these types own the buffer */
1892 free((char *)gs->buf);
1893 gs->buf = NULL;
1894 gs->size = 0;
1895 break;
1896 case GREP_SOURCE_BUF:
1897 /* leave user-provided buf intact */
1898 break;
1902 static int grep_source_load_oid(struct grep_source *gs)
1904 enum object_type type;
1906 gs->buf = repo_read_object_file(gs->repo, gs->identifier, &type,
1907 &gs->size);
1908 if (!gs->buf)
1909 return error(_("'%s': unable to read %s"),
1910 gs->name,
1911 oid_to_hex(gs->identifier));
1912 return 0;
1915 static int grep_source_load_file(struct grep_source *gs)
1917 const char *filename = gs->identifier;
1918 struct stat st;
1919 char *data;
1920 size_t size;
1921 int i;
1923 if (lstat(filename, &st) < 0) {
1924 err_ret:
1925 if (errno != ENOENT)
1926 error_errno(_("failed to stat '%s'"), filename);
1927 return -1;
1929 if (!S_ISREG(st.st_mode))
1930 return -1;
1931 size = xsize_t(st.st_size);
1932 i = open(filename, O_RDONLY);
1933 if (i < 0)
1934 goto err_ret;
1935 data = xmallocz(size);
1936 if (st.st_size != read_in_full(i, data, size)) {
1937 error_errno(_("'%s': short read"), filename);
1938 close(i);
1939 free(data);
1940 return -1;
1942 close(i);
1944 gs->buf = data;
1945 gs->size = size;
1946 return 0;
1949 static int grep_source_load(struct grep_source *gs)
1951 if (gs->buf)
1952 return 0;
1954 switch (gs->type) {
1955 case GREP_SOURCE_FILE:
1956 return grep_source_load_file(gs);
1957 case GREP_SOURCE_OID:
1958 return grep_source_load_oid(gs);
1959 case GREP_SOURCE_BUF:
1960 return gs->buf ? 0 : -1;
1962 BUG("invalid grep_source type to load");
1965 void grep_source_load_driver(struct grep_source *gs,
1966 struct index_state *istate)
1968 if (gs->driver)
1969 return;
1971 grep_attr_lock();
1972 if (gs->path)
1973 gs->driver = userdiff_find_by_path(istate, gs->path);
1974 if (!gs->driver)
1975 gs->driver = userdiff_find_by_name("default");
1976 grep_attr_unlock();
1979 static int grep_source_is_binary(struct grep_source *gs,
1980 struct index_state *istate)
1982 grep_source_load_driver(gs, istate);
1983 if (gs->driver->binary != -1)
1984 return gs->driver->binary;
1986 if (!grep_source_load(gs))
1987 return buffer_is_binary(gs->buf, gs->size);
1989 return 0;