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