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);
59 file_matching(const char *fname)
64 ret = finclude ? false : true;
65 fname_base = basename(fname);
67 for (unsigned int i = 0; i < fpatterns; ++i) {
68 if (fnmatch(fpattern[i].pat, fname, 0) == 0 ||
69 fnmatch(fpattern[i].pat, fname_base, 0) == 0) {
70 if (fpattern[i].mode == EXCL_PAT)
80 dir_matching(const char *dname)
84 ret = dinclude ? false : true;
86 for (unsigned int i = 0; i < dpatterns; ++i) {
88 fnmatch(dpattern[i].pat, dname, 0) == 0) {
89 if (dpattern[i].mode == EXCL_PAT)
99 * Processes a directory when a recursive search is performed with
100 * the -R option. Each appropriate file is passed to procfile().
103 grep_tree(char **argv)
114 fts_flags = FTS_COMFOLLOW;
117 fts_flags = FTS_PHYSICAL;
120 fts_flags = FTS_LOGICAL;
124 fts_flags |= FTS_NOSTAT | FTS_NOCHDIR;
126 if (!(fts = fts_open(argv, fts_flags, NULL)))
128 while ((p = fts_read(fts)) != NULL) {
129 switch (p->fts_info) {
135 warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
140 if (dexclude || dinclude)
141 if (!dir_matching(p->fts_name) ||
142 !dir_matching(p->fts_path))
143 fts_set(fts, p, FTS_SKIP);
146 /* Print a warning for recursive directory loop */
147 warnx("warning: %s: recursive directory loop",
151 /* Check for file exclusion/inclusion */
153 if (fexclude || finclude)
154 ok &= file_matching(p->fts_path);
157 c += procfile(p->fts_path);
167 * Opens a file and processes it. Each file is processed line-by-line
168 * passing the lines to procline().
171 procfile(const char *fn)
181 if (strcmp(fn, "-") == 0) {
182 fn = label != NULL ? label : getstr(1);
185 if (!stat(fn, &sb)) {
186 /* Check if we need to process the file */
187 s = sb.st_mode & S_IFMT;
188 if (s == S_IFDIR && dirbehave == DIR_SKIP)
190 if ((s == S_IFIFO || s == S_IFCHR || s == S_IFBLK
191 || s == S_IFSOCK) && devbehave == DEV_SKIP)
203 ln.file = grep_malloc(strlen(fn) + 1);
211 for (c = 0; c == 0 || !(lflag || qflag); ) {
212 ln.off += ln.len + 1;
213 if ((ln.dat = grep_fgetln(f, &ln.len)) == NULL || ln.len == 0) {
214 if (ln.line_no == 0 && matchall)
219 if (ln.len > 0 && ln.dat[ln.len - 1] == '\n')
223 /* Return if we need to skip a binary file */
224 if (f->binary && binbehave == BINFILE_SKIP) {
230 /* Process the file line-by-line */
231 if ((t = procline(&ln, f->binary)) == 0 && Bflag > 0) {
236 if (mflag && mcount <= 0)
245 printf("%s:", ln.file);
248 if (lflag && !qflag && c != 0)
249 printf("%s%c", fn, nullflag ? 0 : '\n');
250 if (Lflag && !qflag && c == 0)
251 printf("%s%c", fn, nullflag ? 0 : '\n');
252 if (c && !cflag && !lflag && !Lflag &&
253 binbehave == BINFILE_BIN && f->binary && !qflag)
254 printf(getstr(8), fn);
261 #define iswword(x) (iswalnum((x)) || (x) == L'_')
264 * Processes a line comparing it with the specified patterns. Each pattern
265 * is looped to be compared along with the full string, saving each and every
266 * match, which is necessary to colorize the output and to count the
267 * matches. The matching lines are passed to printline() to display the
268 * appropriate output.
271 procline(struct str *l, int nottext)
273 regmatch_t matches[MAX_LINE_MATCHES];
277 int c = 0, m = 0, r = 0;
279 /* Loop to process the whole line */
280 while (st <= l->len) {
282 pmatch.rm_eo = l->len;
284 /* Loop to compare with all the patterns */
285 for (i = 0; i < patterns; i++) {
286 if (fg_pattern[i].pattern)
287 r = fastexec(&fg_pattern[i],
288 l->dat, 1, &pmatch, eflags);
290 r = regexec(&r_pattern[i], l->dat, 1,
292 r = (r == 0) ? 0 : REG_NOMATCH;
293 st = (cflags & REG_NOSUB)
295 : (size_t)pmatch.rm_eo;
296 if (r == REG_NOMATCH)
298 /* Check for full match */
300 if (pmatch.rm_so != 0 ||
301 (size_t)pmatch.rm_eo != l->len)
303 /* Check for whole word match */
304 if (r == 0 && (wflag || fg_pattern[i].word)) {
305 wchar_t wbegin, wend;
307 wbegin = wend = L' ';
308 if (pmatch.rm_so != 0 &&
309 sscanf(&l->dat[pmatch.rm_so - 1],
310 "%lc", &wbegin) != 1)
312 else if ((size_t)pmatch.rm_eo !=
314 sscanf(&l->dat[pmatch.rm_eo],
317 else if (iswword(wbegin) ||
324 if (m < MAX_LINE_MATCHES)
325 matches[m++] = pmatch;
326 /* matches - skip further patterns */
327 if ((color == NULL && !oflag) ||
338 /* One pass if we are not recording matches */
339 if (!wflag && ((color == NULL && !oflag) || qflag || lflag))
342 if (st == (size_t)pmatch.rm_so)
343 break; /* No matches */
347 /* Count the matches if we have a match limit */
351 if (c && binbehave == BINFILE_BIN && nottext)
352 return (c); /* Binary file */
354 /* Dealing with the context */
355 if ((tail || c) && !cflag && !qflag && !lflag && !Lflag) {
357 if (!first && !prev && !tail && Aflag)
366 printline(l, ':', matches, m);
368 printline(l, '-', matches, m);
383 * Safe malloc() for internal use.
386 grep_malloc(size_t size)
390 if ((ptr = malloc(size)) == NULL)
396 * Safe calloc() for internal use.
399 grep_calloc(size_t nmemb, size_t size)
403 if ((ptr = calloc(nmemb, size)) == NULL)
409 * Safe realloc() for internal use.
412 grep_realloc(void *ptr, size_t size)
415 if ((ptr = realloc(ptr, size)) == NULL)
421 * Safe strdup() for internal use.
424 grep_strdup(const char *str)
428 if ((ret = strdup(str)) == NULL)
434 * Prints a matching line according to the command line options.
437 printline(struct str *line, int sep, regmatch_t *matches, int m)
444 fputs(line->file, stdout);
447 printf("%s", line->file);
454 printf("%d", line->line_no);
460 printf("%lld", (long long)line->off);
466 if ((oflag || color) && m > 0) {
467 for (i = 0; i < m; i++) {
469 fwrite(line->dat + a, matches[i].rm_so - a, 1,
472 fprintf(stdout, "\33[%sm\33[K", color);
474 fwrite(line->dat + matches[i].rm_so,
475 matches[i].rm_eo - matches[i].rm_so, 1,
478 fprintf(stdout, "\33[m\33[K");
479 a = matches[i].rm_eo;
484 if (line->len - a > 0)
485 fwrite(line->dat + a, line->len - a, 1, stdout);
489 fwrite(line->dat, line->len, 1, stdout);