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