1 /* $NetBSD: util.c,v 1.9 2011/02/27 17:33:37 joerg Exp $ */
3 /* $OpenBSD: util.c,v 1.39 2010/07/02 22:18:03 tedu Exp $ */
6 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
8 * Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
9 * Copyright (C) 2008-2010 Gabor Kovesdan <gabor@FreeBSD.org>
10 * Copyright (C) 2017 Kyle Evans <kevans@FreeBSD.org>
11 * All rights reserved.
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
39 #include <sys/types.h>
55 #ifndef WITHOUT_FASTMATCH
56 #include "fastmatch.h"
60 static bool first_match = true;
63 * Parsing context; used to hold things like matches made and
67 regmatch_t matches[MAX_MATCHES]; /* Matches made */
68 /* XXX TODO: This should be a chunk, not a line */
69 struct str ln; /* Current line */
70 size_t lnstart; /* Position in line */
71 size_t matchidx; /* Latest match index */
72 int printed; /* Metadata printed? */
73 bool binary; /* Binary file? */
77 * Match printing context
80 long long tail; /* Number of trailing lines to record */
81 int last_outed; /* Number of lines since last output */
82 bool doctx; /* Printing context? */
83 bool printmatch; /* Printing matches? */
84 bool same_file; /* Same file as previously printed? */
87 static void procmatch_match(struct mprintc *mc, struct parsec *pc);
88 static void procmatch_nomatch(struct mprintc *mc, struct parsec *pc);
89 static bool procmatches(struct mprintc *mc, struct parsec *pc, bool matched);
90 #ifdef WITH_INTERNAL_NOSPEC
91 static int litexec(const struct pat *pat, const char *string,
92 size_t nmatch, regmatch_t pmatch[]);
94 static int procline(struct parsec *pc);
95 static void printline(struct parsec *pc, int sep);
96 static void printline_metadata(struct str *line, int sep);
99 file_matching(const char *fname)
101 char *fname_base, *fname_buf;
104 ret = finclude ? false : true;
105 fname_buf = strdup(fname);
106 if (fname_buf == NULL)
108 fname_base = basename(fname_buf);
110 for (unsigned int i = 0; i < fpatterns; ++i) {
111 if (fnmatch(fpattern[i].pat, fname, 0) == 0 ||
112 fnmatch(fpattern[i].pat, fname_base, 0) == 0)
114 * The last pattern matched wins exclusion/inclusion
115 * rights, so we can't reasonably bail out early here.
117 ret = (fpattern[i].mode != EXCL_PAT);
124 dir_matching(const char *dname)
128 ret = dinclude ? false : true;
130 for (unsigned int i = 0; i < dpatterns; ++i) {
131 if (dname != NULL && fnmatch(dpattern[i].pat, dname, 0) == 0)
133 * The last pattern matched wins exclusion/inclusion
134 * rights, so we can't reasonably bail out early here.
136 ret = (dpattern[i].mode != EXCL_PAT);
142 * Processes a directory when a recursive search is performed with
143 * the -R option. Each appropriate file is passed to procfile().
146 grep_tree(char **argv)
152 const char *wd[] = { ".", NULL };
158 fts_flags = FTS_COMFOLLOW;
161 fts_flags = FTS_PHYSICAL;
164 fts_flags = FTS_LOGICAL;
167 fts_flags |= FTS_NOSTAT | FTS_NOCHDIR;
169 fts = fts_open((argv[0] == NULL) ?
170 __DECONST(char * const *, wd) : argv, fts_flags, NULL);
173 while ((p = fts_read(fts)) != NULL) {
174 switch (p->fts_info) {
180 warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
185 if (dexclude || dinclude)
186 if (!dir_matching(p->fts_name) ||
187 !dir_matching(p->fts_path))
188 fts_set(fts, p, FTS_SKIP);
191 /* Print a warning for recursive directory loop */
192 warnx("warning: %s: recursive directory loop",
196 /* Check for file exclusion/inclusion */
198 if (fexclude || finclude)
199 ok &= file_matching(p->fts_path);
202 c += procfile(p->fts_path);
212 procmatch_match(struct mprintc *mc, struct parsec *pc)
216 if (!first_match && (!mc->same_file || mc->last_outed > 0))
223 /* Print the matching line, but only if not quiet/binary */
224 if (mc->printmatch) {
226 while (pc->matchidx >= MAX_MATCHES) {
227 /* Reset matchidx and try again */
229 if (procline(pc) == 0)
235 mc->same_file = true;
241 procmatch_nomatch(struct mprintc *mc, struct parsec *pc)
244 /* Deal with any -A context as needed */
246 grep_printline(&pc->ln, '-');
250 } else if (Bflag == 0 || (Bflag > 0 && enqueue(&pc->ln)))
252 * Enqueue non-matching lines for -B context. If we're not
253 * actually doing -B context or if the enqueue resulted in a
254 * line being rotated out, then go ahead and increment
255 * last_outed to signify a gap between context/match.
261 * Process any matches in the current parsing context, return a boolean
262 * indicating whether we should halt any further processing or not. 'true' to
263 * continue processing, 'false' to halt.
266 procmatches(struct mprintc *mc, struct parsec *pc, bool matched)
270 * XXX TODO: This should loop over pc->matches and handle things on a
271 * line-by-line basis, setting up a `struct str` as needed.
273 /* Deal with any -B context or context separators */
275 procmatch_match(mc, pc);
277 /* Count the matches if we have a match limit */
279 /* XXX TODO: Decrement by number of matched lines */
281 if (mflag && mcount <= 0)
284 } else if (mc->doctx)
285 procmatch_nomatch(mc, pc);
291 * Opens a file and processes it. Each file is processed line-by-line
292 * passing the lines to procline().
295 procfile(const char *fn)
304 if (strcmp(fn, "-") == 0) {
305 fn = label != NULL ? label : getstr(1);
308 if (stat(fn, &sb) == 0) {
309 /* Check if we need to process the file */
310 s = sb.st_mode & S_IFMT;
311 if (dirbehave == DIR_SKIP && s == S_IFDIR)
313 if (devbehave == DEV_SKIP && (s == S_IFIFO ||
314 s == S_IFCHR || s == S_IFBLK || s == S_IFSOCK))
326 pc.ln.file = grep_strdup(fn);
331 pc.binary = f->binary;
332 memset(&mc, 0, sizeof(mc));
333 mc.printmatch = true;
334 if ((pc.binary && binbehave == BINFILE_BIN) || cflag || qflag ||
336 mc.printmatch = false;
337 if (mc.printmatch && (Aflag != 0 || Bflag != 0))
341 for (c = 0; c == 0 || !(lflag || qflag); ) {
343 * XXX TODO: We need to revisit this in a chunking world. We're
344 * not going to be doing per-line statistics because of the
345 * overhead involved. procmatches can figure that stuff out as
347 /* Reset per-line statistics */
352 pc.ln.off += pc.ln.len + 1;
353 /* XXX TODO: Grab a chunk */
354 if ((pc.ln.dat = grep_fgetln(f, &pc.ln.len)) == NULL ||
358 if (pc.ln.len > 0 && pc.ln.dat[pc.ln.len - 1] == fileeol)
362 /* Return if we need to skip a binary file */
363 if (pc.binary && binbehave == BINFILE_SKIP) {
370 if ((t = procline(&pc)) == 0)
373 /* Halt processing if we hit our match limit */
374 if (!procmatches(&mc, &pc, t == 0))
383 printf("%s:", pc.ln.file);
386 if (lflag && !qflag && c != 0)
387 printf("%s%c", fn, nullflag ? 0 : '\n');
388 if (Lflag && !qflag && c == 0)
389 printf("%s%c", fn, nullflag ? 0 : '\n');
390 if (c && !cflag && !lflag && !Lflag &&
391 binbehave == BINFILE_BIN && f->binary && !qflag)
392 printf(getstr(8), fn);
399 #ifdef WITH_INTERNAL_NOSPEC
401 * Internal implementation of literal string search within a string, modeled
402 * after regexec(3), for use when the regex(3) implementation doesn't offer
403 * either REG_NOSPEC or REG_LITERAL. This does not apply in the default FreeBSD
404 * config, but in other scenarios such as building against libgnuregex or on
405 * some non-FreeBSD OSes.
408 litexec(const struct pat *pat, const char *string, size_t nmatch,
411 char *(*strstr_fn)(const char *, const char *);
414 size_t idx, n, ofs, stringlen;
416 if (cflags & REG_ICASE)
417 strstr_fn = strcasestr;
421 ofs = pmatch[0].rm_so;
422 stringlen = pmatch[0].rm_eo;
423 if (ofs >= stringlen)
424 return (REG_NOMATCH);
425 subject = strndup(string, stringlen);
428 for (n = 0; ofs < stringlen;) {
429 search = (subject + ofs);
430 if ((unsigned long)pat->len > strlen(search))
432 sub = strstr_fn(search, pat->pat);
434 * Ignoring the empty string possibility due to context: grep optimizes
435 * for empty patterns and will never reach this point.
440 /* Fill in pmatch if necessary */
442 pmatch[idx].rm_so = ofs + (sub - search);
443 pmatch[idx].rm_eo = pmatch[idx].rm_so + pat->len;
446 ofs = pmatch[idx].rm_so + 1;
448 /* We only needed to know if we match or not */
452 if (n > 0 && nmatch > 0)
453 for (n = idx; n < nmatch; ++n)
454 pmatch[n].rm_so = pmatch[n].rm_eo = -1;
456 return (n > 0 ? 0 : REG_NOMATCH);
458 #endif /* WITH_INTERNAL_NOSPEC */
460 #define iswword(x) (iswalnum((x)) || (x) == L'_')
463 * Processes a line comparing it with the specified patterns. Each pattern
464 * is looped to be compared along with the full string, saving each and every
465 * match, which is necessary to colorize the output and to count the
466 * matches. The matching lines are passed to printline() to display the
467 * appropriate output.
470 procline(struct parsec *pc)
472 regmatch_t pmatch, lastmatch, chkmatch;
473 wchar_t wbegin, wend;
476 int c = 0, r = 0, lastmatches = 0, leflags = eflags;
477 size_t startm = 0, matchidx;
480 matchidx = pc->matchidx;
482 /* Special case: empty pattern with -w flag, check first character */
483 if (matchall && wflag) {
487 if (sscanf(&pc->ln.dat[0], "%lc", &wend) != 1 || iswword(wend))
496 /* Initialize to avoid a false positive warning from GCC. */
497 lastmatch.rm_so = lastmatch.rm_eo = 0;
499 /* Loop to process the whole line */
500 while (st <= pc->ln.len) {
504 if (st > 0 && pc->ln.dat[st - 1] != fileeol)
505 leflags |= REG_NOTBOL;
506 /* Loop to compare with all the patterns */
507 for (i = 0; i < patterns; i++) {
509 pmatch.rm_eo = pc->ln.len;
510 #ifdef WITH_INTERNAL_NOSPEC
511 if (grepbehave == GREP_FIXED)
512 r = litexec(&pattern[i], pc->ln.dat, 1, &pmatch);
515 #ifndef WITHOUT_FASTMATCH
516 if (fg_pattern[i].pattern)
517 r = fastexec(&fg_pattern[i],
518 pc->ln.dat, 1, &pmatch, leflags);
521 r = regexec(&r_pattern[i], pc->ln.dat, 1,
525 /* Check for full match */
526 if (xflag && (pmatch.rm_so != 0 ||
527 (size_t)pmatch.rm_eo != pc->ln.len))
529 /* Check for whole word match */
530 #ifndef WITHOUT_FASTMATCH
531 if (wflag || fg_pattern[i].word) {
535 wbegin = wend = L' ';
536 if (pmatch.rm_so != 0 &&
537 sscanf(&pc->ln.dat[pmatch.rm_so - 1],
538 "%lc", &wbegin) != 1)
540 else if ((size_t)pmatch.rm_eo !=
542 sscanf(&pc->ln.dat[pmatch.rm_eo],
545 else if (iswword(wbegin) ||
549 * If we're doing whole word matching and we
550 * matched once, then we should try the pattern
551 * again after advancing just past the start of
552 * the earliest match. This allows the pattern
553 * to match later on in the line and possibly
554 * still match a whole word.
556 if (r == REG_NOMATCH &&
557 (retry == pc->lnstart ||
558 (unsigned int)pmatch.rm_so + 1 < retry))
559 retry = pmatch.rm_so + 1;
560 if (r == REG_NOMATCH)
570 * Replace previous match if the new one is earlier
571 * and/or longer. This will lead to some amount of
572 * extra work if -o/--color are specified, but it's
573 * worth it from a correctness point of view.
575 if (matchidx > startm) {
576 chkmatch = pc->matches[matchidx - 1];
577 if (pmatch.rm_so < chkmatch.rm_so ||
578 (pmatch.rm_so == chkmatch.rm_so &&
579 (pmatch.rm_eo - pmatch.rm_so) >
580 (chkmatch.rm_eo - chkmatch.rm_so))) {
581 pc->matches[matchidx - 1] = pmatch;
585 /* Advance as normal if not */
586 pc->matches[matchidx++] = pmatch;
589 /* avoid excessive matching - skip further patterns */
590 if ((color == NULL && !oflag) || qflag || lflag ||
591 matchidx >= MAX_MATCHES) {
599 * Advance to just past the start of the earliest match, try
600 * again just in case we still have a chance to match later in
603 if (lastmatches == 0 && retry > pc->lnstart) {
608 /* XXX TODO: We will need to keep going, since we're chunky */
609 /* One pass if we are not recording matches */
610 if (!wflag && ((color == NULL && !oflag) || qflag || lflag || Lflag))
613 /* If we didn't have any matches or REG_NOSUB set */
614 if (lastmatches == 0 || (cflags & REG_NOSUB))
617 if (lastmatches == 0)
620 else if (st == nst && lastmatch.rm_so == lastmatch.rm_eo)
621 /* Zero-length match -- advance one more so we don't get stuck */
624 /* Advance st based on previous matches */
629 /* Reflect the new matchidx in the context */
630 pc->matchidx = matchidx;
637 * Safe malloc() for internal use.
640 grep_malloc(size_t size)
644 if ((ptr = malloc(size)) == NULL)
650 * Safe calloc() for internal use.
653 grep_calloc(size_t nmemb, size_t size)
657 if ((ptr = calloc(nmemb, size)) == NULL)
663 * Safe realloc() for internal use.
666 grep_realloc(void *ptr, size_t size)
669 if ((ptr = realloc(ptr, size)) == NULL)
675 * Safe strdup() for internal use.
678 grep_strdup(const char *str)
682 if ((ret = strdup(str)) == NULL)
688 * Print an entire line as-is, there are no inline matches to consider. This is
689 * used for printing context.
691 void grep_printline(struct str *line, int sep) {
692 printline_metadata(line, sep);
693 fwrite(line->dat, line->len, 1, stdout);
698 printline_metadata(struct str *line, int sep)
705 fputs(line->file, stdout);
708 printf("%s", line->file);
715 printf("%d", line->line_no);
721 printf("%lld", (long long)(line->off + line->boff));
729 * Prints a matching line according to the command line options.
732 printline(struct parsec *pc, int sep)
738 /* If matchall, everything matches but don't actually print for -o */
739 if (oflag && matchall)
742 matchidx = pc->matchidx;
745 if ((oflag || color) && matchidx > 0) {
746 /* Only print metadata once per line if --color */
747 if (!oflag && pc->printed == 0)
748 printline_metadata(&pc->ln, sep);
749 for (i = 0; i < matchidx; i++) {
750 match = pc->matches[i];
751 /* Don't output zero length matches */
752 if (match.rm_so == match.rm_eo)
755 * Metadata is printed on a per-line basis, so every
756 * match gets file metadata with the -o flag.
759 pc->ln.boff = match.rm_so;
760 printline_metadata(&pc->ln, sep);
762 fwrite(pc->ln.dat + a, match.rm_so - a, 1,
765 fprintf(stdout, "\33[%sm\33[K", color);
766 fwrite(pc->ln.dat + match.rm_so,
767 match.rm_eo - match.rm_so, 1, stdout);
769 fprintf(stdout, "\33[m\33[K");
775 if (pc->ln.len - a > 0)
776 fwrite(pc->ln.dat + a, pc->ln.len - a, 1,
781 grep_printline(&pc->ln, sep);