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