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