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