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