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