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