c7f8a47505334f8ca7ff58e5c676177ce30371ac
1#include "cache.h"
2#include "grep.h"
3#include "userdiff.h"
4#include "xdiff-interface.h"
5
6static int grep_source_load(struct grep_source *gs);
7static int grep_source_is_binary(struct grep_source *gs);
8
9
10static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
11 const char *origin, int no,
12 enum grep_pat_token t,
13 enum grep_header_field field)
14{
15 struct grep_pat *p = xcalloc(1, sizeof(*p));
16 p->pattern = xmemdupz(pat, patlen);
17 p->patternlen = patlen;
18 p->origin = origin;
19 p->no = no;
20 p->token = t;
21 p->field = field;
22 return p;
23}
24
25static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
26{
27 **tail = p;
28 *tail = &p->next;
29 p->next = NULL;
30
31 switch (p->token) {
32 case GREP_PATTERN: /* atom */
33 case GREP_PATTERN_HEAD:
34 case GREP_PATTERN_BODY:
35 for (;;) {
36 struct grep_pat *new_pat;
37 size_t len = 0;
38 char *cp = p->pattern + p->patternlen, *nl = NULL;
39 while (++len <= p->patternlen) {
40 if (*(--cp) == '\n') {
41 nl = cp;
42 break;
43 }
44 }
45 if (!nl)
46 break;
47 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
48 p->no, p->token, p->field);
49 new_pat->next = p->next;
50 if (!p->next)
51 *tail = &new_pat->next;
52 p->next = new_pat;
53 *nl = '\0';
54 p->patternlen -= len;
55 }
56 break;
57 default:
58 break;
59 }
60}
61
62void append_header_grep_pattern(struct grep_opt *opt,
63 enum grep_header_field field, const char *pat)
64{
65 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
66 GREP_PATTERN_HEAD, field);
67 do_append_grep_pat(&opt->header_tail, p);
68}
69
70void append_grep_pattern(struct grep_opt *opt, const char *pat,
71 const char *origin, int no, enum grep_pat_token t)
72{
73 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
74}
75
76void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
77 const char *origin, int no, enum grep_pat_token t)
78{
79 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
80 do_append_grep_pat(&opt->pattern_tail, p);
81}
82
83struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
84{
85 struct grep_pat *pat;
86 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
87 *ret = *opt;
88
89 ret->pattern_list = NULL;
90 ret->pattern_tail = &ret->pattern_list;
91
92 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
93 {
94 if(pat->token == GREP_PATTERN_HEAD)
95 append_header_grep_pattern(ret, pat->field,
96 pat->pattern);
97 else
98 append_grep_pat(ret, pat->pattern, pat->patternlen,
99 pat->origin, pat->no, pat->token);
100 }
101
102 return ret;
103}
104
105static NORETURN void compile_regexp_failed(const struct grep_pat *p,
106 const char *error)
107{
108 char where[1024];
109
110 if (p->no)
111 sprintf(where, "In '%s' at %d, ", p->origin, p->no);
112 else if (p->origin)
113 sprintf(where, "%s, ", p->origin);
114 else
115 where[0] = 0;
116
117 die("%s'%s': %s", where, p->pattern, error);
118}
119
120#ifdef USE_LIBPCRE
121static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
122{
123 const char *error;
124 int erroffset;
125 int options = PCRE_MULTILINE;
126
127 if (opt->ignore_case)
128 options |= PCRE_CASELESS;
129
130 p->pcre_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
131 NULL);
132 if (!p->pcre_regexp)
133 compile_regexp_failed(p, error);
134
135 p->pcre_extra_info = pcre_study(p->pcre_regexp, 0, &error);
136 if (!p->pcre_extra_info && error)
137 die("%s", error);
138}
139
140static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
141 regmatch_t *match, int eflags)
142{
143 int ovector[30], ret, flags = 0;
144
145 if (eflags & REG_NOTBOL)
146 flags |= PCRE_NOTBOL;
147
148 ret = pcre_exec(p->pcre_regexp, p->pcre_extra_info, line, eol - line,
149 0, flags, ovector, ARRAY_SIZE(ovector));
150 if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
151 die("pcre_exec failed with error code %d", ret);
152 if (ret > 0) {
153 ret = 0;
154 match->rm_so = ovector[0];
155 match->rm_eo = ovector[1];
156 }
157
158 return ret;
159}
160
161static void free_pcre_regexp(struct grep_pat *p)
162{
163 pcre_free(p->pcre_regexp);
164 pcre_free(p->pcre_extra_info);
165}
166#else /* !USE_LIBPCRE */
167static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
168{
169 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
170}
171
172static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
173 regmatch_t *match, int eflags)
174{
175 return 1;
176}
177
178static void free_pcre_regexp(struct grep_pat *p)
179{
180}
181#endif /* !USE_LIBPCRE */
182
183static int is_fixed(const char *s, size_t len)
184{
185 size_t i;
186
187 /* regcomp cannot accept patterns with NULs so we
188 * consider any pattern containing a NUL fixed.
189 */
190 if (memchr(s, 0, len))
191 return 1;
192
193 for (i = 0; i < len; i++) {
194 if (is_regex_special(s[i]))
195 return 0;
196 }
197
198 return 1;
199}
200
201static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
202{
203 int err;
204
205 p->word_regexp = opt->word_regexp;
206 p->ignore_case = opt->ignore_case;
207
208 if (opt->fixed || is_fixed(p->pattern, p->patternlen))
209 p->fixed = 1;
210 else
211 p->fixed = 0;
212
213 if (p->fixed) {
214 if (opt->regflags & REG_ICASE || p->ignore_case)
215 p->kws = kwsalloc(tolower_trans_tbl);
216 else
217 p->kws = kwsalloc(NULL);
218 kwsincr(p->kws, p->pattern, p->patternlen);
219 kwsprep(p->kws);
220 return;
221 }
222
223 if (opt->pcre) {
224 compile_pcre_regexp(p, opt);
225 return;
226 }
227
228 err = regcomp(&p->regexp, p->pattern, opt->regflags);
229 if (err) {
230 char errbuf[1024];
231 regerror(err, &p->regexp, errbuf, 1024);
232 regfree(&p->regexp);
233 compile_regexp_failed(p, errbuf);
234 }
235}
236
237static struct grep_expr *compile_pattern_or(struct grep_pat **);
238static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
239{
240 struct grep_pat *p;
241 struct grep_expr *x;
242
243 p = *list;
244 if (!p)
245 return NULL;
246 switch (p->token) {
247 case GREP_PATTERN: /* atom */
248 case GREP_PATTERN_HEAD:
249 case GREP_PATTERN_BODY:
250 x = xcalloc(1, sizeof (struct grep_expr));
251 x->node = GREP_NODE_ATOM;
252 x->u.atom = p;
253 *list = p->next;
254 return x;
255 case GREP_OPEN_PAREN:
256 *list = p->next;
257 x = compile_pattern_or(list);
258 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
259 die("unmatched parenthesis");
260 *list = (*list)->next;
261 return x;
262 default:
263 return NULL;
264 }
265}
266
267static struct grep_expr *compile_pattern_not(struct grep_pat **list)
268{
269 struct grep_pat *p;
270 struct grep_expr *x;
271
272 p = *list;
273 if (!p)
274 return NULL;
275 switch (p->token) {
276 case GREP_NOT:
277 if (!p->next)
278 die("--not not followed by pattern expression");
279 *list = p->next;
280 x = xcalloc(1, sizeof (struct grep_expr));
281 x->node = GREP_NODE_NOT;
282 x->u.unary = compile_pattern_not(list);
283 if (!x->u.unary)
284 die("--not followed by non pattern expression");
285 return x;
286 default:
287 return compile_pattern_atom(list);
288 }
289}
290
291static struct grep_expr *compile_pattern_and(struct grep_pat **list)
292{
293 struct grep_pat *p;
294 struct grep_expr *x, *y, *z;
295
296 x = compile_pattern_not(list);
297 p = *list;
298 if (p && p->token == GREP_AND) {
299 if (!p->next)
300 die("--and not followed by pattern expression");
301 *list = p->next;
302 y = compile_pattern_and(list);
303 if (!y)
304 die("--and not followed by pattern expression");
305 z = xcalloc(1, sizeof (struct grep_expr));
306 z->node = GREP_NODE_AND;
307 z->u.binary.left = x;
308 z->u.binary.right = y;
309 return z;
310 }
311 return x;
312}
313
314static struct grep_expr *compile_pattern_or(struct grep_pat **list)
315{
316 struct grep_pat *p;
317 struct grep_expr *x, *y, *z;
318
319 x = compile_pattern_and(list);
320 p = *list;
321 if (x && p && p->token != GREP_CLOSE_PAREN) {
322 y = compile_pattern_or(list);
323 if (!y)
324 die("not a pattern expression %s", p->pattern);
325 z = xcalloc(1, sizeof (struct grep_expr));
326 z->node = GREP_NODE_OR;
327 z->u.binary.left = x;
328 z->u.binary.right = y;
329 return z;
330 }
331 return x;
332}
333
334static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
335{
336 return compile_pattern_or(list);
337}
338
339static void indent(int in)
340{
341 while (in-- > 0)
342 fputc(' ', stderr);
343}
344
345static void dump_grep_pat(struct grep_pat *p)
346{
347 switch (p->token) {
348 case GREP_AND: fprintf(stderr, "*and*"); break;
349 case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
350 case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
351 case GREP_NOT: fprintf(stderr, "*not*"); break;
352 case GREP_OR: fprintf(stderr, "*or*"); break;
353
354 case GREP_PATTERN: fprintf(stderr, "pattern"); break;
355 case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
356 case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
357 }
358
359 switch (p->token) {
360 default: break;
361 case GREP_PATTERN_HEAD:
362 fprintf(stderr, "<head %d>", p->field); break;
363 case GREP_PATTERN_BODY:
364 fprintf(stderr, "<body>"); break;
365 }
366 switch (p->token) {
367 default: break;
368 case GREP_PATTERN_HEAD:
369 case GREP_PATTERN_BODY:
370 case GREP_PATTERN:
371 fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
372 break;
373 }
374 fputc('\n', stderr);
375}
376
377static void dump_grep_expression_1(struct grep_expr *x, int in)
378{
379 indent(in);
380 switch (x->node) {
381 case GREP_NODE_TRUE:
382 fprintf(stderr, "true\n");
383 break;
384 case GREP_NODE_ATOM:
385 dump_grep_pat(x->u.atom);
386 break;
387 case GREP_NODE_NOT:
388 fprintf(stderr, "(not\n");
389 dump_grep_expression_1(x->u.unary, in+1);
390 indent(in);
391 fprintf(stderr, ")\n");
392 break;
393 case GREP_NODE_AND:
394 fprintf(stderr, "(and\n");
395 dump_grep_expression_1(x->u.binary.left, in+1);
396 dump_grep_expression_1(x->u.binary.right, in+1);
397 indent(in);
398 fprintf(stderr, ")\n");
399 break;
400 case GREP_NODE_OR:
401 fprintf(stderr, "(or\n");
402 dump_grep_expression_1(x->u.binary.left, in+1);
403 dump_grep_expression_1(x->u.binary.right, in+1);
404 indent(in);
405 fprintf(stderr, ")\n");
406 break;
407 }
408}
409
410static void dump_grep_expression(struct grep_opt *opt)
411{
412 struct grep_expr *x = opt->pattern_expression;
413
414 if (opt->all_match)
415 fprintf(stderr, "[all-match]\n");
416 dump_grep_expression_1(x, 0);
417 fflush(NULL);
418}
419
420static struct grep_expr *grep_true_expr(void)
421{
422 struct grep_expr *z = xcalloc(1, sizeof(*z));
423 z->node = GREP_NODE_TRUE;
424 return z;
425}
426
427static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
428{
429 struct grep_expr *z = xcalloc(1, sizeof(*z));
430 z->node = GREP_NODE_OR;
431 z->u.binary.left = left;
432 z->u.binary.right = right;
433 return z;
434}
435
436static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
437{
438 struct grep_pat *p;
439 struct grep_expr *header_expr;
440 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
441 enum grep_header_field fld;
442
443 if (!opt->header_list)
444 return NULL;
445
446 for (p = opt->header_list; p; p = p->next) {
447 if (p->token != GREP_PATTERN_HEAD)
448 die("bug: a non-header pattern in grep header list.");
449 if (p->field < 0 || GREP_HEADER_FIELD_MAX <= p->field)
450 die("bug: unknown header field %d", p->field);
451 compile_regexp(p, opt);
452 }
453
454 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
455 header_group[fld] = NULL;
456
457 for (p = opt->header_list; p; p = p->next) {
458 struct grep_expr *h;
459 struct grep_pat *pp = p;
460
461 h = compile_pattern_atom(&pp);
462 if (!h || pp != p->next)
463 die("bug: malformed header expr");
464 if (!header_group[p->field]) {
465 header_group[p->field] = h;
466 continue;
467 }
468 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
469 }
470
471 header_expr = NULL;
472
473 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
474 if (!header_group[fld])
475 continue;
476 if (!header_expr)
477 header_expr = grep_true_expr();
478 header_expr = grep_or_expr(header_group[fld], header_expr);
479 }
480 return header_expr;
481}
482
483static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
484{
485 struct grep_expr *z = x;
486
487 while (x) {
488 assert(x->node == GREP_NODE_OR);
489 if (x->u.binary.right &&
490 x->u.binary.right->node == GREP_NODE_TRUE) {
491 x->u.binary.right = y;
492 break;
493 }
494 x = x->u.binary.right;
495 }
496 return z;
497}
498
499static void compile_grep_patterns_real(struct grep_opt *opt)
500{
501 struct grep_pat *p;
502 struct grep_expr *header_expr = prep_header_patterns(opt);
503
504 for (p = opt->pattern_list; p; p = p->next) {
505 switch (p->token) {
506 case GREP_PATTERN: /* atom */
507 case GREP_PATTERN_HEAD:
508 case GREP_PATTERN_BODY:
509 compile_regexp(p, opt);
510 break;
511 default:
512 opt->extended = 1;
513 break;
514 }
515 }
516
517 if (opt->all_match || header_expr)
518 opt->extended = 1;
519 else if (!opt->extended && !opt->debug)
520 return;
521
522 p = opt->pattern_list;
523 if (p)
524 opt->pattern_expression = compile_pattern_expr(&p);
525 if (p)
526 die("incomplete pattern expression: %s", p->pattern);
527
528 if (!header_expr)
529 return;
530
531 if (!opt->pattern_expression)
532 opt->pattern_expression = header_expr;
533 else if (opt->all_match)
534 opt->pattern_expression = grep_splice_or(header_expr,
535 opt->pattern_expression);
536 else
537 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
538 header_expr);
539 opt->all_match = 1;
540}
541
542void compile_grep_patterns(struct grep_opt *opt)
543{
544 compile_grep_patterns_real(opt);
545 if (opt->debug)
546 dump_grep_expression(opt);
547}
548
549static void free_pattern_expr(struct grep_expr *x)
550{
551 switch (x->node) {
552 case GREP_NODE_TRUE:
553 case GREP_NODE_ATOM:
554 break;
555 case GREP_NODE_NOT:
556 free_pattern_expr(x->u.unary);
557 break;
558 case GREP_NODE_AND:
559 case GREP_NODE_OR:
560 free_pattern_expr(x->u.binary.left);
561 free_pattern_expr(x->u.binary.right);
562 break;
563 }
564 free(x);
565}
566
567void free_grep_patterns(struct grep_opt *opt)
568{
569 struct grep_pat *p, *n;
570
571 for (p = opt->pattern_list; p; p = n) {
572 n = p->next;
573 switch (p->token) {
574 case GREP_PATTERN: /* atom */
575 case GREP_PATTERN_HEAD:
576 case GREP_PATTERN_BODY:
577 if (p->kws)
578 kwsfree(p->kws);
579 else if (p->pcre_regexp)
580 free_pcre_regexp(p);
581 else
582 regfree(&p->regexp);
583 free(p->pattern);
584 break;
585 default:
586 break;
587 }
588 free(p);
589 }
590
591 if (!opt->extended)
592 return;
593 free_pattern_expr(opt->pattern_expression);
594}
595
596static char *end_of_line(char *cp, unsigned long *left)
597{
598 unsigned long l = *left;
599 while (l && *cp != '\n') {
600 l--;
601 cp++;
602 }
603 *left = l;
604 return cp;
605}
606
607static int word_char(char ch)
608{
609 return isalnum(ch) || ch == '_';
610}
611
612static void output_color(struct grep_opt *opt, const void *data, size_t size,
613 const char *color)
614{
615 if (want_color(opt->color) && color && color[0]) {
616 opt->output(opt, color, strlen(color));
617 opt->output(opt, data, size);
618 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
619 } else
620 opt->output(opt, data, size);
621}
622
623static void output_sep(struct grep_opt *opt, char sign)
624{
625 if (opt->null_following_name)
626 opt->output(opt, "\0", 1);
627 else
628 output_color(opt, &sign, 1, opt->color_sep);
629}
630
631static void show_name(struct grep_opt *opt, const char *name)
632{
633 output_color(opt, name, strlen(name), opt->color_filename);
634 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
635}
636
637static int fixmatch(struct grep_pat *p, char *line, char *eol,
638 regmatch_t *match)
639{
640 struct kwsmatch kwsm;
641 size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
642 if (offset == -1) {
643 match->rm_so = match->rm_eo = -1;
644 return REG_NOMATCH;
645 } else {
646 match->rm_so = offset;
647 match->rm_eo = match->rm_so + kwsm.size[0];
648 return 0;
649 }
650}
651
652static int regmatch(const regex_t *preg, char *line, char *eol,
653 regmatch_t *match, int eflags)
654{
655#ifdef REG_STARTEND
656 match->rm_so = 0;
657 match->rm_eo = eol - line;
658 eflags |= REG_STARTEND;
659#endif
660 return regexec(preg, line, 1, match, eflags);
661}
662
663static int patmatch(struct grep_pat *p, char *line, char *eol,
664 regmatch_t *match, int eflags)
665{
666 int hit;
667
668 if (p->fixed)
669 hit = !fixmatch(p, line, eol, match);
670 else if (p->pcre_regexp)
671 hit = !pcrematch(p, line, eol, match, eflags);
672 else
673 hit = !regmatch(&p->regexp, line, eol, match, eflags);
674
675 return hit;
676}
677
678static int strip_timestamp(char *bol, char **eol_p)
679{
680 char *eol = *eol_p;
681 int ch;
682
683 while (bol < --eol) {
684 if (*eol != '>')
685 continue;
686 *eol_p = ++eol;
687 ch = *eol;
688 *eol = '\0';
689 return ch;
690 }
691 return 0;
692}
693
694static struct {
695 const char *field;
696 size_t len;
697} header_field[] = {
698 { "author ", 7 },
699 { "committer ", 10 },
700};
701
702static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
703 enum grep_context ctx,
704 regmatch_t *pmatch, int eflags)
705{
706 int hit = 0;
707 int saved_ch = 0;
708 const char *start = bol;
709
710 if ((p->token != GREP_PATTERN) &&
711 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
712 return 0;
713
714 if (p->token == GREP_PATTERN_HEAD) {
715 const char *field;
716 size_t len;
717 assert(p->field < ARRAY_SIZE(header_field));
718 field = header_field[p->field].field;
719 len = header_field[p->field].len;
720 if (strncmp(bol, field, len))
721 return 0;
722 bol += len;
723 saved_ch = strip_timestamp(bol, &eol);
724 }
725
726 again:
727 hit = patmatch(p, bol, eol, pmatch, eflags);
728
729 if (hit && p->word_regexp) {
730 if ((pmatch[0].rm_so < 0) ||
731 (eol - bol) < pmatch[0].rm_so ||
732 (pmatch[0].rm_eo < 0) ||
733 (eol - bol) < pmatch[0].rm_eo)
734 die("regexp returned nonsense");
735
736 /* Match beginning must be either beginning of the
737 * line, or at word boundary (i.e. the last char must
738 * not be a word char). Similarly, match end must be
739 * either end of the line, or at word boundary
740 * (i.e. the next char must not be a word char).
741 */
742 if ( ((pmatch[0].rm_so == 0) ||
743 !word_char(bol[pmatch[0].rm_so-1])) &&
744 ((pmatch[0].rm_eo == (eol-bol)) ||
745 !word_char(bol[pmatch[0].rm_eo])) )
746 ;
747 else
748 hit = 0;
749
750 /* Words consist of at least one character. */
751 if (pmatch->rm_so == pmatch->rm_eo)
752 hit = 0;
753
754 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
755 /* There could be more than one match on the
756 * line, and the first match might not be
757 * strict word match. But later ones could be!
758 * Forward to the next possible start, i.e. the
759 * next position following a non-word char.
760 */
761 bol = pmatch[0].rm_so + bol + 1;
762 while (word_char(bol[-1]) && bol < eol)
763 bol++;
764 eflags |= REG_NOTBOL;
765 if (bol < eol)
766 goto again;
767 }
768 }
769 if (p->token == GREP_PATTERN_HEAD && saved_ch)
770 *eol = saved_ch;
771 if (hit) {
772 pmatch[0].rm_so += bol - start;
773 pmatch[0].rm_eo += bol - start;
774 }
775 return hit;
776}
777
778static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
779 enum grep_context ctx, int collect_hits)
780{
781 int h = 0;
782 regmatch_t match;
783
784 if (!x)
785 die("Not a valid grep expression");
786 switch (x->node) {
787 case GREP_NODE_TRUE:
788 h = 1;
789 break;
790 case GREP_NODE_ATOM:
791 h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
792 break;
793 case GREP_NODE_NOT:
794 h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
795 break;
796 case GREP_NODE_AND:
797 if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
798 return 0;
799 h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
800 break;
801 case GREP_NODE_OR:
802 if (!collect_hits)
803 return (match_expr_eval(x->u.binary.left,
804 bol, eol, ctx, 0) ||
805 match_expr_eval(x->u.binary.right,
806 bol, eol, ctx, 0));
807 h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
808 x->u.binary.left->hit |= h;
809 h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
810 break;
811 default:
812 die("Unexpected node type (internal error) %d", x->node);
813 }
814 if (collect_hits)
815 x->hit |= h;
816 return h;
817}
818
819static int match_expr(struct grep_opt *opt, char *bol, char *eol,
820 enum grep_context ctx, int collect_hits)
821{
822 struct grep_expr *x = opt->pattern_expression;
823 return match_expr_eval(x, bol, eol, ctx, collect_hits);
824}
825
826static int match_line(struct grep_opt *opt, char *bol, char *eol,
827 enum grep_context ctx, int collect_hits)
828{
829 struct grep_pat *p;
830 regmatch_t match;
831
832 if (opt->extended)
833 return match_expr(opt, bol, eol, ctx, collect_hits);
834
835 /* we do not call with collect_hits without being extended */
836 for (p = opt->pattern_list; p; p = p->next) {
837 if (match_one_pattern(p, bol, eol, ctx, &match, 0))
838 return 1;
839 }
840 return 0;
841}
842
843static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
844 enum grep_context ctx,
845 regmatch_t *pmatch, int eflags)
846{
847 regmatch_t match;
848
849 if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
850 return 0;
851 if (match.rm_so < 0 || match.rm_eo < 0)
852 return 0;
853 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
854 if (match.rm_so > pmatch->rm_so)
855 return 1;
856 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
857 return 1;
858 }
859 pmatch->rm_so = match.rm_so;
860 pmatch->rm_eo = match.rm_eo;
861 return 1;
862}
863
864static int next_match(struct grep_opt *opt, char *bol, char *eol,
865 enum grep_context ctx, regmatch_t *pmatch, int eflags)
866{
867 struct grep_pat *p;
868 int hit = 0;
869
870 pmatch->rm_so = pmatch->rm_eo = -1;
871 if (bol < eol) {
872 for (p = opt->pattern_list; p; p = p->next) {
873 switch (p->token) {
874 case GREP_PATTERN: /* atom */
875 case GREP_PATTERN_HEAD:
876 case GREP_PATTERN_BODY:
877 hit |= match_next_pattern(p, bol, eol, ctx,
878 pmatch, eflags);
879 break;
880 default:
881 break;
882 }
883 }
884 }
885 return hit;
886}
887
888static void show_line(struct grep_opt *opt, char *bol, char *eol,
889 const char *name, unsigned lno, char sign)
890{
891 int rest = eol - bol;
892 char *line_color = NULL;
893
894 if (opt->file_break && opt->last_shown == 0) {
895 if (opt->show_hunk_mark)
896 opt->output(opt, "\n", 1);
897 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
898 if (opt->last_shown == 0) {
899 if (opt->show_hunk_mark) {
900 output_color(opt, "--", 2, opt->color_sep);
901 opt->output(opt, "\n", 1);
902 }
903 } else if (lno > opt->last_shown + 1) {
904 output_color(opt, "--", 2, opt->color_sep);
905 opt->output(opt, "\n", 1);
906 }
907 }
908 if (opt->heading && opt->last_shown == 0) {
909 output_color(opt, name, strlen(name), opt->color_filename);
910 opt->output(opt, "\n", 1);
911 }
912 opt->last_shown = lno;
913
914 if (!opt->heading && opt->pathname) {
915 output_color(opt, name, strlen(name), opt->color_filename);
916 output_sep(opt, sign);
917 }
918 if (opt->linenum) {
919 char buf[32];
920 snprintf(buf, sizeof(buf), "%d", lno);
921 output_color(opt, buf, strlen(buf), opt->color_lineno);
922 output_sep(opt, sign);
923 }
924 if (opt->color) {
925 regmatch_t match;
926 enum grep_context ctx = GREP_CONTEXT_BODY;
927 int ch = *eol;
928 int eflags = 0;
929
930 if (sign == ':')
931 line_color = opt->color_selected;
932 else if (sign == '-')
933 line_color = opt->color_context;
934 else if (sign == '=')
935 line_color = opt->color_function;
936 *eol = '\0';
937 while (next_match(opt, bol, eol, ctx, &match, eflags)) {
938 if (match.rm_so == match.rm_eo)
939 break;
940
941 output_color(opt, bol, match.rm_so, line_color);
942 output_color(opt, bol + match.rm_so,
943 match.rm_eo - match.rm_so,
944 opt->color_match);
945 bol += match.rm_eo;
946 rest -= match.rm_eo;
947 eflags = REG_NOTBOL;
948 }
949 *eol = ch;
950 }
951 output_color(opt, bol, rest, line_color);
952 opt->output(opt, "\n", 1);
953}
954
955#ifndef NO_PTHREADS
956int grep_use_locks;
957
958/*
959 * This lock protects access to the gitattributes machinery, which is
960 * not thread-safe.
961 */
962pthread_mutex_t grep_attr_mutex;
963
964static inline void grep_attr_lock(void)
965{
966 if (grep_use_locks)
967 pthread_mutex_lock(&grep_attr_mutex);
968}
969
970static inline void grep_attr_unlock(void)
971{
972 if (grep_use_locks)
973 pthread_mutex_unlock(&grep_attr_mutex);
974}
975
976/*
977 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
978 */
979pthread_mutex_t grep_read_mutex;
980
981#else
982#define grep_attr_lock()
983#define grep_attr_unlock()
984#endif
985
986static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
987{
988 xdemitconf_t *xecfg = opt->priv;
989 if (xecfg && !xecfg->find_func) {
990 grep_source_load_driver(gs);
991 if (gs->driver->funcname.pattern) {
992 const struct userdiff_funcname *pe = &gs->driver->funcname;
993 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
994 } else {
995 xecfg = opt->priv = NULL;
996 }
997 }
998
999 if (xecfg) {
1000 char buf[1];
1001 return xecfg->find_func(bol, eol - bol, buf, 1,
1002 xecfg->find_func_priv) >= 0;
1003 }
1004
1005 if (bol == eol)
1006 return 0;
1007 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1008 return 1;
1009 return 0;
1010}
1011
1012static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1013 char *bol, unsigned lno)
1014{
1015 while (bol > gs->buf) {
1016 char *eol = --bol;
1017
1018 while (bol > gs->buf && bol[-1] != '\n')
1019 bol--;
1020 lno--;
1021
1022 if (lno <= opt->last_shown)
1023 break;
1024
1025 if (match_funcname(opt, gs, bol, eol)) {
1026 show_line(opt, bol, eol, gs->name, lno, '=');
1027 break;
1028 }
1029 }
1030}
1031
1032static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1033 char *bol, char *end, unsigned lno)
1034{
1035 unsigned cur = lno, from = 1, funcname_lno = 0;
1036 int funcname_needed = !!opt->funcname;
1037
1038 if (opt->funcbody && !match_funcname(opt, gs, bol, end))
1039 funcname_needed = 2;
1040
1041 if (opt->pre_context < lno)
1042 from = lno - opt->pre_context;
1043 if (from <= opt->last_shown)
1044 from = opt->last_shown + 1;
1045
1046 /* Rewind. */
1047 while (bol > gs->buf &&
1048 cur > (funcname_needed == 2 ? opt->last_shown + 1 : from)) {
1049 char *eol = --bol;
1050
1051 while (bol > gs->buf && bol[-1] != '\n')
1052 bol--;
1053 cur--;
1054 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1055 funcname_lno = cur;
1056 funcname_needed = 0;
1057 }
1058 }
1059
1060 /* We need to look even further back to find a function signature. */
1061 if (opt->funcname && funcname_needed)
1062 show_funcname_line(opt, gs, bol, cur);
1063
1064 /* Back forward. */
1065 while (cur < lno) {
1066 char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1067
1068 while (*eol != '\n')
1069 eol++;
1070 show_line(opt, bol, eol, gs->name, cur, sign);
1071 bol = eol + 1;
1072 cur++;
1073 }
1074}
1075
1076static int should_lookahead(struct grep_opt *opt)
1077{
1078 struct grep_pat *p;
1079
1080 if (opt->extended)
1081 return 0; /* punt for too complex stuff */
1082 if (opt->invert)
1083 return 0;
1084 for (p = opt->pattern_list; p; p = p->next) {
1085 if (p->token != GREP_PATTERN)
1086 return 0; /* punt for "header only" and stuff */
1087 }
1088 return 1;
1089}
1090
1091static int look_ahead(struct grep_opt *opt,
1092 unsigned long *left_p,
1093 unsigned *lno_p,
1094 char **bol_p)
1095{
1096 unsigned lno = *lno_p;
1097 char *bol = *bol_p;
1098 struct grep_pat *p;
1099 char *sp, *last_bol;
1100 regoff_t earliest = -1;
1101
1102 for (p = opt->pattern_list; p; p = p->next) {
1103 int hit;
1104 regmatch_t m;
1105
1106 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1107 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1108 continue;
1109 if (earliest < 0 || m.rm_so < earliest)
1110 earliest = m.rm_so;
1111 }
1112
1113 if (earliest < 0) {
1114 *bol_p = bol + *left_p;
1115 *left_p = 0;
1116 return 1;
1117 }
1118 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1119 ; /* find the beginning of the line */
1120 last_bol = sp;
1121
1122 for (sp = bol; sp < last_bol; sp++) {
1123 if (*sp == '\n')
1124 lno++;
1125 }
1126 *left_p -= last_bol - bol;
1127 *bol_p = last_bol;
1128 *lno_p = lno;
1129 return 0;
1130}
1131
1132static void std_output(struct grep_opt *opt, const void *buf, size_t size)
1133{
1134 fwrite(buf, size, 1, stdout);
1135}
1136
1137static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1138{
1139 char *bol;
1140 unsigned long left;
1141 unsigned lno = 1;
1142 unsigned last_hit = 0;
1143 int binary_match_only = 0;
1144 unsigned count = 0;
1145 int try_lookahead = 0;
1146 int show_function = 0;
1147 enum grep_context ctx = GREP_CONTEXT_HEAD;
1148 xdemitconf_t xecfg;
1149
1150 if (!opt->output)
1151 opt->output = std_output;
1152
1153 if (opt->pre_context || opt->post_context || opt->file_break ||
1154 opt->funcbody) {
1155 /* Show hunk marks, except for the first file. */
1156 if (opt->last_shown)
1157 opt->show_hunk_mark = 1;
1158 /*
1159 * If we're using threads then we can't easily identify
1160 * the first file. Always put hunk marks in that case
1161 * and skip the very first one later in work_done().
1162 */
1163 if (opt->output != std_output)
1164 opt->show_hunk_mark = 1;
1165 }
1166 opt->last_shown = 0;
1167
1168 switch (opt->binary) {
1169 case GREP_BINARY_DEFAULT:
1170 if (grep_source_is_binary(gs))
1171 binary_match_only = 1;
1172 break;
1173 case GREP_BINARY_NOMATCH:
1174 if (grep_source_is_binary(gs))
1175 return 0; /* Assume unmatch */
1176 break;
1177 case GREP_BINARY_TEXT:
1178 break;
1179 default:
1180 die("bug: unknown binary handling mode");
1181 }
1182
1183 memset(&xecfg, 0, sizeof(xecfg));
1184 opt->priv = &xecfg;
1185
1186 try_lookahead = should_lookahead(opt);
1187
1188 if (grep_source_load(gs) < 0)
1189 return 0;
1190
1191 bol = gs->buf;
1192 left = gs->size;
1193 while (left) {
1194 char *eol, ch;
1195 int hit;
1196
1197 /*
1198 * look_ahead() skips quickly to the line that possibly
1199 * has the next hit; don't call it if we need to do
1200 * something more than just skipping the current line
1201 * in response to an unmatch for the current line. E.g.
1202 * inside a post-context window, we will show the current
1203 * line as a context around the previous hit when it
1204 * doesn't hit.
1205 */
1206 if (try_lookahead
1207 && !(last_hit
1208 && (show_function ||
1209 lno <= last_hit + opt->post_context))
1210 && look_ahead(opt, &left, &lno, &bol))
1211 break;
1212 eol = end_of_line(bol, &left);
1213 ch = *eol;
1214 *eol = 0;
1215
1216 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1217 ctx = GREP_CONTEXT_BODY;
1218
1219 hit = match_line(opt, bol, eol, ctx, collect_hits);
1220 *eol = ch;
1221
1222 if (collect_hits)
1223 goto next_line;
1224
1225 /* "grep -v -e foo -e bla" should list lines
1226 * that do not have either, so inversion should
1227 * be done outside.
1228 */
1229 if (opt->invert)
1230 hit = !hit;
1231 if (opt->unmatch_name_only) {
1232 if (hit)
1233 return 0;
1234 goto next_line;
1235 }
1236 if (hit) {
1237 count++;
1238 if (opt->status_only)
1239 return 1;
1240 if (opt->name_only) {
1241 show_name(opt, gs->name);
1242 return 1;
1243 }
1244 if (opt->count)
1245 goto next_line;
1246 if (binary_match_only) {
1247 opt->output(opt, "Binary file ", 12);
1248 output_color(opt, gs->name, strlen(gs->name),
1249 opt->color_filename);
1250 opt->output(opt, " matches\n", 9);
1251 return 1;
1252 }
1253 /* Hit at this line. If we haven't shown the
1254 * pre-context lines, we would need to show them.
1255 */
1256 if (opt->pre_context || opt->funcbody)
1257 show_pre_context(opt, gs, bol, eol, lno);
1258 else if (opt->funcname)
1259 show_funcname_line(opt, gs, bol, lno);
1260 show_line(opt, bol, eol, gs->name, lno, ':');
1261 last_hit = lno;
1262 if (opt->funcbody)
1263 show_function = 1;
1264 goto next_line;
1265 }
1266 if (show_function && match_funcname(opt, gs, bol, eol))
1267 show_function = 0;
1268 if (show_function ||
1269 (last_hit && lno <= last_hit + opt->post_context)) {
1270 /* If the last hit is within the post context,
1271 * we need to show this line.
1272 */
1273 show_line(opt, bol, eol, gs->name, lno, '-');
1274 }
1275
1276 next_line:
1277 bol = eol + 1;
1278 if (!left)
1279 break;
1280 left--;
1281 lno++;
1282 }
1283
1284 if (collect_hits)
1285 return 0;
1286
1287 if (opt->status_only)
1288 return 0;
1289 if (opt->unmatch_name_only) {
1290 /* We did not see any hit, so we want to show this */
1291 show_name(opt, gs->name);
1292 return 1;
1293 }
1294
1295 xdiff_clear_find_func(&xecfg);
1296 opt->priv = NULL;
1297
1298 /* NEEDSWORK:
1299 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1300 * which feels mostly useless but sometimes useful. Maybe
1301 * make it another option? For now suppress them.
1302 */
1303 if (opt->count && count) {
1304 char buf[32];
1305 output_color(opt, gs->name, strlen(gs->name), opt->color_filename);
1306 output_sep(opt, ':');
1307 snprintf(buf, sizeof(buf), "%u\n", count);
1308 opt->output(opt, buf, strlen(buf));
1309 return 1;
1310 }
1311 return !!last_hit;
1312}
1313
1314static void clr_hit_marker(struct grep_expr *x)
1315{
1316 /* All-hit markers are meaningful only at the very top level
1317 * OR node.
1318 */
1319 while (1) {
1320 x->hit = 0;
1321 if (x->node != GREP_NODE_OR)
1322 return;
1323 x->u.binary.left->hit = 0;
1324 x = x->u.binary.right;
1325 }
1326}
1327
1328static int chk_hit_marker(struct grep_expr *x)
1329{
1330 /* Top level nodes have hit markers. See if they all are hits */
1331 while (1) {
1332 if (x->node != GREP_NODE_OR)
1333 return x->hit;
1334 if (!x->u.binary.left->hit)
1335 return 0;
1336 x = x->u.binary.right;
1337 }
1338}
1339
1340int grep_source(struct grep_opt *opt, struct grep_source *gs)
1341{
1342 /*
1343 * we do not have to do the two-pass grep when we do not check
1344 * buffer-wide "all-match".
1345 */
1346 if (!opt->all_match)
1347 return grep_source_1(opt, gs, 0);
1348
1349 /* Otherwise the toplevel "or" terms hit a bit differently.
1350 * We first clear hit markers from them.
1351 */
1352 clr_hit_marker(opt->pattern_expression);
1353 grep_source_1(opt, gs, 1);
1354
1355 if (!chk_hit_marker(opt->pattern_expression))
1356 return 0;
1357
1358 return grep_source_1(opt, gs, 0);
1359}
1360
1361int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
1362{
1363 struct grep_source gs;
1364 int r;
1365
1366 grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL);
1367 gs.buf = buf;
1368 gs.size = size;
1369
1370 r = grep_source(opt, &gs);
1371
1372 grep_source_clear(&gs);
1373 return r;
1374}
1375
1376void grep_source_init(struct grep_source *gs, enum grep_source_type type,
1377 const char *name, const void *identifier)
1378{
1379 gs->type = type;
1380 gs->name = name ? xstrdup(name) : NULL;
1381 gs->buf = NULL;
1382 gs->size = 0;
1383 gs->driver = NULL;
1384
1385 switch (type) {
1386 case GREP_SOURCE_FILE:
1387 gs->identifier = xstrdup(identifier);
1388 break;
1389 case GREP_SOURCE_SHA1:
1390 gs->identifier = xmalloc(20);
1391 memcpy(gs->identifier, identifier, 20);
1392 break;
1393 case GREP_SOURCE_BUF:
1394 gs->identifier = NULL;
1395 }
1396}
1397
1398void grep_source_clear(struct grep_source *gs)
1399{
1400 free(gs->name);
1401 gs->name = NULL;
1402 free(gs->identifier);
1403 gs->identifier = NULL;
1404 grep_source_clear_data(gs);
1405}
1406
1407void grep_source_clear_data(struct grep_source *gs)
1408{
1409 switch (gs->type) {
1410 case GREP_SOURCE_FILE:
1411 case GREP_SOURCE_SHA1:
1412 free(gs->buf);
1413 gs->buf = NULL;
1414 gs->size = 0;
1415 break;
1416 case GREP_SOURCE_BUF:
1417 /* leave user-provided buf intact */
1418 break;
1419 }
1420}
1421
1422static int grep_source_load_sha1(struct grep_source *gs)
1423{
1424 enum object_type type;
1425
1426 grep_read_lock();
1427 gs->buf = read_sha1_file(gs->identifier, &type, &gs->size);
1428 grep_read_unlock();
1429
1430 if (!gs->buf)
1431 return error(_("'%s': unable to read %s"),
1432 gs->name,
1433 sha1_to_hex(gs->identifier));
1434 return 0;
1435}
1436
1437static int grep_source_load_file(struct grep_source *gs)
1438{
1439 const char *filename = gs->identifier;
1440 struct stat st;
1441 char *data;
1442 size_t size;
1443 int i;
1444
1445 if (lstat(filename, &st) < 0) {
1446 err_ret:
1447 if (errno != ENOENT)
1448 error(_("'%s': %s"), filename, strerror(errno));
1449 return -1;
1450 }
1451 if (!S_ISREG(st.st_mode))
1452 return -1;
1453 size = xsize_t(st.st_size);
1454 i = open(filename, O_RDONLY);
1455 if (i < 0)
1456 goto err_ret;
1457 data = xmalloc(size + 1);
1458 if (st.st_size != read_in_full(i, data, size)) {
1459 error(_("'%s': short read %s"), filename, strerror(errno));
1460 close(i);
1461 free(data);
1462 return -1;
1463 }
1464 close(i);
1465 data[size] = 0;
1466
1467 gs->buf = data;
1468 gs->size = size;
1469 return 0;
1470}
1471
1472int grep_source_load(struct grep_source *gs)
1473{
1474 if (gs->buf)
1475 return 0;
1476
1477 switch (gs->type) {
1478 case GREP_SOURCE_FILE:
1479 return grep_source_load_file(gs);
1480 case GREP_SOURCE_SHA1:
1481 return grep_source_load_sha1(gs);
1482 case GREP_SOURCE_BUF:
1483 return gs->buf ? 0 : -1;
1484 }
1485 die("BUG: invalid grep_source type");
1486}
1487
1488void grep_source_load_driver(struct grep_source *gs)
1489{
1490 if (gs->driver)
1491 return;
1492
1493 grep_attr_lock();
1494 gs->driver = userdiff_find_by_path(gs->name);
1495 if (!gs->driver)
1496 gs->driver = userdiff_find_by_name("default");
1497 grep_attr_unlock();
1498}
1499
1500int grep_source_is_binary(struct grep_source *gs)
1501{
1502 grep_source_load_driver(gs);
1503 if (gs->driver->binary != -1)
1504 return gs->driver->binary;
1505
1506 if (!grep_source_load(gs))
1507 return buffer_is_binary(gs->buf, gs->size);
1508
1509 return 0;
1510}