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