Grep: Reintroducing local modification for HAMMER
[dragonfly.git] / contrib / grep / src / main.c
1 /* grep.c - main driver file for grep.
2    Copyright (C) 1992, 1997-2002, 2004-2010 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software
16    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
17    02110-1301, USA.  */
18
19 /* Written July 1992 by Mike Haertel.  */
20
21 #include <config.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #if defined HAVE_SETRLIMIT
25 # include <sys/time.h>
26 # include <sys/resource.h>
27 #endif
28 #include "mbsupport.h"
29 #include <wchar.h>
30 #include <wctype.h>
31 #include <fcntl.h>
32 #include <stdio.h>
33 #include "system.h"
34
35 #include "argmatch.h"
36 #include "c-ctype.h"
37 #include "closeout.h"
38 #include "error.h"
39 #include "exclude.h"
40 #include "exitfail.h"
41 #include "getopt.h"
42 #include "grep.h"
43 #include "intprops.h"
44 #include "isdir.h"
45 #include "progname.h"
46 #include "propername.h"
47 #include "savedir.h"
48 #include "version-etc.h"
49 #include "xalloc.h"
50 #include "xstrtol.h"
51
52 #define SEP_CHAR_SELECTED ':'
53 #define SEP_CHAR_REJECTED '-'
54 #define SEP_STR_GROUP    "--"
55
56 #define STREQ(a, b) (strcmp (a, b) == 0)
57
58 #define AUTHORS \
59   proper_name ("Mike Haertel"), \
60   _("others, see\n<http://git.sv.gnu.org/cgit/grep.git/tree/AUTHORS>")
61
62 struct stats
63 {
64   struct stats const *parent;
65   struct stat stat;
66 };
67
68 /* base of chain of stat buffers, used to detect directory loops */
69 static struct stats stats_base;
70
71 /* if non-zero, display usage information and exit */
72 static int show_help;
73
74 /* If non-zero, print the version on standard output and exit.  */
75 static int show_version;
76
77 /* If nonzero, suppress diagnostics for nonexistent or unreadable files.  */
78 static int suppress_errors;
79
80 /* If nonzero, use color markers.  */
81 static int color_option;
82
83 /* If nonzero, show only the part of a line matching the expression. */
84 static int only_matching;
85
86 /* If nonzero, make sure first content char in a line is on a tab stop. */
87 static int align_tabs;
88
89 /* The group separator used when context is requested. */
90 static const char *group_separator = SEP_STR_GROUP;
91
92 /* The context and logic for choosing default --color screen attributes
93    (foreground and background colors, etc.) are the following.
94       -- There are eight basic colors available, each with its own
95          nominal luminosity to the human eye and foreground/background
96          codes (black [0 %, 30/40], blue [11 %, 34/44], red [30 %, 31/41],
97          magenta [41 %, 35/45], green [59 %, 32/42], cyan [70 %, 36/46],
98          yellow [89 %, 33/43], and white [100 %, 37/47]).
99       -- Sometimes, white as a background is actually implemented using
100          a shade of light gray, so that a foreground white can be visible
101          on top of it (but most often not).
102       -- Sometimes, black as a foreground is actually implemented using
103          a shade of dark gray, so that it can be visible on top of a
104          background black (but most often not).
105       -- Sometimes, more colors are available, as extensions.
106       -- Other attributes can be selected/deselected (bold [1/22],
107          underline [4/24], standout/inverse [7/27], blink [5/25], and
108          invisible/hidden [8/28]).  They are sometimes implemented by
109          using colors instead of what their names imply; e.g., bold is
110          often achieved by using brighter colors.  In practice, only bold
111          is really available to us, underline sometimes being mapped by
112          the terminal to some strange color choice, and standout best
113          being left for use by downstream programs such as less(1).
114       -- We cannot assume that any of the extensions or special features
115          are available for the purpose of choosing defaults for everyone.
116       -- The most prevalent default terminal backgrounds are pure black
117          and pure white, and are not necessarily the same shades of
118          those as if they were selected explicitly with SGR sequences.
119          Some terminals use dark or light pictures as default background,
120          but those are covered over by an explicit selection of background
121          color with an SGR sequence; their users will appreciate their
122          background pictures not be covered like this, if possible.
123       -- Some uses of colors attributes is to make some output items
124          more understated (e.g., context lines); this cannot be achieved
125          by changing the background color.
126       -- For these reasons, the grep color defaults should strive not
127          to change the background color from its default, unless it's
128          for a short item that should be highlighted, not understated.
129       -- The grep foreground color defaults (without an explicitly set
130          background) should provide enough contrast to be readable on any
131          terminal with either a black (dark) or white (light) background.
132          This only leaves red, magenta, green, and cyan (and their bold
133          counterparts) and possibly bold blue.  */
134 /* The color strings used for matched text.
135    The user can overwrite them using the deprecated
136    environment variable GREP_COLOR or the new GREP_COLORS.  */
137 static const char *selected_match_color = "01;31";      /* bold red */
138 static const char *context_match_color  = "01;31";      /* bold red */
139
140 /* Other colors.  Defaults look damn good.  */
141 static const char *filename_color = "35";       /* magenta */
142 static const char *line_num_color = "32";       /* green */
143 static const char *byte_num_color = "32";       /* green */
144 static const char *sep_color      = "36";       /* cyan */
145 static const char *selected_line_color = "";    /* default color pair */
146 static const char *context_line_color  = "";    /* default color pair */
147
148 /* Select Graphic Rendition (SGR, "\33[...m") strings.  */
149 /* Also Erase in Line (EL) to Right ("\33[K") by default.  */
150 /*    Why have EL to Right after SGR?
151          -- The behavior of line-wrapping when at the bottom of the
152             terminal screen and at the end of the current line is often
153             such that a new line is introduced, entirely cleared with
154             the current background color which may be different from the
155             default one (see the boolean back_color_erase terminfo(5)
156             capability), thus scrolling the display by one line.
157             The end of this new line will stay in this background color
158             even after reverting to the default background color with
159             "\33[m', unless it is explicitly cleared again with "\33[K"
160             (which is the behavior the user would instinctively expect
161             from the whole thing).  There may be some unavoidable
162             background-color flicker at the end of this new line because
163             of this (when timing with the monitor's redraw is just right).
164          -- The behavior of HT (tab, "\t") is usually the same as that of
165             Cursor Forward Tabulation (CHT) with a default parameter
166             of 1 ("\33[I"), i.e., it performs pure movement to the next
167             tab stop, without any clearing of either content or screen
168             attributes (including background color); try
169                printf 'asdfqwerzxcv\rASDF\tZXCV\n'
170             in a bash(1) shell to demonstrate this.  This is not what the
171             user would instinctively expect of HT (but is ok for CHT).
172             The instinctive behavior would include clearing the terminal
173             cells that are skipped over by HT with blank cells in the
174             current screen attributes, including background color;
175             the boolean dest_tabs_magic_smso terminfo(5) capability
176             indicates this saner behavior for HT, but only some rare
177             terminals have it (although it also indicates a special
178             glitch with standout mode in the Teleray terminal for which
179             it was initially introduced).  The remedy is to add "\33K"
180             after each SGR sequence, be it START (to fix the behavior
181             of any HT after that before another SGR) or END (to fix the
182             behavior of an HT in default background color that would
183             follow a line-wrapping at the bottom of the screen in another
184             background color, and to complement doing it after START).
185             Piping grep's output through a pager such as less(1) avoids
186             any HT problems since the pager performs tab expansion.
187
188       Generic disadvantages of this remedy are:
189          -- Some very rare terminals might support SGR but not EL (nobody
190             will use "grep --color" on a terminal that does not support
191             SGR in the first place).
192          -- Having these extra control sequences might somewhat complicate
193             the task of any program trying to parse "grep --color"
194             output in order to extract structuring information from it.
195       A specific disadvantage to doing it after SGR START is:
196          -- Even more possible background color flicker (when timing
197             with the monitor's redraw is just right), even when not at the
198             bottom of the screen.
199       There are no additional disadvantages specific to doing it after
200       SGR END.
201
202       It would be impractical for GNU grep to become a full-fledged
203       terminal program linked against ncurses or the like, so it will
204       not detect terminfo(5) capabilities.  */
205 static const char *sgr_start = "\33[%sm\33[K";
206 #define SGR_START  sgr_start
207 static const char *sgr_end   = "\33[m\33[K";
208 #define SGR_END    sgr_end
209
210 /* SGR utility macros.  */
211 #define PR_SGR_FMT(fmt, s) do { if (*(s)) printf((fmt), (s)); } while (0)
212 #define PR_SGR_FMT_IF(fmt, s) \
213   do { if (color_option && *(s)) printf((fmt), (s)); } while (0)
214 #define PR_SGR_START(s)    PR_SGR_FMT(   SGR_START, (s))
215 #define PR_SGR_END(s)      PR_SGR_FMT(   SGR_END,   (s))
216 #define PR_SGR_START_IF(s) PR_SGR_FMT_IF(SGR_START, (s))
217 #define PR_SGR_END_IF(s)   PR_SGR_FMT_IF(SGR_END,   (s))
218
219 struct color_cap
220   {
221     const char *name;
222     const char **var;
223     const char *(*fct)(void);
224   };
225
226 static const char *
227 color_cap_mt_fct(void)
228 {
229   /* Our caller just set selected_match_color.  */
230   context_match_color = selected_match_color;
231
232   return NULL;
233 }
234
235 static const char *
236 color_cap_rv_fct(void)
237 {
238   /* By this point, it was 1 (or already -1).  */
239   color_option = -1;  /* That's still != 0.  */
240
241   return NULL;
242 }
243
244 static const char *
245 color_cap_ne_fct(void)
246 {
247   sgr_start = "\33[%sm";
248   sgr_end   = "\33[m";
249
250   return NULL;
251 }
252
253 /* For GREP_COLORS.  */
254 static struct color_cap color_dict[] =
255   {
256     { "mt", &selected_match_color, color_cap_mt_fct }, /* both ms/mc */
257     { "ms", &selected_match_color, NULL }, /* selected matched text */
258     { "mc", &context_match_color,  NULL }, /* context matched text */
259     { "fn", &filename_color,       NULL }, /* filename */
260     { "ln", &line_num_color,       NULL }, /* line number */
261     { "bn", &byte_num_color,       NULL }, /* byte (sic) offset */
262     { "se", &sep_color,            NULL }, /* separator */
263     { "sl", &selected_line_color,  NULL }, /* selected lines */
264     { "cx", &context_line_color,   NULL }, /* context lines */
265     { "rv", NULL,                  color_cap_rv_fct }, /* -v reverses sl/cx */
266     { "ne", NULL,                  color_cap_ne_fct }, /* no EL on SGR_* */
267     { NULL, NULL,                  NULL }
268   };
269
270 static struct exclude *excluded_patterns;
271 static struct exclude *included_patterns;
272 static struct exclude *excluded_directory_patterns;
273 /* Short options.  */
274 static char const short_options[] =
275 "0123456789A:B:C:D:EFGHIPTUVX:abcd:e:f:hiKLlm:noqRrsuvwxyZz";
276
277 /* Non-boolean long options that have no corresponding short equivalents.  */
278 enum
279 {
280   BINARY_FILES_OPTION = CHAR_MAX + 1,
281   COLOR_OPTION,
282   INCLUDE_OPTION,
283   EXCLUDE_OPTION,
284   EXCLUDE_FROM_OPTION,
285   LINE_BUFFERED_OPTION,
286   LABEL_OPTION,
287   EXCLUDE_DIRECTORY_OPTION,
288   GROUP_SEPARATOR_OPTION,
289   MMAP_OPTION
290 };
291
292 /* Long options equivalences. */
293 static struct option const long_options[] =
294 {
295   {"basic-regexp",    no_argument, NULL, 'G'},
296   {"extended-regexp", no_argument, NULL, 'E'},
297   {"fixed-regexp",    no_argument, NULL, 'F'},
298   {"fixed-strings",   no_argument, NULL, 'F'},
299   {"perl-regexp",     no_argument, NULL, 'P'},
300   {"after-context", required_argument, NULL, 'A'},
301   {"before-context", required_argument, NULL, 'B'},
302   {"binary-files", required_argument, NULL, BINARY_FILES_OPTION},
303   {"byte-offset", no_argument, NULL, 'b'},
304   {"context", required_argument, NULL, 'C'},
305   {"color", optional_argument, NULL, COLOR_OPTION},
306   {"colour", optional_argument, NULL, COLOR_OPTION},
307   {"count", no_argument, NULL, 'c'},
308   {"devices", required_argument, NULL, 'D'},
309   {"directories", required_argument, NULL, 'd'},
310   {"exclude", required_argument, NULL, EXCLUDE_OPTION},
311   {"exclude-from", required_argument, NULL, EXCLUDE_FROM_OPTION},
312   {"exclude-dir", required_argument, NULL, EXCLUDE_DIRECTORY_OPTION},
313   {"file", required_argument, NULL, 'f'},
314   {"files-with-matches", no_argument, NULL, 'l'},
315   {"files-without-match", no_argument, NULL, 'L'},
316   {"group-separator", required_argument, NULL, GROUP_SEPARATOR_OPTION},
317   {"help", no_argument, &show_help, 1},
318   {"include", required_argument, NULL, INCLUDE_OPTION},
319   {"ignore-case", no_argument, NULL, 'i'},
320   {"initial-tab", no_argument, NULL, 'T'},
321   {"label", required_argument, NULL, LABEL_OPTION},
322   {"line-buffered", no_argument, NULL, LINE_BUFFERED_OPTION},
323   {"line-number", no_argument, NULL, 'n'},
324   {"line-regexp", no_argument, NULL, 'x'},
325   {"max-count", required_argument, NULL, 'm'},
326
327   /* FIXME: disabled in Mar 2010; warn towards end of 2011; remove in 2013.  */
328   {"mmap", no_argument, NULL, MMAP_OPTION},
329   {"no-filename", no_argument, NULL, 'h'},
330   {"no-group-separator", no_argument, NULL, GROUP_SEPARATOR_OPTION},
331   {"no-messages", no_argument, NULL, 's'},
332   {"null", no_argument, NULL, 'Z'},
333   {"null-data", no_argument, NULL, 'z'},
334   {"only-matching", no_argument, NULL, 'o'},
335   {"quiet", no_argument, NULL, 'q'},
336   {"recursive", no_argument, NULL, 'r'},
337   {"recursive", no_argument, NULL, 'R'},
338   {"regexp", required_argument, NULL, 'e'},
339   {"invert-match", no_argument, NULL, 'v'},
340   {"silent", no_argument, NULL, 'q'},
341   {"text", no_argument, NULL, 'a'},
342   {"binary", no_argument, NULL, 'U'},
343   {"unix-byte-offsets", no_argument, NULL, 'u'},
344   {"version", no_argument, NULL, 'V'},
345   {"with-filename", no_argument, NULL, 'H'},
346   {"word-regexp", no_argument, NULL, 'w'},
347   {0, 0, 0, 0}
348 };
349
350 /* Define flags declared in grep.h. */
351 int match_icase;
352 int match_words;
353 int match_lines;
354 unsigned char eolbyte;
355
356 /* For error messages. */
357 /* The name the program was run with, stripped of any leading path. */
358 static char const *filename;
359 static int errseen;
360
361 enum directories_type
362   {
363     READ_DIRECTORIES = 2,
364     RECURSE_DIRECTORIES,
365     SKIP_DIRECTORIES
366   };
367
368 /* How to handle directories.  */
369 static char const *const directories_args[] =
370 {
371   "read", "recurse", "skip", NULL
372 };
373 static enum directories_type const directories_types[] =
374 {
375   READ_DIRECTORIES, RECURSE_DIRECTORIES, SKIP_DIRECTORIES
376 };
377 ARGMATCH_VERIFY (directories_args, directories_types);
378
379 static enum directories_type directories = READ_DIRECTORIES;
380
381 /* How to handle devices. */
382 static enum
383   {
384     READ_DEVICES,
385     SKIP_DEVICES
386   } devices = READ_DEVICES;
387
388 static int grepdir (char const *, struct stats const *);
389 #if defined HAVE_DOS_FILE_CONTENTS
390 static inline int undossify_input (char *, size_t);
391 #endif
392
393 /* Functions we'll use to search. */
394 static compile_fp_t compile;
395 static execute_fp_t execute;
396
397 /* Like error, but suppress the diagnostic if requested.  */
398 static void
399 suppressible_error (char const *mesg, int errnum)
400 {
401   if (! suppress_errors)
402     error (0, errnum, "%s", mesg);
403   errseen = 1;
404 }
405
406 /* Convert STR to a positive integer, storing the result in *OUT.
407    STR must be a valid context length argument; report an error if it
408    isn't.  */
409 static void
410 context_length_arg (char const *str, int *out)
411 {
412   uintmax_t value;
413   if (! (xstrtoumax (str, 0, 10, &value, "") == LONGINT_OK
414          && 0 <= (*out = value)
415          && *out == value))
416     {
417       error (EXIT_TROUBLE, 0, "%s: %s", str,
418              _("invalid context length argument"));
419     }
420 }
421
422
423 /* Hairy buffering mechanism for grep.  The intent is to keep
424    all reads aligned on a page boundary and multiples of the
425    page size, unless a read yields a partial page.  */
426
427 static char *buffer;            /* Base of buffer. */
428 static size_t bufalloc;         /* Allocated buffer size, counting slop. */
429 #define INITIAL_BUFSIZE 32768   /* Initial buffer size, not counting slop. */
430 static int bufdesc;             /* File descriptor. */
431 static char *bufbeg;            /* Beginning of user-visible stuff. */
432 static char *buflim;            /* Limit of user-visible stuff. */
433 static size_t pagesize;         /* alignment of memory pages */
434 static off_t bufoffset;         /* Read offset; defined on regular files.  */
435 static off_t after_last_match;  /* Pointer after last matching line that
436                                    would have been output if we were
437                                    outputting characters. */
438
439 /* Return VAL aligned to the next multiple of ALIGNMENT.  VAL can be
440    an integer or a pointer.  Both args must be free of side effects.  */
441 #define ALIGN_TO(val, alignment) \
442   ((size_t) (val) % (alignment) == 0 \
443    ? (val) \
444    : (val) + ((alignment) - (size_t) (val) % (alignment)))
445
446 /* Reset the buffer for a new file, returning zero if we should skip it.
447    Initialize on the first time through. */
448 static int
449 reset (int fd, char const *file, struct stats *stats)
450 {
451   if (! pagesize)
452     {
453       pagesize = getpagesize ();
454       if (pagesize == 0 || 2 * pagesize + 1 <= pagesize)
455         abort ();
456       bufalloc = ALIGN_TO (INITIAL_BUFSIZE, pagesize) + pagesize + 1;
457       buffer = xmalloc (bufalloc);
458     }
459
460   bufbeg = buflim = ALIGN_TO (buffer + 1, pagesize);
461   bufbeg[-1] = eolbyte;
462   bufdesc = fd;
463
464   if (S_ISREG (stats->stat.st_mode))
465     {
466       if (file)
467         bufoffset = 0;
468       else
469         {
470           bufoffset = lseek (fd, 0, SEEK_CUR);
471           if (bufoffset < 0)
472             {
473               error (0, errno, _("lseek failed"));
474               return 0;
475             }
476         }
477     }
478   return 1;
479 }
480
481 /* Read new stuff into the buffer, saving the specified
482    amount of old stuff.  When we're done, 'bufbeg' points
483    to the beginning of the buffer contents, and 'buflim'
484    points just after the end.  Return zero if there's an error.  */
485 static int
486 fillbuf (size_t save, struct stats const *stats)
487 {
488   size_t fillsize = 0;
489   int cc = 1;
490   char *readbuf;
491   size_t readsize;
492
493   /* Offset from start of buffer to start of old stuff
494      that we want to save.  */
495   size_t saved_offset = buflim - save - buffer;
496
497   if (pagesize <= buffer + bufalloc - buflim)
498     {
499       readbuf = buflim;
500       bufbeg = buflim - save;
501     }
502   else
503     {
504       size_t minsize = save + pagesize;
505       size_t newsize;
506       size_t newalloc;
507       char *newbuf;
508
509       /* Grow newsize until it is at least as great as minsize.  */
510       for (newsize = bufalloc - pagesize - 1; newsize < minsize; newsize *= 2)
511         if (newsize * 2 < newsize || newsize * 2 + pagesize + 1 < newsize * 2)
512           xalloc_die ();
513
514       /* Try not to allocate more memory than the file size indicates,
515          as that might cause unnecessary memory exhaustion if the file
516          is large.  However, do not use the original file size as a
517          heuristic if we've already read past the file end, as most
518          likely the file is growing.  */
519       if (S_ISREG (stats->stat.st_mode))
520         {
521           off_t to_be_read = stats->stat.st_size - bufoffset;
522           off_t maxsize_off = save + to_be_read;
523           if (0 <= to_be_read && to_be_read <= maxsize_off
524               && maxsize_off == (size_t) maxsize_off
525               && minsize <= (size_t) maxsize_off
526               && (size_t) maxsize_off < newsize)
527             newsize = maxsize_off;
528         }
529
530       /* Add enough room so that the buffer is aligned and has room
531          for byte sentinels fore and aft.  */
532       newalloc = newsize + pagesize + 1;
533
534       newbuf = bufalloc < newalloc ? xmalloc (bufalloc = newalloc) : buffer;
535       readbuf = ALIGN_TO (newbuf + 1 + save, pagesize);
536       bufbeg = readbuf - save;
537       memmove (bufbeg, buffer + saved_offset, save);
538       bufbeg[-1] = eolbyte;
539       if (newbuf != buffer)
540         {
541           free (buffer);
542           buffer = newbuf;
543         }
544     }
545
546   readsize = buffer + bufalloc - readbuf;
547   readsize -= readsize % pagesize;
548
549   if (! fillsize)
550     {
551       ssize_t bytesread;
552       while ((bytesread = read (bufdesc, readbuf, readsize)) < 0
553              && errno == EINTR)
554         continue;
555       if (bytesread < 0)
556         cc = 0;
557       else
558         fillsize = bytesread;
559     }
560
561   bufoffset += fillsize;
562 #if defined HAVE_DOS_FILE_CONTENTS
563   if (fillsize)
564     fillsize = undossify_input (readbuf, fillsize);
565 #endif
566   buflim = readbuf + fillsize;
567   return cc;
568 }
569
570 /* Flags controlling the style of output. */
571 static enum
572 {
573   BINARY_BINARY_FILES,
574   TEXT_BINARY_FILES,
575   WITHOUT_MATCH_BINARY_FILES
576 } binary_files;         /* How to handle binary files.  */
577
578 static int filename_mask;       /* If zero, output nulls after filenames.  */
579 static int out_quiet;           /* Suppress all normal output. */
580 static int out_invert;          /* Print nonmatching stuff. */
581 static int out_file;            /* Print filenames. */
582 static int out_line;            /* Print line numbers. */
583 static int out_byte;            /* Print byte offsets. */
584 static int out_before;          /* Lines of leading context. */
585 static int out_after;           /* Lines of trailing context. */
586 static int count_matches;       /* Count matching lines.  */
587 static int list_files;          /* List matching files.  */
588 static int no_filenames;        /* Suppress file names.  */
589 static off_t max_count;         /* Stop after outputting this many
590                                    lines from an input file.  */
591 static int line_buffered;       /* If nonzero, use line buffering, i.e.
592                                    fflush everyline out.  */
593 static char *label = NULL;      /* Fake filename for stdin */
594
595
596 /* Internal variables to keep track of byte count, context, etc. */
597 static uintmax_t totalcc;       /* Total character count before bufbeg. */
598 static char const *lastnl;      /* Pointer after last newline counted. */
599 static char const *lastout;     /* Pointer after last character output;
600                                    NULL if no character has been output
601                                    or if it's conceptually before bufbeg. */
602 static uintmax_t totalnl;       /* Total newline count before lastnl. */
603 static off_t outleft;           /* Maximum number of lines to be output.  */
604 static int pending;             /* Pending lines of output.
605                                    Always kept 0 if out_quiet is true.  */
606 static int done_on_match;       /* Stop scanning file on first match.  */
607 static int exit_on_match;       /* Exit on first match.  */
608
609 #if defined HAVE_DOS_FILE_CONTENTS
610 # include "dosbuf.c"
611 #endif
612
613 /* Add two numbers that count input bytes or lines, and report an
614    error if the addition overflows.  */
615 static uintmax_t
616 add_count (uintmax_t a, uintmax_t b)
617 {
618   uintmax_t sum = a + b;
619   if (sum < a)
620     error (EXIT_TROUBLE, 0, _("input is too large to count"));
621   return sum;
622 }
623
624 static void
625 nlscan (char const *lim)
626 {
627   size_t newlines = 0;
628   char const *beg;
629   for (beg = lastnl; beg < lim; beg++)
630     {
631       beg = memchr (beg, eolbyte, lim - beg);
632       if (!beg)
633         break;
634       newlines++;
635     }
636   totalnl = add_count (totalnl, newlines);
637   lastnl = lim;
638 }
639
640 /* Print the current filename.  */
641 static void
642 print_filename (void)
643 {
644   PR_SGR_START_IF(filename_color);
645   fputs(filename, stdout);
646   PR_SGR_END_IF(filename_color);
647 }
648
649 /* Print a character separator.  */
650 static void
651 print_sep (char sep)
652 {
653   PR_SGR_START_IF(sep_color);
654   fputc(sep, stdout);
655   PR_SGR_END_IF(sep_color);
656 }
657
658 /* Print a line number or a byte offset.  */
659 static void
660 print_offset (uintmax_t pos, int min_width, const char *color)
661 {
662   /* Do not rely on printf to print pos, since uintmax_t may be longer
663      than long, and long long is not portable.  */
664
665   char buf[sizeof pos * CHAR_BIT];
666   char *p = buf + sizeof buf;
667
668   do
669     {
670       *--p = '0' + pos % 10;
671       --min_width;
672     }
673   while ((pos /= 10) != 0);
674
675   /* Do this to maximize the probability of alignment across lines.  */
676   if (align_tabs)
677     while (--min_width >= 0)
678       *--p = ' ';
679
680   PR_SGR_START_IF(color);
681   fwrite (p, 1, buf + sizeof buf - p, stdout);
682   PR_SGR_END_IF(color);
683 }
684
685 /* Print a whole line head (filename, line, byte).  */
686 static void
687 print_line_head (char const *beg, char const *lim, int sep)
688 {
689   int pending_sep = 0;
690
691   if (out_file)
692     {
693       print_filename();
694       if (filename_mask)
695         pending_sep = 1;
696       else
697         fputc(0, stdout);
698     }
699
700   if (out_line)
701     {
702       if (lastnl < lim)
703         {
704           nlscan (beg);
705           totalnl = add_count (totalnl, 1);
706           lastnl = lim;
707         }
708       if (pending_sep)
709         print_sep(sep);
710       print_offset (totalnl, 4, line_num_color);
711       pending_sep = 1;
712     }
713
714   if (out_byte)
715     {
716       uintmax_t pos = add_count (totalcc, beg - bufbeg);
717 #if defined HAVE_DOS_FILE_CONTENTS
718       pos = dossified_pos (pos);
719 #endif
720       if (pending_sep)
721         print_sep(sep);
722       print_offset (pos, 6, byte_num_color);
723       pending_sep = 1;
724     }
725
726   if (pending_sep)
727     {
728       /* This assumes sep is one column wide.
729          Try doing this any other way with Unicode
730          (and its combining and wide characters)
731          filenames and you're wasting your efforts.  */
732       if (align_tabs)
733         fputs("\t\b", stdout);
734
735       print_sep(sep);
736     }
737 }
738
739 static const char *
740 print_line_middle (const char *beg, const char *lim,
741                    const char *line_color, const char *match_color)
742 {
743   size_t match_size;
744   size_t match_offset;
745   const char *cur = beg;
746   const char *mid = NULL;
747
748   while (cur < lim
749          && ((match_offset = execute(beg, lim - beg, &match_size,
750                                      beg + (cur - beg))) != (size_t) -1))
751     {
752       char const *b = beg + match_offset;
753
754       /* Avoid matching the empty line at the end of the buffer. */
755       if (b == lim)
756         break;
757
758       /* Avoid hanging on grep --color "" foo */
759       if (match_size == 0)
760         {
761           /* Make minimal progress; there may be further non-empty matches.  */
762           /* XXX - Could really advance by one whole multi-octet character.  */
763           match_size = 1;
764           if (!mid)
765             mid = cur;
766         }
767       else
768         {
769           /* This function is called on a matching line only,
770              but is it selected or rejected/context?  */
771           if (only_matching)
772             print_line_head(b, lim, out_invert ? SEP_CHAR_REJECTED
773                                                : SEP_CHAR_SELECTED);
774           else
775             {
776               PR_SGR_START(line_color);
777               if (mid)
778                 {
779                   cur = mid;
780                   mid = NULL;
781                 }
782               fwrite (cur, sizeof (char), b - cur, stdout);
783             }
784
785           PR_SGR_START_IF(match_color);
786           fwrite (b, sizeof (char), match_size, stdout);
787           PR_SGR_END_IF(match_color);
788           if (only_matching)
789             fputs("\n", stdout);
790         }
791       cur = b + match_size;
792     }
793
794   if (only_matching)
795     cur = lim;
796   else if (mid)
797     cur = mid;
798
799   return cur;
800 }
801
802 static const char *
803 print_line_tail (const char *beg, const char *lim, const char *line_color)
804 {
805   size_t  eol_size;
806   size_t tail_size;
807
808   eol_size   = (lim > beg && lim[-1] == eolbyte);
809   eol_size  += (lim - eol_size > beg && lim[-(1 + eol_size)] == '\r');
810   tail_size  =  lim - eol_size - beg;
811
812   if (tail_size > 0)
813     {
814       PR_SGR_START(line_color);
815       fwrite(beg, 1, tail_size, stdout);
816       beg += tail_size;
817       PR_SGR_END(line_color);
818     }
819
820   return beg;
821 }
822
823 static void
824 prline (char const *beg, char const *lim, int sep)
825 {
826   int matching;
827   const char *line_color;
828   const char *match_color;
829
830   if (!only_matching)
831     print_line_head(beg, lim, sep);
832
833   matching = (sep == SEP_CHAR_SELECTED) ^ !!out_invert;
834
835   if (color_option)
836     {
837       line_color  = (  (sep == SEP_CHAR_SELECTED)
838                      ^ (out_invert && (color_option < 0)))
839                   ? selected_line_color  : context_line_color;
840       match_color = (sep == SEP_CHAR_SELECTED)
841                   ? selected_match_color : context_match_color;
842     }
843   else
844     line_color = match_color = NULL; /* Shouldn't be used.  */
845
846   if (   (only_matching && matching)
847       || (color_option  && (*line_color || *match_color)))
848     {
849       /* We already know that non-matching lines have no match (to colorize).  */
850       if (matching && (only_matching || *match_color))
851         beg = print_line_middle(beg, lim, line_color, match_color);
852
853       /* FIXME: this test may be removable.  */
854       if (!only_matching && *line_color)
855         beg = print_line_tail(beg, lim, line_color);
856     }
857
858   if (!only_matching && lim > beg)
859     fwrite (beg, 1, lim - beg, stdout);
860
861   if (ferror (stdout))
862     error (0, errno, _("writing output"));
863
864   lastout = lim;
865
866   if (line_buffered)
867     fflush (stdout);
868 }
869
870 /* Print pending lines of trailing context prior to LIM. Trailing context ends
871    at the next matching line when OUTLEFT is 0.  */
872 static void
873 prpending (char const *lim)
874 {
875   if (!lastout)
876     lastout = bufbeg;
877   while (pending > 0 && lastout < lim)
878     {
879       char const *nl = memchr (lastout, eolbyte, lim - lastout);
880       size_t match_size;
881       --pending;
882       if (outleft
883           || ((execute(lastout, nl + 1 - lastout,
884                        &match_size, NULL) == (size_t) -1)
885               == !out_invert))
886         prline (lastout, nl + 1, SEP_CHAR_REJECTED);
887       else
888         pending = 0;
889     }
890 }
891
892 /* Print the lines between BEG and LIM.  Deal with context crap.
893    If NLINESP is non-null, store a count of lines between BEG and LIM.  */
894 static void
895 prtext (char const *beg, char const *lim, int *nlinesp)
896 {
897   static int used;      /* avoid printing SEP_STR_GROUP before any output */
898   char const *bp, *p;
899   char eol = eolbyte;
900   int i, n;
901
902   if (!out_quiet && pending > 0)
903     prpending (beg);
904
905   p = beg;
906
907   if (!out_quiet)
908     {
909       /* Deal with leading context crap. */
910
911       bp = lastout ? lastout : bufbeg;
912       for (i = 0; i < out_before; ++i)
913         if (p > bp)
914           do
915             --p;
916           while (p[-1] != eol);
917
918       /* We print the SEP_STR_GROUP separator only if our output is
919          discontiguous from the last output in the file. */
920       if ((out_before || out_after) && used && p != lastout && group_separator)
921         {
922           PR_SGR_START_IF(sep_color);
923           fputs (group_separator, stdout);
924           PR_SGR_END_IF(sep_color);
925           fputc('\n', stdout);
926         }
927
928       while (p < beg)
929         {
930           char const *nl = memchr (p, eol, beg - p);
931           nl++;
932           prline (p, nl, SEP_CHAR_REJECTED);
933           p = nl;
934         }
935     }
936
937   if (nlinesp)
938     {
939       /* Caller wants a line count. */
940       for (n = 0; p < lim && n < outleft; n++)
941         {
942           char const *nl = memchr (p, eol, lim - p);
943           nl++;
944           if (!out_quiet)
945             prline (p, nl, SEP_CHAR_SELECTED);
946           p = nl;
947         }
948       *nlinesp = n;
949
950       /* relying on it that this function is never called when outleft = 0.  */
951       after_last_match = bufoffset - (buflim - p);
952     }
953   else
954     if (!out_quiet)
955       prline (beg, lim, SEP_CHAR_SELECTED);
956
957   pending = out_quiet ? 0 : out_after;
958   used = 1;
959 }
960
961 static size_t
962 do_execute (char const *buf, size_t size, size_t *match_size, char const *start_ptr)
963 {
964   size_t result;
965   const char *line_next;
966
967   /* With the current implementation, using --ignore-case with a multi-byte
968      character set is very inefficient when applied to a large buffer
969      containing many matches.  We can avoid much of the wasted effort
970      by matching line-by-line.
971
972      FIXME: this is just an ugly workaround, and it doesn't really
973      belong here.  Also, PCRE is always using this same per-line
974      matching algorithm.  Either we fix -i, or we should refactor
975      this code---for example, we could add another function pointer
976      to struct matcher to split the buffer passed to execute.  It would
977      perform the memchr if line-by-line matching is necessary, or just
978      return buf + size otherwise.  */
979   if (MB_CUR_MAX == 1 || !match_icase)
980     return execute(buf, size, match_size, start_ptr);
981
982   for (line_next = buf; line_next < buf + size; )
983     {
984       const char *line_buf = line_next;
985       const char *line_end = memchr (line_buf, eolbyte, (buf + size) - line_buf);
986       if (line_end == NULL)
987         line_next = line_end = buf + size;
988       else
989         line_next = line_end + 1;
990
991       if (start_ptr && start_ptr >= line_end)
992         continue;
993
994       result = execute (line_buf, line_next - line_buf, match_size, start_ptr);
995       if (result != (size_t) -1)
996         return (line_buf - buf) + result;
997     }
998
999   return (size_t) -1;
1000 }
1001
1002 /* Scan the specified portion of the buffer, matching lines (or
1003    between matching lines if OUT_INVERT is true).  Return a count of
1004    lines printed. */
1005 static int
1006 grepbuf (char const *beg, char const *lim)
1007 {
1008   int nlines, n;
1009   char const *p;
1010   size_t match_offset;
1011   size_t match_size;
1012
1013   nlines = 0;
1014   p = beg;
1015   while ((match_offset = do_execute(p, lim - p, &match_size,
1016                                     NULL)) != (size_t) -1)
1017     {
1018       char const *b = p + match_offset;
1019       char const *endp = b + match_size;
1020       /* Avoid matching the empty line at the end of the buffer. */
1021       if (b == lim)
1022         break;
1023       if (!out_invert)
1024         {
1025           prtext (b, endp, (int *) 0);
1026           nlines++;
1027           outleft--;
1028           if (!outleft || done_on_match)
1029             {
1030               if (exit_on_match)
1031                 exit (EXIT_SUCCESS);
1032               after_last_match = bufoffset - (buflim - endp);
1033               return nlines;
1034             }
1035         }
1036       else if (p < b)
1037         {
1038           prtext (p, b, &n);
1039           nlines += n;
1040           outleft -= n;
1041           if (!outleft)
1042             return nlines;
1043         }
1044       p = endp;
1045     }
1046   if (out_invert && p < lim)
1047     {
1048       prtext (p, lim, &n);
1049       nlines += n;
1050       outleft -= n;
1051     }
1052   return nlines;
1053 }
1054
1055 /* Search a given file.  Normally, return a count of lines printed;
1056    but if the file is a directory and we search it recursively, then
1057    return -2 if there was a match, and -1 otherwise.  */
1058 static int
1059 grep (int fd, char const *file, struct stats *stats)
1060 {
1061   int nlines, i;
1062   int not_text;
1063   size_t residue, save;
1064   char oldc;
1065   char *beg;
1066   char *lim;
1067   char eol = eolbyte;
1068
1069   if (!reset (fd, file, stats))
1070     return 0;
1071
1072   if (file && directories == RECURSE_DIRECTORIES
1073       && S_ISDIR (stats->stat.st_mode))
1074     {
1075       /* Close fd now, so that we don't open a lot of file descriptors
1076          when we recurse deeply.  */
1077       if (close (fd) != 0)
1078         error (0, errno, "%s", file);
1079       return grepdir (file, stats) - 2;
1080     }
1081
1082   totalcc = 0;
1083   lastout = 0;
1084   totalnl = 0;
1085   outleft = max_count;
1086   after_last_match = 0;
1087   pending = 0;
1088
1089   nlines = 0;
1090   residue = 0;
1091   save = 0;
1092
1093   if (! fillbuf (save, stats))
1094     {
1095       if (! is_EISDIR (errno, file))
1096         {
1097           if (errno != EINVAL)
1098             suppressible_error (filename, errno);
1099         }
1100       return 0;
1101     }
1102
1103   not_text = (((binary_files == BINARY_BINARY_FILES && !out_quiet)
1104                || binary_files == WITHOUT_MATCH_BINARY_FILES)
1105               && memchr (bufbeg, eol ? '\0' : '\200', buflim - bufbeg));
1106   if (not_text && binary_files == WITHOUT_MATCH_BINARY_FILES)
1107     return 0;
1108   done_on_match += not_text;
1109   out_quiet += not_text;
1110
1111   for (;;)
1112     {
1113       lastnl = bufbeg;
1114       if (lastout)
1115         lastout = bufbeg;
1116
1117       beg = bufbeg + save;
1118
1119       /* no more data to scan (eof) except for maybe a residue -> break */
1120       if (beg == buflim)
1121         break;
1122
1123       /* Determine new residue (the length of an incomplete line at the end of
1124          the buffer, 0 means there is no incomplete last line).  */
1125       oldc = beg[-1];
1126       beg[-1] = eol;
1127       for (lim = buflim; lim[-1] != eol; lim--)
1128         continue;
1129       beg[-1] = oldc;
1130       if (lim == beg)
1131         lim = beg - residue;
1132       beg -= residue;
1133       residue = buflim - lim;
1134
1135       if (beg < lim)
1136         {
1137           if (outleft)
1138             nlines += grepbuf (beg, lim);
1139           if (pending)
1140             prpending (lim);
1141           if((!outleft && !pending) || (nlines && done_on_match && !out_invert))
1142             goto finish_grep;
1143         }
1144
1145       /* The last OUT_BEFORE lines at the end of the buffer will be needed as
1146          leading context if there is a matching line at the begin of the
1147          next data. Make beg point to their begin.  */
1148       i = 0;
1149       beg = lim;
1150       while (i < out_before && beg > bufbeg && beg != lastout)
1151         {
1152           ++i;
1153           do
1154             --beg;
1155           while (beg[-1] != eol);
1156         }
1157
1158       /* detect if leading context is discontinuous from last printed line.  */
1159       if (beg != lastout)
1160         lastout = 0;
1161
1162       /* Handle some details and read more data to scan.  */
1163       save = residue + lim - beg;
1164       if (out_byte)
1165         totalcc = add_count (totalcc, buflim - bufbeg - save);
1166       if (out_line)
1167         nlscan (beg);
1168       if (! fillbuf (save, stats))
1169         {
1170           if (! is_EISDIR (errno, file))
1171             suppressible_error (filename, errno);
1172           goto finish_grep;
1173         }
1174     }
1175   if (residue)
1176     {
1177       *buflim++ = eol;
1178       if (outleft)
1179         nlines += grepbuf (bufbeg + save - residue, buflim);
1180       if (pending)
1181         prpending (buflim);
1182     }
1183
1184  finish_grep:
1185   done_on_match -= not_text;
1186   out_quiet -= not_text;
1187   if ((not_text & ~out_quiet) && nlines != 0)
1188     printf (_("Binary file %s matches\n"), filename);
1189   return nlines;
1190 }
1191
1192 static int
1193 grepfile (char const *file, struct stats *stats)
1194 {
1195   int desc;
1196   int count;
1197   int status;
1198
1199   if (! file)
1200     {
1201       desc = 0;
1202       filename = label ? label : _("(standard input)");
1203     }
1204   else
1205     {
1206       if (stat (file, &stats->stat) != 0)
1207         {
1208           suppressible_error (file, errno);
1209           return 1;
1210         }
1211       if (directories == SKIP_DIRECTORIES && S_ISDIR (stats->stat.st_mode))
1212         return 1;
1213       if (devices == SKIP_DEVICES && (S_ISCHR (stats->stat.st_mode)
1214                                       || S_ISBLK (stats->stat.st_mode)
1215                                       || S_ISSOCK (stats->stat.st_mode)
1216                                       || S_ISFIFO (stats->stat.st_mode)))
1217         return 1;
1218       while ((desc = open (file, O_RDONLY)) < 0 && errno == EINTR)
1219         continue;
1220
1221       if (desc < 0)
1222         {
1223           int e = errno;
1224
1225           if (is_EISDIR (e, file) && directories == RECURSE_DIRECTORIES)
1226             {
1227               if (stat (file, &stats->stat) != 0)
1228                 {
1229                   error (0, errno, "%s", file);
1230                   return 1;
1231                 }
1232
1233               return grepdir (file, stats);
1234             }
1235
1236           if (!suppress_errors)
1237             {
1238               if (directories == SKIP_DIRECTORIES)
1239                 switch (e)
1240                   {
1241 #if defined EISDIR
1242                   case EISDIR:
1243                     return 1;
1244 #endif
1245                   case EACCES:
1246                     /* When skipping directories, don't worry about
1247                        directories that can't be opened.  */
1248                     if (isdir (file))
1249                       return 1;
1250                     break;
1251                   }
1252             }
1253
1254           suppressible_error (file, e);
1255           return 1;
1256         }
1257
1258       filename = file;
1259     }
1260
1261 #if defined SET_BINARY
1262   /* Set input to binary mode.  Pipes are simulated with files
1263      on DOS, so this includes the case of "foo | grep bar".  */
1264   if (!isatty (desc))
1265     SET_BINARY (desc);
1266 #endif
1267
1268   count = grep (desc, file, stats);
1269   if (count < 0)
1270     status = count + 2;
1271   else
1272     {
1273       if (count_matches)
1274         {
1275           if (out_file)
1276             {
1277               print_filename();
1278               if (filename_mask)
1279                 print_sep(SEP_CHAR_SELECTED);
1280               else
1281                 fputc(0, stdout);
1282             }
1283           printf ("%d\n", count);
1284         }
1285
1286       status = !count;
1287       if (list_files == 1 - 2 * status)
1288         {
1289           print_filename();
1290           fputc('\n' & filename_mask, stdout);
1291         }
1292
1293       if (! file)
1294         {
1295           off_t required_offset = outleft ? bufoffset : after_last_match;
1296           if (required_offset != bufoffset
1297               && lseek (desc, required_offset, SEEK_SET) < 0
1298               && S_ISREG (stats->stat.st_mode))
1299             error (0, errno, "%s", filename);
1300         }
1301       else
1302         while (close (desc) != 0)
1303           if (errno != EINTR)
1304             {
1305               error (0, errno, "%s", file);
1306               break;
1307             }
1308     }
1309
1310   return status;
1311 }
1312
1313 static int
1314 grepdir (char const *dir, struct stats const *stats)
1315 {
1316   struct stats const *ancestor;
1317   char *name_space;
1318   int status = 1;
1319   if ( excluded_directory_patterns &&
1320        excluded_file_name (excluded_directory_patterns, dir)  ) {
1321        return 1;
1322   }
1323
1324
1325   /* Mingw32 does not support st_ino.  No known working hosts use zero
1326      for st_ino, so assume that the Mingw32 bug applies if it's zero.  */
1327   if (stats->stat.st_ino)
1328     for (ancestor = stats;  (ancestor = ancestor->parent) != 0;  )
1329       if (ancestor->stat.st_ino == stats->stat.st_ino
1330           && ancestor->stat.st_dev == stats->stat.st_dev)
1331         {
1332           if (!suppress_errors)
1333             error (0, 0, _("warning: %s: %s"), dir,
1334                    _("recursive directory loop"));
1335           return 1;
1336         }
1337
1338   name_space = savedir (dir, stats->stat.st_size, included_patterns,
1339                         excluded_patterns, excluded_directory_patterns);
1340
1341   if (! name_space)
1342     {
1343       if (errno)
1344         suppressible_error (dir, errno);
1345       else
1346         xalloc_die ();
1347     }
1348   else
1349     {
1350       size_t dirlen = strlen (dir);
1351       int needs_slash = ! (dirlen == FILE_SYSTEM_PREFIX_LEN (dir)
1352                            || ISSLASH (dir[dirlen - 1]));
1353       char *file = NULL;
1354       char const *namep = name_space;
1355       struct stats child;
1356       child.parent = stats;
1357       out_file += !no_filenames;
1358       while (*namep)
1359         {
1360           size_t namelen = strlen (namep);
1361           file = xrealloc (file, dirlen + 1 + namelen + 1);
1362           strcpy (file, dir);
1363           file[dirlen] = '/';
1364           strcpy (file + dirlen + needs_slash, namep);
1365           namep += namelen + 1;
1366           status &= grepfile (file, &child);
1367         }
1368       out_file -= !no_filenames;
1369       free (file);
1370       free (name_space);
1371     }
1372
1373   return status;
1374 }
1375
1376 void usage (int status) __attribute__ ((noreturn));
1377 void
1378 usage (int status)
1379 {
1380   if (status != 0)
1381     {
1382       fprintf (stderr, _("Usage: %s [OPTION]... PATTERN [FILE]...\n"),
1383                program_name);
1384       fprintf (stderr, _("Try `%s --help' for more information.\n"),
1385                program_name);
1386     }
1387   else
1388     {
1389       printf (_("Usage: %s [OPTION]... PATTERN [FILE]...\n"), program_name);
1390       printf (_("\
1391 Search for PATTERN in each FILE or standard input.\n"));
1392       printf ("%s", gettext (before_options));
1393       printf (_("\
1394 Example: %s -i 'hello world' menu.h main.c\n\
1395 \n\
1396 Regexp selection and interpretation:\n"), program_name);
1397       if (matchers[1].name)
1398         printf (_("\
1399   -E, --extended-regexp     PATTERN is an extended regular expression (ERE)\n\
1400   -F, --fixed-strings       PATTERN is a set of newline-separated fixed strings\n\
1401   -G, --basic-regexp        PATTERN is a basic regular expression (BRE)\n\
1402   -P, --perl-regexp         PATTERN is a Perl regular expression\n"));
1403   /* -X is undocumented on purpose. */
1404       printf (_("\
1405   -e, --regexp=PATTERN      use PATTERN for matching\n\
1406   -f, --file=FILE           obtain PATTERN from FILE\n\
1407   -i, --ignore-case         ignore case distinctions\n\
1408   -w, --word-regexp         force PATTERN to match only whole words\n\
1409   -x, --line-regexp         force PATTERN to match only whole lines\n\
1410   -z, --null-data           a data line ends in 0 byte, not newline\n"));
1411       printf (_("\
1412 \n\
1413 Miscellaneous:\n\
1414   -s, --no-messages         suppress error messages\n\
1415   -v, --invert-match        select non-matching lines\n\
1416   -V, --version             print version information and exit\n\
1417       --help                display this help and exit\n\
1418       --mmap                ignored for backwards compatibility\n"));
1419       printf (_("\
1420 \n\
1421 Output control:\n\
1422   -m, --max-count=NUM       stop after NUM matches\n\
1423   -b, --byte-offset         print the byte offset with output lines\n\
1424   -n, --line-number         print line number with output lines\n\
1425       --line-buffered       flush output on every line\n\
1426   -H, --with-filename       print the filename for each match\n\
1427   -h, --no-filename         suppress the prefixing filename on output\n\
1428       --label=LABEL         print LABEL as filename for standard input\n\
1429 "));
1430       printf (_("\
1431   -o, --only-matching       show only the part of a line matching PATTERN\n\
1432   -q, --quiet, --silent     suppress all normal output\n\
1433       --binary-files=TYPE   assume that binary files are TYPE;\n\
1434                             TYPE is `binary', `text', or `without-match'\n\
1435   -a, --text                equivalent to --binary-files=text\n\
1436 "));
1437       printf (_("\
1438   -I                        equivalent to --binary-files=without-match\n\
1439   -d, --directories=ACTION  how to handle directories;\n\
1440                             ACTION is `read', `recurse', or `skip'\n\
1441   -D, --devices=ACTION      how to handle devices, FIFOs and sockets;\n\
1442                             ACTION is `read' or `skip'\n\
1443   -R, -r, --recursive       equivalent to --directories=recurse\n\
1444 "));
1445       printf (_("\
1446       --include=FILE_PATTERN  search only files that match FILE_PATTERN\n\
1447       --exclude=FILE_PATTERN  skip files and directories matching FILE_PATTERN\n\
1448       --exclude-from=FILE   skip files matching any file pattern from FILE\n\
1449       --exclude-dir=PATTERN  directories that match PATTERN will be skipped.\n\
1450 "));
1451       printf (_("\
1452   -L, --files-without-match  print only names of FILEs containing no match\n\
1453   -l, --files-with-matches  print only names of FILEs containing matches\n\
1454   -c, --count               print only a count of matching lines per FILE\n\
1455   -T, --initial-tab         make tabs line up (if needed)\n\
1456   -Z, --null                print 0 byte after FILE name\n"));
1457       printf (_("\
1458 \n\
1459 Context control:\n\
1460   -B, --before-context=NUM  print NUM lines of leading context\n\
1461   -A, --after-context=NUM   print NUM lines of trailing context\n\
1462   -C, --context=NUM         print NUM lines of output context\n\
1463 "));
1464       printf (_("\
1465   -NUM                      same as --context=NUM\n\
1466       --color[=WHEN],\n\
1467       --colour[=WHEN]       use markers to highlight the matching strings;\n\
1468                             WHEN is `always', `never', or `auto'\n\
1469   -U, --binary              do not strip CR characters at EOL (MSDOS)\n\
1470   -u, --unix-byte-offsets   report offsets as if CRs were not there (MSDOS)\n\
1471 \n"));
1472       printf ("%s", _(after_options));
1473       printf (_("\
1474 With no FILE, or when FILE is -, read standard input.  If less than two FILEs\n\
1475 are given, assume -h.  Exit status is 0 if any line was selected, 1 otherwise;\n\
1476 if any error occurs and -q was not given, the exit status is 2.\n"));
1477       printf (_("\nReport bugs to: %s\n"), PACKAGE_BUGREPORT);
1478       printf (_("GNU Grep home page: <%s>\n"),
1479               "http://www.gnu.org/software/grep/");
1480       fputs (_("General help using GNU software: <http://www.gnu.org/gethelp/>\n"),
1481              stdout);
1482
1483     }
1484   exit (status);
1485 }
1486
1487 /* If M is NULL, initialize the matcher to the default.  Otherwise set the
1488    matcher to M if available.  Exit in case of conflicts or if M is not
1489    available.  */
1490 static void
1491 setmatcher (char const *m)
1492 {
1493   static char const *matcher;
1494   unsigned int i;
1495
1496   if (!m)
1497     {
1498       compile = matchers[0].compile;
1499       execute = matchers[0].execute;
1500       if (!matchers[1].name)
1501         matcher = matchers[0].name;
1502     }
1503
1504   else if (matcher)
1505     {
1506       if (matcher && STREQ (matcher, m))
1507         ;
1508
1509       else if (!matchers[1].name)
1510         error (EXIT_TROUBLE, 0, _("%s can only use the %s pattern syntax"),
1511                program_name, matcher);
1512       else
1513         error (EXIT_TROUBLE, 0, _("conflicting matchers specified"));
1514     }
1515
1516   else
1517     {
1518       for (i = 0; matchers[i].name; i++)
1519         if (STREQ (m, matchers[i].name))
1520           {
1521             compile = matchers[i].compile;
1522             execute = matchers[i].execute;
1523             matcher = m;
1524             return;
1525           }
1526
1527       error (EXIT_TROUBLE, 0, _("invalid matcher %s"), m);
1528     }
1529 }
1530
1531 static void
1532 set_limits(void)
1533 {
1534 #if defined HAVE_SETRLIMIT && defined RLIMIT_STACK
1535   struct rlimit rlim;
1536
1537   /* I think every platform needs to do this, so that regex.c
1538      doesn't oveflow the stack.  The default value of
1539      `re_max_failures' is too large for some platforms: it needs
1540      more than 3MB-large stack.
1541
1542      The test for HAVE_SETRLIMIT should go into `configure'.  */
1543   if (!getrlimit (RLIMIT_STACK, &rlim))
1544     {
1545       long newlim;
1546       extern long int re_max_failures; /* from regex.c */
1547
1548       /* Approximate the amount regex.c needs, plus some more.  */
1549       newlim = re_max_failures * 2 * 20 * sizeof (char *);
1550       if (newlim > rlim.rlim_max)
1551         {
1552           newlim = rlim.rlim_max;
1553           re_max_failures = newlim / (2 * 20 * sizeof (char *));
1554         }
1555       if (rlim.rlim_cur < newlim)
1556         {
1557           rlim.rlim_cur = newlim;
1558           setrlimit (RLIMIT_STACK, &rlim);
1559         }
1560     }
1561 #endif
1562 }
1563
1564 /* Find the white-space-separated options specified by OPTIONS, and
1565    using BUF to store copies of these options, set ARGV[0], ARGV[1],
1566    etc. to the option copies.  Return the number N of options found.
1567    Do not set ARGV[N] to NULL.  If ARGV is NULL, do not store ARGV[0]
1568    etc.  Backslash can be used to escape whitespace (and backslashes).  */
1569 static int
1570 prepend_args (char const *options, char *buf, char **argv)
1571 {
1572   char const *o = options;
1573   char *b = buf;
1574   int n = 0;
1575
1576   for (;;)
1577     {
1578       while (c_isspace ((unsigned char) *o))
1579         o++;
1580       if (!*o)
1581         return n;
1582       if (argv)
1583         argv[n] = b;
1584       n++;
1585
1586       do
1587         if ((*b++ = *o++) == '\\' && *o)
1588           b[-1] = *o++;
1589       while (*o && ! c_isspace ((unsigned char) *o));
1590
1591       *b++ = '\0';
1592     }
1593 }
1594
1595 /* Prepend the whitespace-separated options in OPTIONS to the argument
1596    vector of a main program with argument count *PARGC and argument
1597    vector *PARGV.  */
1598 static void
1599 prepend_default_options (char const *options, int *pargc, char ***pargv)
1600 {
1601   if (options && *options)
1602     {
1603       char *buf = xmalloc (strlen (options) + 1);
1604       int prepended = prepend_args (options, buf, (char **) NULL);
1605       int argc = *pargc;
1606       char * const *argv = *pargv;
1607       char **pp = xmalloc ((prepended + argc + 1) * sizeof *pp);
1608       *pargc = prepended + argc;
1609       *pargv = pp;
1610       *pp++ = *argv++;
1611       pp += prepend_args (options, buf, pp);
1612       while ((*pp++ = *argv++))
1613         continue;
1614     }
1615 }
1616
1617 /* Get the next non-digit option from ARGC and ARGV.
1618    Return -1 if there are no more options.
1619    Process any digit options that were encountered on the way,
1620    and store the resulting integer into *DEFAULT_CONTEXT.  */
1621 static int
1622 get_nondigit_option (int argc, char *const *argv, int *default_context)
1623 {
1624   static int prev_digit_optind = -1;
1625   int opt, this_digit_optind, was_digit;
1626   char buf[sizeof (uintmax_t) * CHAR_BIT + 4];
1627   char *p = buf;
1628
1629   was_digit = 0;
1630   this_digit_optind = optind;
1631   while (opt = getopt_long (argc, (char **) argv, short_options, long_options,
1632                             NULL),
1633          '0' <= opt && opt <= '9')
1634     {
1635       if (prev_digit_optind != this_digit_optind || !was_digit)
1636         {
1637           /* Reset to start another context length argument.  */
1638           p = buf;
1639         }
1640       else
1641         {
1642           /* Suppress trivial leading zeros, to avoid incorrect
1643              diagnostic on strings like 00000000000.  */
1644           p -= buf[0] == '0';
1645         }
1646
1647       if (p == buf + sizeof buf - 4)
1648         {
1649           /* Too many digits.  Append "..." to make context_length_arg
1650              complain about "X...", where X contains the digits seen
1651              so far.  */
1652           strcpy (p, "...");
1653           p += 3;
1654           break;
1655         }
1656       *p++ = opt;
1657
1658       was_digit = 1;
1659       prev_digit_optind = this_digit_optind;
1660       this_digit_optind = optind;
1661     }
1662   if (p != buf)
1663     {
1664       *p = '\0';
1665       context_length_arg (buf, default_context);
1666     }
1667
1668   return opt;
1669 }
1670
1671 /* Parse GREP_COLORS.  The default would look like:
1672      GREP_COLORS='ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36'
1673    with boolean capabilities (ne and rv) unset (i.e., omitted).
1674    No character escaping is needed or supported.  */
1675 static void
1676 parse_grep_colors (void)
1677 {
1678   const char *p;
1679   char *q;
1680   char *name;
1681   char *val;
1682
1683   p = getenv("GREP_COLORS"); /* Plural! */
1684   if (p == NULL || *p == '\0')
1685     return;
1686
1687   /* Work off a writable copy.  */
1688   q = xmalloc(strlen(p) + 1);
1689   if (q == NULL)
1690     return;
1691   strcpy(q, p);
1692
1693   name = q;
1694   val = NULL;
1695   /* From now on, be well-formed or you're gone.  */
1696   for (;;)
1697     if (*q == ':' || *q == '\0')
1698       {
1699         char c = *q;
1700         struct color_cap *cap;
1701
1702         *q++ = '\0'; /* Terminate name or val.  */
1703         /* Empty name without val (empty cap)
1704          * won't match and will be ignored.  */
1705         for (cap = color_dict; cap->name; cap++)
1706           if (STREQ (cap->name, name))
1707             break;
1708         /* If name unknown, go on for forward compatibility.  */
1709         if (cap->name)
1710           {
1711             if (cap->var)
1712               {
1713                 if (val)
1714               *(cap->var) = val;
1715                 else
1716               error(0, 0, _("in GREP_COLORS=\"%s\", the \"%s\" capacity "
1717                                 "needs a value (\"=...\"); skipped"), p, name);
1718           }
1719         else if (val)
1720           error(0, 0, _("in GREP_COLORS=\"%s\", the \"%s\" capacity "
1721                 "is boolean and cannot take a value (\"=%s\"); skipped"),
1722                 p, name, val);
1723       }
1724         if (cap->fct)
1725           {
1726             const char *err_str = cap->fct();
1727
1728             if (err_str)
1729               error(0, 0, _("in GREP_COLORS=\"%s\", the \"%s\" capacity %s"),
1730                     p, name, err_str);
1731           }
1732         if (c == '\0')
1733           return;
1734         name = q;
1735         val = NULL;
1736       }
1737     else if (*q == '=')
1738       {
1739         if (q == name || val)
1740           goto ill_formed;
1741         *q++ = '\0'; /* Terminate name.  */
1742         val = q; /* Can be the empty string.  */
1743       }
1744     else if (val == NULL)
1745       q++; /* Accumulate name.  */
1746     else if (*q == ';' || (*q >= '0' && *q <= '9'))
1747       q++; /* Accumulate val.  Protect the terminal from being sent crap.  */
1748     else
1749       goto ill_formed;
1750
1751  ill_formed:
1752   error(0, 0, _("stopped processing of ill-formed GREP_COLORS=\"%s\" "
1753                 "at remaining substring \"%s\""), p, q);
1754 }
1755
1756 int
1757 main (int argc, char **argv)
1758 {
1759   char *keys;
1760   size_t keycc, oldcc, keyalloc;
1761   int with_filenames;
1762   int opt, cc, status;
1763   int default_context;
1764   FILE *fp;
1765
1766   initialize_main (&argc, &argv);
1767   set_program_name (argv[0]);
1768   program_name = argv[0];
1769
1770   keys = NULL;
1771   keycc = 0;
1772   with_filenames = 0;
1773   eolbyte = '\n';
1774   filename_mask = ~0;
1775
1776   max_count = TYPE_MAXIMUM (off_t);
1777
1778   /* The value -1 means to use DEFAULT_CONTEXT. */
1779   out_after = out_before = -1;
1780   /* Default before/after context: chaged by -C/-NUM options */
1781   default_context = 0;
1782   /* Changed by -o option */
1783   only_matching = 0;
1784
1785   /* Internationalization. */
1786 #if defined HAVE_SETLOCALE
1787   setlocale (LC_ALL, "");
1788 #endif
1789 #if defined ENABLE_NLS
1790   bindtextdomain (PACKAGE, LOCALEDIR);
1791   textdomain (PACKAGE);
1792 #endif
1793
1794   exit_failure = EXIT_TROUBLE;
1795   atexit (close_stdout);
1796
1797   prepend_default_options (getenv ("GREP_OPTIONS"), &argc, &argv);
1798   setmatcher (NULL);
1799
1800   while ((opt = get_nondigit_option (argc, argv, &default_context)) != -1)
1801     switch (opt)
1802       {
1803       case 'A':
1804         context_length_arg (optarg, &out_after);
1805         break;
1806
1807       case 'B':
1808         context_length_arg (optarg, &out_before);
1809         break;
1810
1811       case 'C':
1812         /* Set output match context, but let any explicit leading or
1813            trailing amount specified with -A or -B stand. */
1814         context_length_arg (optarg, &default_context);
1815         break;
1816
1817       case 'D':
1818         if (STREQ (optarg, "read"))
1819           devices = READ_DEVICES;
1820         else if (STREQ (optarg, "skip"))
1821           devices = SKIP_DEVICES;
1822         else
1823           error (EXIT_TROUBLE, 0, _("unknown devices method"));
1824         break;
1825
1826       case 'E':
1827         setmatcher ("egrep");
1828         break;
1829
1830       case 'F':
1831         setmatcher ("fgrep");
1832         break;
1833
1834       case 'P':
1835         setmatcher ("perl");
1836         break;
1837
1838       case 'G':
1839         setmatcher ("grep");
1840         break;
1841
1842       case 'X': /* undocumented on purpose */
1843         setmatcher (optarg);
1844         break;
1845
1846       case 'H':
1847         with_filenames = 1;
1848         no_filenames = 0;
1849         break;
1850
1851       case 'I':
1852         binary_files = WITHOUT_MATCH_BINARY_FILES;
1853         break;
1854
1855       case 'T':
1856         align_tabs = 1;
1857         break;
1858
1859       case 'U':
1860 #if defined HAVE_DOS_FILE_CONTENTS
1861         dos_use_file_type = DOS_BINARY;
1862 #endif
1863         break;
1864
1865       case 'u':
1866 #if defined HAVE_DOS_FILE_CONTENTS
1867         dos_report_unix_offset = 1;
1868 #endif
1869         break;
1870
1871       case 'V':
1872         show_version = 1;
1873         break;
1874
1875       case 'a':
1876         binary_files = TEXT_BINARY_FILES;
1877         break;
1878
1879       case 'b':
1880         out_byte = 1;
1881         break;
1882
1883       case 'c':
1884         count_matches = 1;
1885         break;
1886
1887       case 'd':
1888         directories = XARGMATCH ("--directories", optarg,
1889                                  directories_args, directories_types);
1890         break;
1891
1892       case 'e':
1893         cc = strlen (optarg);
1894         keys = xrealloc (keys, keycc + cc + 1);
1895         strcpy (&keys[keycc], optarg);
1896         keycc += cc;
1897         keys[keycc++] = '\n';
1898         break;
1899
1900       case 'f':
1901         fp = STREQ (optarg, "-") ? stdin : fopen (optarg, "r");
1902         if (!fp)
1903           error (EXIT_TROUBLE, errno, "%s", optarg);
1904         for (keyalloc = 1; keyalloc <= keycc + 1; keyalloc *= 2)
1905           ;
1906         keys = xrealloc (keys, keyalloc);
1907         oldcc = keycc;
1908         while (!feof (fp)
1909                && (cc = fread (keys + keycc, 1, keyalloc - 1 - keycc, fp)) > 0)
1910           {
1911             keycc += cc;
1912             if (keycc == keyalloc - 1)
1913               keys = xrealloc (keys, keyalloc *= 2);
1914           }
1915         if (fp != stdin)
1916           fclose(fp);
1917         /* Append final newline if file ended in non-newline. */
1918         if (oldcc != keycc && keys[keycc - 1] != '\n')
1919           keys[keycc++] = '\n';
1920         break;
1921
1922       case 'h':
1923         with_filenames = 0;
1924         no_filenames = 1;
1925         break;
1926
1927       case 'i':
1928       case 'y':                 /* For old-timers . . . */
1929         match_icase = 1;
1930         break;
1931
1932       case 'L':
1933         /* Like -l, except list files that don't contain matches.
1934            Inspired by the same option in Hume's gre. */
1935         list_files = -1;
1936         break;
1937
1938       case 'l':
1939         list_files = 1;
1940         break;
1941
1942       case 'm':
1943         {
1944           uintmax_t value;
1945           switch (xstrtoumax (optarg, 0, 10, &value, ""))
1946             {
1947             case LONGINT_OK:
1948               max_count = value;
1949               if (0 <= max_count && max_count == value)
1950                 break;
1951               /* Fall through.  */
1952             case LONGINT_OVERFLOW:
1953               max_count = TYPE_MAXIMUM (off_t);
1954               break;
1955
1956             default:
1957               error (EXIT_TROUBLE, 0, _("invalid max count"));
1958             }
1959         }
1960         break;
1961
1962       case 'n':
1963         out_line = 1;
1964         break;
1965
1966       case 'o':
1967         only_matching = 1;
1968         break;
1969
1970       case 'q':
1971         exit_on_match = 1;
1972         exit_failure = 0;
1973         break;
1974
1975       case 'R':
1976       case 'r':
1977         directories = RECURSE_DIRECTORIES;
1978         break;
1979
1980       case 's':
1981         suppress_errors = 1;
1982         break;
1983
1984       case 'v':
1985         out_invert = 1;
1986         break;
1987
1988       case 'w':
1989         match_words = 1;
1990         break;
1991
1992       case 'x':
1993         match_lines = 1;
1994         break;
1995
1996       case 'Z':
1997         filename_mask = 0;
1998         break;
1999
2000       case 'z':
2001         eolbyte = '\0';
2002         break;
2003
2004       case BINARY_FILES_OPTION:
2005         if (STREQ (optarg, "binary"))
2006           binary_files = BINARY_BINARY_FILES;
2007         else if (STREQ (optarg, "text"))
2008           binary_files = TEXT_BINARY_FILES;
2009         else if (STREQ (optarg, "without-match"))
2010           binary_files = WITHOUT_MATCH_BINARY_FILES;
2011         else
2012           error (EXIT_TROUBLE, 0, _("unknown binary-files type"));
2013         break;
2014
2015       case COLOR_OPTION:
2016         if(optarg) {
2017           if(!strcasecmp(optarg, "always") || !strcasecmp(optarg, "yes") ||
2018              !strcasecmp(optarg, "force"))
2019             color_option = 1;
2020           else if(!strcasecmp(optarg, "never") || !strcasecmp(optarg, "no") ||
2021                   !strcasecmp(optarg, "none"))
2022             color_option = 0;
2023           else if(!strcasecmp(optarg, "auto") || !strcasecmp(optarg, "tty") ||
2024                   !strcasecmp(optarg, "if-tty"))
2025             color_option = 2;
2026           else
2027             show_help = 1;
2028         } else
2029           color_option = 2;
2030         if (color_option == 2)
2031           {
2032             char const *t;
2033             if (isatty (STDOUT_FILENO) && (t = getenv ("TERM"))
2034                 && !STREQ (t, "dumb"))
2035               color_option = 1;
2036             else
2037               color_option = 0;
2038           }
2039         break;
2040
2041       case EXCLUDE_OPTION:
2042         if (!excluded_patterns)
2043           excluded_patterns = new_exclude ();
2044         add_exclude (excluded_patterns, optarg, EXCLUDE_WILDCARDS);
2045         break;
2046       case EXCLUDE_FROM_OPTION:
2047         if (!excluded_patterns)
2048           excluded_patterns = new_exclude ();
2049         if (add_exclude_file (add_exclude, excluded_patterns, optarg,
2050                               EXCLUDE_WILDCARDS, '\n') != 0)
2051           {
2052             error (EXIT_TROUBLE, errno, "%s", optarg);
2053           }
2054         break;
2055
2056       case EXCLUDE_DIRECTORY_OPTION:
2057         if (!excluded_directory_patterns)
2058           excluded_directory_patterns = new_exclude ();
2059         add_exclude (excluded_directory_patterns, optarg, EXCLUDE_WILDCARDS);
2060         break;
2061
2062       case INCLUDE_OPTION:
2063         if (!included_patterns)
2064           included_patterns = new_exclude ();
2065         add_exclude (included_patterns, optarg,
2066                      EXCLUDE_WILDCARDS | EXCLUDE_INCLUDE);
2067         break;
2068
2069       case GROUP_SEPARATOR_OPTION:
2070         group_separator = optarg;
2071         break;
2072
2073       case LINE_BUFFERED_OPTION:
2074         line_buffered = 1;
2075         break;
2076
2077       case LABEL_OPTION:
2078         label = optarg;
2079         break;
2080
2081       case MMAP_OPTION:
2082       case 0:
2083         /* long options */
2084         break;
2085
2086       default:
2087         usage (EXIT_TROUBLE);
2088         break;
2089
2090       }
2091
2092   /* POSIX.2 says that -q overrides -l, which in turn overrides the
2093      other output options.  */
2094   if (exit_on_match)
2095     list_files = 0;
2096   if (exit_on_match | list_files)
2097     {
2098       count_matches = 0;
2099       done_on_match = 1;
2100     }
2101   out_quiet = count_matches | done_on_match;
2102
2103   if (out_after < 0)
2104     out_after = default_context;
2105   if (out_before < 0)
2106     out_before = default_context;
2107
2108   if (color_option)
2109     {
2110       /* Legacy.  */
2111       char *userval = getenv ("GREP_COLOR");
2112       if (userval != NULL && *userval != '\0')
2113         selected_match_color = context_match_color = userval;
2114
2115       /* New GREP_COLORS has priority.  */
2116       parse_grep_colors();
2117     }
2118
2119   if (show_version)
2120     {
2121       version_etc (stdout, program_name, PACKAGE_NAME, VERSION, AUTHORS, \
2122                    (char *) NULL);                                      \
2123       exit (EXIT_SUCCESS);                                              \
2124     }
2125
2126   if (show_help)
2127     usage (EXIT_SUCCESS);
2128
2129   if (keys)
2130     {
2131       if (keycc == 0)
2132         {
2133           /* No keys were specified (e.g. -f /dev/null).  Match nothing.  */
2134           out_invert ^= 1;
2135           match_lines = match_words = 0;
2136         }
2137       else
2138         /* Strip trailing newline. */
2139         --keycc;
2140     }
2141   else
2142     if (optind < argc)
2143       {
2144         /* A copy must be made in case of an xrealloc() or free() later.  */
2145         keycc = strlen(argv[optind]);
2146         keys = xmalloc(keycc + 1);
2147         strcpy(keys, argv[optind++]);
2148       }
2149     else
2150       usage (EXIT_TROUBLE);
2151
2152   set_limits();
2153   compile(keys, keycc);
2154   free (keys);
2155
2156   if ((argc - optind > 1 && !no_filenames) || with_filenames)
2157     out_file = 1;
2158
2159 #ifdef SET_BINARY
2160   /* Output is set to binary mode because we shouldn't convert
2161      NL to CR-LF pairs, especially when grepping binary files.  */
2162   if (!isatty (1))
2163     SET_BINARY (1);
2164 #endif
2165
2166   if (max_count == 0)
2167     exit (EXIT_FAILURE);
2168
2169   if (optind < argc)
2170     {
2171         status = 1;
2172         do
2173         {
2174           char *file = argv[optind];
2175           if ((included_patterns || excluded_patterns)
2176               && !isdir (file))
2177             {
2178               if (included_patterns
2179                   && excluded_file_name (included_patterns, file))
2180                 continue;
2181               if (excluded_patterns
2182                   && excluded_file_name (excluded_patterns, file))
2183                 continue;
2184             }
2185           status &= grepfile (STREQ (file, "-") ? (char *) NULL : file,
2186                               &stats_base);
2187         }
2188         while ( ++optind < argc);
2189     }
2190   else
2191     status = grepfile ((char *) NULL, &stats_base);
2192
2193   /* We register via atexit() to test stdout.  */
2194   exit (errseen ? EXIT_TROUBLE : status);
2195 }
2196 /* vim:set shiftwidth=2: */