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