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