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>
57 static bool first_match = true;
60 * Match printing context
63 long long tail; /* Number of trailing lines to record */
64 int last_outed; /* Number of lines since last output */
65 bool doctx; /* Printing context? */
66 bool printmatch; /* Printing matches? */
67 bool same_file; /* Same file as previously printed? */
70 static void procmatch_match(struct mprintc *mc, struct parsec *pc);
71 static void procmatch_nomatch(struct mprintc *mc, struct parsec *pc);
72 static bool procmatches(struct mprintc *mc, struct parsec *pc, bool matched);
73 #ifdef WITH_INTERNAL_NOSPEC
74 static int litexec(const struct pat *pat, const char *string,
75 size_t nmatch, regmatch_t pmatch[]);
77 static bool procline(struct parsec *pc);
78 static void printline(struct parsec *pc, int sep);
79 static void printline_metadata(struct str *line, int sep);
82 file_matching(const char *fname)
84 char *fname_base, *fname_buf;
87 ret = finclude ? false : true;
88 fname_buf = strdup(fname);
89 if (fname_buf == NULL)
91 fname_base = basename(fname_buf);
93 for (unsigned int i = 0; i < fpatterns; ++i) {
94 if (fnmatch(fpattern[i].pat, fname, 0) == 0 ||
95 fnmatch(fpattern[i].pat, fname_base, 0) == 0)
97 * The last pattern matched wins exclusion/inclusion
98 * rights, so we can't reasonably bail out early here.
100 ret = (fpattern[i].mode != EXCL_PAT);
107 dir_matching(const char *dname)
111 ret = dinclude ? false : true;
113 for (unsigned int i = 0; i < dpatterns; ++i) {
114 if (dname != NULL && fnmatch(dpattern[i].pat, dname, 0) == 0)
116 * The last pattern matched wins exclusion/inclusion
117 * rights, so we can't reasonably bail out early here.
119 ret = (dpattern[i].mode != EXCL_PAT);
125 * Processes a directory when a recursive search is performed with
126 * the -R option. Each appropriate file is passed to procfile().
129 grep_tree(char **argv)
135 const char *wd[] = { ".", NULL };
139 /* This switch effectively initializes 'fts_flags' */
142 fts_flags = FTS_COMFOLLOW;
145 fts_flags = FTS_PHYSICAL;
148 fts_flags = FTS_LOGICAL;
151 fts_flags |= FTS_NOSTAT | FTS_NOCHDIR;
153 fts = fts_open((argv[0] == NULL) ?
154 __DECONST(char * const *, wd) : argv, fts_flags, NULL);
157 while (errno = 0, (p = fts_read(fts)) != NULL) {
158 switch (p->fts_info) {
164 warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
169 if (dexclude || dinclude)
170 if (!dir_matching(p->fts_name) ||
171 !dir_matching(p->fts_path))
172 fts_set(fts, p, FTS_SKIP);
175 /* Print a warning for recursive directory loop */
176 warnx("warning: %s: recursive directory loop",
180 /* Check for file exclusion/inclusion */
182 if (fexclude || finclude)
183 ok &= file_matching(p->fts_path);
185 if (ok && procfile(p->fts_path))
198 procmatch_match(struct mprintc *mc, struct parsec *pc)
202 if (!first_match && (!mc->same_file || mc->last_outed > 0))
209 /* Print the matching line, but only if not quiet/binary */
210 if (mc->printmatch) {
212 while (pc->matchidx >= MAX_MATCHES) {
213 /* Reset matchidx and try again */
215 if (procline(pc) == !vflag)
221 mc->same_file = true;
227 procmatch_nomatch(struct mprintc *mc, struct parsec *pc)
230 /* Deal with any -A context as needed */
232 grep_printline(&pc->ln, '-');
236 } else if (Bflag == 0 || (Bflag > 0 && enqueue(&pc->ln)))
238 * Enqueue non-matching lines for -B context. If we're not
239 * actually doing -B context or if the enqueue resulted in a
240 * line being rotated out, then go ahead and increment
241 * last_outed to signify a gap between context/match.
247 * Process any matches in the current parsing context, return a boolean
248 * indicating whether we should halt any further processing or not. 'true' to
249 * continue processing, 'false' to halt.
252 procmatches(struct mprintc *mc, struct parsec *pc, bool matched)
256 * XXX TODO: This should loop over pc->matches and handle things on a
257 * line-by-line basis, setting up a `struct str` as needed.
259 /* Deal with any -B context or context separators */
261 procmatch_match(mc, pc);
263 /* Count the matches if we have a match limit */
265 /* XXX TODO: Decrement by number of matched lines */
270 } else if (mc->doctx)
271 procmatch_nomatch(mc, pc);
277 * Opens a file and processes it. Each file is processed line-by-line
278 * passing the lines to procline().
281 procfile(const char *fn)
291 if (strcmp(fn, "-") == 0) {
292 fn = label != NULL ? label : errstr[1];
295 if (stat(fn, &sb) == 0) {
296 /* Check if we need to process the file */
297 s = sb.st_mode & S_IFMT;
298 if (dirbehave == DIR_SKIP && s == S_IFDIR)
300 if (devbehave == DEV_SKIP && (s == S_IFIFO ||
301 s == S_IFCHR || s == S_IFBLK || s == S_IFSOCK))
313 pc.ln.file = grep_strdup(fn);
318 pc.binary = f->binary;
320 memset(&mc, 0, sizeof(mc));
321 mc.printmatch = true;
322 if ((pc.binary && binbehave == BINFILE_BIN) || cflag || qflag ||
324 mc.printmatch = false;
325 if (mc.printmatch && (Aflag != 0 || Bflag != 0))
327 if (mc.printmatch && (Aflag != 0 || Bflag != 0 || mflag || nflag))
331 for (lines = 0; lines == 0 || !(lflag || qflag); ) {
333 * XXX TODO: We need to revisit this in a chunking world. We're
334 * not going to be doing per-line statistics because of the
335 * overhead involved. procmatches can figure that stuff out as
337 /* Reset per-line statistics */
342 pc.ln.off += pc.ln.len + 1;
343 /* XXX TODO: Grab a chunk */
344 if ((pc.ln.dat = grep_fgetln(f, &pc)) == NULL ||
348 if (pc.ln.len > 0 && pc.ln.dat[pc.ln.len - 1] == fileeol)
352 /* Return if we need to skip a binary file */
353 if (pc.binary && binbehave == BINFILE_SKIP) {
360 line_matched = procline(&pc) == !vflag;
364 /* Halt processing if we hit our match limit */
365 if (!procmatches(&mc, &pc, line_matched))
374 printf("%s:", pc.ln.file);
375 printf("%u\n", lines);
377 if (lflag && !qflag && lines != 0)
378 printf("%s%c", fn, nullflag ? 0 : '\n');
379 if (Lflag && !qflag && lines == 0)
380 printf("%s%c", fn, nullflag ? 0 : '\n');
381 if (lines != 0 && !cflag && !lflag && !Lflag &&
382 binbehave == BINFILE_BIN && f->binary && !qflag)
383 printf(errstr[7], fn);
390 #ifdef WITH_INTERNAL_NOSPEC
392 * Internal implementation of literal string search within a string, modeled
393 * after regexec(3), for use when the regex(3) implementation doesn't offer
394 * either REG_NOSPEC or REG_LITERAL. This does not apply in the default FreeBSD
395 * config, but in other scenarios such as building against libgnuregex or on
396 * some non-FreeBSD OSes.
399 litexec(const struct pat *pat, const char *string, size_t nmatch,
402 char *(*strstr_fn)(const char *, const char *);
405 size_t idx, n, ofs, stringlen;
407 if (cflags & REG_ICASE)
408 strstr_fn = strcasestr;
412 ofs = pmatch[0].rm_so;
413 stringlen = pmatch[0].rm_eo;
414 if (ofs >= stringlen)
415 return (REG_NOMATCH);
416 subject = strndup(string, stringlen);
419 for (n = 0; ofs < stringlen;) {
420 search = (subject + ofs);
421 if ((unsigned long)pat->len > strlen(search))
423 sub = strstr_fn(search, pat->pat);
425 * Ignoring the empty string possibility due to context: grep optimizes
426 * for empty patterns and will never reach this point.
431 /* Fill in pmatch if necessary */
433 pmatch[idx].rm_so = ofs + (sub - search);
434 pmatch[idx].rm_eo = pmatch[idx].rm_so + pat->len;
437 ofs = pmatch[idx].rm_so + 1;
439 /* We only needed to know if we match or not */
443 if (n > 0 && nmatch > 0)
444 for (n = idx; n < nmatch; ++n)
445 pmatch[n].rm_so = pmatch[n].rm_eo = -1;
447 return (n > 0 ? 0 : REG_NOMATCH);
449 #endif /* WITH_INTERNAL_NOSPEC */
451 #define iswword(x) (iswalnum((x)) || (x) == L'_')
454 * Processes a line comparing it with the specified patterns. Each pattern
455 * is looped to be compared along with the full string, saving each and every
456 * match, which is necessary to colorize the output and to count the
457 * matches. The matching lines are passed to printline() to display the
458 * appropriate output.
461 procline(struct parsec *pc)
463 regmatch_t pmatch, lastmatch, chkmatch;
464 wchar_t wbegin, wend;
467 int r = 0, leflags = eflags;
468 size_t startm = 0, matchidx;
470 bool lastmatched, matched;
472 matchidx = pc->matchidx;
475 * With matchall (empty pattern), we can try to take some shortcuts.
476 * Emtpy patterns trivially match every line except in the -w and -x
477 * cases. For -w (whole-word) cases, we only match if the first
478 * character isn't a word-character. For -x (whole-line) cases, we only
479 * match if the line is empty.
486 if (sscanf(&pc->ln.dat[0], "%lc", &wend) == 1 &&
493 * If we don't have any other patterns, we really don't match.
494 * If we do have other patterns, we must fall through and check
504 /* Initialize to avoid a false positive warning from GCC. */
505 lastmatch.rm_so = lastmatch.rm_eo = 0;
507 /* Loop to process the whole line */
508 while (st <= pc->ln.len) {
512 if (st > 0 && pc->ln.dat[st - 1] != fileeol)
513 leflags |= REG_NOTBOL;
514 /* Loop to compare with all the patterns */
515 for (i = 0; i < patterns; i++) {
517 pmatch.rm_eo = pc->ln.len;
518 #ifdef WITH_INTERNAL_NOSPEC
519 if (grepbehave == GREP_FIXED)
520 r = litexec(&pattern[i], pc->ln.dat, 1, &pmatch);
523 r = regexec(&r_pattern[i], pc->ln.dat, 1, &pmatch,
527 /* Check for full match */
528 if (xflag && (pmatch.rm_so != 0 ||
529 (size_t)pmatch.rm_eo != pc->ln.len))
531 /* Check for whole word match */
533 wbegin = wend = L' ';
534 if (pmatch.rm_so != 0 &&
535 sscanf(&pc->ln.dat[pmatch.rm_so - 1],
536 "%lc", &wbegin) != 1)
538 else if ((size_t)pmatch.rm_eo !=
540 sscanf(&pc->ln.dat[pmatch.rm_eo],
543 else if (iswword(wbegin) ||
547 * If we're doing whole word matching and we
548 * matched once, then we should try the pattern
549 * again after advancing just past the start of
550 * the earliest match. This allows the pattern
551 * to match later on in the line and possibly
552 * still match a whole word.
554 if (r == REG_NOMATCH &&
555 (retry == pc->lnstart ||
556 (unsigned int)pmatch.rm_so + 1 < retry))
557 retry = pmatch.rm_so + 1;
558 if (r == REG_NOMATCH)
568 * Replace previous match if the new one is earlier
569 * and/or longer. This will lead to some amount of
570 * extra work if -o/--color are specified, but it's
571 * worth it from a correctness point of view.
573 if (matchidx > startm) {
574 chkmatch = pc->matches[matchidx - 1];
575 if (pmatch.rm_so < chkmatch.rm_so ||
576 (pmatch.rm_so == chkmatch.rm_so &&
577 (pmatch.rm_eo - pmatch.rm_so) >
578 (chkmatch.rm_eo - chkmatch.rm_so))) {
579 pc->matches[matchidx - 1] = pmatch;
583 /* Advance as normal if not */
584 pc->matches[matchidx++] = pmatch;
587 /* avoid excessive matching - skip further patterns */
588 if ((color == NULL && !oflag) || qflag || lflag ||
589 matchidx >= MAX_MATCHES) {
597 * Advance to just past the start of the earliest match, try
598 * again just in case we still have a chance to match later in
601 if (!lastmatched && retry > pc->lnstart) {
606 /* XXX TODO: We will need to keep going, since we're chunky */
607 /* One pass if we are not recording matches */
608 if (!wflag && ((color == NULL && !oflag) || qflag || lflag || Lflag))
611 /* If we didn't have any matches or REG_NOSUB set */
612 if (!lastmatched || (cflags & REG_NOSUB))
618 else if (st == nst && lastmatch.rm_so == lastmatch.rm_eo)
619 /* Zero-length match -- advance one more so we don't get stuck */
622 /* Advance st based on previous matches */
627 /* Reflect the new matchidx in the context */
628 pc->matchidx = matchidx;
633 * Safe malloc() for internal use.
636 grep_malloc(size_t size)
640 if ((ptr = malloc(size)) == NULL)
646 * Safe calloc() for internal use.
649 grep_calloc(size_t nmemb, size_t size)
653 if ((ptr = calloc(nmemb, size)) == NULL)
659 * Safe realloc() for internal use.
662 grep_realloc(void *ptr, size_t size)
665 if ((ptr = realloc(ptr, size)) == NULL)
671 * Safe strdup() for internal use.
674 grep_strdup(const char *str)
678 if ((ret = strdup(str)) == NULL)
684 * Print an entire line as-is, there are no inline matches to consider. This is
685 * used for printing context.
687 void grep_printline(struct str *line, int sep) {
688 printline_metadata(line, sep);
689 fwrite(line->dat, line->len, 1, stdout);
694 printline_metadata(struct str *line, int sep)
701 fputs(line->file, stdout);
704 printf("%s", line->file);
711 printf("%d", line->line_no);
717 printf("%lld", (long long)(line->off + line->boff));
725 * Prints a matching line according to the command line options.
728 printline(struct parsec *pc, int sep)
734 /* If matchall, everything matches but don't actually print for -o */
735 if (oflag && matchall)
738 matchidx = pc->matchidx;
741 if ((oflag || color) && matchidx > 0) {
742 /* Only print metadata once per line if --color */
743 if (!oflag && pc->printed == 0)
744 printline_metadata(&pc->ln, sep);
745 for (i = 0; i < matchidx; i++) {
746 match = pc->matches[i];
747 /* Don't output zero length matches */
748 if (match.rm_so == match.rm_eo)
751 * Metadata is printed on a per-line basis, so every
752 * match gets file metadata with the -o flag.
755 pc->ln.boff = match.rm_so;
756 printline_metadata(&pc->ln, sep);
758 fwrite(pc->ln.dat + a, match.rm_so - a, 1,
761 fprintf(stdout, "\33[%sm\33[K", color);
762 fwrite(pc->ln.dat + match.rm_so,
763 match.rm_eo - match.rm_so, 1, stdout);
765 fprintf(stdout, "\33[m\33[K");
771 if (pc->ln.len - a > 0)
772 fwrite(pc->ln.dat + a, pc->ln.len - a, 1,
777 grep_printline(&pc->ln, sep);