Annotation of src/usr.bin/grep/grep.c, Revision 1.39
1.39 ! deraadt 1: /* $OpenBSD: grep.c,v 1.38 2007/02/13 21:48:20 kili 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.33 jaredy 32: #include <sys/queue.h>
1.1 deraadt 33:
1.18 millert 34: #include <ctype.h>
1.3 deraadt 35: #include <err.h>
36: #include <errno.h>
37: #include <getopt.h>
38: #include <regex.h>
1.1 deraadt 39: #include <stdio.h>
40: #include <stdlib.h>
1.3 deraadt 41: #include <string.h>
1.1 deraadt 42: #include <unistd.h>
43:
1.3 deraadt 44: #include "grep.h"
45:
46: /* Flags passed to regcomp() and regexec() */
47: int cflags;
48: int eflags = REG_STARTEND;
49:
50: int matchall; /* shortcut */
51: int patterns, pattern_sz;
52: char **pattern;
53: regex_t *r_pattern;
1.13 tedu 54: fastgrep_t *fg_pattern;
1.3 deraadt 55:
56: /* For regex errors */
57: char re_error[RE_ERROR_BUF + 1];
58:
59: /* Command-line flags */
60: int Aflag; /* -A x: print x lines trailing each match */
61: int Bflag; /* -B x: print x lines leading each match */
62: int Eflag; /* -E: interpret pattern as extended regexp */
63: int Fflag; /* -F: interpret pattern as list of fixed strings */
64: int Gflag; /* -G: interpret pattern as basic regexp */
65: int Hflag; /* -H: if -R, follow explicitly listed symlinks */
66: int Lflag; /* -L: only show names of files with no matches */
67: int Pflag; /* -P: if -R, no symlinks are followed */
68: int Rflag; /* -R: recursively search directory trees */
69: int Sflag; /* -S: if -R, follow all symlinks */
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:
1.33 jaredy 100: struct patfile {
101: const char *pf_file;
102: SLIST_ENTRY(patfile) pf_next;
103: };
104: SLIST_HEAD(, patfile) patfilelh;
105:
1.8 tedu 106: extern char *__progname;
1.3 deraadt 107:
108: static void
109: usage(void)
110: {
1.5 deraadt 111: fprintf(stderr,
112: #ifdef NOZ
1.30 jmc 113: "usage: %s [-abcEFGHhIiLlnoPqRSsUVvwx] [-A num] [-B num] [-C[num]]\n"
1.5 deraadt 114: #else
1.30 jmc 115: "usage: %s [-abcEFGHhIiLlnoPqRSsUVvwxZ] [-A num] [-B num] [-C[num]]\n"
1.5 deraadt 116: #endif
1.30 jmc 117: "\t[-e pattern] [-f file] [--binary-files=value] [--context[=num]]\n"
118: "\t[--line-buffered] [pattern] [file ...]\n", __progname);
1.3 deraadt 119: exit(2);
120: }
121:
1.5 deraadt 122: #ifdef NOZ
1.9 tedu 123: static char *optstr = "0123456789A:B:CEFGHILPSRUVabce:f:hilnoqrsuvwxy";
1.5 deraadt 124: #else
1.9 tedu 125: static char *optstr = "0123456789A:B:CEFGHILPSRUVZabce:f:hilnoqrsuvwxy";
1.5 deraadt 126: #endif
1.3 deraadt 127:
1.5 deraadt 128: struct option long_options[] =
1.3 deraadt 129: {
1.19 deraadt 130: {"binary-files", required_argument, NULL, BIN_OPT},
131: {"help", no_argument, NULL, HELP_OPT},
132: {"mmap", no_argument, NULL, MMAP_OPT},
1.27 otto 133: {"line-buffered", no_argument, NULL, LINEBUF_OPT},
1.19 deraadt 134: {"after-context", required_argument, NULL, 'A'},
135: {"before-context", required_argument, NULL, 'B'},
136: {"context", optional_argument, NULL, 'C'},
137: {"devices", required_argument, NULL, 'D'},
138: {"extended-regexp", no_argument, NULL, 'E'},
139: {"fixed-strings", no_argument, NULL, 'F'},
140: {"basic-regexp", no_argument, NULL, 'G'},
141: {"binary", no_argument, NULL, 'U'},
142: {"version", no_argument, NULL, 'V'},
143: {"text", no_argument, NULL, 'a'},
144: {"byte-offset", no_argument, NULL, 'b'},
145: {"count", no_argument, NULL, 'c'},
146: {"regexp", required_argument, NULL, 'e'},
147: {"file", required_argument, NULL, 'f'},
148: {"no-filename", no_argument, NULL, 'h'},
149: {"ignore-case", no_argument, NULL, 'i'},
150: {"files-without-match", no_argument, NULL, 'L'},
151: {"files-with-matches", no_argument, NULL, 'l'},
152: {"line-number", no_argument, NULL, 'n'},
153: {"quiet", no_argument, NULL, 'q'},
154: {"silent", no_argument, NULL, 'q'},
155: {"recursive", no_argument, NULL, 'r'},
156: {"no-messages", no_argument, NULL, 's'},
157: {"revert-match", no_argument, NULL, 'v'},
158: {"word-regexp", no_argument, NULL, 'w'},
159: {"line-regexp", no_argument, NULL, 'x'},
160: {"unix-byte-offsets", no_argument, NULL, 'u'},
1.5 deraadt 161: #ifndef NOZ
1.19 deraadt 162: {"decompress", no_argument, NULL, 'Z'},
1.5 deraadt 163: #endif
1.19 deraadt 164: {NULL, no_argument, NULL, 0}
1.3 deraadt 165: };
166:
1.1 deraadt 167:
1.3 deraadt 168: static void
169: add_pattern(char *pat, size_t len)
170: {
1.36 jaredy 171: if (!xflag && (len == 0 || matchall)) {
1.3 deraadt 172: matchall = 1;
173: return;
174: }
175: if (patterns == pattern_sz) {
176: pattern_sz *= 2;
1.22 millert 177: pattern = grep_realloc(pattern, ++pattern_sz * sizeof(*pattern));
1.3 deraadt 178: }
1.37 ray 179: if (len > 0 && pat[len - 1] == '\n')
1.3 deraadt 180: --len;
1.15 tedu 181: /* pat may not be NUL-terminated */
1.28 millert 182: if (wflag && !Fflag) {
1.32 otto 183: int bol = 0, eol = 0, extra;
1.26 millert 184: if (pat[0] == '^')
185: bol = 1;
1.36 jaredy 186: if (len > 0 && pat[len - 1] == '$')
1.26 millert 187: eol = 1;
1.32 otto 188: extra = Eflag ? 2 : 4;
189: pattern[patterns] = grep_malloc(len + 15 + extra);
190: snprintf(pattern[patterns], len + 15 + extra,
191: "%s[[:<:]]%s%.*s%s[[:>:]]%s",
192: bol ? "^" : "",
193: Eflag ? "(" : "\\(",
194: (int)len - bol - eol, pat + bol,
195: Eflag ? ")" : "\\)",
1.26 millert 196: eol ? "$" : "");
1.32 otto 197: len += 14 + extra;
1.25 millert 198: } else {
199: pattern[patterns] = grep_malloc(len + 1);
200: memcpy(pattern[patterns], pat, len);
201: pattern[patterns][len] = '\0';
202: }
1.3 deraadt 203: ++patterns;
204: }
1.1 deraadt 205:
1.3 deraadt 206: static void
1.35 otto 207: add_patterns(char *pats)
208: {
209: char *nl;
210:
211: while ((nl = strchr(pats, '\n')) != NULL) {
212: add_pattern(pats, nl - pats);
213: pats = nl + 1;
214: }
215: add_pattern(pats, strlen(pats));
216: }
217:
218: static void
1.33 jaredy 219: read_patterns(const char *fn)
1.3 deraadt 220: {
221: FILE *f;
222: char *line;
223: size_t len;
224:
225: if ((f = fopen(fn, "r")) == NULL)
1.20 millert 226: err(2, "%s", fn);
1.38 kili 227: while ((line = fgetln(f, &len)) != NULL)
228: add_pattern(line, *line == '\n' ? 0 : len);
1.3 deraadt 229: if (ferror(f))
1.20 millert 230: err(2, "%s", fn);
1.3 deraadt 231: fclose(f);
232: }
1.1 deraadt 233:
234: int
1.3 deraadt 235: main(int argc, char *argv[])
1.1 deraadt 236: {
1.38 kili 237: int c, lastc, prevoptind, newarg, i, needpattern;
1.33 jaredy 238: struct patfile *patfile, *pf_next;
1.21 millert 239: long l;
240: char *ep;
1.3 deraadt 241:
1.33 jaredy 242: SLIST_INIT(&patfilelh);
1.16 tedu 243: switch (__progname[0]) {
244: case 'e':
245: Eflag++;
246: break;
247: case 'f':
248: Fflag++;
249: break;
250: case 'g':
251: Gflag++;
252: break;
253: #ifndef NOZ
254: case 'z':
255: Zflag++;
256: switch(__progname[1]) {
257: case 'e':
258: Eflag++;
259: break;
260: case 'f':
261: Fflag++;
262: break;
263: case 'g':
264: Gflag++;
265: break;
266: }
267: break;
268: #endif
269: }
270:
1.18 millert 271: lastc = '\0';
1.23 millert 272: newarg = 1;
273: prevoptind = 1;
1.38 kili 274: needpattern = 1;
1.5 deraadt 275: while ((c = getopt_long(argc, argv, optstr,
1.17 millert 276: long_options, NULL)) != -1) {
1.3 deraadt 277: switch (c) {
278: case '0': case '1': case '2': case '3': case '4':
279: case '5': case '6': case '7': case '8': case '9':
1.23 millert 280: if (newarg || !isdigit(lastc))
281: Aflag = 0;
282: else if (Aflag > INT_MAX / 10)
283: errx(2, "context out of range");
284: Aflag = Bflag = (Aflag * 10) + (c - '0');
1.3 deraadt 285: break;
286: case 'A':
287: case 'B':
1.21 millert 288: l = strtol(optarg, &ep, 10);
289: if (ep == optarg || *ep != '\0' ||
290: l <= 0 || l >= INT_MAX)
291: errx(2, "context out of range");
292: if (c == 'A')
293: Aflag = (int)l;
294: else
295: Bflag = (int)l;
1.3 deraadt 296: break;
297: case 'C':
1.5 deraadt 298: if (optarg == NULL)
1.3 deraadt 299: Aflag = Bflag = 2;
1.21 millert 300: else {
301: l = strtol(optarg, &ep, 10);
302: if (ep == optarg || *ep != '\0' ||
303: l <= 0 || l >= INT_MAX)
304: errx(2, "context out of range");
305: Aflag = Bflag = (int)l;
306: }
1.1 deraadt 307: break;
308: case 'E':
1.16 tedu 309: Fflag = Gflag = 0;
1.3 deraadt 310: Eflag++;
1.1 deraadt 311: break;
312: case 'F':
1.16 tedu 313: Eflag = Gflag = 0;
1.3 deraadt 314: Fflag++;
315: break;
316: case 'G':
1.16 tedu 317: Eflag = Fflag = 0;
1.3 deraadt 318: Gflag++;
1.1 deraadt 319: break;
320: case 'H':
1.3 deraadt 321: Hflag++;
1.1 deraadt 322: break;
1.9 tedu 323: case 'I':
324: binbehave = BIN_FILE_SKIP;
325: break;
1.1 deraadt 326: case 'L':
1.3 deraadt 327: lflag = 0;
328: Lflag = qflag = 1;
1.1 deraadt 329: break;
330: case 'P':
1.3 deraadt 331: Pflag++;
332: break;
333: case 'S':
334: Sflag++;
1.1 deraadt 335: break;
336: case 'R':
1.3 deraadt 337: case 'r':
338: Rflag++;
339: oflag++;
340: break;
341: case 'U':
1.9 tedu 342: binbehave = BIN_FILE_BIN;
1.3 deraadt 343: break;
344: case 'V':
345: fprintf(stderr, "grep version %u.%u\n", VER_MAJ, VER_MIN);
1.9 tedu 346: exit(0);
1.1 deraadt 347: break;
1.5 deraadt 348: #ifndef NOZ
1.3 deraadt 349: case 'Z':
350: Zflag++;
1.1 deraadt 351: break;
1.5 deraadt 352: #endif
1.1 deraadt 353: case 'a':
1.9 tedu 354: binbehave = BIN_FILE_TEXT;
1.1 deraadt 355: break;
356: case 'b':
1.3 deraadt 357: bflag = 1;
1.1 deraadt 358: break;
359: case 'c':
1.3 deraadt 360: cflag = 1;
1.1 deraadt 361: break;
362: case 'e':
1.35 otto 363: add_patterns(optarg);
1.38 kili 364: needpattern = 0;
1.1 deraadt 365: break;
366: case 'f':
1.33 jaredy 367: patfile = grep_malloc(sizeof(*patfile));
368: patfile->pf_file = optarg;
369: SLIST_INSERT_HEAD(&patfilelh, patfile, pf_next);
1.38 kili 370: needpattern = 0;
1.1 deraadt 371: break;
372: case 'h':
1.3 deraadt 373: oflag = 0;
374: hflag = 1;
1.1 deraadt 375: break;
376: case 'i':
1.3 deraadt 377: case 'y':
1.13 tedu 378: iflag = 1;
1.1 deraadt 379: cflags |= REG_ICASE;
380: break;
381: case 'l':
1.3 deraadt 382: Lflag = 0;
383: lflag = qflag = 1;
1.1 deraadt 384: break;
385: case 'n':
1.3 deraadt 386: nflag = 1;
387: break;
388: case 'o':
389: hflag = 0;
390: oflag = 1;
1.1 deraadt 391: break;
392: case 'q':
1.3 deraadt 393: qflag = 1;
1.1 deraadt 394: break;
395: case 's':
1.3 deraadt 396: sflag = 1;
1.1 deraadt 397: break;
398: case 'v':
1.3 deraadt 399: vflag = 1;
1.1 deraadt 400: break;
401: case 'w':
1.3 deraadt 402: wflag = 1;
1.1 deraadt 403: break;
404: case 'x':
1.3 deraadt 405: xflag = 1;
1.1 deraadt 406: break;
1.9 tedu 407: case BIN_OPT:
408: if (strcmp("binary", optarg) == 0)
409: binbehave = BIN_FILE_BIN;
410: else if (strcmp("without-match", optarg) == 0)
411: binbehave = BIN_FILE_SKIP;
412: else if (strcmp("text", optarg) == 0)
413: binbehave = BIN_FILE_TEXT;
414: else
415: errx(2, "Unknown binary-files option");
416: break;
417: case 'u':
418: case MMAP_OPT:
419: /* default, compatibility */
420: break;
1.27 otto 421: case LINEBUF_OPT:
422: lbflag = 1;
423: break;
1.9 tedu 424: case HELP_OPT:
1.1 deraadt 425: default:
426: usage();
427: }
1.18 millert 428: lastc = c;
1.23 millert 429: newarg = optind != prevoptind;
1.18 millert 430: prevoptind = optind;
1.1 deraadt 431: }
1.3 deraadt 432: argc -= optind;
433: argv += optind;
1.33 jaredy 434:
435: for (patfile = SLIST_FIRST(&patfilelh); patfile != NULL;
436: patfile = pf_next) {
437: pf_next = SLIST_NEXT(patfile, pf_next);
438: read_patterns(patfile->pf_file);
439: free(patfile);
440: }
1.3 deraadt 441:
1.38 kili 442: if (argc == 0 && needpattern)
1.1 deraadt 443: usage();
444:
1.38 kili 445: if (argc != 0 && needpattern) {
1.35 otto 446: add_patterns(*argv);
1.3 deraadt 447: --argc;
448: ++argv;
449: }
1.5 deraadt 450:
1.16 tedu 451: if (Eflag)
452: cflags |= REG_EXTENDED;
1.39 ! deraadt 453: fg_pattern = grep_calloc(patterns, sizeof(*fg_pattern));
! 454: r_pattern = grep_calloc(patterns, sizeof(*r_pattern));
1.3 deraadt 455: for (i = 0; i < patterns; ++i) {
1.28 millert 456: /* Check if cheating is allowed (always is for fgrep). */
457: if (Fflag) {
458: fgrepcomp(&fg_pattern[i], pattern[i]);
459: } else {
460: if (fastcomp(&fg_pattern[i], pattern[i])) {
461: /* Fall back to full regex library */
462: c = regcomp(&r_pattern[i], pattern[i], cflags);
463: if (c != 0) {
464: regerror(c, &r_pattern[i], re_error,
465: RE_ERROR_BUF);
466: errx(2, "%s", re_error);
467: }
1.13 tedu 468: }
1.1 deraadt 469: }
470: }
1.29 deraadt 471:
1.27 otto 472: if (lbflag)
473: setlinebuf(stdout);
1.1 deraadt 474:
1.3 deraadt 475: if ((argc == 0 || argc == 1) && !oflag)
476: hflag = 1;
1.1 deraadt 477:
1.3 deraadt 478: if (argc == 0)
479: exit(!procfile(NULL));
1.5 deraadt 480:
1.3 deraadt 481: if (Rflag)
482: c = grep_tree(argv);
1.1 deraadt 483: else
1.3 deraadt 484: for (c = 0; argc--; ++argv)
485: c += procfile(*argv);
1.1 deraadt 486:
1.3 deraadt 487: exit(!c);
1.1 deraadt 488: }