]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/grep/grep.c
grep: turn off -w if -x is specified
[FreeBSD/FreeBSD.git] / usr.bin / grep / grep.c
1 /*      $NetBSD: grep.c,v 1.6 2011/04/18 03:48:23 joerg Exp $   */
2 /*      $FreeBSD$       */
3 /*      $OpenBSD: grep.c,v 1.42 2010/07/02 22:18:03 tedu Exp $  */
4
5 /*-
6  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
7  *
8  * Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
9  * Copyright (C) 2008-2009 Gabor Kovesdan <gabor@FreeBSD.org>
10  * All rights reserved.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36
37 #include <sys/stat.h>
38 #include <sys/types.h>
39
40 #include <ctype.h>
41 #include <err.h>
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <getopt.h>
45 #include <limits.h>
46 #include <libgen.h>
47 #include <locale.h>
48 #include <stdbool.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <unistd.h>
53
54 #include "grep.h"
55
56 const char      *errstr[] = {
57         "",
58 /* 1*/  "(standard input)",
59 /* 2*/  "unknown %s option",
60 /* 3*/  "usage: %s [-abcDEFGHhIiLlmnOoPqRSsUVvwxz] [-A num] [-B num] [-C[num]]\n",
61 /* 4*/  "\t[-e pattern] [-f file] [--binary-files=value] [--color=when]\n",
62 /* 5*/  "\t[--context[=num]] [--directories=action] [--label] [--line-buffered]\n",
63 /* 6*/  "\t[--null] [pattern] [file ...]\n",
64 /* 7*/  "Binary file %s matches\n",
65 /* 8*/  "%s (BSD grep) %s\n",
66 /* 9*/  "%s (BSD grep, GNU compatible) %s\n",
67 };
68
69 /* Flags passed to regcomp() and regexec() */
70 int              cflags = REG_NOSUB | REG_NEWLINE;
71 int              eflags = REG_STARTEND;
72
73 bool             matchall;
74
75 /* Searching patterns */
76 unsigned int     patterns;
77 static unsigned int pattern_sz;
78 struct pat      *pattern;
79 regex_t         *r_pattern;
80
81 /* Filename exclusion/inclusion patterns */
82 unsigned int    fpatterns, dpatterns;
83 static unsigned int fpattern_sz, dpattern_sz;
84 struct epat     *dpattern, *fpattern;
85
86 /* For regex errors  */
87 char     re_error[RE_ERROR_BUF + 1];
88
89 /* Command-line flags */
90 long long Aflag;        /* -A x: print x lines trailing each match */
91 long long Bflag;        /* -B x: print x lines leading each match */
92 bool     Hflag;         /* -H: always print file name */
93 bool     Lflag;         /* -L: only show names of files with no matches */
94 bool     bflag;         /* -b: show block numbers for each match */
95 bool     cflag;         /* -c: only show a count of matching lines */
96 bool     hflag;         /* -h: don't print filename headers */
97 bool     iflag;         /* -i: ignore case */
98 bool     lflag;         /* -l: only show names of files with matches */
99 bool     mflag;         /* -m x: stop reading the files after x matches */
100 long long mcount;       /* count for -m */
101 long long mlimit;       /* requested value for -m */
102 char     fileeol;       /* indicator for eol */
103 bool     nflag;         /* -n: show line numbers in front of matching lines */
104 bool     oflag;         /* -o: print only matching part */
105 bool     qflag;         /* -q: quiet mode (don't output anything) */
106 bool     sflag;         /* -s: silent mode (ignore errors) */
107 bool     vflag;         /* -v: only show non-matching lines */
108 bool     wflag;         /* -w: pattern must start and end on word boundaries */
109 bool     xflag;         /* -x: pattern must match entire line */
110 bool     lbflag;        /* --line-buffered */
111 bool     nullflag;      /* --null */
112 char    *label;         /* --label */
113 const char *color;      /* --color */
114 int      grepbehave = GREP_BASIC;       /* -EFGP: type of the regex */
115 int      binbehave = BINFILE_BIN;       /* -aIU: handling of binary files */
116 int      filebehave = FILE_STDIO;
117 int      devbehave = DEV_READ;          /* -D: handling of devices */
118 int      dirbehave = DIR_READ;          /* -dRr: handling of directories */
119 int      linkbehave = LINK_READ;        /* -OpS: handling of symlinks */
120
121 bool     dexclude, dinclude;    /* --exclude-dir and --include-dir */
122 bool     fexclude, finclude;    /* --exclude and --include */
123
124 enum {
125         BIN_OPT = CHAR_MAX + 1,
126         COLOR_OPT,
127         HELP_OPT,
128         MMAP_OPT,
129         LINEBUF_OPT,
130         LABEL_OPT,
131         NULL_OPT,
132         R_EXCLUDE_OPT,
133         R_INCLUDE_OPT,
134         R_DEXCLUDE_OPT,
135         R_DINCLUDE_OPT
136 };
137
138 static inline const char        *init_color(const char *);
139
140 /* Housekeeping */
141 bool     file_err;      /* file reading error */
142
143 /*
144  * Prints usage information and returns 2.
145  */
146 static void
147 usage(void)
148 {
149         fprintf(stderr, errstr[3], getprogname());
150         fprintf(stderr, "%s", errstr[4]);
151         fprintf(stderr, "%s", errstr[5]);
152         fprintf(stderr, "%s", errstr[6]);
153         exit(2);
154 }
155
156 static const char       *optstr = "0123456789A:B:C:D:EFGHILOPSRUVabcd:e:f:hilm:nopqrsuvwxyz";
157
158 static const struct option long_options[] =
159 {
160         {"binary-files",        required_argument,      NULL, BIN_OPT},
161         {"help",                no_argument,            NULL, HELP_OPT},
162         {"mmap",                no_argument,            NULL, MMAP_OPT},
163         {"line-buffered",       no_argument,            NULL, LINEBUF_OPT},
164         {"label",               required_argument,      NULL, LABEL_OPT},
165         {"null",                no_argument,            NULL, NULL_OPT},
166         {"color",               optional_argument,      NULL, COLOR_OPT},
167         {"colour",              optional_argument,      NULL, COLOR_OPT},
168         {"exclude",             required_argument,      NULL, R_EXCLUDE_OPT},
169         {"include",             required_argument,      NULL, R_INCLUDE_OPT},
170         {"exclude-dir",         required_argument,      NULL, R_DEXCLUDE_OPT},
171         {"include-dir",         required_argument,      NULL, R_DINCLUDE_OPT},
172         {"after-context",       required_argument,      NULL, 'A'},
173         {"text",                no_argument,            NULL, 'a'},
174         {"before-context",      required_argument,      NULL, 'B'},
175         {"byte-offset",         no_argument,            NULL, 'b'},
176         {"context",             optional_argument,      NULL, 'C'},
177         {"count",               no_argument,            NULL, 'c'},
178         {"devices",             required_argument,      NULL, 'D'},
179         {"directories",         required_argument,      NULL, 'd'},
180         {"extended-regexp",     no_argument,            NULL, 'E'},
181         {"regexp",              required_argument,      NULL, 'e'},
182         {"fixed-strings",       no_argument,            NULL, 'F'},
183         {"file",                required_argument,      NULL, 'f'},
184         {"basic-regexp",        no_argument,            NULL, 'G'},
185         {"no-filename",         no_argument,            NULL, 'h'},
186         {"with-filename",       no_argument,            NULL, 'H'},
187         {"ignore-case",         no_argument,            NULL, 'i'},
188         {"files-with-matches",  no_argument,            NULL, 'l'},
189         {"files-without-match", no_argument,            NULL, 'L'},
190         {"max-count",           required_argument,      NULL, 'm'},
191         {"line-number",         no_argument,            NULL, 'n'},
192         {"only-matching",       no_argument,            NULL, 'o'},
193         {"quiet",               no_argument,            NULL, 'q'},
194         {"silent",              no_argument,            NULL, 'q'},
195         {"recursive",           no_argument,            NULL, 'r'},
196         {"no-messages",         no_argument,            NULL, 's'},
197         {"binary",              no_argument,            NULL, 'U'},
198         {"unix-byte-offsets",   no_argument,            NULL, 'u'},
199         {"invert-match",        no_argument,            NULL, 'v'},
200         {"version",             no_argument,            NULL, 'V'},
201         {"word-regexp",         no_argument,            NULL, 'w'},
202         {"line-regexp",         no_argument,            NULL, 'x'},
203         {"null-data",           no_argument,            NULL, 'z'},
204         {NULL,                  no_argument,            NULL, 0}
205 };
206
207 /*
208  * Adds a searching pattern to the internal array.
209  */
210 static void
211 add_pattern(char *pat, size_t len)
212 {
213
214         /* Check if we can do a shortcut */
215         if (len == 0) {
216                 matchall = true;
217                 return;
218         }
219         /* Increase size if necessary */
220         if (patterns == pattern_sz) {
221                 pattern_sz *= 2;
222                 pattern = grep_realloc(pattern, ++pattern_sz *
223                     sizeof(struct pat));
224         }
225         if (len > 0 && pat[len - 1] == '\n')
226                 --len;
227         /* pat may not be NUL-terminated */
228         pattern[patterns].pat = grep_malloc(len + 1);
229         memcpy(pattern[patterns].pat, pat, len);
230         pattern[patterns].len = len;
231         pattern[patterns].pat[len] = '\0';
232         ++patterns;
233 }
234
235 /*
236  * Adds a file include/exclude pattern to the internal array.
237  */
238 static void
239 add_fpattern(const char *pat, int mode)
240 {
241
242         /* Increase size if necessary */
243         if (fpatterns == fpattern_sz) {
244                 fpattern_sz *= 2;
245                 fpattern = grep_realloc(fpattern, ++fpattern_sz *
246                     sizeof(struct epat));
247         }
248         fpattern[fpatterns].pat = grep_strdup(pat);
249         fpattern[fpatterns].mode = mode;
250         ++fpatterns;
251 }
252
253 /*
254  * Adds a directory include/exclude pattern to the internal array.
255  */
256 static void
257 add_dpattern(const char *pat, int mode)
258 {
259
260         /* Increase size if necessary */
261         if (dpatterns == dpattern_sz) {
262                 dpattern_sz *= 2;
263                 dpattern = grep_realloc(dpattern, ++dpattern_sz *
264                     sizeof(struct epat));
265         }
266         dpattern[dpatterns].pat = grep_strdup(pat);
267         dpattern[dpatterns].mode = mode;
268         ++dpatterns;
269 }
270
271 /*
272  * Reads searching patterns from a file and adds them with add_pattern().
273  */
274 static void
275 read_patterns(const char *fn)
276 {
277         struct stat st;
278         FILE *f;
279         char *line;
280         size_t len;
281         ssize_t rlen;
282
283         if (strcmp(fn, "-") == 0)
284                 f = stdin;
285         else if ((f = fopen(fn, "r")) == NULL)
286                 err(2, "%s", fn);
287         if ((fstat(fileno(f), &st) == -1) || (S_ISDIR(st.st_mode))) {
288                 fclose(f);
289                 return;
290         }
291         len = 0;
292         line = NULL;
293         while ((rlen = getline(&line, &len, f)) != -1) {
294                 if (line[0] == '\0')
295                         continue;
296                 add_pattern(line, line[0] == '\n' ? 0 : (size_t)rlen);
297         }
298
299         free(line);
300         if (ferror(f))
301                 err(2, "%s", fn);
302         if (strcmp(fn, "-") != 0)
303                 fclose(f);
304 }
305
306 static inline const char *
307 init_color(const char *d)
308 {
309         char *c;
310
311         c = getenv("GREP_COLOR");
312         return (c != NULL && c[0] != '\0' ? c : d);
313 }
314
315 int
316 main(int argc, char *argv[])
317 {
318         char **aargv, **eargv, *eopts;
319         char *ep;
320         const char *pn;
321         long long l;
322         unsigned int aargc, eargc, i;
323         int c, lastc, needpattern, newarg, prevoptind;
324         bool matched;
325
326         setlocale(LC_ALL, "");
327
328         /*
329          * Check how we've bene invoked to determine the behavior we should
330          * exhibit. In this way we can have all the functionalities in one
331          * binary without the need of scripting and using ugly hacks.
332          */
333         pn = getprogname();
334         switch (pn[0]) {
335         case 'e':
336                 grepbehave = GREP_EXTENDED;
337                 break;
338         case 'f':
339                 grepbehave = GREP_FIXED;
340                 break;
341         case 'r':
342                 dirbehave = DIR_RECURSE;
343                 Hflag = true;
344                 break;
345         }
346
347         lastc = '\0';
348         newarg = 1;
349         prevoptind = 1;
350         needpattern = 1;
351         fileeol = '\n';
352
353         eopts = getenv("GREP_OPTIONS");
354
355         /* support for extra arguments in GREP_OPTIONS */
356         eargc = 0;
357         if (eopts != NULL && eopts[0] != '\0') {
358                 char *str;
359
360                 /* make an estimation of how many extra arguments we have */
361                 for (unsigned int j = 0; j < strlen(eopts); j++)
362                         if (eopts[j] == ' ')
363                                 eargc++;
364
365                 eargv = (char **)grep_malloc(sizeof(char *) * (eargc + 1));
366
367                 eargc = 0;
368                 /* parse extra arguments */
369                 while ((str = strsep(&eopts, " ")) != NULL)
370                         if (str[0] != '\0')
371                                 eargv[eargc++] = grep_strdup(str);
372
373                 aargv = (char **)grep_calloc(eargc + argc + 1,
374                     sizeof(char *));
375
376                 aargv[0] = argv[0];
377                 for (i = 0; i < eargc; i++)
378                         aargv[i + 1] = eargv[i];
379                 for (int j = 1; j < argc; j++, i++)
380                         aargv[i + 1] = argv[j];
381
382                 aargc = eargc + argc;
383         } else {
384                 aargv = argv;
385                 aargc = argc;
386         }
387
388         while (((c = getopt_long(aargc, aargv, optstr, long_options, NULL)) !=
389             -1)) {
390                 switch (c) {
391                 case '0': case '1': case '2': case '3': case '4':
392                 case '5': case '6': case '7': case '8': case '9':
393                         if (newarg || !isdigit(lastc))
394                                 Aflag = 0;
395                         else if (Aflag > LLONG_MAX / 10 - 1) {
396                                 errno = ERANGE;
397                                 err(2, NULL);
398                         }
399
400                         Aflag = Bflag = (Aflag * 10) + (c - '0');
401                         break;
402                 case 'C':
403                         if (optarg == NULL) {
404                                 Aflag = Bflag = 2;
405                                 break;
406                         }
407                         /* FALLTHROUGH */
408                 case 'A':
409                         /* FALLTHROUGH */
410                 case 'B':
411                         errno = 0;
412                         l = strtoll(optarg, &ep, 10);
413                         if (errno == ERANGE || errno == EINVAL)
414                                 err(2, NULL);
415                         else if (ep[0] != '\0') {
416                                 errno = EINVAL;
417                                 err(2, NULL);
418                         } else if (l < 0) {
419                                 errno = EINVAL;
420                                 err(2, "context argument must be non-negative");
421                         }
422
423                         if (c == 'A')
424                                 Aflag = l;
425                         else if (c == 'B')
426                                 Bflag = l;
427                         else
428                                 Aflag = Bflag = l;
429                         break;
430                 case 'a':
431                         binbehave = BINFILE_TEXT;
432                         break;
433                 case 'b':
434                         bflag = true;
435                         break;
436                 case 'c':
437                         cflag = true;
438                         break;
439                 case 'D':
440                         if (strcasecmp(optarg, "skip") == 0)
441                                 devbehave = DEV_SKIP;
442                         else if (strcasecmp(optarg, "read") == 0)
443                                 devbehave = DEV_READ;
444                         else
445                                 errx(2, errstr[2], "--devices");
446                         break;
447                 case 'd':
448                         if (strcasecmp("recurse", optarg) == 0) {
449                                 Hflag = true;
450                                 dirbehave = DIR_RECURSE;
451                         } else if (strcasecmp("skip", optarg) == 0)
452                                 dirbehave = DIR_SKIP;
453                         else if (strcasecmp("read", optarg) == 0)
454                                 dirbehave = DIR_READ;
455                         else
456                                 errx(2, errstr[2], "--directories");
457                         break;
458                 case 'E':
459                         grepbehave = GREP_EXTENDED;
460                         break;
461                 case 'e':
462                         {
463                                 char *token;
464                                 char *string = optarg;
465
466                                 while ((token = strsep(&string, "\n")) != NULL)
467                                         add_pattern(token, strlen(token));
468                         }
469                         needpattern = 0;
470                         break;
471                 case 'F':
472                         grepbehave = GREP_FIXED;
473                         break;
474                 case 'f':
475                         read_patterns(optarg);
476                         needpattern = 0;
477                         break;
478                 case 'G':
479                         grepbehave = GREP_BASIC;
480                         break;
481                 case 'H':
482                         Hflag = true;
483                         break;
484                 case 'h':
485                         Hflag = false;
486                         hflag = true;
487                         break;
488                 case 'I':
489                         binbehave = BINFILE_SKIP;
490                         break;
491                 case 'i':
492                 case 'y':
493                         iflag =  true;
494                         cflags |= REG_ICASE;
495                         break;
496                 case 'L':
497                         lflag = false;
498                         Lflag = true;
499                         break;
500                 case 'l':
501                         Lflag = false;
502                         lflag = true;
503                         break;
504                 case 'm':
505                         mflag = true;
506                         errno = 0;
507                         mlimit = mcount = strtoll(optarg, &ep, 10);
508                         if (((errno == ERANGE) && (mcount == LLONG_MAX)) ||
509                             ((errno == EINVAL) && (mcount == 0)))
510                                 err(2, NULL);
511                         else if (ep[0] != '\0') {
512                                 errno = EINVAL;
513                                 err(2, NULL);
514                         }
515                         break;
516                 case 'n':
517                         nflag = true;
518                         break;
519                 case 'O':
520                         linkbehave = LINK_EXPLICIT;
521                         break;
522                 case 'o':
523                         oflag = true;
524                         cflags &= ~REG_NOSUB;
525                         break;
526                 case 'p':
527                         linkbehave = LINK_SKIP;
528                         break;
529                 case 'q':
530                         qflag = true;
531                         break;
532                 case 'S':
533                         linkbehave = LINK_READ;
534                         break;
535                 case 'R':
536                 case 'r':
537                         dirbehave = DIR_RECURSE;
538                         Hflag = true;
539                         break;
540                 case 's':
541                         sflag = true;
542                         break;
543                 case 'U':
544                         binbehave = BINFILE_BIN;
545                         break;
546                 case 'u':
547                 case MMAP_OPT:
548                         filebehave = FILE_MMAP;
549                         break;
550                 case 'V':
551 #ifdef WITH_GNU_COMPAT
552                         printf(errstr[9], getprogname(), VERSION);
553 #else
554                         printf(errstr[8], getprogname(), VERSION);
555 #endif
556                         exit(0);
557                 case 'v':
558                         vflag = true;
559                         break;
560                 case 'w':
561                         wflag = true;
562                         cflags &= ~REG_NOSUB;
563                         break;
564                 case 'x':
565                         xflag = true;
566                         cflags &= ~REG_NOSUB;
567                         break;
568                 case 'z':
569                         fileeol = '\0';
570                         break;
571                 case BIN_OPT:
572                         if (strcasecmp("binary", optarg) == 0)
573                                 binbehave = BINFILE_BIN;
574                         else if (strcasecmp("without-match", optarg) == 0)
575                                 binbehave = BINFILE_SKIP;
576                         else if (strcasecmp("text", optarg) == 0)
577                                 binbehave = BINFILE_TEXT;
578                         else
579                                 errx(2, errstr[2], "--binary-files");
580                         break;
581                 case COLOR_OPT:
582                         color = NULL;
583                         if (optarg == NULL || strcasecmp("auto", optarg) == 0 ||
584                             strcasecmp("tty", optarg) == 0 ||
585                             strcasecmp("if-tty", optarg) == 0) {
586                                 char *term;
587
588                                 term = getenv("TERM");
589                                 if (isatty(STDOUT_FILENO) && term != NULL &&
590                                     strcasecmp(term, "dumb") != 0)
591                                         color = init_color("01;31");
592                         } else if (strcasecmp("always", optarg) == 0 ||
593                             strcasecmp("yes", optarg) == 0 ||
594                             strcasecmp("force", optarg) == 0) {
595                                 color = init_color("01;31");
596                         } else if (strcasecmp("never", optarg) != 0 &&
597                             strcasecmp("none", optarg) != 0 &&
598                             strcasecmp("no", optarg) != 0)
599                                 errx(2, errstr[2], "--color");
600                         cflags &= ~REG_NOSUB;
601                         break;
602                 case LABEL_OPT:
603                         label = optarg;
604                         break;
605                 case LINEBUF_OPT:
606                         lbflag = true;
607                         break;
608                 case NULL_OPT:
609                         nullflag = true;
610                         break;
611                 case R_INCLUDE_OPT:
612                         finclude = true;
613                         add_fpattern(optarg, INCL_PAT);
614                         break;
615                 case R_EXCLUDE_OPT:
616                         fexclude = true;
617                         add_fpattern(optarg, EXCL_PAT);
618                         break;
619                 case R_DINCLUDE_OPT:
620                         dinclude = true;
621                         add_dpattern(optarg, INCL_PAT);
622                         break;
623                 case R_DEXCLUDE_OPT:
624                         dexclude = true;
625                         add_dpattern(optarg, EXCL_PAT);
626                         break;
627                 case HELP_OPT:
628                 default:
629                         usage();
630                 }
631                 lastc = c;
632                 newarg = optind != prevoptind;
633                 prevoptind = optind;
634         }
635         aargc -= optind;
636         aargv += optind;
637
638         /* xflag takes precedence, don't confuse the matching bits. */
639         if (wflag && xflag)
640                 wflag = false;
641
642         /* Fail if we don't have any pattern */
643         if (aargc == 0 && needpattern)
644                 usage();
645
646         /* Process patterns from command line */
647         if (aargc != 0 && needpattern) {
648                 char *token;
649                 char *string = *aargv;
650
651                 while ((token = strsep(&string, "\n")) != NULL)
652                         add_pattern(token, strlen(token));
653                 --aargc;
654                 ++aargv;
655         }
656
657         switch (grepbehave) {
658         case GREP_BASIC:
659                 break;
660         case GREP_FIXED:
661                 /*
662                  * regex(3) implementations that support fixed-string searches generally
663                  * define either REG_NOSPEC or REG_LITERAL. Set the appropriate flag
664                  * here. If neither are defined, GREP_FIXED later implies that the
665                  * internal literal matcher should be used. Other cflags that have
666                  * the same interpretation as REG_NOSPEC and REG_LITERAL should be
667                  * similarly added here, and grep.h should be amended to take this into
668                  * consideration when defining WITH_INTERNAL_NOSPEC.
669                  */
670 #if defined(REG_NOSPEC)
671                 cflags |= REG_NOSPEC;
672 #elif defined(REG_LITERAL)
673                 cflags |= REG_LITERAL;
674 #endif
675                 break;
676         case GREP_EXTENDED:
677                 cflags |= REG_EXTENDED;
678                 break;
679         default:
680                 /* NOTREACHED */
681                 usage();
682         }
683
684         r_pattern = grep_calloc(patterns, sizeof(*r_pattern));
685
686 #ifdef WITH_INTERNAL_NOSPEC
687         if (grepbehave != GREP_FIXED) {
688 #else
689         {
690 #endif
691                 /* Check if cheating is allowed (always is for fgrep). */
692                 for (i = 0; i < patterns; ++i) {
693                         c = regcomp(&r_pattern[i], pattern[i].pat, cflags);
694                         if (c != 0) {
695                                 regerror(c, &r_pattern[i], re_error,
696                                     RE_ERROR_BUF);
697                                 errx(2, "%s", re_error);
698                         }
699                 }
700         }
701
702         if (lbflag)
703                 setlinebuf(stdout);
704
705         if ((aargc == 0 || aargc == 1) && !Hflag)
706                 hflag = true;
707
708         initqueue();
709
710         if (aargc == 0 && dirbehave != DIR_RECURSE)
711                 exit(!procfile("-"));
712
713         if (dirbehave == DIR_RECURSE)
714                 matched = grep_tree(aargv);
715         else
716                 for (matched = false; aargc--; ++aargv) {
717                         if ((finclude || fexclude) && !file_matching(*aargv))
718                                 continue;
719                         if (procfile(*aargv))
720                                 matched = true;
721                 }
722
723         if (Lflag)
724                 matched = !matched;
725
726         /*
727          * Calculate the correct return value according to the
728          * results and the command line option.
729          */
730         exit(matched ? (file_err ? (qflag ? 0 : 2) : 0) : (file_err ? 2 : 1));
731 }