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>
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
36 #include <sys/types.h>
52 #ifndef WITHOUT_FASTMATCH
53 #include "fastmatch.h"
57 static bool first_match = true;
60 * Parsing context; used to hold things like matches made and
64 regmatch_t matches[MAX_LINE_MATCHES]; /* Matches made */
65 struct str ln; /* Current line */
66 size_t matchidx; /* Latest used match index */
67 bool binary; /* Binary file? */
71 static int procline(struct parsec *pc);
72 static void printline(struct parsec *pc, int sep);
73 static void printline_metadata(struct str *line, int sep);
76 file_matching(const char *fname)
78 char *fname_base, *fname_buf;
81 ret = finclude ? false : true;
82 fname_buf = strdup(fname);
83 if (fname_buf == NULL)
85 fname_base = basename(fname_buf);
87 for (unsigned int i = 0; i < fpatterns; ++i) {
88 if (fnmatch(fpattern[i].pat, fname, 0) == 0 ||
89 fnmatch(fpattern[i].pat, fname_base, 0) == 0) {
90 if (fpattern[i].mode == EXCL_PAT) {
102 dir_matching(const char *dname)
106 ret = dinclude ? false : true;
108 for (unsigned int i = 0; i < dpatterns; ++i) {
110 fnmatch(dpattern[i].pat, dname, 0) == 0) {
111 if (dpattern[i].mode == EXCL_PAT)
121 * Processes a directory when a recursive search is performed with
122 * the -R option. Each appropriate file is passed to procfile().
125 grep_tree(char **argv)
131 const char *wd[] = { ".", NULL };
137 fts_flags = FTS_COMFOLLOW;
140 fts_flags = FTS_PHYSICAL;
143 fts_flags = FTS_LOGICAL;
147 fts_flags |= FTS_NOSTAT | FTS_NOCHDIR;
149 fts = fts_open((argv[0] == NULL) ?
150 __DECONST(char * const *, wd) : argv, fts_flags, NULL);
153 while ((p = fts_read(fts)) != NULL) {
154 switch (p->fts_info) {
160 warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
165 if (dexclude || dinclude)
166 if (!dir_matching(p->fts_name) ||
167 !dir_matching(p->fts_path))
168 fts_set(fts, p, FTS_SKIP);
171 /* Print a warning for recursive directory loop */
172 warnx("warning: %s: recursive directory loop",
176 /* Check for file exclusion/inclusion */
178 if (fexclude || finclude)
179 ok &= file_matching(p->fts_path);
182 c += procfile(p->fts_path);
192 * Opens a file and processes it. Each file is processed line-by-line
193 * passing the lines to procline().
196 procfile(const char *fn)
203 int c, last_outed, t, tail;
204 bool doctx, same_file;
206 if (strcmp(fn, "-") == 0) {
207 fn = label != NULL ? label : getstr(1);
210 if (!stat(fn, &sb)) {
211 /* Check if we need to process the file */
212 s = sb.st_mode & S_IFMT;
213 if (s == S_IFDIR && dirbehave == DIR_SKIP)
215 if ((s == S_IFIFO || s == S_IFCHR || s == S_IFBLK
216 || s == S_IFSOCK) && devbehave == DEV_SKIP)
230 pc.ln.file = grep_malloc(strlen(fn) + 1);
231 strcpy(pc.ln.file, fn);
235 pc.binary = f->binary;
240 if ((!pc.binary || binbehave != BINFILE_BIN) && !cflag && !qflag &&
241 !lflag && !Lflag && (Aflag != 0 || Bflag != 0))
246 for (c = 0; c == 0 || !(lflag || qflag); ) {
247 /* Reset match count for every line processed */
249 pc.ln.off += pc.ln.len + 1;
250 if ((pc.ln.dat = grep_fgetln(f, &pc.ln.len)) == NULL ||
252 if (pc.ln.line_no == 0 && matchall)
254 * An empty file with an empty pattern and the
255 * -w flag does not match
257 exit(matchall && wflag ? 1 : 0);
262 if (pc.ln.len > 0 && pc.ln.dat[pc.ln.len - 1] == fileeol)
266 /* Return if we need to skip a binary file */
267 if (pc.binary && binbehave == BINFILE_SKIP) {
274 if ((t = procline(&pc)) == 0)
277 /* Deal with any -B context or context separators */
278 if (t == 0 && doctx) {
279 if (!first_match && (!same_file || last_outed > 0))
285 /* Print the matching line, but only if not quiet/binary */
286 if (t == 0 && !qflag && !pc.binary) {
292 if (t != 0 && doctx) {
293 /* Deal with any -A context */
301 * Enqueue non-matching lines for -B context.
302 * If we're not actually doing -B context or if
303 * the enqueue resulted in a line being rotated
304 * out, then go ahead and increment last_outed
305 * to signify a gap between context/match.
307 if (Bflag == 0 || (Bflag > 0 && enqueue(ln)))
312 /* Count the matches if we have a match limit */
313 if (t == 0 && mflag) {
315 if (mflag && mcount <= 0)
326 printf("%s:", pc.ln.file);
329 if (lflag && !qflag && c != 0)
330 printf("%s%c", fn, nullflag ? 0 : '\n');
331 if (Lflag && !qflag && c == 0)
332 printf("%s%c", fn, nullflag ? 0 : '\n');
333 if (c && !cflag && !lflag && !Lflag &&
334 binbehave == BINFILE_BIN && f->binary && !qflag)
335 printf(getstr(8), fn);
342 #define iswword(x) (iswalnum((x)) || (x) == L'_')
345 * Processes a line comparing it with the specified patterns. Each pattern
346 * is looped to be compared along with the full string, saving each and every
347 * match, which is necessary to colorize the output and to count the
348 * matches. The matching lines are passed to printline() to display the
349 * appropriate output.
352 procline(struct parsec *pc)
354 regmatch_t pmatch, lastmatch, chkmatch;
355 wchar_t wbegin, wend;
356 size_t st = 0, nst = 0;
358 int c = 0, r = 0, lastmatches = 0, leflags = eflags;
359 size_t startm = 0, matchidx;
362 matchidx = pc->matchidx;
364 /* Special case: empty pattern with -w flag, check first character */
365 if (matchall && wflag) {
369 if (sscanf(&pc->ln.dat[0], "%lc", &wend) != 1 || iswword(wend))
376 /* Initialize to avoid a false positive warning from GCC. */
377 lastmatch.rm_so = lastmatch.rm_eo = 0;
379 /* Loop to process the whole line */
380 while (st <= pc->ln.len) {
385 leflags |= REG_NOTBOL;
386 /* Loop to compare with all the patterns */
387 for (i = 0; i < patterns; i++) {
389 pmatch.rm_eo = pc->ln.len;
390 #ifndef WITHOUT_FASTMATCH
391 if (fg_pattern[i].pattern)
392 r = fastexec(&fg_pattern[i],
393 pc->ln.dat, 1, &pmatch, leflags);
396 r = regexec(&r_pattern[i], pc->ln.dat, 1,
400 /* Check for full match */
401 if (xflag && (pmatch.rm_so != 0 ||
402 (size_t)pmatch.rm_eo != pc->ln.len))
404 /* Check for whole word match */
405 #ifndef WITHOUT_FASTMATCH
406 if (wflag || fg_pattern[i].word) {
410 wbegin = wend = L' ';
411 if (pmatch.rm_so != 0 &&
412 sscanf(&pc->ln.dat[pmatch.rm_so - 1],
413 "%lc", &wbegin) != 1)
415 else if ((size_t)pmatch.rm_eo !=
417 sscanf(&pc->ln.dat[pmatch.rm_eo],
420 else if (iswword(wbegin) ||
424 * If we're doing whole word matching and we
425 * matched once, then we should try the pattern
426 * again after advancing just past the start of
427 * the earliest match. This allows the pattern
428 * to match later on in the line and possibly
429 * still match a whole word.
431 if (r == REG_NOMATCH &&
432 (retry == 0 || pmatch.rm_so + 1 < retry))
433 retry = pmatch.rm_so + 1;
434 if (r == REG_NOMATCH)
445 * Replace previous match if the new one is earlier
446 * and/or longer. This will lead to some amount of
447 * extra work if -o/--color are specified, but it's
448 * worth it from a correctness point of view.
450 if (matchidx > startm) {
451 chkmatch = pc->matches[matchidx - 1];
452 if (pmatch.rm_so < chkmatch.rm_so ||
453 (pmatch.rm_so == chkmatch.rm_so &&
454 (pmatch.rm_eo - pmatch.rm_so) >
455 (chkmatch.rm_eo - chkmatch.rm_so))) {
456 pc->matches[matchidx - 1] = pmatch;
460 /* Advance as normal if not */
461 pc->matches[matchidx++] = pmatch;
464 /* avoid excessive matching - skip further patterns */
465 if ((color == NULL && !oflag) || qflag || lflag ||
466 matchidx >= MAX_LINE_MATCHES)
471 * Advance to just past the start of the earliest match, try
472 * again just in case we still have a chance to match later in
475 if (lastmatches == 0 && retry > 0) {
480 /* One pass if we are not recording matches */
481 if (!wflag && ((color == NULL && !oflag) || qflag || lflag || Lflag))
484 /* If we didn't have any matches or REG_NOSUB set */
485 if (lastmatches == 0 || (cflags & REG_NOSUB))
488 if (lastmatches == 0)
491 else if (st == nst && lastmatch.rm_so == lastmatch.rm_eo)
492 /* Zero-length match -- advance one more so we don't get stuck */
495 /* Advance st based on previous matches */
499 /* Reflect the new matchidx in the context */
500 pc->matchidx = matchidx;
507 * Safe malloc() for internal use.
510 grep_malloc(size_t size)
514 if ((ptr = malloc(size)) == NULL)
520 * Safe calloc() for internal use.
523 grep_calloc(size_t nmemb, size_t size)
527 if ((ptr = calloc(nmemb, size)) == NULL)
533 * Safe realloc() for internal use.
536 grep_realloc(void *ptr, size_t size)
539 if ((ptr = realloc(ptr, size)) == NULL)
545 * Safe strdup() for internal use.
548 grep_strdup(const char *str)
552 if ((ret = strdup(str)) == NULL)
558 * Print an entire line as-is, there are no inline matches to consider. This is
559 * used for printing context.
561 void grep_printline(struct str *line, int sep) {
562 printline_metadata(line, sep);
563 fwrite(line->dat, line->len, 1, stdout);
568 printline_metadata(struct str *line, int sep)
575 fputs(line->file, stdout);
578 printf("%s", line->file);
585 printf("%d", line->line_no);
591 printf("%lld", (long long)line->off);
599 * Prints a matching line according to the command line options.
602 printline(struct parsec *pc, int sep)
608 /* If matchall, everything matches but don't actually print for -o */
609 if (oflag && matchall)
612 matchidx = pc->matchidx;
615 if ((oflag || color) && matchidx > 0) {
616 printline_metadata(&pc->ln, sep);
617 for (i = 0; i < matchidx; i++) {
618 match = pc->matches[i];
619 /* Don't output zero length matches */
620 if (match.rm_so == match.rm_eo)
623 fwrite(pc->ln.dat + a, match.rm_so - a, 1,
626 fprintf(stdout, "\33[%sm\33[K", color);
627 fwrite(pc->ln.dat + match.rm_so,
628 match.rm_eo - match.rm_so, 1, stdout);
630 fprintf(stdout, "\33[m\33[K");
636 if (pc->ln.len - a > 0)
637 fwrite(pc->ln.dat + a, pc->ln.len - a, 1,
642 grep_printline(&pc->ln, sep);