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 * Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
7 * Copyright (C) 2008-2010 Gabor Kovesdan <gabor@FreeBSD.org>
8 * Copyright (C) 2017 Kyle Evans <kevans@FreeBSD.org>
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
37 #include <sys/types.h>
53 #ifndef WITHOUT_FASTMATCH
54 #include "fastmatch.h"
58 static bool first_match = true;
61 * Parsing context; used to hold things like matches made and
65 regmatch_t matches[MAX_MATCHES]; /* Matches made */
66 struct str ln; /* Current line */
67 size_t lnstart; /* Position in line */
68 size_t matchidx; /* Latest match index */
69 int printed; /* Metadata printed? */
70 bool binary; /* Binary file? */
74 static int procline(struct parsec *pc);
75 static void printline(struct parsec *pc, int sep);
76 static void printline_metadata(struct str *line, int sep);
79 file_matching(const char *fname)
81 char *fname_base, *fname_buf;
84 ret = finclude ? false : true;
85 fname_buf = strdup(fname);
86 if (fname_buf == NULL)
88 fname_base = basename(fname_buf);
90 for (unsigned int i = 0; i < fpatterns; ++i) {
91 if (fnmatch(fpattern[i].pat, fname, 0) == 0 ||
92 fnmatch(fpattern[i].pat, fname_base, 0) == 0) {
93 if (fpattern[i].mode == EXCL_PAT) {
105 dir_matching(const char *dname)
109 ret = dinclude ? false : true;
111 for (unsigned int i = 0; i < dpatterns; ++i) {
113 fnmatch(dpattern[i].pat, dname, 0) == 0) {
114 if (dpattern[i].mode == EXCL_PAT)
124 * Processes a directory when a recursive search is performed with
125 * the -R option. Each appropriate file is passed to procfile().
128 grep_tree(char **argv)
134 const char *wd[] = { ".", NULL };
140 fts_flags = FTS_COMFOLLOW;
143 fts_flags = FTS_PHYSICAL;
146 fts_flags = FTS_LOGICAL;
150 fts_flags |= FTS_NOSTAT | FTS_NOCHDIR;
152 fts = fts_open((argv[0] == NULL) ?
153 __DECONST(char * const *, wd) : argv, fts_flags, NULL);
156 while ((p = fts_read(fts)) != NULL) {
157 switch (p->fts_info) {
163 warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
168 if (dexclude || dinclude)
169 if (!dir_matching(p->fts_name) ||
170 !dir_matching(p->fts_path))
171 fts_set(fts, p, FTS_SKIP);
174 /* Print a warning for recursive directory loop */
175 warnx("warning: %s: recursive directory loop",
179 /* Check for file exclusion/inclusion */
181 if (fexclude || finclude)
182 ok &= file_matching(p->fts_path);
185 c += procfile(p->fts_path);
195 * Opens a file and processes it. Each file is processed line-by-line
196 * passing the lines to procline().
199 procfile(const char *fn)
207 int c, last_outed, t;
208 bool doctx, printmatch, same_file;
210 if (strcmp(fn, "-") == 0) {
211 fn = label != NULL ? label : getstr(1);
214 if (!stat(fn, &sb)) {
215 /* Check if we need to process the file */
216 s = sb.st_mode & S_IFMT;
217 if (s == S_IFDIR && dirbehave == DIR_SKIP)
219 if ((s == S_IFIFO || s == S_IFCHR || s == S_IFBLK
220 || s == S_IFSOCK) && devbehave == DEV_SKIP)
234 pc.ln.file = grep_malloc(strlen(fn) + 1);
235 strcpy(pc.ln.file, fn);
240 pc.binary = f->binary;
247 if ((pc.binary && binbehave == BINFILE_BIN) || cflag || qflag ||
250 if (printmatch && (Aflag != 0 || Bflag != 0))
254 for (c = 0; c == 0 || !(lflag || qflag); ) {
255 /* Reset per-line statistics */
260 pc.ln.off += pc.ln.len + 1;
261 if ((pc.ln.dat = grep_fgetln(f, &pc.ln.len)) == NULL ||
265 if (pc.ln.len > 0 && pc.ln.dat[pc.ln.len - 1] == fileeol)
269 /* Return if we need to skip a binary file */
270 if (pc.binary && binbehave == BINFILE_SKIP) {
277 if ((t = procline(&pc)) == 0)
280 /* Deal with any -B context or context separators */
281 if (t == 0 && doctx) {
282 if (!first_match && (!same_file || last_outed > 0))
288 /* Print the matching line, but only if not quiet/binary */
289 if (t == 0 && printmatch) {
291 while (pc.matchidx >= MAX_MATCHES) {
292 /* Reset matchidx and try again */
294 if (procline(&pc) == 0)
303 if (t != 0 && doctx) {
304 /* Deal with any -A context */
306 grep_printline(&pc.ln, '-');
312 * Enqueue non-matching lines for -B context.
313 * If we're not actually doing -B context or if
314 * the enqueue resulted in a line being rotated
315 * out, then go ahead and increment last_outed
316 * to signify a gap between context/match.
318 if (Bflag == 0 || (Bflag > 0 && enqueue(ln)))
323 /* Count the matches if we have a match limit */
324 if (t == 0 && mflag) {
326 if (mflag && mcount <= 0)
337 printf("%s:", pc.ln.file);
340 if (lflag && !qflag && c != 0)
341 printf("%s%c", fn, nullflag ? 0 : '\n');
342 if (Lflag && !qflag && c == 0)
343 printf("%s%c", fn, nullflag ? 0 : '\n');
344 if (c && !cflag && !lflag && !Lflag &&
345 binbehave == BINFILE_BIN && f->binary && !qflag)
346 printf(getstr(8), fn);
353 #define iswword(x) (iswalnum((x)) || (x) == L'_')
356 * Processes a line comparing it with the specified patterns. Each pattern
357 * is looped to be compared along with the full string, saving each and every
358 * match, which is necessary to colorize the output and to count the
359 * matches. The matching lines are passed to printline() to display the
360 * appropriate output.
363 procline(struct parsec *pc)
365 regmatch_t pmatch, lastmatch, chkmatch;
366 wchar_t wbegin, wend;
369 int c = 0, r = 0, lastmatches = 0, leflags = eflags;
370 size_t startm = 0, matchidx;
373 matchidx = pc->matchidx;
375 /* Special case: empty pattern with -w flag, check first character */
376 if (matchall && wflag) {
380 if (sscanf(&pc->ln.dat[0], "%lc", &wend) != 1 || iswword(wend))
389 /* Initialize to avoid a false positive warning from GCC. */
390 lastmatch.rm_so = lastmatch.rm_eo = 0;
392 /* Loop to process the whole line */
393 while (st <= pc->ln.len) {
397 if (st > 0 && pc->ln.dat[st - 1] != fileeol)
398 leflags |= REG_NOTBOL;
399 /* Loop to compare with all the patterns */
400 for (i = 0; i < patterns; i++) {
402 pmatch.rm_eo = pc->ln.len;
403 #ifndef WITHOUT_FASTMATCH
404 if (fg_pattern[i].pattern)
405 r = fastexec(&fg_pattern[i],
406 pc->ln.dat, 1, &pmatch, leflags);
409 r = regexec(&r_pattern[i], pc->ln.dat, 1,
413 /* Check for full match */
414 if (xflag && (pmatch.rm_so != 0 ||
415 (size_t)pmatch.rm_eo != pc->ln.len))
417 /* Check for whole word match */
418 #ifndef WITHOUT_FASTMATCH
419 if (wflag || fg_pattern[i].word) {
423 wbegin = wend = L' ';
424 if (pmatch.rm_so != 0 &&
425 sscanf(&pc->ln.dat[pmatch.rm_so - 1],
426 "%lc", &wbegin) != 1)
428 else if ((size_t)pmatch.rm_eo !=
430 sscanf(&pc->ln.dat[pmatch.rm_eo],
433 else if (iswword(wbegin) ||
437 * If we're doing whole word matching and we
438 * matched once, then we should try the pattern
439 * again after advancing just past the start of
440 * the earliest match. This allows the pattern
441 * to match later on in the line and possibly
442 * still match a whole word.
444 if (r == REG_NOMATCH &&
445 (retry == pc->lnstart ||
446 pmatch.rm_so + 1 < retry))
447 retry = pmatch.rm_so + 1;
448 if (r == REG_NOMATCH)
458 * Replace previous match if the new one is earlier
459 * and/or longer. This will lead to some amount of
460 * extra work if -o/--color are specified, but it's
461 * worth it from a correctness point of view.
463 if (matchidx > startm) {
464 chkmatch = pc->matches[matchidx - 1];
465 if (pmatch.rm_so < chkmatch.rm_so ||
466 (pmatch.rm_so == chkmatch.rm_so &&
467 (pmatch.rm_eo - pmatch.rm_so) >
468 (chkmatch.rm_eo - chkmatch.rm_so))) {
469 pc->matches[matchidx - 1] = pmatch;
473 /* Advance as normal if not */
474 pc->matches[matchidx++] = pmatch;
477 /* avoid excessive matching - skip further patterns */
478 if ((color == NULL && !oflag) || qflag || lflag ||
479 matchidx >= MAX_MATCHES) {
487 * Advance to just past the start of the earliest match, try
488 * again just in case we still have a chance to match later in
491 if (lastmatches == 0 && retry > pc->lnstart) {
496 /* One pass if we are not recording matches */
497 if (!wflag && ((color == NULL && !oflag) || qflag || lflag || Lflag))
500 /* If we didn't have any matches or REG_NOSUB set */
501 if (lastmatches == 0 || (cflags & REG_NOSUB))
504 if (lastmatches == 0)
507 else if (st == nst && lastmatch.rm_so == lastmatch.rm_eo)
508 /* Zero-length match -- advance one more so we don't get stuck */
511 /* Advance st based on previous matches */
516 /* Reflect the new matchidx in the context */
517 pc->matchidx = matchidx;
524 * Safe malloc() for internal use.
527 grep_malloc(size_t size)
531 if ((ptr = malloc(size)) == NULL)
537 * Safe calloc() for internal use.
540 grep_calloc(size_t nmemb, size_t size)
544 if ((ptr = calloc(nmemb, size)) == NULL)
550 * Safe realloc() for internal use.
553 grep_realloc(void *ptr, size_t size)
556 if ((ptr = realloc(ptr, size)) == NULL)
562 * Safe strdup() for internal use.
565 grep_strdup(const char *str)
569 if ((ret = strdup(str)) == NULL)
575 * Print an entire line as-is, there are no inline matches to consider. This is
576 * used for printing context.
578 void grep_printline(struct str *line, int sep) {
579 printline_metadata(line, sep);
580 fwrite(line->dat, line->len, 1, stdout);
585 printline_metadata(struct str *line, int sep)
592 fputs(line->file, stdout);
595 printf("%s", line->file);
602 printf("%d", line->line_no);
608 printf("%lld", (long long)(line->off + line->boff));
616 * Prints a matching line according to the command line options.
619 printline(struct parsec *pc, int sep)
625 /* If matchall, everything matches but don't actually print for -o */
626 if (oflag && matchall)
629 matchidx = pc->matchidx;
632 if ((oflag || color) && matchidx > 0) {
633 /* Only print metadata once per line if --color */
634 if (!oflag && pc->printed == 0)
635 printline_metadata(&pc->ln, sep);
636 for (i = 0; i < matchidx; i++) {
637 match = pc->matches[i];
638 /* Don't output zero length matches */
639 if (match.rm_so == match.rm_eo)
642 * Metadata is printed on a per-line basis, so every
643 * match gets file metadata with the -o flag.
646 pc->ln.boff = match.rm_so;
647 printline_metadata(&pc->ln, sep);
649 fwrite(pc->ln.dat + a, match.rm_so - a, 1,
652 fprintf(stdout, "\33[%sm\33[K", color);
653 fwrite(pc->ln.dat + match.rm_so,
654 match.rm_eo - match.rm_so, 1, stdout);
656 fprintf(stdout, "\33[m\33[K");
662 if (pc->ln.len - a > 0)
663 fwrite(pc->ln.dat + a, pc->ln.len - a, 1,
668 grep_printline(&pc->ln, sep);