Annotation of src/usr.bin/grep/grep.c, Revision 1.52
1.52 ! dlg 1: /* $OpenBSD: grep.c,v 1.51 2015/04/30 13:49:04 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>
30: #include <sys/stat.h>
1.33 jaredy 31: #include <sys/queue.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 */
1.43 tedu 63: int Hflag; /* -H: always print filename header */
1.3 deraadt 64: int Lflag; /* -L: only show names of files with no matches */
65: int Rflag; /* -R: recursively search directory trees */
1.5 deraadt 66: #ifndef NOZ
1.3 deraadt 67: int Zflag; /* -Z: decompress input before processing */
1.5 deraadt 68: #endif
1.3 deraadt 69: int bflag; /* -b: show block numbers for each match */
70: int cflag; /* -c: only show a count of matching lines */
71: int hflag; /* -h: don't print filename headers */
72: int iflag; /* -i: ignore case */
73: int lflag; /* -l: only show names of files with matches */
74: int nflag; /* -n: show line numbers in front of matching lines */
1.44 tedu 75: int oflag; /* -o: print each match */
1.3 deraadt 76: int qflag; /* -q: quiet mode (don't output anything) */
77: int sflag; /* -s: silent mode (ignore errors) */
78: int vflag; /* -v: only show non-matching lines */
79: int wflag; /* -w: pattern must start and end on word boundaries */
80: int xflag; /* -x: pattern must match entire line */
1.27 otto 81: int lbflag; /* --line-buffered */
1.3 deraadt 82:
1.9 tedu 83: int binbehave = BIN_FILE_BIN;
84:
85: enum {
86: BIN_OPT = CHAR_MAX + 1,
87: HELP_OPT,
1.27 otto 88: MMAP_OPT,
89: LINEBUF_OPT
1.9 tedu 90: };
91:
1.3 deraadt 92: /* Housekeeping */
1.10 tedu 93: int first; /* flag whether or not this is our first match */
1.3 deraadt 94: int tail; /* lines left to print */
1.45 millert 95: int file_err; /* file reading error */
1.3 deraadt 96:
1.33 jaredy 97: struct patfile {
98: const char *pf_file;
99: SLIST_ENTRY(patfile) pf_next;
100: };
101: SLIST_HEAD(, patfile) patfilelh;
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.44 tedu 110: "usage: %s [-abcEFGHhIiLlnoqRsUVvwx] [-A num] [-B num] [-C[num]]\n"
1.5 deraadt 111: #else
1.44 tedu 112: "usage: %s [-abcEFGHhIiLlnoqRsUVvwxZ] [-A num] [-B num] [-C[num]]\n"
1.5 deraadt 113: #endif
1.30 jmc 114: "\t[-e pattern] [-f file] [--binary-files=value] [--context[=num]]\n"
115: "\t[--line-buffered] [pattern] [file ...]\n", __progname);
1.3 deraadt 116: exit(2);
117: }
118:
1.5 deraadt 119: #ifdef NOZ
1.46 millert 120: static const char optstr[] = "0123456789A:B:CEFGHILRUVabce:f:hilnoqrsuvwxy";
1.5 deraadt 121: #else
1.46 millert 122: static const char optstr[] = "0123456789A:B:CEFGHILRUVZabce:f:hilnoqrsuvwxy";
1.5 deraadt 123: #endif
1.3 deraadt 124:
1.46 millert 125: static const 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'},
1.43 tedu 138: {"with-filename", no_argument, NULL, 'H'},
1.19 deraadt 139: {"binary", no_argument, NULL, 'U'},
140: {"version", no_argument, NULL, 'V'},
141: {"text", no_argument, NULL, 'a'},
142: {"byte-offset", no_argument, NULL, 'b'},
143: {"count", no_argument, NULL, 'c'},
144: {"regexp", required_argument, NULL, 'e'},
145: {"file", required_argument, NULL, 'f'},
146: {"no-filename", no_argument, NULL, 'h'},
147: {"ignore-case", no_argument, NULL, 'i'},
148: {"files-without-match", no_argument, NULL, 'L'},
149: {"files-with-matches", no_argument, NULL, 'l'},
150: {"line-number", no_argument, NULL, 'n'},
151: {"quiet", no_argument, NULL, 'q'},
152: {"silent", no_argument, NULL, 'q'},
153: {"recursive", no_argument, NULL, 'r'},
154: {"no-messages", no_argument, NULL, 's'},
155: {"revert-match", no_argument, NULL, 'v'},
156: {"word-regexp", no_argument, NULL, 'w'},
157: {"line-regexp", no_argument, NULL, 'x'},
158: {"unix-byte-offsets", no_argument, NULL, 'u'},
1.5 deraadt 159: #ifndef NOZ
1.19 deraadt 160: {"decompress", no_argument, NULL, 'Z'},
1.5 deraadt 161: #endif
1.19 deraadt 162: {NULL, no_argument, NULL, 0}
1.3 deraadt 163: };
164:
1.1 deraadt 165:
1.3 deraadt 166: static void
167: add_pattern(char *pat, size_t len)
168: {
1.36 jaredy 169: if (!xflag && (len == 0 || matchall)) {
1.3 deraadt 170: matchall = 1;
171: return;
172: }
173: if (patterns == pattern_sz) {
174: pattern_sz *= 2;
1.48 deraadt 175: pattern = grep_reallocarray(pattern, ++pattern_sz, sizeof(*pattern));
1.3 deraadt 176: }
1.37 ray 177: if (len > 0 && pat[len - 1] == '\n')
1.3 deraadt 178: --len;
1.15 tedu 179: /* pat may not be NUL-terminated */
1.28 millert 180: if (wflag && !Fflag) {
1.32 otto 181: int bol = 0, eol = 0, extra;
1.26 millert 182: if (pat[0] == '^')
183: bol = 1;
1.36 jaredy 184: if (len > 0 && pat[len - 1] == '$')
1.26 millert 185: eol = 1;
1.32 otto 186: extra = Eflag ? 2 : 4;
187: pattern[patterns] = grep_malloc(len + 15 + extra);
188: snprintf(pattern[patterns], len + 15 + extra,
189: "%s[[:<:]]%s%.*s%s[[:>:]]%s",
190: bol ? "^" : "",
191: Eflag ? "(" : "\\(",
192: (int)len - bol - eol, pat + bol,
193: Eflag ? ")" : "\\)",
1.26 millert 194: eol ? "$" : "");
1.32 otto 195: len += 14 + extra;
1.25 millert 196: } else {
197: pattern[patterns] = grep_malloc(len + 1);
198: memcpy(pattern[patterns], pat, len);
199: pattern[patterns][len] = '\0';
200: }
1.3 deraadt 201: ++patterns;
202: }
1.1 deraadt 203:
1.3 deraadt 204: static void
1.35 otto 205: add_patterns(char *pats)
206: {
207: char *nl;
208:
209: while ((nl = strchr(pats, '\n')) != NULL) {
210: add_pattern(pats, nl - pats);
211: pats = nl + 1;
212: }
213: add_pattern(pats, strlen(pats));
214: }
215:
216: static void
1.33 jaredy 217: read_patterns(const char *fn)
1.3 deraadt 218: {
219: FILE *f;
220: char *line;
221: size_t len;
222:
223: if ((f = fopen(fn, "r")) == NULL)
1.20 millert 224: err(2, "%s", fn);
1.38 kili 225: while ((line = fgetln(f, &len)) != NULL)
226: add_pattern(line, *line == '\n' ? 0 : len);
1.3 deraadt 227: if (ferror(f))
1.20 millert 228: err(2, "%s", fn);
1.3 deraadt 229: fclose(f);
230: }
1.1 deraadt 231:
232: int
1.3 deraadt 233: main(int argc, char *argv[])
1.1 deraadt 234: {
1.41 jacekm 235: int c, lastc, prevoptind, newarg, i, needpattern, exprs, expr_sz;
1.33 jaredy 236: struct patfile *patfile, *pf_next;
1.21 millert 237: long l;
1.52 ! dlg 238: char **expr;
! 239: const char *errstr;
1.3 deraadt 240:
1.33 jaredy 241: SLIST_INIT(&patfilelh);
1.16 tedu 242: switch (__progname[0]) {
243: case 'e':
1.49 tedu 244: Eflag = 1;
1.16 tedu 245: break;
246: case 'f':
1.49 tedu 247: Fflag = 1;
1.16 tedu 248: break;
249: #ifndef NOZ
250: case 'z':
1.49 tedu 251: Zflag = 1;
1.16 tedu 252: switch(__progname[1]) {
253: case 'e':
1.49 tedu 254: Eflag = 1;
1.16 tedu 255: break;
256: case 'f':
1.49 tedu 257: Fflag = 1;
1.16 tedu 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.38 kili 267: needpattern = 1;
1.41 jacekm 268: expr_sz = exprs = 0;
269: expr = NULL;
1.5 deraadt 270: while ((c = getopt_long(argc, argv, optstr,
1.17 millert 271: long_options, NULL)) != -1) {
1.3 deraadt 272: switch (c) {
273: case '0': case '1': case '2': case '3': case '4':
274: case '5': case '6': case '7': case '8': case '9':
1.23 millert 275: if (newarg || !isdigit(lastc))
276: Aflag = 0;
277: else if (Aflag > INT_MAX / 10)
278: errx(2, "context out of range");
279: Aflag = Bflag = (Aflag * 10) + (c - '0');
1.3 deraadt 280: break;
281: case 'A':
282: case 'B':
1.52 ! dlg 283: l = strtonum(optarg, 1, INT_MAX, &errstr);
! 284: if (errstr != NULL)
! 285: errx(2, "context %s", errstr);
1.21 millert 286: if (c == 'A')
287: Aflag = (int)l;
288: else
289: Bflag = (int)l;
1.3 deraadt 290: break;
291: case 'C':
1.5 deraadt 292: if (optarg == NULL)
1.3 deraadt 293: Aflag = Bflag = 2;
1.21 millert 294: else {
1.52 ! dlg 295: l = strtonum(optarg, 1, INT_MAX, &errstr);
! 296: if (errstr != NULL)
! 297: errx(2, "context %s", errstr);
1.21 millert 298: Aflag = Bflag = (int)l;
299: }
1.1 deraadt 300: break;
301: case 'E':
1.49 tedu 302: Fflag = 0;
303: Eflag = 1;
1.1 deraadt 304: break;
305: case 'F':
1.49 tedu 306: Eflag = 0;
307: Fflag = 1;
1.3 deraadt 308: break;
309: case 'G':
1.16 tedu 310: Eflag = Fflag = 0;
1.1 deraadt 311: break;
1.43 tedu 312: case 'H':
1.49 tedu 313: Hflag = 1;
1.43 tedu 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 'R':
1.3 deraadt 323: case 'r':
1.49 tedu 324: Rflag = 1;
1.3 deraadt 325: break;
326: case 'U':
1.9 tedu 327: binbehave = BIN_FILE_BIN;
1.3 deraadt 328: break;
329: case 'V':
330: fprintf(stderr, "grep version %u.%u\n", VER_MAJ, VER_MIN);
1.9 tedu 331: exit(0);
1.1 deraadt 332: break;
1.5 deraadt 333: #ifndef NOZ
1.3 deraadt 334: case 'Z':
1.49 tedu 335: Zflag = 1;
1.1 deraadt 336: break;
1.5 deraadt 337: #endif
1.1 deraadt 338: case 'a':
1.9 tedu 339: binbehave = BIN_FILE_TEXT;
1.1 deraadt 340: break;
341: case 'b':
1.3 deraadt 342: bflag = 1;
1.1 deraadt 343: break;
344: case 'c':
1.3 deraadt 345: cflag = 1;
1.1 deraadt 346: break;
347: case 'e':
1.41 jacekm 348: /* defer adding of expressions until all arguments are parsed */
349: if (exprs == expr_sz) {
350: expr_sz *= 2;
1.48 deraadt 351: expr = grep_reallocarray(expr, ++expr_sz,
352: sizeof(*expr));
1.41 jacekm 353: }
1.38 kili 354: needpattern = 0;
1.41 jacekm 355: expr[exprs] = optarg;
356: ++exprs;
1.1 deraadt 357: break;
358: case 'f':
1.33 jaredy 359: patfile = grep_malloc(sizeof(*patfile));
360: patfile->pf_file = optarg;
361: SLIST_INSERT_HEAD(&patfilelh, patfile, pf_next);
1.38 kili 362: needpattern = 0;
1.1 deraadt 363: break;
364: case 'h':
1.3 deraadt 365: hflag = 1;
1.1 deraadt 366: break;
367: case 'i':
1.3 deraadt 368: case 'y':
1.13 tedu 369: iflag = 1;
1.1 deraadt 370: cflags |= REG_ICASE;
371: break;
372: case 'l':
1.3 deraadt 373: Lflag = 0;
374: lflag = qflag = 1;
1.1 deraadt 375: break;
376: case 'n':
1.3 deraadt 377: nflag = 1;
1.44 tedu 378: break;
379: case 'o':
380: oflag = 1;
1.3 deraadt 381: break;
1.1 deraadt 382: case 'q':
1.3 deraadt 383: qflag = 1;
1.1 deraadt 384: break;
385: case 's':
1.3 deraadt 386: sflag = 1;
1.1 deraadt 387: break;
388: case 'v':
1.3 deraadt 389: vflag = 1;
1.1 deraadt 390: break;
391: case 'w':
1.3 deraadt 392: wflag = 1;
1.1 deraadt 393: break;
394: case 'x':
1.3 deraadt 395: xflag = 1;
1.1 deraadt 396: break;
1.9 tedu 397: case BIN_OPT:
398: if (strcmp("binary", optarg) == 0)
399: binbehave = BIN_FILE_BIN;
400: else if (strcmp("without-match", optarg) == 0)
401: binbehave = BIN_FILE_SKIP;
402: else if (strcmp("text", optarg) == 0)
403: binbehave = BIN_FILE_TEXT;
404: else
405: errx(2, "Unknown binary-files option");
406: break;
407: case 'u':
408: case MMAP_OPT:
409: /* default, compatibility */
410: break;
1.27 otto 411: case LINEBUF_OPT:
412: lbflag = 1;
413: break;
1.9 tedu 414: case HELP_OPT:
1.1 deraadt 415: default:
416: usage();
417: }
1.18 millert 418: lastc = c;
1.23 millert 419: newarg = optind != prevoptind;
1.18 millert 420: prevoptind = optind;
1.1 deraadt 421: }
1.3 deraadt 422: argc -= optind;
423: argv += optind;
1.41 jacekm 424:
425: for (i = 0; i < exprs; i++)
426: add_patterns(expr[i]);
427: free(expr);
428: expr = NULL;
1.33 jaredy 429:
430: for (patfile = SLIST_FIRST(&patfilelh); patfile != NULL;
431: patfile = pf_next) {
432: pf_next = SLIST_NEXT(patfile, pf_next);
433: read_patterns(patfile->pf_file);
434: free(patfile);
435: }
1.3 deraadt 436:
1.38 kili 437: if (argc == 0 && needpattern)
1.1 deraadt 438: usage();
439:
1.38 kili 440: if (argc != 0 && needpattern) {
1.35 otto 441: add_patterns(*argv);
1.3 deraadt 442: --argc;
443: ++argv;
444: }
1.5 deraadt 445:
1.51 millert 446: if (Rflag && argc == 0)
447: warnx("warning: recursive search of stdin");
1.16 tedu 448: if (Eflag)
449: cflags |= REG_EXTENDED;
1.42 tedu 450: if (Fflag)
451: cflags |= REG_NOSPEC;
452: #ifdef SMALL
453: /* Sorry, this won't work */
454: if (Fflag && wflag)
455: errx(1, "Can't use small fgrep with -w");
456: #endif
1.39 deraadt 457: fg_pattern = grep_calloc(patterns, sizeof(*fg_pattern));
458: r_pattern = grep_calloc(patterns, sizeof(*r_pattern));
1.3 deraadt 459: for (i = 0; i < patterns; ++i) {
1.28 millert 460: /* Check if cheating is allowed (always is for fgrep). */
1.42 tedu 461: #ifndef SMALL
1.28 millert 462: if (Fflag) {
463: fgrepcomp(&fg_pattern[i], pattern[i]);
1.42 tedu 464: } else
465: #endif
466: {
1.28 millert 467: if (fastcomp(&fg_pattern[i], pattern[i])) {
468: /* Fall back to full regex library */
469: c = regcomp(&r_pattern[i], pattern[i], cflags);
470: if (c != 0) {
471: regerror(c, &r_pattern[i], re_error,
472: RE_ERROR_BUF);
473: errx(2, "%s", re_error);
474: }
1.13 tedu 475: }
1.1 deraadt 476: }
477: }
1.29 deraadt 478:
1.27 otto 479: if (lbflag)
1.47 millert 480: setvbuf(stdout, NULL, _IOLBF, 0);
1.1 deraadt 481:
1.43 tedu 482: if ((argc == 0 || argc == 1) && !Rflag && !Hflag)
1.3 deraadt 483: hflag = 1;
1.1 deraadt 484:
1.3 deraadt 485: if (argc == 0)
486: exit(!procfile(NULL));
1.5 deraadt 487:
1.3 deraadt 488: if (Rflag)
489: c = grep_tree(argv);
1.1 deraadt 490: else
1.3 deraadt 491: for (c = 0; argc--; ++argv)
492: c += procfile(*argv);
1.1 deraadt 493:
1.45 millert 494: exit(c ? (file_err ? (qflag ? 0 : 2) : 0) : (file_err ? 2 : 1));
1.1 deraadt 495: }