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