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