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