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