]> git.ipfire.org Git - thirdparty/git.git/blob - grep.c
grep: extract grep_binexp() from grep_or_expr()
[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 int literal = !opt->ignore_case && (p->fixed || p->is_fixed);
366
367 /*
368 * Call pcre2_general_context_create() before calling any
369 * other pcre2_*(). It sets up our malloc()/free() functions
370 * with which everything else is allocated.
371 */
372 p->pcre2_general_context = pcre2_general_context_create(
373 pcre2_malloc, pcre2_free, NULL);
374 if (!p->pcre2_general_context)
375 die("Couldn't allocate PCRE2 general context");
376
377 if (opt->ignore_case) {
378 if (!opt->ignore_locale && has_non_ascii(p->pattern)) {
379 p->pcre2_tables = pcre2_maketables(p->pcre2_general_context);
380 p->pcre2_compile_context = pcre2_compile_context_create(p->pcre2_general_context);
381 pcre2_set_character_tables(p->pcre2_compile_context,
382 p->pcre2_tables);
383 }
384 options |= PCRE2_CASELESS;
385 }
386 if (!opt->ignore_locale && is_utf8_locale() && !literal)
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 *grep_not_expr(struct grep_expr *expr)
599 {
600 struct grep_expr *z = xcalloc(1, sizeof(*z));
601 z->node = GREP_NODE_NOT;
602 z->u.unary = expr;
603 return z;
604 }
605
606 static struct grep_expr *grep_binexp(enum grep_expr_node kind,
607 struct grep_expr *left,
608 struct grep_expr *right)
609 {
610 struct grep_expr *z = xcalloc(1, sizeof(*z));
611 z->node = kind;
612 z->u.binary.left = left;
613 z->u.binary.right = right;
614 return z;
615 }
616
617 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
618 {
619 return grep_binexp(GREP_NODE_OR, left, right);
620 }
621
622 static struct grep_expr *compile_pattern_or(struct grep_pat **);
623 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
624 {
625 struct grep_pat *p;
626 struct grep_expr *x;
627
628 p = *list;
629 if (!p)
630 return NULL;
631 switch (p->token) {
632 case GREP_PATTERN: /* atom */
633 case GREP_PATTERN_HEAD:
634 case GREP_PATTERN_BODY:
635 CALLOC_ARRAY(x, 1);
636 x->node = GREP_NODE_ATOM;
637 x->u.atom = p;
638 *list = p->next;
639 return x;
640 case GREP_OPEN_PAREN:
641 *list = p->next;
642 x = compile_pattern_or(list);
643 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
644 die("unmatched parenthesis");
645 *list = (*list)->next;
646 return x;
647 default:
648 return NULL;
649 }
650 }
651
652 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
653 {
654 struct grep_pat *p;
655 struct grep_expr *x;
656
657 p = *list;
658 if (!p)
659 return NULL;
660 switch (p->token) {
661 case GREP_NOT:
662 if (!p->next)
663 die("--not not followed by pattern expression");
664 *list = p->next;
665 x = compile_pattern_not(list);
666 if (!x)
667 die("--not followed by non pattern expression");
668 return grep_not_expr(x);
669 default:
670 return compile_pattern_atom(list);
671 }
672 }
673
674 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
675 {
676 struct grep_pat *p;
677 struct grep_expr *x, *y, *z;
678
679 x = compile_pattern_not(list);
680 p = *list;
681 if (p && p->token == GREP_AND) {
682 if (!x)
683 die("--and not preceded by pattern expression");
684 if (!p->next)
685 die("--and not followed by pattern expression");
686 *list = p->next;
687 y = compile_pattern_and(list);
688 if (!y)
689 die("--and not followed by pattern expression");
690 CALLOC_ARRAY(z, 1);
691 z->node = GREP_NODE_AND;
692 z->u.binary.left = x;
693 z->u.binary.right = y;
694 return z;
695 }
696 return x;
697 }
698
699 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
700 {
701 struct grep_pat *p;
702 struct grep_expr *x, *y;
703
704 x = compile_pattern_and(list);
705 p = *list;
706 if (x && p && p->token != GREP_CLOSE_PAREN) {
707 y = compile_pattern_or(list);
708 if (!y)
709 die("not a pattern expression %s", p->pattern);
710 return grep_or_expr(x, y);
711 }
712 return x;
713 }
714
715 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
716 {
717 return compile_pattern_or(list);
718 }
719
720 static struct grep_expr *grep_true_expr(void)
721 {
722 struct grep_expr *z = xcalloc(1, sizeof(*z));
723 z->node = GREP_NODE_TRUE;
724 return z;
725 }
726
727 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
728 {
729 struct grep_pat *p;
730 struct grep_expr *header_expr;
731 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
732 enum grep_header_field fld;
733
734 if (!opt->header_list)
735 return NULL;
736
737 for (p = opt->header_list; p; p = p->next) {
738 if (p->token != GREP_PATTERN_HEAD)
739 BUG("a non-header pattern in grep header list.");
740 if (p->field < GREP_HEADER_FIELD_MIN ||
741 GREP_HEADER_FIELD_MAX <= p->field)
742 BUG("unknown header field %d", p->field);
743 compile_regexp(p, opt);
744 }
745
746 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
747 header_group[fld] = NULL;
748
749 for (p = opt->header_list; p; p = p->next) {
750 struct grep_expr *h;
751 struct grep_pat *pp = p;
752
753 h = compile_pattern_atom(&pp);
754 if (!h || pp != p->next)
755 BUG("malformed header expr");
756 if (!header_group[p->field]) {
757 header_group[p->field] = h;
758 continue;
759 }
760 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
761 }
762
763 header_expr = NULL;
764
765 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
766 if (!header_group[fld])
767 continue;
768 if (!header_expr)
769 header_expr = grep_true_expr();
770 header_expr = grep_or_expr(header_group[fld], header_expr);
771 }
772 return header_expr;
773 }
774
775 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
776 {
777 struct grep_expr *z = x;
778
779 while (x) {
780 assert(x->node == GREP_NODE_OR);
781 if (x->u.binary.right &&
782 x->u.binary.right->node == GREP_NODE_TRUE) {
783 x->u.binary.right = y;
784 break;
785 }
786 x = x->u.binary.right;
787 }
788 return z;
789 }
790
791 void compile_grep_patterns(struct grep_opt *opt)
792 {
793 struct grep_pat *p;
794 struct grep_expr *header_expr = prep_header_patterns(opt);
795
796 for (p = opt->pattern_list; p; p = p->next) {
797 switch (p->token) {
798 case GREP_PATTERN: /* atom */
799 case GREP_PATTERN_HEAD:
800 case GREP_PATTERN_BODY:
801 compile_regexp(p, opt);
802 break;
803 default:
804 opt->extended = 1;
805 break;
806 }
807 }
808
809 if (opt->all_match || opt->no_body_match || header_expr)
810 opt->extended = 1;
811 else if (!opt->extended)
812 return;
813
814 p = opt->pattern_list;
815 if (p)
816 opt->pattern_expression = compile_pattern_expr(&p);
817 if (p)
818 die("incomplete pattern expression: %s", p->pattern);
819
820 if (opt->no_body_match && opt->pattern_expression)
821 opt->pattern_expression = grep_not_expr(opt->pattern_expression);
822
823 if (!header_expr)
824 return;
825
826 if (!opt->pattern_expression)
827 opt->pattern_expression = header_expr;
828 else if (opt->all_match)
829 opt->pattern_expression = grep_splice_or(header_expr,
830 opt->pattern_expression);
831 else
832 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
833 header_expr);
834 opt->all_match = 1;
835 }
836
837 static void free_pattern_expr(struct grep_expr *x)
838 {
839 switch (x->node) {
840 case GREP_NODE_TRUE:
841 case GREP_NODE_ATOM:
842 break;
843 case GREP_NODE_NOT:
844 free_pattern_expr(x->u.unary);
845 break;
846 case GREP_NODE_AND:
847 case GREP_NODE_OR:
848 free_pattern_expr(x->u.binary.left);
849 free_pattern_expr(x->u.binary.right);
850 break;
851 }
852 free(x);
853 }
854
855 void free_grep_patterns(struct grep_opt *opt)
856 {
857 struct grep_pat *p, *n;
858
859 for (p = opt->pattern_list; p; p = n) {
860 n = p->next;
861 switch (p->token) {
862 case GREP_PATTERN: /* atom */
863 case GREP_PATTERN_HEAD:
864 case GREP_PATTERN_BODY:
865 if (p->pcre2_pattern)
866 free_pcre2_pattern(p);
867 else
868 regfree(&p->regexp);
869 free(p->pattern);
870 break;
871 default:
872 break;
873 }
874 free(p);
875 }
876
877 if (!opt->extended)
878 return;
879 free_pattern_expr(opt->pattern_expression);
880 }
881
882 static const char *end_of_line(const char *cp, unsigned long *left)
883 {
884 unsigned long l = *left;
885 while (l && *cp != '\n') {
886 l--;
887 cp++;
888 }
889 *left = l;
890 return cp;
891 }
892
893 static int word_char(char ch)
894 {
895 return isalnum(ch) || ch == '_';
896 }
897
898 static void output_color(struct grep_opt *opt, const void *data, size_t size,
899 const char *color)
900 {
901 if (want_color(opt->color) && color && color[0]) {
902 opt->output(opt, color, strlen(color));
903 opt->output(opt, data, size);
904 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
905 } else
906 opt->output(opt, data, size);
907 }
908
909 static void output_sep(struct grep_opt *opt, char sign)
910 {
911 if (opt->null_following_name)
912 opt->output(opt, "\0", 1);
913 else
914 output_color(opt, &sign, 1, opt->colors[GREP_COLOR_SEP]);
915 }
916
917 static void show_name(struct grep_opt *opt, const char *name)
918 {
919 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
920 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
921 }
922
923 static int patmatch(struct grep_pat *p,
924 const char *line, const char *eol,
925 regmatch_t *match, int eflags)
926 {
927 int hit;
928
929 if (p->pcre2_pattern)
930 hit = !pcre2match(p, line, eol, match, eflags);
931 else
932 hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
933 eflags);
934
935 return hit;
936 }
937
938 static void strip_timestamp(const char *bol, const char **eol_p)
939 {
940 const char *eol = *eol_p;
941
942 while (bol < --eol) {
943 if (*eol != '>')
944 continue;
945 *eol_p = ++eol;
946 break;
947 }
948 }
949
950 static struct {
951 const char *field;
952 size_t len;
953 } header_field[] = {
954 { "author ", 7 },
955 { "committer ", 10 },
956 { "reflog ", 7 },
957 };
958
959 static int headerless_match_one_pattern(struct grep_pat *p,
960 const char *bol, const char *eol,
961 enum grep_context ctx,
962 regmatch_t *pmatch, int eflags)
963 {
964 int hit = 0;
965 const char *start = bol;
966
967 if ((p->token != GREP_PATTERN) &&
968 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
969 return 0;
970
971 again:
972 hit = patmatch(p, bol, eol, pmatch, eflags);
973
974 if (hit && p->word_regexp) {
975 if ((pmatch[0].rm_so < 0) ||
976 (eol - bol) < pmatch[0].rm_so ||
977 (pmatch[0].rm_eo < 0) ||
978 (eol - bol) < pmatch[0].rm_eo)
979 die("regexp returned nonsense");
980
981 /* Match beginning must be either beginning of the
982 * line, or at word boundary (i.e. the last char must
983 * not be a word char). Similarly, match end must be
984 * either end of the line, or at word boundary
985 * (i.e. the next char must not be a word char).
986 */
987 if ( ((pmatch[0].rm_so == 0) ||
988 !word_char(bol[pmatch[0].rm_so-1])) &&
989 ((pmatch[0].rm_eo == (eol-bol)) ||
990 !word_char(bol[pmatch[0].rm_eo])) )
991 ;
992 else
993 hit = 0;
994
995 /* Words consist of at least one character. */
996 if (pmatch->rm_so == pmatch->rm_eo)
997 hit = 0;
998
999 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
1000 /* There could be more than one match on the
1001 * line, and the first match might not be
1002 * strict word match. But later ones could be!
1003 * Forward to the next possible start, i.e. the
1004 * next position following a non-word char.
1005 */
1006 bol = pmatch[0].rm_so + bol + 1;
1007 while (word_char(bol[-1]) && bol < eol)
1008 bol++;
1009 eflags |= REG_NOTBOL;
1010 if (bol < eol)
1011 goto again;
1012 }
1013 }
1014 if (hit) {
1015 pmatch[0].rm_so += bol - start;
1016 pmatch[0].rm_eo += bol - start;
1017 }
1018 return hit;
1019 }
1020
1021 static int match_one_pattern(struct grep_pat *p,
1022 const char *bol, const char *eol,
1023 enum grep_context ctx, regmatch_t *pmatch,
1024 int eflags)
1025 {
1026 const char *field;
1027 size_t len;
1028
1029 if (p->token == GREP_PATTERN_HEAD) {
1030 assert(p->field < ARRAY_SIZE(header_field));
1031 field = header_field[p->field].field;
1032 len = header_field[p->field].len;
1033 if (strncmp(bol, field, len))
1034 return 0;
1035 bol += len;
1036
1037 switch (p->field) {
1038 case GREP_HEADER_AUTHOR:
1039 case GREP_HEADER_COMMITTER:
1040 strip_timestamp(bol, &eol);
1041 break;
1042 default:
1043 break;
1044 }
1045 }
1046
1047 return headerless_match_one_pattern(p, bol, eol, ctx, pmatch, eflags);
1048 }
1049
1050
1051 static int match_expr_eval(struct grep_opt *opt, struct grep_expr *x,
1052 const char *bol, const char *eol,
1053 enum grep_context ctx, ssize_t *col,
1054 ssize_t *icol, int collect_hits)
1055 {
1056 int h = 0;
1057
1058 if (!x)
1059 die("Not a valid grep expression");
1060 switch (x->node) {
1061 case GREP_NODE_TRUE:
1062 h = 1;
1063 break;
1064 case GREP_NODE_ATOM:
1065 {
1066 regmatch_t tmp;
1067 h = match_one_pattern(x->u.atom, bol, eol, ctx,
1068 &tmp, 0);
1069 if (h && (*col < 0 || tmp.rm_so < *col))
1070 *col = tmp.rm_so;
1071 }
1072 if (x->u.atom->token == GREP_PATTERN_BODY)
1073 opt->body_hit |= h;
1074 break;
1075 case GREP_NODE_NOT:
1076 /*
1077 * Upon visiting a GREP_NODE_NOT, col and icol become swapped.
1078 */
1079 h = !match_expr_eval(opt, x->u.unary, bol, eol, ctx, icol, col,
1080 0);
1081 break;
1082 case GREP_NODE_AND:
1083 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1084 icol, 0);
1085 if (h || opt->columnnum) {
1086 /*
1087 * Don't short-circuit AND when given --column, since a
1088 * NOT earlier in the tree may turn this into an OR. In
1089 * this case, see the below comment.
1090 */
1091 h &= match_expr_eval(opt, x->u.binary.right, bol, eol,
1092 ctx, col, icol, 0);
1093 }
1094 break;
1095 case GREP_NODE_OR:
1096 if (!(collect_hits || opt->columnnum)) {
1097 /*
1098 * Don't short-circuit OR when given --column (or
1099 * collecting hits) to ensure we don't skip a later
1100 * child that would produce an earlier match.
1101 */
1102 return (match_expr_eval(opt, x->u.binary.left, bol, eol,
1103 ctx, col, icol, 0) ||
1104 match_expr_eval(opt, x->u.binary.right, bol,
1105 eol, ctx, col, icol, 0));
1106 }
1107 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1108 icol, 0);
1109 if (collect_hits)
1110 x->u.binary.left->hit |= h;
1111 h |= match_expr_eval(opt, x->u.binary.right, bol, eol, ctx, col,
1112 icol, collect_hits);
1113 break;
1114 default:
1115 die("Unexpected node type (internal error) %d", x->node);
1116 }
1117 if (collect_hits)
1118 x->hit |= h;
1119 return h;
1120 }
1121
1122 static int match_expr(struct grep_opt *opt,
1123 const char *bol, const char *eol,
1124 enum grep_context ctx, ssize_t *col,
1125 ssize_t *icol, int collect_hits)
1126 {
1127 struct grep_expr *x = opt->pattern_expression;
1128 return match_expr_eval(opt, x, bol, eol, ctx, col, icol, collect_hits);
1129 }
1130
1131 static int match_line(struct grep_opt *opt,
1132 const char *bol, const char *eol,
1133 ssize_t *col, ssize_t *icol,
1134 enum grep_context ctx, int collect_hits)
1135 {
1136 struct grep_pat *p;
1137 int hit = 0;
1138
1139 if (opt->extended)
1140 return match_expr(opt, bol, eol, ctx, col, icol,
1141 collect_hits);
1142
1143 /* we do not call with collect_hits without being extended */
1144 for (p = opt->pattern_list; p; p = p->next) {
1145 regmatch_t tmp;
1146 if (match_one_pattern(p, bol, eol, ctx, &tmp, 0)) {
1147 hit |= 1;
1148 if (!opt->columnnum) {
1149 /*
1150 * Without --column, any single match on a line
1151 * is enough to know that it needs to be
1152 * printed. With --column, scan _all_ patterns
1153 * to find the earliest.
1154 */
1155 break;
1156 }
1157 if (*col < 0 || tmp.rm_so < *col)
1158 *col = tmp.rm_so;
1159 }
1160 }
1161 return hit;
1162 }
1163
1164 static int match_next_pattern(struct grep_pat *p,
1165 const char *bol, const char *eol,
1166 enum grep_context ctx,
1167 regmatch_t *pmatch, int eflags)
1168 {
1169 regmatch_t match;
1170
1171 if (!headerless_match_one_pattern(p, bol, eol, ctx, &match, eflags))
1172 return 0;
1173 if (match.rm_so < 0 || match.rm_eo < 0)
1174 return 0;
1175 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1176 if (match.rm_so > pmatch->rm_so)
1177 return 1;
1178 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1179 return 1;
1180 }
1181 pmatch->rm_so = match.rm_so;
1182 pmatch->rm_eo = match.rm_eo;
1183 return 1;
1184 }
1185
1186 int grep_next_match(struct grep_opt *opt,
1187 const char *bol, const char *eol,
1188 enum grep_context ctx, regmatch_t *pmatch,
1189 enum grep_header_field field, int eflags)
1190 {
1191 struct grep_pat *p;
1192 int hit = 0;
1193
1194 pmatch->rm_so = pmatch->rm_eo = -1;
1195 if (bol < eol) {
1196 for (p = ((ctx == GREP_CONTEXT_HEAD)
1197 ? opt->header_list : opt->pattern_list);
1198 p; p = p->next) {
1199 switch (p->token) {
1200 case GREP_PATTERN_HEAD:
1201 if ((field != GREP_HEADER_FIELD_MAX) &&
1202 (p->field != field))
1203 continue;
1204 /* fall thru */
1205 case GREP_PATTERN: /* atom */
1206 case GREP_PATTERN_BODY:
1207 hit |= match_next_pattern(p, bol, eol, ctx,
1208 pmatch, eflags);
1209 break;
1210 default:
1211 break;
1212 }
1213 }
1214 }
1215 return hit;
1216 }
1217
1218 static void show_line_header(struct grep_opt *opt, const char *name,
1219 unsigned lno, ssize_t cno, char sign)
1220 {
1221 if (opt->heading && opt->last_shown == 0) {
1222 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1223 opt->output(opt, "\n", 1);
1224 }
1225 opt->last_shown = lno;
1226
1227 if (!opt->heading && opt->pathname) {
1228 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1229 output_sep(opt, sign);
1230 }
1231 if (opt->linenum) {
1232 char buf[32];
1233 xsnprintf(buf, sizeof(buf), "%d", lno);
1234 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_LINENO]);
1235 output_sep(opt, sign);
1236 }
1237 /*
1238 * Treat 'cno' as the 1-indexed offset from the start of a non-context
1239 * line to its first match. Otherwise, 'cno' is 0 indicating that we are
1240 * being called with a context line.
1241 */
1242 if (opt->columnnum && cno) {
1243 char buf[32];
1244 xsnprintf(buf, sizeof(buf), "%"PRIuMAX, (uintmax_t)cno);
1245 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_COLUMNNO]);
1246 output_sep(opt, sign);
1247 }
1248 }
1249
1250 static void show_line(struct grep_opt *opt,
1251 const char *bol, const char *eol,
1252 const char *name, unsigned lno, ssize_t cno, char sign)
1253 {
1254 int rest = eol - bol;
1255 const char *match_color = NULL;
1256 const char *line_color = NULL;
1257
1258 if (opt->file_break && opt->last_shown == 0) {
1259 if (opt->show_hunk_mark)
1260 opt->output(opt, "\n", 1);
1261 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1262 if (opt->last_shown == 0) {
1263 if (opt->show_hunk_mark) {
1264 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1265 opt->output(opt, "\n", 1);
1266 }
1267 } else if (lno > opt->last_shown + 1) {
1268 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1269 opt->output(opt, "\n", 1);
1270 }
1271 }
1272 if (!opt->only_matching) {
1273 /*
1274 * In case the line we're being called with contains more than
1275 * one match, leave printing each header to the loop below.
1276 */
1277 show_line_header(opt, name, lno, cno, sign);
1278 }
1279 if (opt->color || opt->only_matching) {
1280 regmatch_t match;
1281 enum grep_context ctx = GREP_CONTEXT_BODY;
1282 int eflags = 0;
1283
1284 if (opt->color) {
1285 if (sign == ':')
1286 match_color = opt->colors[GREP_COLOR_MATCH_SELECTED];
1287 else
1288 match_color = opt->colors[GREP_COLOR_MATCH_CONTEXT];
1289 if (sign == ':')
1290 line_color = opt->colors[GREP_COLOR_SELECTED];
1291 else if (sign == '-')
1292 line_color = opt->colors[GREP_COLOR_CONTEXT];
1293 else if (sign == '=')
1294 line_color = opt->colors[GREP_COLOR_FUNCTION];
1295 }
1296 while (grep_next_match(opt, bol, eol, ctx, &match,
1297 GREP_HEADER_FIELD_MAX, eflags)) {
1298 if (match.rm_so == match.rm_eo)
1299 break;
1300
1301 if (opt->only_matching)
1302 show_line_header(opt, name, lno, cno, sign);
1303 else
1304 output_color(opt, bol, match.rm_so, line_color);
1305 output_color(opt, bol + match.rm_so,
1306 match.rm_eo - match.rm_so, match_color);
1307 if (opt->only_matching)
1308 opt->output(opt, "\n", 1);
1309 bol += match.rm_eo;
1310 cno += match.rm_eo;
1311 rest -= match.rm_eo;
1312 eflags = REG_NOTBOL;
1313 }
1314 }
1315 if (!opt->only_matching) {
1316 output_color(opt, bol, rest, line_color);
1317 opt->output(opt, "\n", 1);
1318 }
1319 }
1320
1321 int grep_use_locks;
1322
1323 /*
1324 * This lock protects access to the gitattributes machinery, which is
1325 * not thread-safe.
1326 */
1327 pthread_mutex_t grep_attr_mutex;
1328
1329 static inline void grep_attr_lock(void)
1330 {
1331 if (grep_use_locks)
1332 pthread_mutex_lock(&grep_attr_mutex);
1333 }
1334
1335 static inline void grep_attr_unlock(void)
1336 {
1337 if (grep_use_locks)
1338 pthread_mutex_unlock(&grep_attr_mutex);
1339 }
1340
1341 static int match_funcname(struct grep_opt *opt, struct grep_source *gs,
1342 const char *bol, const char *eol)
1343 {
1344 xdemitconf_t *xecfg = opt->priv;
1345 if (xecfg && !xecfg->find_func) {
1346 grep_source_load_driver(gs, opt->repo->index);
1347 if (gs->driver->funcname.pattern) {
1348 const struct userdiff_funcname *pe = &gs->driver->funcname;
1349 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1350 } else {
1351 xecfg = opt->priv = NULL;
1352 }
1353 }
1354
1355 if (xecfg) {
1356 char buf[1];
1357 return xecfg->find_func(bol, eol - bol, buf, 1,
1358 xecfg->find_func_priv) >= 0;
1359 }
1360
1361 if (bol == eol)
1362 return 0;
1363 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1364 return 1;
1365 return 0;
1366 }
1367
1368 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1369 const char *bol, unsigned lno)
1370 {
1371 while (bol > gs->buf) {
1372 const char *eol = --bol;
1373
1374 while (bol > gs->buf && bol[-1] != '\n')
1375 bol--;
1376 lno--;
1377
1378 if (lno <= opt->last_shown)
1379 break;
1380
1381 if (match_funcname(opt, gs, bol, eol)) {
1382 show_line(opt, bol, eol, gs->name, lno, 0, '=');
1383 break;
1384 }
1385 }
1386 }
1387
1388 static int is_empty_line(const char *bol, const char *eol);
1389
1390 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1391 const char *bol, const char *end, unsigned lno)
1392 {
1393 unsigned cur = lno, from = 1, funcname_lno = 0, orig_from;
1394 int funcname_needed = !!opt->funcname, comment_needed = 0;
1395
1396 if (opt->pre_context < lno)
1397 from = lno - opt->pre_context;
1398 if (from <= opt->last_shown)
1399 from = opt->last_shown + 1;
1400 orig_from = from;
1401 if (opt->funcbody) {
1402 if (match_funcname(opt, gs, bol, end))
1403 comment_needed = 1;
1404 else
1405 funcname_needed = 1;
1406 from = opt->last_shown + 1;
1407 }
1408
1409 /* Rewind. */
1410 while (bol > gs->buf && cur > from) {
1411 const char *next_bol = bol;
1412 const char *eol = --bol;
1413
1414 while (bol > gs->buf && bol[-1] != '\n')
1415 bol--;
1416 cur--;
1417 if (comment_needed && (is_empty_line(bol, eol) ||
1418 match_funcname(opt, gs, bol, eol))) {
1419 comment_needed = 0;
1420 from = orig_from;
1421 if (cur < from) {
1422 cur++;
1423 bol = next_bol;
1424 break;
1425 }
1426 }
1427 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1428 funcname_lno = cur;
1429 funcname_needed = 0;
1430 if (opt->funcbody)
1431 comment_needed = 1;
1432 else
1433 from = orig_from;
1434 }
1435 }
1436
1437 /* We need to look even further back to find a function signature. */
1438 if (opt->funcname && funcname_needed)
1439 show_funcname_line(opt, gs, bol, cur);
1440
1441 /* Back forward. */
1442 while (cur < lno) {
1443 const char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1444
1445 while (*eol != '\n')
1446 eol++;
1447 show_line(opt, bol, eol, gs->name, cur, 0, sign);
1448 bol = eol + 1;
1449 cur++;
1450 }
1451 }
1452
1453 static int should_lookahead(struct grep_opt *opt)
1454 {
1455 struct grep_pat *p;
1456
1457 if (opt->extended)
1458 return 0; /* punt for too complex stuff */
1459 if (opt->invert)
1460 return 0;
1461 for (p = opt->pattern_list; p; p = p->next) {
1462 if (p->token != GREP_PATTERN)
1463 return 0; /* punt for "header only" and stuff */
1464 }
1465 return 1;
1466 }
1467
1468 static int look_ahead(struct grep_opt *opt,
1469 unsigned long *left_p,
1470 unsigned *lno_p,
1471 const char **bol_p)
1472 {
1473 unsigned lno = *lno_p;
1474 const char *bol = *bol_p;
1475 struct grep_pat *p;
1476 const char *sp, *last_bol;
1477 regoff_t earliest = -1;
1478
1479 for (p = opt->pattern_list; p; p = p->next) {
1480 int hit;
1481 regmatch_t m;
1482
1483 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1484 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1485 continue;
1486 if (earliest < 0 || m.rm_so < earliest)
1487 earliest = m.rm_so;
1488 }
1489
1490 if (earliest < 0) {
1491 *bol_p = bol + *left_p;
1492 *left_p = 0;
1493 return 1;
1494 }
1495 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1496 ; /* find the beginning of the line */
1497 last_bol = sp;
1498
1499 for (sp = bol; sp < last_bol; sp++) {
1500 if (*sp == '\n')
1501 lno++;
1502 }
1503 *left_p -= last_bol - bol;
1504 *bol_p = last_bol;
1505 *lno_p = lno;
1506 return 0;
1507 }
1508
1509 static int fill_textconv_grep(struct repository *r,
1510 struct userdiff_driver *driver,
1511 struct grep_source *gs)
1512 {
1513 struct diff_filespec *df;
1514 char *buf;
1515 size_t size;
1516
1517 if (!driver || !driver->textconv)
1518 return grep_source_load(gs);
1519
1520 /*
1521 * The textconv interface is intimately tied to diff_filespecs, so we
1522 * have to pretend to be one. If we could unify the grep_source
1523 * and diff_filespec structs, this mess could just go away.
1524 */
1525 df = alloc_filespec(gs->path);
1526 switch (gs->type) {
1527 case GREP_SOURCE_OID:
1528 fill_filespec(df, gs->identifier, 1, 0100644);
1529 break;
1530 case GREP_SOURCE_FILE:
1531 fill_filespec(df, null_oid(), 0, 0100644);
1532 break;
1533 default:
1534 BUG("attempt to textconv something without a path?");
1535 }
1536
1537 /*
1538 * fill_textconv is not remotely thread-safe; it modifies the global
1539 * diff tempfile structure, writes to the_repo's odb and might
1540 * internally call thread-unsafe functions such as the
1541 * prepare_packed_git() lazy-initializator. Because of the last two, we
1542 * must ensure mutual exclusion between this call and the object reading
1543 * API, thus we use obj_read_lock() here.
1544 *
1545 * TODO: allowing text conversion to run in parallel with object
1546 * reading operations might increase performance in the multithreaded
1547 * non-worktreee git-grep with --textconv.
1548 */
1549 obj_read_lock();
1550 size = fill_textconv(r, driver, df, &buf);
1551 obj_read_unlock();
1552 free_filespec(df);
1553
1554 /*
1555 * The normal fill_textconv usage by the diff machinery would just keep
1556 * the textconv'd buf separate from the diff_filespec. But much of the
1557 * grep code passes around a grep_source and assumes that its "buf"
1558 * pointer is the beginning of the thing we are searching. So let's
1559 * install our textconv'd version into the grep_source, taking care not
1560 * to leak any existing buffer.
1561 */
1562 grep_source_clear_data(gs);
1563 gs->buf = buf;
1564 gs->size = size;
1565
1566 return 0;
1567 }
1568
1569 static int is_empty_line(const char *bol, const char *eol)
1570 {
1571 while (bol < eol && isspace(*bol))
1572 bol++;
1573 return bol == eol;
1574 }
1575
1576 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1577 {
1578 const char *bol;
1579 const char *peek_bol = NULL;
1580 unsigned long left;
1581 unsigned lno = 1;
1582 unsigned last_hit = 0;
1583 int binary_match_only = 0;
1584 unsigned count = 0;
1585 int try_lookahead = 0;
1586 int show_function = 0;
1587 struct userdiff_driver *textconv = NULL;
1588 enum grep_context ctx = GREP_CONTEXT_HEAD;
1589 xdemitconf_t xecfg;
1590
1591 if (!opt->status_only && gs->name == NULL)
1592 BUG("grep call which could print a name requires "
1593 "grep_source.name be non-NULL");
1594
1595 if (!opt->output)
1596 opt->output = std_output;
1597
1598 if (opt->pre_context || opt->post_context || opt->file_break ||
1599 opt->funcbody) {
1600 /* Show hunk marks, except for the first file. */
1601 if (opt->last_shown)
1602 opt->show_hunk_mark = 1;
1603 /*
1604 * If we're using threads then we can't easily identify
1605 * the first file. Always put hunk marks in that case
1606 * and skip the very first one later in work_done().
1607 */
1608 if (opt->output != std_output)
1609 opt->show_hunk_mark = 1;
1610 }
1611 opt->last_shown = 0;
1612
1613 if (opt->allow_textconv) {
1614 grep_source_load_driver(gs, opt->repo->index);
1615 /*
1616 * We might set up the shared textconv cache data here, which
1617 * is not thread-safe. Also, get_oid_with_context() and
1618 * parse_object() might be internally called. As they are not
1619 * currently thread-safe and might be racy with object reading,
1620 * obj_read_lock() must be called.
1621 */
1622 grep_attr_lock();
1623 obj_read_lock();
1624 textconv = userdiff_get_textconv(opt->repo, gs->driver);
1625 obj_read_unlock();
1626 grep_attr_unlock();
1627 }
1628
1629 /*
1630 * We know the result of a textconv is text, so we only have to care
1631 * about binary handling if we are not using it.
1632 */
1633 if (!textconv) {
1634 switch (opt->binary) {
1635 case GREP_BINARY_DEFAULT:
1636 if (grep_source_is_binary(gs, opt->repo->index))
1637 binary_match_only = 1;
1638 break;
1639 case GREP_BINARY_NOMATCH:
1640 if (grep_source_is_binary(gs, opt->repo->index))
1641 return 0; /* Assume unmatch */
1642 break;
1643 case GREP_BINARY_TEXT:
1644 break;
1645 default:
1646 BUG("unknown binary handling mode");
1647 }
1648 }
1649
1650 memset(&xecfg, 0, sizeof(xecfg));
1651 opt->priv = &xecfg;
1652
1653 try_lookahead = should_lookahead(opt);
1654
1655 if (fill_textconv_grep(opt->repo, textconv, gs) < 0)
1656 return 0;
1657
1658 bol = gs->buf;
1659 left = gs->size;
1660 while (left) {
1661 const char *eol;
1662 int hit;
1663 ssize_t cno;
1664 ssize_t col = -1, icol = -1;
1665
1666 /*
1667 * look_ahead() skips quickly to the line that possibly
1668 * has the next hit; don't call it if we need to do
1669 * something more than just skipping the current line
1670 * in response to an unmatch for the current line. E.g.
1671 * inside a post-context window, we will show the current
1672 * line as a context around the previous hit when it
1673 * doesn't hit.
1674 */
1675 if (try_lookahead
1676 && !(last_hit
1677 && (show_function ||
1678 lno <= last_hit + opt->post_context))
1679 && look_ahead(opt, &left, &lno, &bol))
1680 break;
1681 eol = end_of_line(bol, &left);
1682
1683 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1684 ctx = GREP_CONTEXT_BODY;
1685
1686 hit = match_line(opt, bol, eol, &col, &icol, ctx, collect_hits);
1687
1688 if (collect_hits)
1689 goto next_line;
1690
1691 /* "grep -v -e foo -e bla" should list lines
1692 * that do not have either, so inversion should
1693 * be done outside.
1694 */
1695 if (opt->invert)
1696 hit = !hit;
1697 if (opt->unmatch_name_only) {
1698 if (hit)
1699 return 0;
1700 goto next_line;
1701 }
1702 if (hit) {
1703 count++;
1704 if (opt->status_only)
1705 return 1;
1706 if (opt->name_only) {
1707 show_name(opt, gs->name);
1708 return 1;
1709 }
1710 if (opt->count)
1711 goto next_line;
1712 if (binary_match_only) {
1713 opt->output(opt, "Binary file ", 12);
1714 output_color(opt, gs->name, strlen(gs->name),
1715 opt->colors[GREP_COLOR_FILENAME]);
1716 opt->output(opt, " matches\n", 9);
1717 return 1;
1718 }
1719 /* Hit at this line. If we haven't shown the
1720 * pre-context lines, we would need to show them.
1721 */
1722 if (opt->pre_context || opt->funcbody)
1723 show_pre_context(opt, gs, bol, eol, lno);
1724 else if (opt->funcname)
1725 show_funcname_line(opt, gs, bol, lno);
1726 cno = opt->invert ? icol : col;
1727 if (cno < 0) {
1728 /*
1729 * A negative cno indicates that there was no
1730 * match on the line. We are thus inverted and
1731 * being asked to show all lines that _don't_
1732 * match a given expression. Therefore, set cno
1733 * to 0 to suggest the whole line matches.
1734 */
1735 cno = 0;
1736 }
1737 show_line(opt, bol, eol, gs->name, lno, cno + 1, ':');
1738 last_hit = lno;
1739 if (opt->funcbody)
1740 show_function = 1;
1741 goto next_line;
1742 }
1743 if (show_function && (!peek_bol || peek_bol < bol)) {
1744 unsigned long peek_left = left;
1745 const char *peek_eol = eol;
1746
1747 /*
1748 * Trailing empty lines are not interesting.
1749 * Peek past them to see if they belong to the
1750 * body of the current function.
1751 */
1752 peek_bol = bol;
1753 while (is_empty_line(peek_bol, peek_eol)) {
1754 peek_bol = peek_eol + 1;
1755 peek_eol = end_of_line(peek_bol, &peek_left);
1756 }
1757
1758 if (match_funcname(opt, gs, peek_bol, peek_eol))
1759 show_function = 0;
1760 }
1761 if (show_function ||
1762 (last_hit && lno <= last_hit + opt->post_context)) {
1763 /* If the last hit is within the post context,
1764 * we need to show this line.
1765 */
1766 show_line(opt, bol, eol, gs->name, lno, col + 1, '-');
1767 }
1768
1769 next_line:
1770 bol = eol + 1;
1771 if (!left)
1772 break;
1773 left--;
1774 lno++;
1775 }
1776
1777 if (collect_hits)
1778 return 0;
1779
1780 if (opt->status_only)
1781 return opt->unmatch_name_only;
1782 if (opt->unmatch_name_only) {
1783 /* We did not see any hit, so we want to show this */
1784 show_name(opt, gs->name);
1785 return 1;
1786 }
1787
1788 xdiff_clear_find_func(&xecfg);
1789 opt->priv = NULL;
1790
1791 /* NEEDSWORK:
1792 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1793 * which feels mostly useless but sometimes useful. Maybe
1794 * make it another option? For now suppress them.
1795 */
1796 if (opt->count && count) {
1797 char buf[32];
1798 if (opt->pathname) {
1799 output_color(opt, gs->name, strlen(gs->name),
1800 opt->colors[GREP_COLOR_FILENAME]);
1801 output_sep(opt, ':');
1802 }
1803 xsnprintf(buf, sizeof(buf), "%u\n", count);
1804 opt->output(opt, buf, strlen(buf));
1805 return 1;
1806 }
1807 return !!last_hit;
1808 }
1809
1810 static void clr_hit_marker(struct grep_expr *x)
1811 {
1812 /* All-hit markers are meaningful only at the very top level
1813 * OR node.
1814 */
1815 while (1) {
1816 x->hit = 0;
1817 if (x->node != GREP_NODE_OR)
1818 return;
1819 x->u.binary.left->hit = 0;
1820 x = x->u.binary.right;
1821 }
1822 }
1823
1824 static int chk_hit_marker(struct grep_expr *x)
1825 {
1826 /* Top level nodes have hit markers. See if they all are hits */
1827 while (1) {
1828 if (x->node != GREP_NODE_OR)
1829 return x->hit;
1830 if (!x->u.binary.left->hit)
1831 return 0;
1832 x = x->u.binary.right;
1833 }
1834 }
1835
1836 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1837 {
1838 /*
1839 * we do not have to do the two-pass grep when we do not check
1840 * buffer-wide "all-match".
1841 */
1842 if (!opt->all_match && !opt->no_body_match)
1843 return grep_source_1(opt, gs, 0);
1844
1845 /* Otherwise the toplevel "or" terms hit a bit differently.
1846 * We first clear hit markers from them.
1847 */
1848 clr_hit_marker(opt->pattern_expression);
1849 opt->body_hit = 0;
1850 grep_source_1(opt, gs, 1);
1851
1852 if (opt->all_match && !chk_hit_marker(opt->pattern_expression))
1853 return 0;
1854 if (opt->no_body_match && opt->body_hit)
1855 return 0;
1856
1857 return grep_source_1(opt, gs, 0);
1858 }
1859
1860 static void grep_source_init_buf(struct grep_source *gs,
1861 const char *buf,
1862 unsigned long size)
1863 {
1864 gs->type = GREP_SOURCE_BUF;
1865 gs->name = NULL;
1866 gs->path = NULL;
1867 gs->buf = buf;
1868 gs->size = size;
1869 gs->driver = NULL;
1870 gs->identifier = NULL;
1871 }
1872
1873 int grep_buffer(struct grep_opt *opt, const char *buf, unsigned long size)
1874 {
1875 struct grep_source gs;
1876 int r;
1877
1878 grep_source_init_buf(&gs, buf, size);
1879
1880 r = grep_source(opt, &gs);
1881
1882 grep_source_clear(&gs);
1883 return r;
1884 }
1885
1886 void grep_source_init_file(struct grep_source *gs, const char *name,
1887 const char *path)
1888 {
1889 gs->type = GREP_SOURCE_FILE;
1890 gs->name = xstrdup_or_null(name);
1891 gs->path = xstrdup_or_null(path);
1892 gs->buf = NULL;
1893 gs->size = 0;
1894 gs->driver = NULL;
1895 gs->identifier = xstrdup(path);
1896 }
1897
1898 void grep_source_init_oid(struct grep_source *gs, const char *name,
1899 const char *path, const struct object_id *oid,
1900 struct repository *repo)
1901 {
1902 gs->type = GREP_SOURCE_OID;
1903 gs->name = xstrdup_or_null(name);
1904 gs->path = xstrdup_or_null(path);
1905 gs->buf = NULL;
1906 gs->size = 0;
1907 gs->driver = NULL;
1908 gs->identifier = oiddup(oid);
1909 gs->repo = repo;
1910 }
1911
1912 void grep_source_clear(struct grep_source *gs)
1913 {
1914 FREE_AND_NULL(gs->name);
1915 FREE_AND_NULL(gs->path);
1916 FREE_AND_NULL(gs->identifier);
1917 grep_source_clear_data(gs);
1918 }
1919
1920 void grep_source_clear_data(struct grep_source *gs)
1921 {
1922 switch (gs->type) {
1923 case GREP_SOURCE_FILE:
1924 case GREP_SOURCE_OID:
1925 /* these types own the buffer */
1926 free((char *)gs->buf);
1927 gs->buf = NULL;
1928 gs->size = 0;
1929 break;
1930 case GREP_SOURCE_BUF:
1931 /* leave user-provided buf intact */
1932 break;
1933 }
1934 }
1935
1936 static int grep_source_load_oid(struct grep_source *gs)
1937 {
1938 enum object_type type;
1939
1940 gs->buf = repo_read_object_file(gs->repo, gs->identifier, &type,
1941 &gs->size);
1942 if (!gs->buf)
1943 return error(_("'%s': unable to read %s"),
1944 gs->name,
1945 oid_to_hex(gs->identifier));
1946 return 0;
1947 }
1948
1949 static int grep_source_load_file(struct grep_source *gs)
1950 {
1951 const char *filename = gs->identifier;
1952 struct stat st;
1953 char *data;
1954 size_t size;
1955 int i;
1956
1957 if (lstat(filename, &st) < 0) {
1958 err_ret:
1959 if (errno != ENOENT)
1960 error_errno(_("failed to stat '%s'"), filename);
1961 return -1;
1962 }
1963 if (!S_ISREG(st.st_mode))
1964 return -1;
1965 size = xsize_t(st.st_size);
1966 i = open(filename, O_RDONLY);
1967 if (i < 0)
1968 goto err_ret;
1969 data = xmallocz(size);
1970 if (st.st_size != read_in_full(i, data, size)) {
1971 error_errno(_("'%s': short read"), filename);
1972 close(i);
1973 free(data);
1974 return -1;
1975 }
1976 close(i);
1977
1978 gs->buf = data;
1979 gs->size = size;
1980 return 0;
1981 }
1982
1983 static int grep_source_load(struct grep_source *gs)
1984 {
1985 if (gs->buf)
1986 return 0;
1987
1988 switch (gs->type) {
1989 case GREP_SOURCE_FILE:
1990 return grep_source_load_file(gs);
1991 case GREP_SOURCE_OID:
1992 return grep_source_load_oid(gs);
1993 case GREP_SOURCE_BUF:
1994 return gs->buf ? 0 : -1;
1995 }
1996 BUG("invalid grep_source type to load");
1997 }
1998
1999 void grep_source_load_driver(struct grep_source *gs,
2000 struct index_state *istate)
2001 {
2002 if (gs->driver)
2003 return;
2004
2005 grep_attr_lock();
2006 if (gs->path)
2007 gs->driver = userdiff_find_by_path(istate, gs->path);
2008 if (!gs->driver)
2009 gs->driver = userdiff_find_by_name("default");
2010 grep_attr_unlock();
2011 }
2012
2013 static int grep_source_is_binary(struct grep_source *gs,
2014 struct index_state *istate)
2015 {
2016 grep_source_load_driver(gs, istate);
2017 if (gs->driver->binary != -1)
2018 return gs->driver->binary;
2019
2020 if (!grep_source_load(gs))
2021 return buffer_is_binary(gs->buf, gs->size);
2022
2023 return 0;
2024 }