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