Annotation of src/usr.bin/grep/grep.c, Revision 1.29
1.29 ! deraadt 1: /* $OpenBSD: grep.c,v 1.28 2004/05/07 14:51:42 millert Exp $ */
1.6 deraadt 2:
1.1 deraadt 3: /*-
1.3 deraadt 4: * Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
5: * All rights reserved.
1.1 deraadt 6: *
7: * Redistribution and use in source and binary forms, with or without
8: * modification, are permitted provided that the following conditions
9: * are met:
10: * 1. Redistributions of source code must retain the above copyright
11: * notice, this list of conditions and the following disclaimer.
12: * 2. Redistributions in binary form must reproduce the above copyright
13: * notice, this list of conditions and the following disclaimer in the
14: * documentation and/or other materials provided with the distribution.
15: *
16: * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17: * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18: * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19: * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20: * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21: * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22: * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23: * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24: * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25: * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26: * SUCH DAMAGE.
27: */
28:
1.3 deraadt 29: #include <sys/types.h>
1.9 tedu 30: #include <sys/limits.h>
1.3 deraadt 31: #include <sys/stat.h>
1.1 deraadt 32:
1.18 millert 33: #include <ctype.h>
1.3 deraadt 34: #include <err.h>
35: #include <errno.h>
36: #include <getopt.h>
37: #include <regex.h>
1.1 deraadt 38: #include <stdio.h>
39: #include <stdlib.h>
1.3 deraadt 40: #include <string.h>
1.1 deraadt 41: #include <unistd.h>
42:
1.3 deraadt 43: #include "grep.h"
44:
45: /* Flags passed to regcomp() and regexec() */
46: int cflags;
47: int eflags = REG_STARTEND;
48:
49: int matchall; /* shortcut */
50: int patterns, pattern_sz;
51: char **pattern;
52: regex_t *r_pattern;
1.13 tedu 53: fastgrep_t *fg_pattern;
1.3 deraadt 54:
55: /* For regex errors */
56: char re_error[RE_ERROR_BUF + 1];
57:
58: /* Command-line flags */
59: int Aflag; /* -A x: print x lines trailing each match */
60: int Bflag; /* -B x: print x lines leading each match */
61: int Eflag; /* -E: interpret pattern as extended regexp */
62: int Fflag; /* -F: interpret pattern as list of fixed strings */
63: int Gflag; /* -G: interpret pattern as basic regexp */
64: int Hflag; /* -H: if -R, follow explicitly listed symlinks */
65: int Lflag; /* -L: only show names of files with no matches */
66: int Pflag; /* -P: if -R, no symlinks are followed */
67: int Rflag; /* -R: recursively search directory trees */
68: int Sflag; /* -S: if -R, follow all symlinks */
69: int Vflag; /* -V: display version information */
1.5 deraadt 70: #ifndef NOZ
1.3 deraadt 71: int Zflag; /* -Z: decompress input before processing */
1.5 deraadt 72: #endif
1.3 deraadt 73: int bflag; /* -b: show block numbers for each match */
74: int cflag; /* -c: only show a count of matching lines */
75: int hflag; /* -h: don't print filename headers */
76: int iflag; /* -i: ignore case */
77: int lflag; /* -l: only show names of files with matches */
78: int nflag; /* -n: show line numbers in front of matching lines */
79: int oflag; /* -o: always print file name */
80: int qflag; /* -q: quiet mode (don't output anything) */
81: int sflag; /* -s: silent mode (ignore errors) */
82: int vflag; /* -v: only show non-matching lines */
83: int wflag; /* -w: pattern must start and end on word boundaries */
84: int xflag; /* -x: pattern must match entire line */
1.27 otto 85: int lbflag; /* --line-buffered */
1.3 deraadt 86:
1.9 tedu 87: int binbehave = BIN_FILE_BIN;
88:
89: enum {
90: BIN_OPT = CHAR_MAX + 1,
91: HELP_OPT,
1.27 otto 92: MMAP_OPT,
93: LINEBUF_OPT
1.9 tedu 94: };
95:
1.3 deraadt 96: /* Housekeeping */
1.10 tedu 97: int first; /* flag whether or not this is our first match */
1.3 deraadt 98: int tail; /* lines left to print */
99: int lead; /* number of lines in leading context queue */
1.13 tedu 100: int boleol; /* At least one pattern has a bol or eol */
1.17 millert 101: size_t maxPatternLen; /* Longest length of all patterns */
1.3 deraadt 102:
1.8 tedu 103: extern char *__progname;
1.3 deraadt 104:
105: static void
106: usage(void)
107: {
1.5 deraadt 108: fprintf(stderr,
109: #ifdef NOZ
1.24 mcbride 110: "usage: %s [-AB num] [-CEFGHILPRSUVabchilnoqsvwx]\n"
1.5 deraadt 111: #else
1.24 mcbride 112: "usage: %s [-AB num] [-CEFGHILPRSUVZabchilnoqsvwx]\n"
1.5 deraadt 113: #endif
1.27 otto 114: "\t[--context[=num]] [--binary-files=value] [--line-buffered]\n"
1.24 mcbride 115: "\t[-e pattern] [-f file] [pattern] [file ...]\n", __progname);
1.3 deraadt 116: exit(2);
117: }
118:
1.5 deraadt 119: #ifdef NOZ
1.9 tedu 120: static char *optstr = "0123456789A:B:CEFGHILPSRUVabce:f:hilnoqrsuvwxy";
1.5 deraadt 121: #else
1.9 tedu 122: static char *optstr = "0123456789A:B:CEFGHILPSRUVZabce:f:hilnoqrsuvwxy";
1.5 deraadt 123: #endif
1.3 deraadt 124:
1.5 deraadt 125: struct option long_options[] =
1.3 deraadt 126: {
1.19 deraadt 127: {"binary-files", required_argument, NULL, BIN_OPT},
128: {"help", no_argument, NULL, HELP_OPT},
129: {"mmap", no_argument, NULL, MMAP_OPT},
1.27 otto 130: {"line-buffered", no_argument, NULL, LINEBUF_OPT},
1.19 deraadt 131: {"after-context", required_argument, NULL, 'A'},
132: {"before-context", required_argument, NULL, 'B'},
133: {"context", optional_argument, NULL, 'C'},
134: {"devices", required_argument, NULL, 'D'},
135: {"extended-regexp", no_argument, NULL, 'E'},
136: {"fixed-strings", no_argument, NULL, 'F'},
137: {"basic-regexp", no_argument, NULL, 'G'},
138: {"binary", no_argument, NULL, 'U'},
139: {"version", no_argument, NULL, 'V'},
140: {"text", no_argument, NULL, 'a'},
141: {"byte-offset", no_argument, NULL, 'b'},
142: {"count", no_argument, NULL, 'c'},
143: {"regexp", required_argument, NULL, 'e'},
144: {"file", required_argument, NULL, 'f'},
145: {"no-filename", no_argument, NULL, 'h'},
146: {"ignore-case", no_argument, NULL, 'i'},
147: {"files-without-match", no_argument, NULL, 'L'},
148: {"files-with-matches", no_argument, NULL, 'l'},
149: {"line-number", no_argument, NULL, 'n'},
150: {"quiet", no_argument, NULL, 'q'},
151: {"silent", no_argument, NULL, 'q'},
152: {"recursive", no_argument, NULL, 'r'},
153: {"no-messages", no_argument, NULL, 's'},
154: {"revert-match", no_argument, NULL, 'v'},
155: {"word-regexp", no_argument, NULL, 'w'},
156: {"line-regexp", no_argument, NULL, 'x'},
157: {"unix-byte-offsets", no_argument, NULL, 'u'},
1.5 deraadt 158: #ifndef NOZ
1.19 deraadt 159: {"decompress", no_argument, NULL, 'Z'},
1.5 deraadt 160: #endif
1.19 deraadt 161: {NULL, no_argument, NULL, 0}
1.3 deraadt 162: };
163:
1.1 deraadt 164:
1.3 deraadt 165: static void
166: add_pattern(char *pat, size_t len)
167: {
168: if (len == 0 || matchall) {
169: matchall = 1;
170: return;
171: }
172: if (patterns == pattern_sz) {
173: pattern_sz *= 2;
1.22 millert 174: pattern = grep_realloc(pattern, ++pattern_sz * sizeof(*pattern));
1.3 deraadt 175: }
1.11 tedu 176: if (pat[len - 1] == '\n')
1.3 deraadt 177: --len;
1.15 tedu 178: /* pat may not be NUL-terminated */
1.28 millert 179: if (wflag && !Fflag) {
1.26 millert 180: int bol = 0, eol = 0;
181: if (pat[0] == '^')
182: bol = 1;
183: if (pat[len - 1] == '$')
184: eol = 1;
1.25 millert 185: pattern[patterns] = grep_malloc(len + 15);
1.26 millert 186: snprintf(pattern[patterns], len + 15, "%s[[:<:]]%.*s[[:>:]]%s",
187: bol ? "^" : "", (int)len - bol - eol, pat + bol,
188: eol ? "$" : "");
189: len += 14;
1.25 millert 190: } else {
191: pattern[patterns] = grep_malloc(len + 1);
192: memcpy(pattern[patterns], pat, len);
193: pattern[patterns][len] = '\0';
194: }
1.3 deraadt 195: ++patterns;
1.13 tedu 196:
197: if (len > maxPatternLen)
198: maxPatternLen = len;
1.3 deraadt 199: }
1.1 deraadt 200:
1.3 deraadt 201: static void
202: read_patterns(char *fn)
203: {
204: FILE *f;
205: char *line;
206: size_t len;
207: int nl;
208:
209: if ((f = fopen(fn, "r")) == NULL)
1.20 millert 210: err(2, "%s", fn);
1.3 deraadt 211: nl = 0;
212: while ((line = fgetln(f, &len)) != NULL) {
213: if (*line == '\n') {
214: ++nl;
215: continue;
216: }
217: if (nl) {
218: matchall = 1;
219: break;
220: }
221: nl = 0;
222: add_pattern(line, len);
223: }
224: if (ferror(f))
1.20 millert 225: err(2, "%s", fn);
1.3 deraadt 226: fclose(f);
227: }
1.1 deraadt 228:
229: int
1.3 deraadt 230: main(int argc, char *argv[])
1.1 deraadt 231: {
1.23 millert 232: int c, lastc, prevoptind, newarg, i;
1.21 millert 233: long l;
234: char *ep;
1.3 deraadt 235:
1.16 tedu 236: switch (__progname[0]) {
237: case 'e':
238: Eflag++;
239: break;
240: case 'f':
241: Fflag++;
242: break;
243: case 'g':
244: Gflag++;
245: break;
246: #ifndef NOZ
247: case 'z':
248: Zflag++;
249: switch(__progname[1]) {
250: case 'e':
251: Eflag++;
252: break;
253: case 'f':
254: Fflag++;
255: break;
256: case 'g':
257: Gflag++;
258: break;
259: }
260: break;
261: #endif
262: }
263:
1.18 millert 264: lastc = '\0';
1.23 millert 265: newarg = 1;
266: prevoptind = 1;
1.5 deraadt 267: while ((c = getopt_long(argc, argv, optstr,
1.17 millert 268: long_options, NULL)) != -1) {
1.3 deraadt 269: switch (c) {
270: case '0': case '1': case '2': case '3': case '4':
271: case '5': case '6': case '7': case '8': case '9':
1.23 millert 272: if (newarg || !isdigit(lastc))
273: Aflag = 0;
274: else if (Aflag > INT_MAX / 10)
275: errx(2, "context out of range");
276: Aflag = Bflag = (Aflag * 10) + (c - '0');
1.3 deraadt 277: break;
278: case 'A':
279: case 'B':
1.21 millert 280: l = strtol(optarg, &ep, 10);
281: if (ep == optarg || *ep != '\0' ||
282: l <= 0 || l >= INT_MAX)
283: errx(2, "context out of range");
284: if (c == 'A')
285: Aflag = (int)l;
286: else
287: Bflag = (int)l;
1.3 deraadt 288: break;
289: case 'C':
1.5 deraadt 290: if (optarg == NULL)
1.3 deraadt 291: Aflag = Bflag = 2;
1.21 millert 292: else {
293: l = strtol(optarg, &ep, 10);
294: if (ep == optarg || *ep != '\0' ||
295: l <= 0 || l >= INT_MAX)
296: errx(2, "context out of range");
297: Aflag = Bflag = (int)l;
298: }
1.1 deraadt 299: break;
300: case 'E':
1.16 tedu 301: Fflag = Gflag = 0;
1.3 deraadt 302: Eflag++;
1.1 deraadt 303: break;
304: case 'F':
1.16 tedu 305: Eflag = Gflag = 0;
1.3 deraadt 306: Fflag++;
307: break;
308: case 'G':
1.16 tedu 309: Eflag = Fflag = 0;
1.3 deraadt 310: Gflag++;
1.1 deraadt 311: break;
312: case 'H':
1.3 deraadt 313: Hflag++;
1.1 deraadt 314: break;
1.9 tedu 315: case 'I':
316: binbehave = BIN_FILE_SKIP;
317: break;
1.1 deraadt 318: case 'L':
1.3 deraadt 319: lflag = 0;
320: Lflag = qflag = 1;
1.1 deraadt 321: break;
322: case 'P':
1.3 deraadt 323: Pflag++;
324: break;
325: case 'S':
326: Sflag++;
1.1 deraadt 327: break;
328: case 'R':
1.3 deraadt 329: case 'r':
330: Rflag++;
331: oflag++;
332: break;
333: case 'U':
1.9 tedu 334: binbehave = BIN_FILE_BIN;
1.3 deraadt 335: break;
336: case 'V':
337: fprintf(stderr, "grep version %u.%u\n", VER_MAJ, VER_MIN);
1.9 tedu 338: exit(0);
1.1 deraadt 339: break;
1.5 deraadt 340: #ifndef NOZ
1.3 deraadt 341: case 'Z':
342: Zflag++;
1.1 deraadt 343: break;
1.5 deraadt 344: #endif
1.1 deraadt 345: case 'a':
1.9 tedu 346: binbehave = BIN_FILE_TEXT;
1.1 deraadt 347: break;
348: case 'b':
1.3 deraadt 349: bflag = 1;
1.1 deraadt 350: break;
351: case 'c':
1.3 deraadt 352: cflag = 1;
1.1 deraadt 353: break;
354: case 'e':
1.3 deraadt 355: add_pattern(optarg, strlen(optarg));
1.1 deraadt 356: break;
357: case 'f':
1.3 deraadt 358: read_patterns(optarg);
1.1 deraadt 359: break;
360: case 'h':
1.3 deraadt 361: oflag = 0;
362: hflag = 1;
1.1 deraadt 363: break;
364: case 'i':
1.3 deraadt 365: case 'y':
1.13 tedu 366: iflag = 1;
1.1 deraadt 367: cflags |= REG_ICASE;
368: break;
369: case 'l':
1.3 deraadt 370: Lflag = 0;
371: lflag = qflag = 1;
1.1 deraadt 372: break;
373: case 'n':
1.3 deraadt 374: nflag = 1;
375: break;
376: case 'o':
377: hflag = 0;
378: oflag = 1;
1.1 deraadt 379: break;
380: case 'q':
1.3 deraadt 381: qflag = 1;
1.1 deraadt 382: break;
383: case 's':
1.3 deraadt 384: sflag = 1;
1.1 deraadt 385: break;
386: case 'v':
1.3 deraadt 387: vflag = 1;
1.1 deraadt 388: break;
389: case 'w':
1.3 deraadt 390: wflag = 1;
1.1 deraadt 391: break;
392: case 'x':
1.3 deraadt 393: xflag = 1;
1.1 deraadt 394: break;
1.9 tedu 395: case BIN_OPT:
396: if (strcmp("binary", optarg) == 0)
397: binbehave = BIN_FILE_BIN;
398: else if (strcmp("without-match", optarg) == 0)
399: binbehave = BIN_FILE_SKIP;
400: else if (strcmp("text", optarg) == 0)
401: binbehave = BIN_FILE_TEXT;
402: else
403: errx(2, "Unknown binary-files option");
404: break;
405: case 'u':
406: case MMAP_OPT:
407: /* default, compatibility */
408: break;
1.27 otto 409: case LINEBUF_OPT:
410: lbflag = 1;
411: break;
1.9 tedu 412: case HELP_OPT:
1.1 deraadt 413: default:
414: usage();
415: }
1.18 millert 416: lastc = c;
1.23 millert 417: newarg = optind != prevoptind;
1.18 millert 418: prevoptind = optind;
1.1 deraadt 419: }
1.3 deraadt 420: argc -= optind;
421: argv += optind;
422:
423: if (argc == 0 && patterns == 0)
1.1 deraadt 424: usage();
425:
1.3 deraadt 426: if (patterns == 0) {
427: add_pattern(*argv, strlen(*argv));
428: --argc;
429: ++argv;
430: }
1.5 deraadt 431:
1.16 tedu 432: if (Eflag)
433: cflags |= REG_EXTENDED;
1.13 tedu 434: fg_pattern = grep_malloc(patterns * sizeof(*fg_pattern));
1.22 millert 435: r_pattern = grep_malloc(patterns * sizeof(*r_pattern));
1.3 deraadt 436: for (i = 0; i < patterns; ++i) {
1.28 millert 437: /* Check if cheating is allowed (always is for fgrep). */
438: if (Fflag) {
439: fgrepcomp(&fg_pattern[i], pattern[i]);
440: } else {
441: if (fastcomp(&fg_pattern[i], pattern[i])) {
442: /* Fall back to full regex library */
443: c = regcomp(&r_pattern[i], pattern[i], cflags);
444: if (c != 0) {
445: regerror(c, &r_pattern[i], re_error,
446: RE_ERROR_BUF);
447: errx(2, "%s", re_error);
448: }
1.13 tedu 449: }
1.1 deraadt 450: }
451: }
1.29 ! deraadt 452:
1.27 otto 453: if (lbflag)
454: setlinebuf(stdout);
1.1 deraadt 455:
1.3 deraadt 456: if ((argc == 0 || argc == 1) && !oflag)
457: hflag = 1;
1.1 deraadt 458:
1.3 deraadt 459: if (argc == 0)
460: exit(!procfile(NULL));
1.5 deraadt 461:
1.3 deraadt 462: if (Rflag)
463: c = grep_tree(argv);
1.1 deraadt 464: else
1.3 deraadt 465: for (c = 0; argc--; ++argv)
466: c += procfile(*argv);
1.1 deraadt 467:
1.3 deraadt 468: exit(!c);
1.1 deraadt 469: }