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 #include "fastmatch.h"
55 static int linesqueued;
56 static int procline(struct str *l, int);
62 file_matching(const char *fname)
67 ret = finclude ? false : true;
68 fname_base = basename(fname);
70 for (unsigned int i = 0; i < fpatterns; ++i) {
71 if (fnmatch(fpattern[i].pat, fname, 0) == 0 ||
72 fnmatch(fpattern[i].pat, fname_base, 0) == 0) {
73 if (fpattern[i].mode == EXCL_PAT)
83 dir_matching(const char *dname)
87 ret = dinclude ? false : true;
89 for (unsigned int i = 0; i < dpatterns; ++i) {
91 fnmatch(dpattern[i].pat, dname, 0) == 0) {
92 if (dpattern[i].mode == EXCL_PAT)
102 * Processes a directory when a recursive search is performed with
103 * the -R option. Each appropriate file is passed to procfile().
106 grep_tree(char **argv)
112 const char *wd[] = { ".", NULL };
118 fts_flags = FTS_COMFOLLOW;
121 fts_flags = FTS_PHYSICAL;
124 fts_flags = FTS_LOGICAL;
128 fts_flags |= FTS_NOSTAT | FTS_NOCHDIR;
130 fts = fts_open((argv[0] == NULL) ?
131 __DECONST(char * const *, wd) : argv, fts_flags, NULL);
134 while ((p = fts_read(fts)) != NULL) {
135 switch (p->fts_info) {
141 warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
146 if (dexclude || dinclude)
147 if (!dir_matching(p->fts_name) ||
148 !dir_matching(p->fts_path))
149 fts_set(fts, p, FTS_SKIP);
152 /* Print a warning for recursive directory loop */
153 warnx("warning: %s: recursive directory loop",
157 /* Check for file exclusion/inclusion */
159 if (fexclude || finclude)
160 ok &= file_matching(p->fts_path);
163 c += procfile(p->fts_path);
173 * Opens a file and processes it. Each file is processed line-by-line
174 * passing the lines to procline().
177 procfile(const char *fn)
187 if (strcmp(fn, "-") == 0) {
188 fn = label != NULL ? label : getstr(1);
191 if (!stat(fn, &sb)) {
192 /* Check if we need to process the file */
193 s = sb.st_mode & S_IFMT;
194 if (s == S_IFDIR && dirbehave == DIR_SKIP)
196 if ((s == S_IFIFO || s == S_IFCHR || s == S_IFBLK
197 || s == S_IFSOCK) && devbehave == DEV_SKIP)
209 ln.file = grep_malloc(strlen(fn) + 1);
219 for (c = 0; c == 0 || !(lflag || qflag); ) {
220 ln.off += ln.len + 1;
221 if ((ln.dat = grep_fgetln(f, &ln.len)) == NULL || ln.len == 0) {
222 if (ln.line_no == 0 && matchall)
227 if (ln.len > 0 && ln.dat[ln.len - 1] == fileeol)
231 /* Return if we need to skip a binary file */
232 if (f->binary && binbehave == BINFILE_SKIP) {
239 /* Process the file line-by-line, enqueue non-matching lines */
240 if ((t = procline(&ln, f->binary)) == 0 && Bflag > 0) {
241 /* Except don't enqueue lines that appear in -A ctx */
242 if (ln.line_no == 0 || lasta != ln.line_no) {
243 /* queue is maxed to Bflag number of lines */
249 * Indicate to procline() that we have ctx
250 * overlap and make sure queue is empty.
258 if (mflag && mcount <= 0)
267 printf("%s:", ln.file);
270 if (lflag && !qflag && c != 0)
271 printf("%s%c", fn, nullflag ? 0 : '\n');
272 if (Lflag && !qflag && c == 0)
273 printf("%s%c", fn, nullflag ? 0 : '\n');
274 if (c && !cflag && !lflag && !Lflag &&
275 binbehave == BINFILE_BIN && f->binary && !qflag)
276 printf(getstr(8), fn);
283 #define iswword(x) (iswalnum((x)) || (x) == L'_')
286 * Processes a line comparing it with the specified patterns. Each pattern
287 * is looped to be compared along with the full string, saving each and every
288 * match, which is necessary to colorize the output and to count the
289 * matches. The matching lines are passed to printline() to display the
290 * appropriate output.
293 procline(struct str *l, int nottext)
295 regmatch_t matches[MAX_LINE_MATCHES];
296 regmatch_t pmatch, lastmatch;
297 size_t st = 0, nst = 0;
299 int c = 0, m = 0, r = 0, lastmatches = 0, leflags = eflags;
302 /* Initialize to avoid a false positive warning from GCC. */
303 lastmatch.rm_so = lastmatch.rm_eo = 0;
305 /* Loop to process the whole line */
306 while (st <= l->len) {
310 leflags |= REG_NOTBOL;
311 /* Loop to compare with all the patterns */
312 for (i = 0; i < patterns; i++) {
314 pmatch.rm_eo = l->len;
315 if (fg_pattern[i].pattern)
316 r = fastexec(&fg_pattern[i],
317 l->dat, 1, &pmatch, leflags);
319 r = regexec(&r_pattern[i], l->dat, 1,
321 r = (r == 0) ? 0 : REG_NOMATCH;
322 if (r == REG_NOMATCH)
324 /* Check for full match */
326 if (pmatch.rm_so != 0 ||
327 (size_t)pmatch.rm_eo != l->len)
329 /* Check for whole word match */
330 if (r == 0 && (wflag || fg_pattern[i].word)) {
331 wchar_t wbegin, wend;
333 wbegin = wend = L' ';
334 if (pmatch.rm_so != 0 &&
335 sscanf(&l->dat[pmatch.rm_so - 1],
336 "%lc", &wbegin) != 1)
338 else if ((size_t)pmatch.rm_eo !=
340 sscanf(&l->dat[pmatch.rm_eo],
343 else if (iswword(wbegin) ||
353 if (m < MAX_LINE_MATCHES) {
354 /* Replace previous match if the new one is earlier and/or longer */
356 if (pmatch.rm_so < matches[m-1].rm_so ||
357 (pmatch.rm_so == matches[m-1].rm_so && (pmatch.rm_eo - pmatch.rm_so) > (matches[m-1].rm_eo - matches[m-1].rm_so))) {
358 matches[m-1] = pmatch;
362 /* Advance as normal if not */
363 matches[m++] = pmatch;
368 /* matches - skip further patterns */
369 if ((color == NULL && !oflag) ||
380 /* One pass if we are not recording matches */
381 if (!wflag && ((color == NULL && !oflag) || qflag || lflag || Lflag))
384 /* If we didn't have any matches or REG_NOSUB set */
385 if (lastmatches == 0 || (cflags & REG_NOSUB))
388 if (lastmatches == 0)
391 else if (st == nst && lastmatch.rm_so == lastmatch.rm_eo)
392 /* Zero-length match -- advance one more so we don't get stuck */
395 /* Advance st based on previous matches */
400 /* Count the matches if we have a match limit */
404 if (c && binbehave == BINFILE_BIN && nottext)
405 return (c); /* Binary file */
407 /* Dealing with the context */
408 if ((tail || c) && !cflag && !qflag && !lflag && !Lflag) {
410 if (!first && !prev && !tail && (Bflag || Aflag) &&
419 printline(l, ':', matches, m);
421 /* Print -A lines following matches */
423 printline(l, '-', matches, m);
438 * Safe malloc() for internal use.
441 grep_malloc(size_t size)
445 if ((ptr = malloc(size)) == NULL)
451 * Safe calloc() for internal use.
454 grep_calloc(size_t nmemb, size_t size)
458 if ((ptr = calloc(nmemb, size)) == NULL)
464 * Safe realloc() for internal use.
467 grep_realloc(void *ptr, size_t size)
470 if ((ptr = realloc(ptr, size)) == NULL)
476 * Safe strdup() for internal use.
479 grep_strdup(const char *str)
483 if ((ret = strdup(str)) == NULL)
489 * Prints a matching line according to the command line options.
492 printline(struct str *line, int sep, regmatch_t *matches, int m)
497 /* If matchall, everything matches but don't actually print for -o */
498 if (oflag && matchall)
503 fputs(line->file, stdout);
506 printf("%s", line->file);
513 printf("%d", line->line_no);
519 printf("%lld", (long long)line->off);
525 if ((oflag || color) && m > 0) {
526 for (i = 0; i < m; i++) {
527 /* Don't output zero length matches */
528 if (matches[i].rm_so == matches[i].rm_eo)
531 fwrite(line->dat + a, matches[i].rm_so - a, 1,
534 fprintf(stdout, "\33[%sm\33[K", color);
536 fwrite(line->dat + matches[i].rm_so,
537 matches[i].rm_eo - matches[i].rm_so, 1,
540 fprintf(stdout, "\33[m\33[K");
541 a = matches[i].rm_eo;
546 if (line->len - a > 0)
547 fwrite(line->dat + a, line->len - a, 1, stdout);
551 fwrite(line->dat, line->len, 1, stdout);