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