]> git.ipfire.org Git - thirdparty/git.git/blame - grep.c
urlmatch.h: use config_fn_t type
[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"
cbd53a21 6#include "object-store.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"
65156bb7 15#include "wrapper.h"
83b5d2f5 16
07a7d656 17static int grep_source_load(struct grep_source *gs);
acd00ea0
NTND
18static int grep_source_is_binary(struct grep_source *gs,
19 struct index_state *istate);
07a7d656 20
96313423
21static void std_output(struct grep_opt *opt, const void *buf, size_t size)
22{
23 fwrite(buf, size, 1, stdout);
24}
25
fa151dc5
NTND
26static const char *color_grep_slots[] = {
27 [GREP_COLOR_CONTEXT] = "context",
28 [GREP_COLOR_FILENAME] = "filename",
29 [GREP_COLOR_FUNCTION] = "function",
30 [GREP_COLOR_LINENO] = "lineNumber",
d036d667 31 [GREP_COLOR_COLUMNNO] = "column",
fa151dc5
NTND
32 [GREP_COLOR_MATCH_CONTEXT] = "matchContext",
33 [GREP_COLOR_MATCH_SELECTED] = "matchSelected",
34 [GREP_COLOR_SELECTED] = "selected",
35 [GREP_COLOR_SEP] = "separator",
36};
37
7687a054
JH
38static int parse_pattern_type_arg(const char *opt, const char *arg)
39{
40 if (!strcmp(arg, "default"))
41 return GREP_PATTERN_TYPE_UNSPECIFIED;
42 else if (!strcmp(arg, "basic"))
43 return GREP_PATTERN_TYPE_BRE;
44 else if (!strcmp(arg, "extended"))
45 return GREP_PATTERN_TYPE_ERE;
46 else if (!strcmp(arg, "fixed"))
47 return GREP_PATTERN_TYPE_FIXED;
48 else if (!strcmp(arg, "perl"))
49 return GREP_PATTERN_TYPE_PCRE;
50 die("bad %s argument: %s", opt, arg);
51}
52
3ac68a93
NTND
53define_list_config_array_extra(color_grep_slots, {"match"});
54
7687a054
JH
55/*
56 * Read the configuration file once and store it in
57 * the grep_defaults template.
58 */
59int grep_config(const char *var, const char *value, void *cb)
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
NTND
93 if (!strcmp(var, "color.grep.match")) {
94 if (grep_config("color.grep.matchcontext", value, cb) < 0)
95 return -1;
96 if (grep_config("color.grep.matchselected", value, cb) < 0)
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 */
455static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
456{
94da9193
ÆAB
457 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
458}
459
460static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
461 regmatch_t *match, int eflags)
462{
463 return 1;
464}
465
466static void free_pcre2_pattern(struct grep_pat *p)
467{
468}
94da9193 469
793dc676
NTND
470static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
471{
472 struct strbuf sb = STRBUF_INIT;
473 int err;
1ceababc 474 int regflags = 0;
793dc676
NTND
475
476 basic_regex_quote_buf(&sb, p->pattern);
793dc676
NTND
477 if (opt->ignore_case)
478 regflags |= REG_ICASE;
479 err = regcomp(&p->regexp, sb.buf, regflags);
793dc676
NTND
480 strbuf_release(&sb);
481 if (err) {
482 char errbuf[1024];
483 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
793dc676
NTND
484 compile_regexp_failed(p, errbuf);
485 }
486}
b65abcaf 487#endif /* !USE_LIBPCRE2 */
793dc676 488
83b5d2f5
JH
489static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
490{
c822255c 491 int err;
07a3d411 492 int regflags = REG_NEWLINE;
c822255c 493
04bf052e
ÆAB
494 if (opt->pattern_type_option == GREP_PATTERN_TYPE_UNSPECIFIED)
495 opt->pattern_type_option = (opt->extended_regexp_option
496 ? GREP_PATTERN_TYPE_ERE
497 : GREP_PATTERN_TYPE_BRE);
498
d7eb527d 499 p->word_regexp = opt->word_regexp;
5183bf67 500 p->ignore_case = opt->ignore_case;
04bf052e 501 p->fixed = opt->pattern_type_option == GREP_PATTERN_TYPE_FIXED;
d7eb527d 502
04bf052e 503 if (opt->pattern_type_option != GREP_PATTERN_TYPE_PCRE &&
ae807d77 504 memchr(p->pattern, 0, p->patternlen))
45d1f37c
ÆAB
505 die(_("given pattern contains NULL byte (via -f <file>). This is only supported with -P under PCRE v2"));
506
09872f64 507 p->is_fixed = is_fixed(p->pattern, p->patternlen);
8a599983
ÆAB
508#ifdef USE_LIBPCRE2
509 if (!p->fixed && !p->is_fixed) {
510 const char *no_jit = "(*NO_JIT)";
511 const int no_jit_len = strlen(no_jit);
512 if (starts_with(p->pattern, no_jit) &&
513 is_fixed(p->pattern + no_jit_len,
514 p->patternlen - no_jit_len))
515 p->is_fixed = 1;
516 }
517#endif
09872f64 518 if (p->fixed || p->is_fixed) {
b65abcaf 519#ifdef USE_LIBPCRE2
09872f64 520 if (p->is_fixed) {
b65abcaf
ÆAB
521 compile_pcre2_pattern(p, opt);
522 } else {
523 /*
524 * E.g. t7811-grep-open.sh relies on the
525 * pattern being restored.
526 */
527 char *old_pattern = p->pattern;
528 size_t old_patternlen = p->patternlen;
529 struct strbuf sb = STRBUF_INIT;
530
531 /*
532 * There is the PCRE2_LITERAL flag, but it's
533 * only in PCRE v2 10.30 and later. Needing to
534 * ifdef our way around that and dealing with
535 * it + PCRE2_MULTILINE being an error is more
536 * complex than just quoting this ourselves.
537 */
538 strbuf_add(&sb, "\\Q", 2);
539 strbuf_add(&sb, p->pattern, p->patternlen);
540 strbuf_add(&sb, "\\E", 2);
541
542 p->pattern = sb.buf;
543 p->patternlen = sb.len;
544 compile_pcre2_pattern(p, opt);
545 p->pattern = old_pattern;
546 p->patternlen = old_patternlen;
547 strbuf_release(&sb);
548 }
549#else /* !USE_LIBPCRE2 */
793dc676 550 compile_fixed_regexp(p, opt);
b65abcaf 551#endif /* !USE_LIBPCRE2 */
793dc676 552 return;
9eceddee 553 }
c822255c 554
04bf052e 555 if (opt->pattern_type_option == GREP_PATTERN_TYPE_PCRE) {
94da9193
ÆAB
556 compile_pcre2_pattern(p, opt);
557 return;
558 }
559
07a3d411
ÆAB
560 if (p->ignore_case)
561 regflags |= REG_ICASE;
04bf052e 562 if (opt->pattern_type_option == GREP_PATTERN_TYPE_ERE)
07a3d411
ÆAB
563 regflags |= REG_EXTENDED;
564 err = regcomp(&p->regexp, p->pattern, regflags);
83b5d2f5
JH
565 if (err) {
566 char errbuf[1024];
83b5d2f5 567 regerror(err, &p->regexp, errbuf, 1024);
a30c148a 568 compile_regexp_failed(p, errbuf);
83b5d2f5
JH
569 }
570}
571
e2b15427
RS
572static struct grep_expr *grep_not_expr(struct grep_expr *expr)
573{
574 struct grep_expr *z = xcalloc(1, sizeof(*z));
575 z->node = GREP_NODE_NOT;
576 z->u.unary = expr;
577 return z;
578}
579
f2d27598
TB
580static struct grep_expr *grep_binexp(enum grep_expr_node kind,
581 struct grep_expr *left,
582 struct grep_expr *right)
9dbf00ba
RS
583{
584 struct grep_expr *z = xcalloc(1, sizeof(*z));
f2d27598 585 z->node = kind;
9dbf00ba
RS
586 z->u.binary.left = left;
587 z->u.binary.right = right;
588 return z;
589}
590
f2d27598
TB
591static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
592{
593 return grep_binexp(GREP_NODE_OR, left, right);
594}
595
0a6adc26
TB
596static struct grep_expr *grep_and_expr(struct grep_expr *left, struct grep_expr *right)
597{
598 return grep_binexp(GREP_NODE_AND, left, right);
599}
600
0ab7befa 601static struct grep_expr *compile_pattern_or(struct grep_pat **);
83b5d2f5
JH
602static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
603{
604 struct grep_pat *p;
605 struct grep_expr *x;
606
607 p = *list;
c922b01f
LT
608 if (!p)
609 return NULL;
83b5d2f5
JH
610 switch (p->token) {
611 case GREP_PATTERN: /* atom */
480c1ca6
JH
612 case GREP_PATTERN_HEAD:
613 case GREP_PATTERN_BODY:
ca56dadb 614 CALLOC_ARRAY(x, 1);
83b5d2f5
JH
615 x->node = GREP_NODE_ATOM;
616 x->u.atom = p;
617 *list = p->next;
618 return x;
619 case GREP_OPEN_PAREN:
620 *list = p->next;
0ab7befa 621 x = compile_pattern_or(list);
83b5d2f5
JH
622 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
623 die("unmatched parenthesis");
624 *list = (*list)->next;
625 return x;
626 default:
627 return NULL;
628 }
629}
630
631static struct grep_expr *compile_pattern_not(struct grep_pat **list)
632{
633 struct grep_pat *p;
634 struct grep_expr *x;
635
636 p = *list;
c922b01f
LT
637 if (!p)
638 return NULL;
83b5d2f5
JH
639 switch (p->token) {
640 case GREP_NOT:
641 if (!p->next)
642 die("--not not followed by pattern expression");
643 *list = p->next;
e2b15427
RS
644 x = compile_pattern_not(list);
645 if (!x)
83b5d2f5 646 die("--not followed by non pattern expression");
e2b15427 647 return grep_not_expr(x);
83b5d2f5
JH
648 default:
649 return compile_pattern_atom(list);
650 }
651}
652
653static struct grep_expr *compile_pattern_and(struct grep_pat **list)
654{
655 struct grep_pat *p;
0a6adc26 656 struct grep_expr *x, *y;
83b5d2f5
JH
657
658 x = compile_pattern_not(list);
659 p = *list;
660 if (p && p->token == GREP_AND) {
fe7fe62d
RS
661 if (!x)
662 die("--and not preceded by pattern expression");
83b5d2f5
JH
663 if (!p->next)
664 die("--and not followed by pattern expression");
665 *list = p->next;
666 y = compile_pattern_and(list);
667 if (!y)
668 die("--and not followed by pattern expression");
0a6adc26 669 return grep_and_expr(x, y);
83b5d2f5
JH
670 }
671 return x;
672}
673
674static struct grep_expr *compile_pattern_or(struct grep_pat **list)
675{
676 struct grep_pat *p;
9dbf00ba 677 struct grep_expr *x, *y;
83b5d2f5
JH
678
679 x = compile_pattern_and(list);
680 p = *list;
681 if (x && p && p->token != GREP_CLOSE_PAREN) {
682 y = compile_pattern_or(list);
683 if (!y)
684 die("not a pattern expression %s", p->pattern);
9dbf00ba 685 return grep_or_expr(x, y);
83b5d2f5
JH
686 }
687 return x;
688}
689
690static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
691{
692 return compile_pattern_or(list);
693}
694
5aaeb733
JH
695static struct grep_expr *grep_true_expr(void)
696{
697 struct grep_expr *z = xcalloc(1, sizeof(*z));
698 z->node = GREP_NODE_TRUE;
699 return z;
700}
701
95ce9ce2 702static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
83b5d2f5
JH
703{
704 struct grep_pat *p;
95ce9ce2 705 struct grep_expr *header_expr;
5aaeb733
JH
706 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
707 enum grep_header_field fld;
83b5d2f5 708
95ce9ce2
JH
709 if (!opt->header_list)
710 return NULL;
2385f246 711
95ce9ce2
JH
712 for (p = opt->header_list; p; p = p->next) {
713 if (p->token != GREP_PATTERN_HEAD)
033abf97 714 BUG("a non-header pattern in grep header list.");
3ce3ffb8
AP
715 if (p->field < GREP_HEADER_FIELD_MIN ||
716 GREP_HEADER_FIELD_MAX <= p->field)
033abf97 717 BUG("unknown header field %d", p->field);
95ce9ce2 718 compile_regexp(p, opt);
80235ba7 719 }
5aaeb733
JH
720
721 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
722 header_group[fld] = NULL;
723
724 for (p = opt->header_list; p; p = p->next) {
725 struct grep_expr *h;
726 struct grep_pat *pp = p;
727
728 h = compile_pattern_atom(&pp);
729 if (!h || pp != p->next)
033abf97 730 BUG("malformed header expr");
5aaeb733
JH
731 if (!header_group[p->field]) {
732 header_group[p->field] = h;
733 continue;
734 }
735 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
736 }
737
738 header_expr = NULL;
739
740 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
741 if (!header_group[fld])
742 continue;
743 if (!header_expr)
744 header_expr = grep_true_expr();
745 header_expr = grep_or_expr(header_group[fld], header_expr);
746 }
95ce9ce2
JH
747 return header_expr;
748}
749
13e4fc7e
JH
750static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
751{
752 struct grep_expr *z = x;
753
754 while (x) {
755 assert(x->node == GREP_NODE_OR);
756 if (x->u.binary.right &&
757 x->u.binary.right->node == GREP_NODE_TRUE) {
758 x->u.binary.right = y;
759 break;
760 }
761 x = x->u.binary.right;
762 }
763 return z;
764}
765
15c96497 766void compile_grep_patterns(struct grep_opt *opt)
95ce9ce2
JH
767{
768 struct grep_pat *p;
769 struct grep_expr *header_expr = prep_header_patterns(opt);
db84376f 770 int extended = 0;
0ab7befa 771
83b5d2f5 772 for (p = opt->pattern_list; p; p = p->next) {
480c1ca6
JH
773 switch (p->token) {
774 case GREP_PATTERN: /* atom */
775 case GREP_PATTERN_HEAD:
776 case GREP_PATTERN_BODY:
c822255c 777 compile_regexp(p, opt);
480c1ca6
JH
778 break;
779 default:
db84376f 780 extended = 1;
480c1ca6
JH
781 break;
782 }
83b5d2f5
JH
783 }
784
794c0002 785 if (opt->all_match || opt->no_body_match || header_expr)
db84376f
ÆAB
786 extended = 1;
787 else if (!extended)
83b5d2f5
JH
788 return;
789
83b5d2f5 790 p = opt->pattern_list;
ba150a3f
MB
791 if (p)
792 opt->pattern_expression = compile_pattern_expr(&p);
83b5d2f5
JH
793 if (p)
794 die("incomplete pattern expression: %s", p->pattern);
80235ba7 795
794c0002
RS
796 if (opt->no_body_match && opt->pattern_expression)
797 opt->pattern_expression = grep_not_expr(opt->pattern_expression);
798
80235ba7
JH
799 if (!header_expr)
800 return;
801
5aaeb733 802 if (!opt->pattern_expression)
80235ba7 803 opt->pattern_expression = header_expr;
13e4fc7e
JH
804 else if (opt->all_match)
805 opt->pattern_expression = grep_splice_or(header_expr,
806 opt->pattern_expression);
5aaeb733
JH
807 else
808 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
809 header_expr);
80235ba7 810 opt->all_match = 1;
83b5d2f5
JH
811}
812
b48fb5b6
JH
813static void free_pattern_expr(struct grep_expr *x)
814{
815 switch (x->node) {
5aaeb733 816 case GREP_NODE_TRUE:
b48fb5b6
JH
817 case GREP_NODE_ATOM:
818 break;
819 case GREP_NODE_NOT:
820 free_pattern_expr(x->u.unary);
821 break;
822 case GREP_NODE_AND:
823 case GREP_NODE_OR:
824 free_pattern_expr(x->u.binary.left);
825 free_pattern_expr(x->u.binary.right);
826 break;
827 }
828 free(x);
829}
830
891c9965 831static void free_grep_pat(struct grep_pat *pattern)
b48fb5b6
JH
832{
833 struct grep_pat *p, *n;
834
891c9965 835 for (p = pattern; p; p = n) {
b48fb5b6
JH
836 n = p->next;
837 switch (p->token) {
838 case GREP_PATTERN: /* atom */
839 case GREP_PATTERN_HEAD:
840 case GREP_PATTERN_BODY:
7599730b 841 if (p->pcre2_pattern)
94da9193 842 free_pcre2_pattern(p);
63e7e9d8
MK
843 else
844 regfree(&p->regexp);
526a858a 845 free(p->pattern);
b48fb5b6
JH
846 break;
847 default:
848 break;
849 }
850 free(p);
851 }
891c9965 852}
b48fb5b6 853
891c9965
ÆAB
854void free_grep_patterns(struct grep_opt *opt)
855{
856 free_grep_pat(opt->pattern_list);
fb2ebe72 857 free_grep_pat(opt->header_list);
891c9965
ÆAB
858
859 if (opt->pattern_expression)
860 free_pattern_expr(opt->pattern_expression);
b48fb5b6
JH
861}
862
1a845fbc 863static const char *end_of_line(const char *cp, unsigned long *left)
83b5d2f5
JH
864{
865 unsigned long l = *left;
866 while (l && *cp != '\n') {
867 l--;
868 cp++;
869 }
870 *left = l;
871 return cp;
872}
873
874static int word_char(char ch)
875{
876 return isalnum(ch) || ch == '_';
877}
878
55f638bd
ML
879static void output_color(struct grep_opt *opt, const void *data, size_t size,
880 const char *color)
881{
daa0c3d9 882 if (want_color(opt->color) && color && color[0]) {
55f638bd
ML
883 opt->output(opt, color, strlen(color));
884 opt->output(opt, data, size);
885 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
886 } else
887 opt->output(opt, data, size);
888}
889
890static void output_sep(struct grep_opt *opt, char sign)
891{
892 if (opt->null_following_name)
893 opt->output(opt, "\0", 1);
894 else
fa151dc5 895 output_color(opt, &sign, 1, opt->colors[GREP_COLOR_SEP]);
55f638bd
ML
896}
897
83caecca
RZ
898static void show_name(struct grep_opt *opt, const char *name)
899{
fa151dc5 900 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
5b594f45 901 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
83caecca
RZ
902}
903
1a845fbc
JK
904static int patmatch(struct grep_pat *p,
905 const char *line, const char *eol,
97e77784
MK
906 regmatch_t *match, int eflags)
907{
908 int hit;
909
7599730b 910 if (p->pcre2_pattern)
94da9193 911 hit = !pcre2match(p, line, eol, match, eflags);
97e77784 912 else
b7d36ffc
JS
913 hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
914 eflags);
97e77784
MK
915
916 return hit;
917}
918
1a845fbc 919static void strip_timestamp(const char *bol, const char **eol_p)
a4d7d2c6 920{
1a845fbc 921 const char *eol = *eol_p;
a4d7d2c6
JH
922
923 while (bol < --eol) {
924 if (*eol != '>')
925 continue;
926 *eol_p = ++eol;
cc8e26ee 927 break;
a4d7d2c6 928 }
a4d7d2c6
JH
929}
930
931static struct {
932 const char *field;
933 size_t len;
934} header_field[] = {
935 { "author ", 7 },
936 { "committer ", 10 },
72fd13f7 937 { "reflog ", 7 },
a4d7d2c6
JH
938};
939
3f566c4e
HM
940static int headerless_match_one_pattern(struct grep_pat *p,
941 const char *bol, const char *eol,
942 enum grep_context ctx,
943 regmatch_t *pmatch, int eflags)
83b5d2f5
JH
944{
945 int hit = 0;
e701fadb 946 const char *start = bol;
83b5d2f5 947
480c1ca6
JH
948 if ((p->token != GREP_PATTERN) &&
949 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
950 return 0;
951
83b5d2f5 952 again:
97e77784 953 hit = patmatch(p, bol, eol, pmatch, eflags);
83b5d2f5 954
d7eb527d 955 if (hit && p->word_regexp) {
83b5d2f5 956 if ((pmatch[0].rm_so < 0) ||
84201eae 957 (eol - bol) < pmatch[0].rm_so ||
83b5d2f5
JH
958 (pmatch[0].rm_eo < 0) ||
959 (eol - bol) < pmatch[0].rm_eo)
960 die("regexp returned nonsense");
961
962 /* Match beginning must be either beginning of the
963 * line, or at word boundary (i.e. the last char must
964 * not be a word char). Similarly, match end must be
965 * either end of the line, or at word boundary
966 * (i.e. the next char must not be a word char).
967 */
fb62eb7f 968 if ( ((pmatch[0].rm_so == 0) ||
83b5d2f5
JH
969 !word_char(bol[pmatch[0].rm_so-1])) &&
970 ((pmatch[0].rm_eo == (eol-bol)) ||
971 !word_char(bol[pmatch[0].rm_eo])) )
972 ;
973 else
974 hit = 0;
975
84201eae
RS
976 /* Words consist of at least one character. */
977 if (pmatch->rm_so == pmatch->rm_eo)
978 hit = 0;
979
83b5d2f5
JH
980 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
981 /* There could be more than one match on the
982 * line, and the first match might not be
983 * strict word match. But later ones could be!
fb62eb7f
RS
984 * Forward to the next possible start, i.e. the
985 * next position following a non-word char.
83b5d2f5
JH
986 */
987 bol = pmatch[0].rm_so + bol + 1;
fb62eb7f
RS
988 while (word_char(bol[-1]) && bol < eol)
989 bol++;
dbb6a4ad 990 eflags |= REG_NOTBOL;
fb62eb7f
RS
991 if (bol < eol)
992 goto again;
83b5d2f5
JH
993 }
994 }
e701fadb
RS
995 if (hit) {
996 pmatch[0].rm_so += bol - start;
997 pmatch[0].rm_eo += bol - start;
998 }
83b5d2f5
JH
999 return hit;
1000}
1001
3f566c4e
HM
1002static int match_one_pattern(struct grep_pat *p,
1003 const char *bol, const char *eol,
1004 enum grep_context ctx, regmatch_t *pmatch,
1005 int eflags)
1006{
1007 const char *field;
1008 size_t len;
1009
1010 if (p->token == GREP_PATTERN_HEAD) {
1011 assert(p->field < ARRAY_SIZE(header_field));
1012 field = header_field[p->field].field;
1013 len = header_field[p->field].len;
1014 if (strncmp(bol, field, len))
1015 return 0;
1016 bol += len;
1017
1018 switch (p->field) {
1019 case GREP_HEADER_AUTHOR:
1020 case GREP_HEADER_COMMITTER:
1021 strip_timestamp(bol, &eol);
1022 break;
1023 default:
1024 break;
1025 }
1026 }
1027
1028 return headerless_match_one_pattern(p, bol, eol, ctx, pmatch, eflags);
1029}
1030
1031
1a845fbc
JK
1032static int match_expr_eval(struct grep_opt *opt, struct grep_expr *x,
1033 const char *bol, const char *eol,
1034 enum grep_context ctx, ssize_t *col,
68d686e6 1035 ssize_t *icol, int collect_hits)
83b5d2f5 1036{
0ab7befa
JH
1037 int h = 0;
1038
83b5d2f5 1039 switch (x->node) {
5aaeb733
JH
1040 case GREP_NODE_TRUE:
1041 h = 1;
1042 break;
83b5d2f5 1043 case GREP_NODE_ATOM:
68d686e6
TB
1044 {
1045 regmatch_t tmp;
1046 h = match_one_pattern(x->u.atom, bol, eol, ctx,
1047 &tmp, 0);
1048 if (h && (*col < 0 || tmp.rm_so < *col))
1049 *col = tmp.rm_so;
1050 }
794c0002
RS
1051 if (x->u.atom->token == GREP_PATTERN_BODY)
1052 opt->body_hit |= h;
83b5d2f5
JH
1053 break;
1054 case GREP_NODE_NOT:
68d686e6
TB
1055 /*
1056 * Upon visiting a GREP_NODE_NOT, col and icol become swapped.
1057 */
1058 h = !match_expr_eval(opt, x->u.unary, bol, eol, ctx, icol, col,
1059 0);
0ab7befa 1060 break;
83b5d2f5 1061 case GREP_NODE_AND:
017c0fcf 1062 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
68d686e6 1063 icol, 0);
017c0fcf
TB
1064 if (h || opt->columnnum) {
1065 /*
1066 * Don't short-circuit AND when given --column, since a
1067 * NOT earlier in the tree may turn this into an OR. In
1068 * this case, see the below comment.
1069 */
1070 h &= match_expr_eval(opt, x->u.binary.right, bol, eol,
1071 ctx, col, icol, 0);
1072 }
0ab7befa 1073 break;
83b5d2f5 1074 case GREP_NODE_OR:
017c0fcf
TB
1075 if (!(collect_hits || opt->columnnum)) {
1076 /*
1077 * Don't short-circuit OR when given --column (or
1078 * collecting hits) to ensure we don't skip a later
1079 * child that would produce an earlier match.
1080 */
68d686e6
TB
1081 return (match_expr_eval(opt, x->u.binary.left, bol, eol,
1082 ctx, col, icol, 0) ||
1083 match_expr_eval(opt, x->u.binary.right, bol,
1084 eol, ctx, col, icol, 0));
017c0fcf 1085 }
68d686e6
TB
1086 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1087 icol, 0);
017c0fcf
TB
1088 if (collect_hits)
1089 x->u.binary.left->hit |= h;
68d686e6 1090 h |= match_expr_eval(opt, x->u.binary.right, bol, eol, ctx, col,
017c0fcf 1091 icol, collect_hits);
0ab7befa
JH
1092 break;
1093 default:
d7530708 1094 die("Unexpected node type (internal error) %d", x->node);
83b5d2f5 1095 }
0ab7befa
JH
1096 if (collect_hits)
1097 x->hit |= h;
1098 return h;
83b5d2f5
JH
1099}
1100
1a845fbc
JK
1101static int match_expr(struct grep_opt *opt,
1102 const char *bol, const char *eol,
68d686e6
TB
1103 enum grep_context ctx, ssize_t *col,
1104 ssize_t *icol, int collect_hits)
83b5d2f5
JH
1105{
1106 struct grep_expr *x = opt->pattern_expression;
68d686e6 1107 return match_expr_eval(opt, x, bol, eol, ctx, col, icol, collect_hits);
83b5d2f5
JH
1108}
1109
1a845fbc
JK
1110static int match_line(struct grep_opt *opt,
1111 const char *bol, const char *eol,
68d686e6 1112 ssize_t *col, ssize_t *icol,
0ab7befa 1113 enum grep_context ctx, int collect_hits)
83b5d2f5
JH
1114{
1115 struct grep_pat *p;
017c0fcf 1116 int hit = 0;
79212772 1117
db84376f 1118 if (opt->pattern_expression)
68d686e6
TB
1119 return match_expr(opt, bol, eol, ctx, col, icol,
1120 collect_hits);
0ab7befa
JH
1121
1122 /* we do not call with collect_hits without being extended */
83b5d2f5 1123 for (p = opt->pattern_list; p; p = p->next) {
68d686e6
TB
1124 regmatch_t tmp;
1125 if (match_one_pattern(p, bol, eol, ctx, &tmp, 0)) {
017c0fcf
TB
1126 hit |= 1;
1127 if (!opt->columnnum) {
1128 /*
1129 * Without --column, any single match on a line
1130 * is enough to know that it needs to be
1131 * printed. With --column, scan _all_ patterns
1132 * to find the earliest.
1133 */
1134 break;
1135 }
1136 if (*col < 0 || tmp.rm_so < *col)
1137 *col = tmp.rm_so;
68d686e6 1138 }
83b5d2f5 1139 }
017c0fcf 1140 return hit;
83b5d2f5
JH
1141}
1142
1a845fbc
JK
1143static int match_next_pattern(struct grep_pat *p,
1144 const char *bol, const char *eol,
7e8f59d5
RS
1145 enum grep_context ctx,
1146 regmatch_t *pmatch, int eflags)
1147{
1148 regmatch_t match;
1149
3f566c4e 1150 if (!headerless_match_one_pattern(p, bol, eol, ctx, &match, eflags))
7e8f59d5
RS
1151 return 0;
1152 if (match.rm_so < 0 || match.rm_eo < 0)
1153 return 0;
1154 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1155 if (match.rm_so > pmatch->rm_so)
1156 return 1;
1157 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1158 return 1;
1159 }
1160 pmatch->rm_so = match.rm_so;
1161 pmatch->rm_eo = match.rm_eo;
1162 return 1;
1163}
1164
3f566c4e
HM
1165int grep_next_match(struct grep_opt *opt,
1166 const char *bol, const char *eol,
1167 enum grep_context ctx, regmatch_t *pmatch,
1168 enum grep_header_field field, int eflags)
7e8f59d5
RS
1169{
1170 struct grep_pat *p;
1171 int hit = 0;
1172
1173 pmatch->rm_so = pmatch->rm_eo = -1;
1174 if (bol < eol) {
3f566c4e
HM
1175 for (p = ((ctx == GREP_CONTEXT_HEAD)
1176 ? opt->header_list : opt->pattern_list);
1177 p; p = p->next) {
7e8f59d5 1178 switch (p->token) {
7e8f59d5 1179 case GREP_PATTERN_HEAD:
3f566c4e
HM
1180 if ((field != GREP_HEADER_FIELD_MAX) &&
1181 (p->field != field))
1182 continue;
1183 /* fall thru */
1184 case GREP_PATTERN: /* atom */
7e8f59d5
RS
1185 case GREP_PATTERN_BODY:
1186 hit |= match_next_pattern(p, bol, eol, ctx,
1187 pmatch, eflags);
1188 break;
1189 default:
1190 break;
1191 }
1192 }
1193 }
1194 return hit;
1195}
1196
c707ded3
TB
1197static void show_line_header(struct grep_opt *opt, const char *name,
1198 unsigned lno, ssize_t cno, char sign)
7e8f59d5 1199{
1d84f72e 1200 if (opt->heading && opt->last_shown == 0) {
fa151dc5 1201 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1d84f72e
RS
1202 opt->output(opt, "\n", 1);
1203 }
5dd06d38
RS
1204 opt->last_shown = lno;
1205
1d84f72e 1206 if (!opt->heading && opt->pathname) {
fa151dc5 1207 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
55f638bd 1208 output_sep(opt, sign);
5b594f45
FK
1209 }
1210 if (opt->linenum) {
1211 char buf[32];
1a168e5c 1212 xsnprintf(buf, sizeof(buf), "%d", lno);
fa151dc5 1213 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_LINENO]);
55f638bd 1214 output_sep(opt, sign);
5b594f45 1215 }
89252cd0
TB
1216 /*
1217 * Treat 'cno' as the 1-indexed offset from the start of a non-context
1218 * line to its first match. Otherwise, 'cno' is 0 indicating that we are
1219 * being called with a context line.
1220 */
1221 if (opt->columnnum && cno) {
1222 char buf[32];
1223 xsnprintf(buf, sizeof(buf), "%"PRIuMAX, (uintmax_t)cno);
d036d667 1224 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_COLUMNNO]);
89252cd0
TB
1225 output_sep(opt, sign);
1226 }
c707ded3
TB
1227}
1228
1a845fbc
JK
1229static void show_line(struct grep_opt *opt,
1230 const char *bol, const char *eol,
c707ded3
TB
1231 const char *name, unsigned lno, ssize_t cno, char sign)
1232{
1233 int rest = eol - bol;
9d8db06e
TB
1234 const char *match_color = NULL;
1235 const char *line_color = NULL;
c707ded3
TB
1236
1237 if (opt->file_break && opt->last_shown == 0) {
1238 if (opt->show_hunk_mark)
1239 opt->output(opt, "\n", 1);
1240 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1241 if (opt->last_shown == 0) {
1242 if (opt->show_hunk_mark) {
87ece7ce 1243 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
c707ded3
TB
1244 opt->output(opt, "\n", 1);
1245 }
1246 } else if (lno > opt->last_shown + 1) {
87ece7ce 1247 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
c707ded3
TB
1248 opt->output(opt, "\n", 1);
1249 }
1250 }
9d8db06e
TB
1251 if (!opt->only_matching) {
1252 /*
1253 * In case the line we're being called with contains more than
1254 * one match, leave printing each header to the loop below.
1255 */
1256 show_line_header(opt, name, lno, cno, sign);
1257 }
1258 if (opt->color || opt->only_matching) {
7e8f59d5
RS
1259 regmatch_t match;
1260 enum grep_context ctx = GREP_CONTEXT_BODY;
7e8f59d5
RS
1261 int eflags = 0;
1262
9d8db06e
TB
1263 if (opt->color) {
1264 if (sign == ':')
87ece7ce 1265 match_color = opt->colors[GREP_COLOR_MATCH_SELECTED];
9d8db06e 1266 else
87ece7ce 1267 match_color = opt->colors[GREP_COLOR_MATCH_CONTEXT];
9d8db06e 1268 if (sign == ':')
87ece7ce 1269 line_color = opt->colors[GREP_COLOR_SELECTED];
9d8db06e 1270 else if (sign == '-')
87ece7ce 1271 line_color = opt->colors[GREP_COLOR_CONTEXT];
9d8db06e 1272 else if (sign == '=')
87ece7ce 1273 line_color = opt->colors[GREP_COLOR_FUNCTION];
9d8db06e 1274 }
3f566c4e
HM
1275 while (grep_next_match(opt, bol, eol, ctx, &match,
1276 GREP_HEADER_FIELD_MAX, eflags)) {
1f5b9cc4
RS
1277 if (match.rm_so == match.rm_eo)
1278 break;
5b594f45 1279
9d8db06e
TB
1280 if (opt->only_matching)
1281 show_line_header(opt, name, lno, cno, sign);
1282 else
1283 output_color(opt, bol, match.rm_so, line_color);
55f638bd 1284 output_color(opt, bol + match.rm_so,
79a77109 1285 match.rm_eo - match.rm_so, match_color);
9d8db06e
TB
1286 if (opt->only_matching)
1287 opt->output(opt, "\n", 1);
7e8f59d5 1288 bol += match.rm_eo;
9d8db06e 1289 cno += match.rm_eo;
7e8f59d5
RS
1290 rest -= match.rm_eo;
1291 eflags = REG_NOTBOL;
1292 }
7e8f59d5 1293 }
9d8db06e
TB
1294 if (!opt->only_matching) {
1295 output_color(opt, bol, rest, line_color);
1296 opt->output(opt, "\n", 1);
1297 }
7e8f59d5
RS
1298}
1299
78db6ea9
JK
1300int grep_use_locks;
1301
0579f91d
TR
1302/*
1303 * This lock protects access to the gitattributes machinery, which is
1304 * not thread-safe.
1305 */
1306pthread_mutex_t grep_attr_mutex;
1307
78db6ea9 1308static inline void grep_attr_lock(void)
0579f91d 1309{
78db6ea9 1310 if (grep_use_locks)
0579f91d
TR
1311 pthread_mutex_lock(&grep_attr_mutex);
1312}
1313
78db6ea9 1314static inline void grep_attr_unlock(void)
0579f91d 1315{
78db6ea9 1316 if (grep_use_locks)
0579f91d
TR
1317 pthread_mutex_unlock(&grep_attr_mutex);
1318}
b3aeb285 1319
1a845fbc
JK
1320static int match_funcname(struct grep_opt *opt, struct grep_source *gs,
1321 const char *bol, const char *eol)
2944e4e6 1322{
60ecac98 1323 xdemitconf_t *xecfg = opt->priv;
0579f91d 1324 if (xecfg && !xecfg->find_func) {
acd00ea0 1325 grep_source_load_driver(gs, opt->repo->index);
94ad9d9e
JK
1326 if (gs->driver->funcname.pattern) {
1327 const struct userdiff_funcname *pe = &gs->driver->funcname;
0579f91d
TR
1328 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1329 } else {
1330 xecfg = opt->priv = NULL;
1331 }
1332 }
1333
1334 if (xecfg) {
60ecac98
RS
1335 char buf[1];
1336 return xecfg->find_func(bol, eol - bol, buf, 1,
1337 xecfg->find_func_priv) >= 0;
1338 }
1339
2944e4e6
RS
1340 if (bol == eol)
1341 return 0;
1342 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1343 return 1;
1344 return 0;
1345}
1346
e1327023 1347static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1a845fbc 1348 const char *bol, unsigned lno)
2944e4e6 1349{
e1327023 1350 while (bol > gs->buf) {
1a845fbc 1351 const char *eol = --bol;
2944e4e6 1352
e1327023 1353 while (bol > gs->buf && bol[-1] != '\n')
2944e4e6
RS
1354 bol--;
1355 lno--;
1356
1357 if (lno <= opt->last_shown)
1358 break;
1359
e1327023 1360 if (match_funcname(opt, gs, bol, eol)) {
89252cd0 1361 show_line(opt, bol, eol, gs->name, lno, 0, '=');
2944e4e6
RS
1362 break;
1363 }
1364 }
1365}
1366
a5dc20b0
RS
1367static int is_empty_line(const char *bol, const char *eol);
1368
e1327023 1369static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1a845fbc 1370 const char *bol, const char *end, unsigned lno)
49de3216 1371{
6653a01b 1372 unsigned cur = lno, from = 1, funcname_lno = 0, orig_from;
a5dc20b0 1373 int funcname_needed = !!opt->funcname, comment_needed = 0;
ba8ea749 1374
49de3216
RS
1375 if (opt->pre_context < lno)
1376 from = lno - opt->pre_context;
1377 if (from <= opt->last_shown)
1378 from = opt->last_shown + 1;
6653a01b 1379 orig_from = from;
a5dc20b0
RS
1380 if (opt->funcbody) {
1381 if (match_funcname(opt, gs, bol, end))
1382 comment_needed = 1;
1383 else
1384 funcname_needed = 1;
6653a01b
RS
1385 from = opt->last_shown + 1;
1386 }
49de3216
RS
1387
1388 /* Rewind. */
6653a01b 1389 while (bol > gs->buf && cur > from) {
1a845fbc
JK
1390 const char *next_bol = bol;
1391 const char *eol = --bol;
2944e4e6 1392
e1327023 1393 while (bol > gs->buf && bol[-1] != '\n')
49de3216
RS
1394 bol--;
1395 cur--;
a5dc20b0
RS
1396 if (comment_needed && (is_empty_line(bol, eol) ||
1397 match_funcname(opt, gs, bol, eol))) {
1398 comment_needed = 0;
1399 from = orig_from;
1400 if (cur < from) {
1401 cur++;
1402 bol = next_bol;
1403 break;
1404 }
1405 }
e1327023 1406 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
2944e4e6
RS
1407 funcname_lno = cur;
1408 funcname_needed = 0;
a5dc20b0
RS
1409 if (opt->funcbody)
1410 comment_needed = 1;
1411 else
1412 from = orig_from;
2944e4e6 1413 }
49de3216
RS
1414 }
1415
2944e4e6
RS
1416 /* We need to look even further back to find a function signature. */
1417 if (opt->funcname && funcname_needed)
e1327023 1418 show_funcname_line(opt, gs, bol, cur);
2944e4e6 1419
49de3216
RS
1420 /* Back forward. */
1421 while (cur < lno) {
1a845fbc 1422 const char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
49de3216
RS
1423
1424 while (*eol != '\n')
1425 eol++;
89252cd0 1426 show_line(opt, bol, eol, gs->name, cur, 0, sign);
49de3216
RS
1427 bol = eol + 1;
1428 cur++;
1429 }
1430}
1431
a26345b6
JH
1432static int should_lookahead(struct grep_opt *opt)
1433{
1434 struct grep_pat *p;
1435
db84376f 1436 if (opt->pattern_expression)
a26345b6
JH
1437 return 0; /* punt for too complex stuff */
1438 if (opt->invert)
1439 return 0;
1440 for (p = opt->pattern_list; p; p = p->next) {
1441 if (p->token != GREP_PATTERN)
1442 return 0; /* punt for "header only" and stuff */
1443 }
1444 return 1;
1445}
1446
1447static int look_ahead(struct grep_opt *opt,
1448 unsigned long *left_p,
1449 unsigned *lno_p,
1a845fbc 1450 const char **bol_p)
a26345b6
JH
1451{
1452 unsigned lno = *lno_p;
1a845fbc 1453 const char *bol = *bol_p;
a26345b6 1454 struct grep_pat *p;
1a845fbc 1455 const char *sp, *last_bol;
a26345b6
JH
1456 regoff_t earliest = -1;
1457
1458 for (p = opt->pattern_list; p; p = p->next) {
1459 int hit;
1460 regmatch_t m;
1461
97e77784 1462 hit = patmatch(p, bol, bol + *left_p, &m, 0);
a26345b6
JH
1463 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1464 continue;
1465 if (earliest < 0 || m.rm_so < earliest)
1466 earliest = m.rm_so;
1467 }
1468
1469 if (earliest < 0) {
1470 *bol_p = bol + *left_p;
1471 *left_p = 0;
1472 return 1;
1473 }
1474 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1475 ; /* find the beginning of the line */
1476 last_bol = sp;
1477
1478 for (sp = bol; sp < last_bol; sp++) {
1479 if (*sp == '\n')
1480 lno++;
1481 }
1482 *left_p -= last_bol - bol;
1483 *bol_p = last_bol;
1484 *lno_p = lno;
1485 return 0;
1486}
1487
38bbc2ea
NTND
1488static int fill_textconv_grep(struct repository *r,
1489 struct userdiff_driver *driver,
335ec3bf
JK
1490 struct grep_source *gs)
1491{
1492 struct diff_filespec *df;
1493 char *buf;
1494 size_t size;
1495
1496 if (!driver || !driver->textconv)
1497 return grep_source_load(gs);
1498
1499 /*
1500 * The textconv interface is intimately tied to diff_filespecs, so we
1501 * have to pretend to be one. If we could unify the grep_source
1502 * and diff_filespec structs, this mess could just go away.
1503 */
1504 df = alloc_filespec(gs->path);
1505 switch (gs->type) {
1c41c82b 1506 case GREP_SOURCE_OID:
335ec3bf
JK
1507 fill_filespec(df, gs->identifier, 1, 0100644);
1508 break;
1509 case GREP_SOURCE_FILE:
14228447 1510 fill_filespec(df, null_oid(), 0, 0100644);
335ec3bf
JK
1511 break;
1512 default:
033abf97 1513 BUG("attempt to textconv something without a path?");
335ec3bf
JK
1514 }
1515
1516 /*
1d1729ca
MT
1517 * fill_textconv is not remotely thread-safe; it modifies the global
1518 * diff tempfile structure, writes to the_repo's odb and might
1519 * internally call thread-unsafe functions such as the
1520 * prepare_packed_git() lazy-initializator. Because of the last two, we
1521 * must ensure mutual exclusion between this call and the object reading
1522 * API, thus we use obj_read_lock() here.
1523 *
1524 * TODO: allowing text conversion to run in parallel with object
1525 * reading operations might increase performance in the multithreaded
1526 * non-worktreee git-grep with --textconv.
335ec3bf 1527 */
1d1729ca 1528 obj_read_lock();
38bbc2ea 1529 size = fill_textconv(r, driver, df, &buf);
1d1729ca 1530 obj_read_unlock();
335ec3bf
JK
1531 free_filespec(df);
1532
1533 /*
1534 * The normal fill_textconv usage by the diff machinery would just keep
1535 * the textconv'd buf separate from the diff_filespec. But much of the
1536 * grep code passes around a grep_source and assumes that its "buf"
1537 * pointer is the beginning of the thing we are searching. So let's
1538 * install our textconv'd version into the grep_source, taking care not
1539 * to leak any existing buffer.
1540 */
1541 grep_source_clear_data(gs);
1542 gs->buf = buf;
1543 gs->size = size;
1544
1545 return 0;
1546}
1547
4aa2c475
RS
1548static int is_empty_line(const char *bol, const char *eol)
1549{
1550 while (bol < eol && isspace(*bol))
1551 bol++;
1552 return bol == eol;
1553}
1554
e1327023 1555static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
83b5d2f5 1556{
1a845fbc
JK
1557 const char *bol;
1558 const char *peek_bol = NULL;
e1327023 1559 unsigned long left;
83b5d2f5 1560 unsigned lno = 1;
83b5d2f5 1561 unsigned last_hit = 0;
83b5d2f5 1562 int binary_match_only = 0;
83b5d2f5 1563 unsigned count = 0;
a26345b6 1564 int try_lookahead = 0;
ba8ea749 1565 int show_function = 0;
335ec3bf 1566 struct userdiff_driver *textconv = NULL;
480c1ca6 1567 enum grep_context ctx = GREP_CONTEXT_HEAD;
60ecac98 1568 xdemitconf_t xecfg;
83b5d2f5 1569
de99eb0c
ES
1570 if (!opt->status_only && gs->name == NULL)
1571 BUG("grep call which could print a name requires "
1572 "grep_source.name be non-NULL");
1573
5b594f45
FK
1574 if (!opt->output)
1575 opt->output = std_output;
1576
ba8ea749
RS
1577 if (opt->pre_context || opt->post_context || opt->file_break ||
1578 opt->funcbody) {
08303c36
RS
1579 /* Show hunk marks, except for the first file. */
1580 if (opt->last_shown)
1581 opt->show_hunk_mark = 1;
1582 /*
1583 * If we're using threads then we can't easily identify
1584 * the first file. Always put hunk marks in that case
1585 * and skip the very first one later in work_done().
1586 */
1587 if (opt->output != std_output)
1588 opt->show_hunk_mark = 1;
1589 }
431d6e7b
RS
1590 opt->last_shown = 0;
1591
335ec3bf 1592 if (opt->allow_textconv) {
acd00ea0 1593 grep_source_load_driver(gs, opt->repo->index);
335ec3bf
JK
1594 /*
1595 * We might set up the shared textconv cache data here, which
1d1729ca
MT
1596 * is not thread-safe. Also, get_oid_with_context() and
1597 * parse_object() might be internally called. As they are not
84544f2e 1598 * currently thread-safe and might be racy with object reading,
1d1729ca 1599 * obj_read_lock() must be called.
335ec3bf
JK
1600 */
1601 grep_attr_lock();
1d1729ca 1602 obj_read_lock();
bd7ad45b 1603 textconv = userdiff_get_textconv(opt->repo, gs->driver);
1d1729ca 1604 obj_read_unlock();
335ec3bf
JK
1605 grep_attr_unlock();
1606 }
1607
1608 /*
1609 * We know the result of a textconv is text, so we only have to care
1610 * about binary handling if we are not using it.
1611 */
1612 if (!textconv) {
1613 switch (opt->binary) {
1614 case GREP_BINARY_DEFAULT:
acd00ea0 1615 if (grep_source_is_binary(gs, opt->repo->index))
335ec3bf
JK
1616 binary_match_only = 1;
1617 break;
1618 case GREP_BINARY_NOMATCH:
acd00ea0 1619 if (grep_source_is_binary(gs, opt->repo->index))
335ec3bf
JK
1620 return 0; /* Assume unmatch */
1621 break;
1622 case GREP_BINARY_TEXT:
1623 break;
1624 default:
033abf97 1625 BUG("unknown binary handling mode");
335ec3bf 1626 }
83b5d2f5
JH
1627 }
1628
60ecac98 1629 memset(&xecfg, 0, sizeof(xecfg));
0579f91d
TR
1630 opt->priv = &xecfg;
1631
a26345b6 1632 try_lookahead = should_lookahead(opt);
60ecac98 1633
38bbc2ea 1634 if (fill_textconv_grep(opt->repo, textconv, gs) < 0)
08265798
JK
1635 return 0;
1636
e1327023
JK
1637 bol = gs->buf;
1638 left = gs->size;
83b5d2f5 1639 while (left) {
1a845fbc 1640 const char *eol;
0ab7befa 1641 int hit;
89252cd0 1642 ssize_t cno;
68d686e6 1643 ssize_t col = -1, icol = -1;
83b5d2f5 1644
a26345b6 1645 /*
8997da38 1646 * look_ahead() skips quickly to the line that possibly
a26345b6
JH
1647 * has the next hit; don't call it if we need to do
1648 * something more than just skipping the current line
1649 * in response to an unmatch for the current line. E.g.
1650 * inside a post-context window, we will show the current
1651 * line as a context around the previous hit when it
1652 * doesn't hit.
1653 */
1654 if (try_lookahead
1655 && !(last_hit
ba8ea749
RS
1656 && (show_function ||
1657 lno <= last_hit + opt->post_context))
a26345b6
JH
1658 && look_ahead(opt, &left, &lno, &bol))
1659 break;
83b5d2f5 1660 eol = end_of_line(bol, &left);
83b5d2f5 1661
480c1ca6
JH
1662 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1663 ctx = GREP_CONTEXT_BODY;
1664
68d686e6 1665 hit = match_line(opt, bol, eol, &col, &icol, ctx, collect_hits);
83b5d2f5 1666
0ab7befa
JH
1667 if (collect_hits)
1668 goto next_line;
1669
83b5d2f5
JH
1670 /* "grep -v -e foo -e bla" should list lines
1671 * that do not have either, so inversion should
1672 * be done outside.
1673 */
1674 if (opt->invert)
1675 hit = !hit;
1676 if (opt->unmatch_name_only) {
1677 if (hit)
1678 return 0;
1679 goto next_line;
1680 }
68437ede 1681 if (hit && (opt->max_count < 0 || count < opt->max_count)) {
83b5d2f5
JH
1682 count++;
1683 if (opt->status_only)
1684 return 1;
321ffcc0 1685 if (opt->name_only) {
e1327023 1686 show_name(opt, gs->name);
321ffcc0
RS
1687 return 1;
1688 }
c30c10cf
RS
1689 if (opt->count)
1690 goto next_line;
83b5d2f5 1691 if (binary_match_only) {
5b594f45 1692 opt->output(opt, "Binary file ", 12);
e1327023 1693 output_color(opt, gs->name, strlen(gs->name),
fa151dc5 1694 opt->colors[GREP_COLOR_FILENAME]);
5b594f45 1695 opt->output(opt, " matches\n", 9);
83b5d2f5
JH
1696 return 1;
1697 }
83b5d2f5
JH
1698 /* Hit at this line. If we haven't shown the
1699 * pre-context lines, we would need to show them.
83b5d2f5 1700 */
ba8ea749 1701 if (opt->pre_context || opt->funcbody)
e1327023 1702 show_pre_context(opt, gs, bol, eol, lno);
2944e4e6 1703 else if (opt->funcname)
e1327023 1704 show_funcname_line(opt, gs, bol, lno);
89252cd0
TB
1705 cno = opt->invert ? icol : col;
1706 if (cno < 0) {
1707 /*
1708 * A negative cno indicates that there was no
1709 * match on the line. We are thus inverted and
1710 * being asked to show all lines that _don't_
1711 * match a given expression. Therefore, set cno
1712 * to 0 to suggest the whole line matches.
1713 */
1714 cno = 0;
1715 }
1716 show_line(opt, bol, eol, gs->name, lno, cno + 1, ':');
5dd06d38 1717 last_hit = lno;
ba8ea749
RS
1718 if (opt->funcbody)
1719 show_function = 1;
1720 goto next_line;
83b5d2f5 1721 }
4aa2c475
RS
1722 if (show_function && (!peek_bol || peek_bol < bol)) {
1723 unsigned long peek_left = left;
1a845fbc 1724 const char *peek_eol = eol;
4aa2c475
RS
1725
1726 /*
1727 * Trailing empty lines are not interesting.
1728 * Peek past them to see if they belong to the
1729 * body of the current function.
1730 */
1731 peek_bol = bol;
1732 while (is_empty_line(peek_bol, peek_eol)) {
1733 peek_bol = peek_eol + 1;
1734 peek_eol = end_of_line(peek_bol, &peek_left);
1735 }
1736
1737 if (match_funcname(opt, gs, peek_bol, peek_eol))
1738 show_function = 0;
1739 }
ba8ea749
RS
1740 if (show_function ||
1741 (last_hit && lno <= last_hit + opt->post_context)) {
83b5d2f5
JH
1742 /* If the last hit is within the post context,
1743 * we need to show this line.
1744 */
89252cd0 1745 show_line(opt, bol, eol, gs->name, lno, col + 1, '-');
83b5d2f5 1746 }
83b5d2f5
JH
1747
1748 next_line:
1749 bol = eol + 1;
1750 if (!left)
1751 break;
1752 left--;
1753 lno++;
1754 }
1755
0ab7befa
JH
1756 if (collect_hits)
1757 return 0;
b48fb5b6 1758
83b5d2f5 1759 if (opt->status_only)
e1f68c66 1760 return opt->unmatch_name_only;
83b5d2f5
JH
1761 if (opt->unmatch_name_only) {
1762 /* We did not see any hit, so we want to show this */
e1327023 1763 show_name(opt, gs->name);
83b5d2f5
JH
1764 return 1;
1765 }
1766
60ecac98
RS
1767 xdiff_clear_find_func(&xecfg);
1768 opt->priv = NULL;
1769
83b5d2f5
JH
1770 /* NEEDSWORK:
1771 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1772 * which feels mostly useless but sometimes useful. Maybe
1773 * make it another option? For now suppress them.
1774 */
5b594f45
FK
1775 if (opt->count && count) {
1776 char buf[32];
f76d947a
RS
1777 if (opt->pathname) {
1778 output_color(opt, gs->name, strlen(gs->name),
fa151dc5 1779 opt->colors[GREP_COLOR_FILENAME]);
f76d947a
RS
1780 output_sep(opt, ':');
1781 }
1a168e5c 1782 xsnprintf(buf, sizeof(buf), "%u\n", count);
5b594f45 1783 opt->output(opt, buf, strlen(buf));
c30c10cf 1784 return 1;
5b594f45 1785 }
83b5d2f5
JH
1786 return !!last_hit;
1787}
1788
0ab7befa
JH
1789static void clr_hit_marker(struct grep_expr *x)
1790{
1791 /* All-hit markers are meaningful only at the very top level
1792 * OR node.
1793 */
1794 while (1) {
1795 x->hit = 0;
1796 if (x->node != GREP_NODE_OR)
1797 return;
1798 x->u.binary.left->hit = 0;
1799 x = x->u.binary.right;
1800 }
1801}
1802
1803static int chk_hit_marker(struct grep_expr *x)
1804{
1805 /* Top level nodes have hit markers. See if they all are hits */
1806 while (1) {
1807 if (x->node != GREP_NODE_OR)
1808 return x->hit;
1809 if (!x->u.binary.left->hit)
1810 return 0;
1811 x = x->u.binary.right;
1812 }
1813}
1814
e1327023 1815int grep_source(struct grep_opt *opt, struct grep_source *gs)
0ab7befa
JH
1816{
1817 /*
1818 * we do not have to do the two-pass grep when we do not check
1819 * buffer-wide "all-match".
1820 */
794c0002 1821 if (!opt->all_match && !opt->no_body_match)
e1327023 1822 return grep_source_1(opt, gs, 0);
0ab7befa
JH
1823
1824 /* Otherwise the toplevel "or" terms hit a bit differently.
1825 * We first clear hit markers from them.
1826 */
1827 clr_hit_marker(opt->pattern_expression);
794c0002 1828 opt->body_hit = 0;
e1327023 1829 grep_source_1(opt, gs, 1);
0ab7befa 1830
794c0002
RS
1831 if (opt->all_match && !chk_hit_marker(opt->pattern_expression))
1832 return 0;
1833 if (opt->no_body_match && opt->body_hit)
0ab7befa
JH
1834 return 0;
1835
e1327023
JK
1836 return grep_source_1(opt, gs, 0);
1837}
1838
1e668716
JK
1839static void grep_source_init_buf(struct grep_source *gs,
1840 const char *buf,
50d92b5f
JT
1841 unsigned long size)
1842{
1843 gs->type = GREP_SOURCE_BUF;
1844 gs->name = NULL;
1845 gs->path = NULL;
1846 gs->buf = buf;
1847 gs->size = size;
1848 gs->driver = NULL;
1849 gs->identifier = NULL;
1850}
1851
1e668716 1852int grep_buffer(struct grep_opt *opt, const char *buf, unsigned long size)
e1327023
JK
1853{
1854 struct grep_source gs;
1855 int r;
1856
50d92b5f 1857 grep_source_init_buf(&gs, buf, size);
e1327023
JK
1858
1859 r = grep_source(opt, &gs);
1860
1861 grep_source_clear(&gs);
1862 return r;
1863}
1864
50d92b5f
JT
1865void grep_source_init_file(struct grep_source *gs, const char *name,
1866 const char *path)
e1327023 1867{
50d92b5f 1868 gs->type = GREP_SOURCE_FILE;
8c53f071
JK
1869 gs->name = xstrdup_or_null(name);
1870 gs->path = xstrdup_or_null(path);
e1327023
JK
1871 gs->buf = NULL;
1872 gs->size = 0;
94ad9d9e 1873 gs->driver = NULL;
50d92b5f
JT
1874 gs->identifier = xstrdup(path);
1875}
e1327023 1876
50d92b5f 1877void grep_source_init_oid(struct grep_source *gs, const char *name,
0693806b
JT
1878 const char *path, const struct object_id *oid,
1879 struct repository *repo)
50d92b5f
JT
1880{
1881 gs->type = GREP_SOURCE_OID;
1882 gs->name = xstrdup_or_null(name);
1883 gs->path = xstrdup_or_null(path);
1884 gs->buf = NULL;
1885 gs->size = 0;
1886 gs->driver = NULL;
1887 gs->identifier = oiddup(oid);
0693806b 1888 gs->repo = repo;
e1327023
JK
1889}
1890
1891void grep_source_clear(struct grep_source *gs)
1892{
88ce3ef6
ÆAB
1893 FREE_AND_NULL(gs->name);
1894 FREE_AND_NULL(gs->path);
1895 FREE_AND_NULL(gs->identifier);
e1327023
JK
1896 grep_source_clear_data(gs);
1897}
1898
1899void grep_source_clear_data(struct grep_source *gs)
1900{
1901 switch (gs->type) {
1902 case GREP_SOURCE_FILE:
1c41c82b 1903 case GREP_SOURCE_OID:
1e668716
JK
1904 /* these types own the buffer */
1905 free((char *)gs->buf);
1906 gs->buf = NULL;
e1327023
JK
1907 gs->size = 0;
1908 break;
1909 case GREP_SOURCE_BUF:
1910 /* leave user-provided buf intact */
1911 break;
1912 }
1913}
1914
1c41c82b 1915static int grep_source_load_oid(struct grep_source *gs)
e1327023
JK
1916{
1917 enum object_type type;
1918
0693806b
JT
1919 gs->buf = repo_read_object_file(gs->repo, gs->identifier, &type,
1920 &gs->size);
e1327023
JK
1921 if (!gs->buf)
1922 return error(_("'%s': unable to read %s"),
1923 gs->name,
1c41c82b 1924 oid_to_hex(gs->identifier));
e1327023
JK
1925 return 0;
1926}
1927
1928static int grep_source_load_file(struct grep_source *gs)
1929{
1930 const char *filename = gs->identifier;
1931 struct stat st;
1932 char *data;
1933 size_t size;
1934 int i;
1935
1936 if (lstat(filename, &st) < 0) {
1937 err_ret:
1938 if (errno != ENOENT)
7645d8f1 1939 error_errno(_("failed to stat '%s'"), filename);
e1327023
JK
1940 return -1;
1941 }
1942 if (!S_ISREG(st.st_mode))
1943 return -1;
1944 size = xsize_t(st.st_size);
1945 i = open(filename, O_RDONLY);
1946 if (i < 0)
1947 goto err_ret;
3733e694 1948 data = xmallocz(size);
e1327023 1949 if (st.st_size != read_in_full(i, data, size)) {
7645d8f1 1950 error_errno(_("'%s': short read"), filename);
e1327023
JK
1951 close(i);
1952 free(data);
1953 return -1;
1954 }
1955 close(i);
e1327023
JK
1956
1957 gs->buf = data;
1958 gs->size = size;
1959 return 0;
1960}
1961
3083301e 1962static int grep_source_load(struct grep_source *gs)
e1327023
JK
1963{
1964 if (gs->buf)
1965 return 0;
1966
1967 switch (gs->type) {
1968 case GREP_SOURCE_FILE:
1969 return grep_source_load_file(gs);
1c41c82b
BW
1970 case GREP_SOURCE_OID:
1971 return grep_source_load_oid(gs);
e1327023
JK
1972 case GREP_SOURCE_BUF:
1973 return gs->buf ? 0 : -1;
1974 }
033abf97 1975 BUG("invalid grep_source type to load");
0ab7befa 1976}
94ad9d9e 1977
acd00ea0
NTND
1978void grep_source_load_driver(struct grep_source *gs,
1979 struct index_state *istate)
94ad9d9e
JK
1980{
1981 if (gs->driver)
1982 return;
1983
1984 grep_attr_lock();
1d1729ca 1985 if (gs->path)
acd00ea0 1986 gs->driver = userdiff_find_by_path(istate, gs->path);
94ad9d9e
JK
1987 if (!gs->driver)
1988 gs->driver = userdiff_find_by_name("default");
1989 grep_attr_unlock();
1990}
41b59bfc 1991
acd00ea0
NTND
1992static int grep_source_is_binary(struct grep_source *gs,
1993 struct index_state *istate)
41b59bfc 1994{
acd00ea0 1995 grep_source_load_driver(gs, istate);
41b59bfc
JK
1996 if (gs->driver->binary != -1)
1997 return gs->driver->binary;
1998
1999 if (!grep_source_load(gs))
2000 return buffer_is_binary(gs->buf, gs->size);
2001
2002 return 0;
2003}