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