Upgrade grep version 2.7 to 2.9 on the vendor branch
[dragonfly.git] / contrib / grep / src / main.c
1 /* grep.c - main driver file for grep.
2    Copyright (C) 1992, 1997-2002, 2004-2011 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 <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         suppressible_error (filename, errno);
1097       return 0;
1098     }
1099
1100   not_text = (((binary_files == BINARY_BINARY_FILES && !out_quiet)
1101                || binary_files == WITHOUT_MATCH_BINARY_FILES)
1102               && memchr (bufbeg, eol ? '\0' : '\200', buflim - bufbeg));
1103   if (not_text && binary_files == WITHOUT_MATCH_BINARY_FILES)
1104     return 0;
1105   done_on_match += not_text;
1106   out_quiet += not_text;
1107
1108   for (;;)
1109     {
1110       lastnl = bufbeg;
1111       if (lastout)
1112         lastout = bufbeg;
1113
1114       beg = bufbeg + save;
1115
1116       /* no more data to scan (eof) except for maybe a residue -> break */
1117       if (beg == buflim)
1118         break;
1119
1120       /* Determine new residue (the length of an incomplete line at the end of
1121          the buffer, 0 means there is no incomplete last line).  */
1122       oldc = beg[-1];
1123       beg[-1] = eol;
1124       for (lim = buflim; lim[-1] != eol; lim--)
1125         continue;
1126       beg[-1] = oldc;
1127       if (lim == beg)
1128         lim = beg - residue;
1129       beg -= residue;
1130       residue = buflim - lim;
1131
1132       if (beg < lim)
1133         {
1134           if (outleft)
1135             nlines += grepbuf (beg, lim);
1136           if (pending)
1137             prpending (lim);
1138           if((!outleft && !pending) || (nlines && done_on_match && !out_invert))
1139             goto finish_grep;
1140         }
1141
1142       /* The last OUT_BEFORE lines at the end of the buffer will be needed as
1143          leading context if there is a matching line at the begin of the
1144          next data. Make beg point to their begin.  */
1145       i = 0;
1146       beg = lim;
1147       while (i < out_before && beg > bufbeg && beg != lastout)
1148         {
1149           ++i;
1150           do
1151             --beg;
1152           while (beg[-1] != eol);
1153         }
1154
1155       /* detect if leading context is discontinuous from last printed line.  */
1156       if (beg != lastout)
1157         lastout = 0;
1158
1159       /* Handle some details and read more data to scan.  */
1160       save = residue + lim - beg;
1161       if (out_byte)
1162         totalcc = add_count (totalcc, buflim - bufbeg - save);
1163       if (out_line)
1164         nlscan (beg);
1165       if (! fillbuf (save, stats))
1166         {
1167           if (! is_EISDIR (errno, file))
1168             suppressible_error (filename, errno);
1169           goto finish_grep;
1170         }
1171     }
1172   if (residue)
1173     {
1174       *buflim++ = eol;
1175       if (outleft)
1176         nlines += grepbuf (bufbeg + save - residue, buflim);
1177       if (pending)
1178         prpending (buflim);
1179     }
1180
1181  finish_grep:
1182   done_on_match -= not_text;
1183   out_quiet -= not_text;
1184   if ((not_text & ~out_quiet) && nlines != 0)
1185     printf (_("Binary file %s matches\n"), filename);
1186   return nlines;
1187 }
1188
1189 static int
1190 grepfile (char const *file, struct stats *stats)
1191 {
1192   int desc;
1193   int count;
1194   int status;
1195
1196   if (! file)
1197     {
1198       desc = 0;
1199       filename = label ? label : _("(standard input)");
1200     }
1201   else
1202     {
1203       if (stat (file, &stats->stat) != 0)
1204         {
1205           suppressible_error (file, errno);
1206           return 1;
1207         }
1208       if (directories == SKIP_DIRECTORIES && S_ISDIR (stats->stat.st_mode))
1209         return 1;
1210       if (devices == SKIP_DEVICES && (S_ISCHR (stats->stat.st_mode)
1211                                       || S_ISBLK (stats->stat.st_mode)
1212                                       || S_ISSOCK (stats->stat.st_mode)
1213                                       || S_ISFIFO (stats->stat.st_mode)))
1214         return 1;
1215       while ((desc = open (file, O_RDONLY)) < 0 && errno == EINTR)
1216         continue;
1217
1218       if (desc < 0)
1219         {
1220           int e = errno;
1221
1222           if (is_EISDIR (e, file) && directories == RECURSE_DIRECTORIES)
1223             {
1224               if (stat (file, &stats->stat) != 0)
1225                 {
1226                   error (0, errno, "%s", file);
1227                   return 1;
1228                 }
1229
1230               return grepdir (file, stats);
1231             }
1232
1233           if (!suppress_errors)
1234             {
1235               if (directories == SKIP_DIRECTORIES)
1236                 switch (e)
1237                   {
1238 #if defined EISDIR
1239                   case EISDIR:
1240                     return 1;
1241 #endif
1242                   case EACCES:
1243                     /* When skipping directories, don't worry about
1244                        directories that can't be opened.  */
1245                     if (isdir (file))
1246                       return 1;
1247                     break;
1248                   }
1249             }
1250
1251           suppressible_error (file, e);
1252           return 1;
1253         }
1254
1255       filename = file;
1256     }
1257
1258 #if defined SET_BINARY
1259   /* Set input to binary mode.  Pipes are simulated with files
1260      on DOS, so this includes the case of "foo | grep bar".  */
1261   if (!isatty (desc))
1262     SET_BINARY (desc);
1263 #endif
1264
1265   count = grep (desc, file, stats);
1266   if (count < 0)
1267     status = count + 2;
1268   else
1269     {
1270       if (count_matches)
1271         {
1272           if (out_file)
1273             {
1274               print_filename();
1275               if (filename_mask)
1276                 print_sep(SEP_CHAR_SELECTED);
1277               else
1278                 fputc(0, stdout);
1279             }
1280           printf ("%d\n", count);
1281         }
1282
1283       status = !count;
1284       if (list_files == 1 - 2 * status)
1285         {
1286           print_filename();
1287           fputc('\n' & filename_mask, stdout);
1288         }
1289
1290       if (! file)
1291         {
1292           off_t required_offset = outleft ? bufoffset : after_last_match;
1293           if (required_offset != bufoffset
1294               && lseek (desc, required_offset, SEEK_SET) < 0
1295               && S_ISREG (stats->stat.st_mode))
1296             error (0, errno, "%s", filename);
1297         }
1298       else
1299         while (close (desc) != 0)
1300           if (errno != EINTR)
1301             {
1302               error (0, errno, "%s", file);
1303               break;
1304             }
1305     }
1306
1307   return status;
1308 }
1309
1310 static int
1311 grepdir (char const *dir, struct stats const *stats)
1312 {
1313   struct stats const *ancestor;
1314   char *name_space;
1315   int status = 1;
1316   if ( excluded_directory_patterns &&
1317        excluded_file_name (excluded_directory_patterns, dir)  ) {
1318        return 1;
1319   }
1320
1321
1322   /* Mingw32 does not support st_ino.  No known working hosts use zero
1323      for st_ino, so assume that the Mingw32 bug applies if it's zero.  */
1324   if (stats->stat.st_ino)
1325     for (ancestor = stats;  (ancestor = ancestor->parent) != 0;  )
1326       if (ancestor->stat.st_ino == stats->stat.st_ino
1327           && ancestor->stat.st_dev == stats->stat.st_dev)
1328         {
1329           if (!suppress_errors)
1330             error (0, 0, _("warning: %s: %s"), dir,
1331                    _("recursive directory loop"));
1332           return 1;
1333         }
1334
1335   name_space = savedir (dir, stats->stat.st_size, included_patterns,
1336                         excluded_patterns, excluded_directory_patterns);
1337
1338   if (! name_space)
1339     {
1340       if (errno)
1341         suppressible_error (dir, errno);
1342       else
1343         xalloc_die ();
1344     }
1345   else
1346     {
1347       size_t dirlen = strlen (dir);
1348       int needs_slash = ! (dirlen == FILE_SYSTEM_PREFIX_LEN (dir)
1349                            || ISSLASH (dir[dirlen - 1]));
1350       char *file = NULL;
1351       char const *namep = name_space;
1352       struct stats child;
1353       child.parent = stats;
1354       out_file += !no_filenames;
1355       while (*namep)
1356         {
1357           size_t namelen = strlen (namep);
1358           file = xrealloc (file, dirlen + 1 + namelen + 1);
1359           strcpy (file, dir);
1360           file[dirlen] = '/';
1361           strcpy (file + dirlen + needs_slash, namep);
1362           namep += namelen + 1;
1363           status &= grepfile (file, &child);
1364         }
1365       out_file -= !no_filenames;
1366       free (file);
1367       free (name_space);
1368     }
1369
1370   return status;
1371 }
1372
1373 void usage (int status) __attribute__ ((noreturn));
1374 void
1375 usage (int status)
1376 {
1377   if (status != 0)
1378     {
1379       fprintf (stderr, _("Usage: %s [OPTION]... PATTERN [FILE]...\n"),
1380                program_name);
1381       fprintf (stderr, _("Try `%s --help' for more information.\n"),
1382                program_name);
1383     }
1384   else
1385     {
1386       printf (_("Usage: %s [OPTION]... PATTERN [FILE]...\n"), program_name);
1387       printf (_("\
1388 Search for PATTERN in each FILE or standard input.\n"));
1389       printf ("%s", gettext (before_options));
1390       printf (_("\
1391 Example: %s -i 'hello world' menu.h main.c\n\
1392 \n\
1393 Regexp selection and interpretation:\n"), program_name);
1394       if (matchers[1].name)
1395         printf (_("\
1396   -E, --extended-regexp     PATTERN is an extended regular expression (ERE)\n\
1397   -F, --fixed-strings       PATTERN is a set of newline-separated fixed strings\n\
1398   -G, --basic-regexp        PATTERN is a basic regular expression (BRE)\n\
1399   -P, --perl-regexp         PATTERN is a Perl regular expression\n"));
1400   /* -X is undocumented on purpose. */
1401       printf (_("\
1402   -e, --regexp=PATTERN      use PATTERN for matching\n\
1403   -f, --file=FILE           obtain PATTERN from FILE\n\
1404   -i, --ignore-case         ignore case distinctions\n\
1405   -w, --word-regexp         force PATTERN to match only whole words\n\
1406   -x, --line-regexp         force PATTERN to match only whole lines\n\
1407   -z, --null-data           a data line ends in 0 byte, not newline\n"));
1408       printf (_("\
1409 \n\
1410 Miscellaneous:\n\
1411   -s, --no-messages         suppress error messages\n\
1412   -v, --invert-match        select non-matching lines\n\
1413   -V, --version             print version information and exit\n\
1414       --help                display this help and exit\n\
1415       --mmap                ignored for backwards compatibility\n"));
1416       printf (_("\
1417 \n\
1418 Output control:\n\
1419   -m, --max-count=NUM       stop after NUM matches\n\
1420   -b, --byte-offset         print the byte offset with output lines\n\
1421   -n, --line-number         print line number with output lines\n\
1422       --line-buffered       flush output on every line\n\
1423   -H, --with-filename       print the filename for each match\n\
1424   -h, --no-filename         suppress the prefixing filename on output\n\
1425       --label=LABEL         print LABEL as filename for standard input\n\
1426 "));
1427       printf (_("\
1428   -o, --only-matching       show only the part of a line matching PATTERN\n\
1429   -q, --quiet, --silent     suppress all normal output\n\
1430       --binary-files=TYPE   assume that binary files are TYPE;\n\
1431                             TYPE is `binary', `text', or `without-match'\n\
1432   -a, --text                equivalent to --binary-files=text\n\
1433 "));
1434       printf (_("\
1435   -I                        equivalent to --binary-files=without-match\n\
1436   -d, --directories=ACTION  how to handle directories;\n\
1437                             ACTION is `read', `recurse', or `skip'\n\
1438   -D, --devices=ACTION      how to handle devices, FIFOs and sockets;\n\
1439                             ACTION is `read' or `skip'\n\
1440   -R, -r, --recursive       equivalent to --directories=recurse\n\
1441 "));
1442       printf (_("\
1443       --include=FILE_PATTERN  search only files that match FILE_PATTERN\n\
1444       --exclude=FILE_PATTERN  skip files and directories matching FILE_PATTERN\n\
1445       --exclude-from=FILE   skip files matching any file pattern from FILE\n\
1446       --exclude-dir=PATTERN  directories that match PATTERN will be skipped.\n\
1447 "));
1448       printf (_("\
1449   -L, --files-without-match  print only names of FILEs containing no match\n\
1450   -l, --files-with-matches  print only names of FILEs containing matches\n\
1451   -c, --count               print only a count of matching lines per FILE\n\
1452   -T, --initial-tab         make tabs line up (if needed)\n\
1453   -Z, --null                print 0 byte after FILE name\n"));
1454       printf (_("\
1455 \n\
1456 Context control:\n\
1457   -B, --before-context=NUM  print NUM lines of leading context\n\
1458   -A, --after-context=NUM   print NUM lines of trailing context\n\
1459   -C, --context=NUM         print NUM lines of output context\n\
1460 "));
1461       printf (_("\
1462   -NUM                      same as --context=NUM\n\
1463       --color[=WHEN],\n\
1464       --colour[=WHEN]       use markers to highlight the matching strings;\n\
1465                             WHEN is `always', `never', or `auto'\n\
1466   -U, --binary              do not strip CR characters at EOL (MSDOS)\n\
1467   -u, --unix-byte-offsets   report offsets as if CRs were not there (MSDOS)\n\
1468 \n"));
1469       printf ("%s", _(after_options));
1470       printf (_("\
1471 With no FILE, or when FILE is -, read standard input.  If less than two FILEs\n\
1472 are given, assume -h.  Exit status is 0 if any line was selected, 1 otherwise;\n\
1473 if any error occurs and -q was not given, the exit status is 2.\n"));
1474       printf (_("\nReport bugs to: %s\n"), PACKAGE_BUGREPORT);
1475       printf (_("GNU Grep home page: <%s>\n"),
1476               "http://www.gnu.org/software/grep/");
1477       fputs (_("General help using GNU software: <http://www.gnu.org/gethelp/>\n"),
1478              stdout);
1479
1480     }
1481   exit (status);
1482 }
1483
1484 /* If M is NULL, initialize the matcher to the default.  Otherwise set the
1485    matcher to M if available.  Exit in case of conflicts or if M is not
1486    available.  */
1487 static void
1488 setmatcher (char const *m)
1489 {
1490   static char const *matcher;
1491   unsigned int i;
1492
1493   if (!m)
1494     {
1495       compile = matchers[0].compile;
1496       execute = matchers[0].execute;
1497       if (!matchers[1].name)
1498         matcher = matchers[0].name;
1499     }
1500
1501   else if (matcher)
1502     {
1503       if (matcher && STREQ (matcher, m))
1504         ;
1505
1506       else if (!matchers[1].name)
1507         error (EXIT_TROUBLE, 0, _("%s can only use the %s pattern syntax"),
1508                program_name, matcher);
1509       else
1510         error (EXIT_TROUBLE, 0, _("conflicting matchers specified"));
1511     }
1512
1513   else
1514     {
1515       for (i = 0; matchers[i].name; i++)
1516         if (STREQ (m, matchers[i].name))
1517           {
1518             compile = matchers[i].compile;
1519             execute = matchers[i].execute;
1520             matcher = m;
1521             return;
1522           }
1523
1524       error (EXIT_TROUBLE, 0, _("invalid matcher %s"), m);
1525     }
1526 }
1527
1528 static void
1529 set_limits(void)
1530 {
1531 #if defined HAVE_SETRLIMIT && defined RLIMIT_STACK
1532   struct rlimit rlim;
1533
1534   /* I think every platform needs to do this, so that regex.c
1535      doesn't oveflow the stack.  The default value of
1536      `re_max_failures' is too large for some platforms: it needs
1537      more than 3MB-large stack.
1538
1539      The test for HAVE_SETRLIMIT should go into `configure'.  */
1540   if (!getrlimit (RLIMIT_STACK, &rlim))
1541     {
1542       long newlim;
1543       extern long int re_max_failures; /* from regex.c */
1544
1545       /* Approximate the amount regex.c needs, plus some more.  */
1546       newlim = re_max_failures * 2 * 20 * sizeof (char *);
1547       if (newlim > rlim.rlim_max)
1548         {
1549           newlim = rlim.rlim_max;
1550           re_max_failures = newlim / (2 * 20 * sizeof (char *));
1551         }
1552       if (rlim.rlim_cur < newlim)
1553         {
1554           rlim.rlim_cur = newlim;
1555           setrlimit (RLIMIT_STACK, &rlim);
1556         }
1557     }
1558 #endif
1559 }
1560
1561 /* Find the white-space-separated options specified by OPTIONS, and
1562    using BUF to store copies of these options, set ARGV[0], ARGV[1],
1563    etc. to the option copies.  Return the number N of options found.
1564    Do not set ARGV[N] to NULL.  If ARGV is NULL, do not store ARGV[0]
1565    etc.  Backslash can be used to escape whitespace (and backslashes).  */
1566 static int
1567 prepend_args (char const *options, char *buf, char **argv)
1568 {
1569   char const *o = options;
1570   char *b = buf;
1571   int n = 0;
1572
1573   for (;;)
1574     {
1575       while (c_isspace ((unsigned char) *o))
1576         o++;
1577       if (!*o)
1578         return n;
1579       if (argv)
1580         argv[n] = b;
1581       n++;
1582
1583       do
1584         if ((*b++ = *o++) == '\\' && *o)
1585           b[-1] = *o++;
1586       while (*o && ! c_isspace ((unsigned char) *o));
1587
1588       *b++ = '\0';
1589     }
1590 }
1591
1592 /* Prepend the whitespace-separated options in OPTIONS to the argument
1593    vector of a main program with argument count *PARGC and argument
1594    vector *PARGV.  */
1595 static void
1596 prepend_default_options (char const *options, int *pargc, char ***pargv)
1597 {
1598   if (options && *options)
1599     {
1600       char *buf = xmalloc (strlen (options) + 1);
1601       int prepended = prepend_args (options, buf, (char **) NULL);
1602       int argc = *pargc;
1603       char * const *argv = *pargv;
1604       char **pp = xmalloc ((prepended + argc + 1) * sizeof *pp);
1605       *pargc = prepended + argc;
1606       *pargv = pp;
1607       *pp++ = *argv++;
1608       pp += prepend_args (options, buf, pp);
1609       while ((*pp++ = *argv++))
1610         continue;
1611     }
1612 }
1613
1614 /* Get the next non-digit option from ARGC and ARGV.
1615    Return -1 if there are no more options.
1616    Process any digit options that were encountered on the way,
1617    and store the resulting integer into *DEFAULT_CONTEXT.  */
1618 static int
1619 get_nondigit_option (int argc, char *const *argv, int *default_context)
1620 {
1621   static int prev_digit_optind = -1;
1622   int opt, this_digit_optind, was_digit;
1623   char buf[sizeof (uintmax_t) * CHAR_BIT + 4];
1624   char *p = buf;
1625
1626   was_digit = 0;
1627   this_digit_optind = optind;
1628   while (opt = getopt_long (argc, (char **) argv, short_options, long_options,
1629                             NULL),
1630          '0' <= opt && opt <= '9')
1631     {
1632       if (prev_digit_optind != this_digit_optind || !was_digit)
1633         {
1634           /* Reset to start another context length argument.  */
1635           p = buf;
1636         }
1637       else
1638         {
1639           /* Suppress trivial leading zeros, to avoid incorrect
1640              diagnostic on strings like 00000000000.  */
1641           p -= buf[0] == '0';
1642         }
1643
1644       if (p == buf + sizeof buf - 4)
1645         {
1646           /* Too many digits.  Append "..." to make context_length_arg
1647              complain about "X...", where X contains the digits seen
1648              so far.  */
1649           strcpy (p, "...");
1650           p += 3;
1651           break;
1652         }
1653       *p++ = opt;
1654
1655       was_digit = 1;
1656       prev_digit_optind = this_digit_optind;
1657       this_digit_optind = optind;
1658     }
1659   if (p != buf)
1660     {
1661       *p = '\0';
1662       context_length_arg (buf, default_context);
1663     }
1664
1665   return opt;
1666 }
1667
1668 /* Parse GREP_COLORS.  The default would look like:
1669      GREP_COLORS='ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36'
1670    with boolean capabilities (ne and rv) unset (i.e., omitted).
1671    No character escaping is needed or supported.  */
1672 static void
1673 parse_grep_colors (void)
1674 {
1675   const char *p;
1676   char *q;
1677   char *name;
1678   char *val;
1679
1680   p = getenv("GREP_COLORS"); /* Plural! */
1681   if (p == NULL || *p == '\0')
1682     return;
1683
1684   /* Work off a writable copy.  */
1685   q = xstrdup(p);
1686
1687   name = q;
1688   val = NULL;
1689   /* From now on, be well-formed or you're gone.  */
1690   for (;;)
1691     if (*q == ':' || *q == '\0')
1692       {
1693         char c = *q;
1694         struct color_cap *cap;
1695
1696         *q++ = '\0'; /* Terminate name or val.  */
1697         /* Empty name without val (empty cap)
1698          * won't match and will be ignored.  */
1699         for (cap = color_dict; cap->name; cap++)
1700           if (STREQ (cap->name, name))
1701             break;
1702         /* If name unknown, go on for forward compatibility.  */
1703         if (cap->name)
1704           {
1705             if (cap->var)
1706               {
1707                 if (val)
1708               *(cap->var) = val;
1709                 else
1710               error(0, 0, _("in GREP_COLORS=\"%s\", the \"%s\" capacity "
1711                                 "needs a value (\"=...\"); skipped"), p, name);
1712           }
1713         else if (val)
1714           error(0, 0, _("in GREP_COLORS=\"%s\", the \"%s\" capacity "
1715                 "is boolean and cannot take a value (\"=%s\"); skipped"),
1716                 p, name, val);
1717       }
1718         if (cap->fct)
1719           {
1720             const char *err_str = cap->fct();
1721
1722             if (err_str)
1723               error(0, 0, _("in GREP_COLORS=\"%s\", the \"%s\" capacity %s"),
1724                     p, name, err_str);
1725           }
1726         if (c == '\0')
1727           return;
1728         name = q;
1729         val = NULL;
1730       }
1731     else if (*q == '=')
1732       {
1733         if (q == name || val)
1734           goto ill_formed;
1735         *q++ = '\0'; /* Terminate name.  */
1736         val = q; /* Can be the empty string.  */
1737       }
1738     else if (val == NULL)
1739       q++; /* Accumulate name.  */
1740     else if (*q == ';' || (*q >= '0' && *q <= '9'))
1741       q++; /* Accumulate val.  Protect the terminal from being sent crap.  */
1742     else
1743       goto ill_formed;
1744
1745  ill_formed:
1746   error(0, 0, _("stopped processing of ill-formed GREP_COLORS=\"%s\" "
1747                 "at remaining substring \"%s\""), p, q);
1748 }
1749
1750 int
1751 main (int argc, char **argv)
1752 {
1753   char *keys;
1754   size_t keycc, oldcc, keyalloc;
1755   int with_filenames;
1756   int opt, cc, status;
1757   int default_context;
1758   FILE *fp;
1759
1760   exit_failure = EXIT_TROUBLE;
1761   initialize_main (&argc, &argv);
1762   set_program_name (argv[0]);
1763   program_name = argv[0];
1764
1765   keys = NULL;
1766   keycc = 0;
1767   with_filenames = 0;
1768   eolbyte = '\n';
1769   filename_mask = ~0;
1770
1771   max_count = TYPE_MAXIMUM (off_t);
1772
1773   /* The value -1 means to use DEFAULT_CONTEXT. */
1774   out_after = out_before = -1;
1775   /* Default before/after context: chaged by -C/-NUM options */
1776   default_context = 0;
1777   /* Changed by -o option */
1778   only_matching = 0;
1779
1780   /* Internationalization. */
1781 #if defined HAVE_SETLOCALE
1782   setlocale (LC_ALL, "");
1783 #endif
1784 #if defined ENABLE_NLS
1785   bindtextdomain (PACKAGE, LOCALEDIR);
1786   textdomain (PACKAGE);
1787 #endif
1788
1789   exit_failure = EXIT_TROUBLE;
1790   atexit (close_stdout);
1791
1792   prepend_default_options (getenv ("GREP_OPTIONS"), &argc, &argv);
1793   setmatcher (NULL);
1794
1795   while ((opt = get_nondigit_option (argc, argv, &default_context)) != -1)
1796     switch (opt)
1797       {
1798       case 'A':
1799         context_length_arg (optarg, &out_after);
1800         break;
1801
1802       case 'B':
1803         context_length_arg (optarg, &out_before);
1804         break;
1805
1806       case 'C':
1807         /* Set output match context, but let any explicit leading or
1808            trailing amount specified with -A or -B stand. */
1809         context_length_arg (optarg, &default_context);
1810         break;
1811
1812       case 'D':
1813         if (STREQ (optarg, "read"))
1814           devices = READ_DEVICES;
1815         else if (STREQ (optarg, "skip"))
1816           devices = SKIP_DEVICES;
1817         else
1818           error (EXIT_TROUBLE, 0, _("unknown devices method"));
1819         break;
1820
1821       case 'E':
1822         setmatcher ("egrep");
1823         break;
1824
1825       case 'F':
1826         setmatcher ("fgrep");
1827         break;
1828
1829       case 'P':
1830         setmatcher ("perl");
1831         break;
1832
1833       case 'G':
1834         setmatcher ("grep");
1835         break;
1836
1837       case 'X': /* undocumented on purpose */
1838         setmatcher (optarg);
1839         break;
1840
1841       case 'H':
1842         with_filenames = 1;
1843         no_filenames = 0;
1844         break;
1845
1846       case 'I':
1847         binary_files = WITHOUT_MATCH_BINARY_FILES;
1848         break;
1849
1850       case 'T':
1851         align_tabs = 1;
1852         break;
1853
1854       case 'U':
1855 #if defined HAVE_DOS_FILE_CONTENTS
1856         dos_use_file_type = DOS_BINARY;
1857 #endif
1858         break;
1859
1860       case 'u':
1861 #if defined HAVE_DOS_FILE_CONTENTS
1862         dos_report_unix_offset = 1;
1863 #endif
1864         break;
1865
1866       case 'V':
1867         show_version = 1;
1868         break;
1869
1870       case 'a':
1871         binary_files = TEXT_BINARY_FILES;
1872         break;
1873
1874       case 'b':
1875         out_byte = 1;
1876         break;
1877
1878       case 'c':
1879         count_matches = 1;
1880         break;
1881
1882       case 'd':
1883         directories = XARGMATCH ("--directories", optarg,
1884                                  directories_args, directories_types);
1885         break;
1886
1887       case 'e':
1888         cc = strlen (optarg);
1889         keys = xrealloc (keys, keycc + cc + 1);
1890         strcpy (&keys[keycc], optarg);
1891         keycc += cc;
1892         keys[keycc++] = '\n';
1893         break;
1894
1895       case 'f':
1896         fp = STREQ (optarg, "-") ? stdin : fopen (optarg, "r");
1897         if (!fp)
1898           error (EXIT_TROUBLE, errno, "%s", optarg);
1899         for (keyalloc = 1; keyalloc <= keycc + 1; keyalloc *= 2)
1900           ;
1901         keys = xrealloc (keys, keyalloc);
1902         oldcc = keycc;
1903         while (!feof (fp)
1904                && (cc = fread (keys + keycc, 1, keyalloc - 1 - keycc, fp)) > 0)
1905           {
1906             keycc += cc;
1907             if (keycc == keyalloc - 1)
1908               keys = xrealloc (keys, keyalloc *= 2);
1909           }
1910         if (fp != stdin)
1911           fclose(fp);
1912         /* Append final newline if file ended in non-newline. */
1913         if (oldcc != keycc && keys[keycc - 1] != '\n')
1914           keys[keycc++] = '\n';
1915         break;
1916
1917       case 'h':
1918         with_filenames = 0;
1919         no_filenames = 1;
1920         break;
1921
1922       case 'i':
1923       case 'y':                 /* For old-timers . . . */
1924         match_icase = 1;
1925         break;
1926
1927       case 'L':
1928         /* Like -l, except list files that don't contain matches.
1929            Inspired by the same option in Hume's gre. */
1930         list_files = -1;
1931         break;
1932
1933       case 'l':
1934         list_files = 1;
1935         break;
1936
1937       case 'm':
1938         {
1939           uintmax_t value;
1940           switch (xstrtoumax (optarg, 0, 10, &value, ""))
1941             {
1942             case LONGINT_OK:
1943               max_count = value;
1944               if (0 <= max_count && max_count == value)
1945                 break;
1946               /* Fall through.  */
1947             case LONGINT_OVERFLOW:
1948               max_count = TYPE_MAXIMUM (off_t);
1949               break;
1950
1951             default:
1952               error (EXIT_TROUBLE, 0, _("invalid max count"));
1953             }
1954         }
1955         break;
1956
1957       case 'n':
1958         out_line = 1;
1959         break;
1960
1961       case 'o':
1962         only_matching = 1;
1963         break;
1964
1965       case 'q':
1966         exit_on_match = 1;
1967         exit_failure = 0;
1968         break;
1969
1970       case 'R':
1971       case 'r':
1972         directories = RECURSE_DIRECTORIES;
1973         break;
1974
1975       case 's':
1976         suppress_errors = 1;
1977         break;
1978
1979       case 'v':
1980         out_invert = 1;
1981         break;
1982
1983       case 'w':
1984         match_words = 1;
1985         break;
1986
1987       case 'x':
1988         match_lines = 1;
1989         break;
1990
1991       case 'Z':
1992         filename_mask = 0;
1993         break;
1994
1995       case 'z':
1996         eolbyte = '\0';
1997         break;
1998
1999       case BINARY_FILES_OPTION:
2000         if (STREQ (optarg, "binary"))
2001           binary_files = BINARY_BINARY_FILES;
2002         else if (STREQ (optarg, "text"))
2003           binary_files = TEXT_BINARY_FILES;
2004         else if (STREQ (optarg, "without-match"))
2005           binary_files = WITHOUT_MATCH_BINARY_FILES;
2006         else
2007           error (EXIT_TROUBLE, 0, _("unknown binary-files type"));
2008         break;
2009
2010       case COLOR_OPTION:
2011         if(optarg) {
2012           if(!strcasecmp(optarg, "always") || !strcasecmp(optarg, "yes") ||
2013              !strcasecmp(optarg, "force"))
2014             color_option = 1;
2015           else if(!strcasecmp(optarg, "never") || !strcasecmp(optarg, "no") ||
2016                   !strcasecmp(optarg, "none"))
2017             color_option = 0;
2018           else if(!strcasecmp(optarg, "auto") || !strcasecmp(optarg, "tty") ||
2019                   !strcasecmp(optarg, "if-tty"))
2020             color_option = 2;
2021           else
2022             show_help = 1;
2023         } else
2024           color_option = 2;
2025         if (color_option == 2)
2026           {
2027             char const *t;
2028             if (isatty (STDOUT_FILENO) && (t = getenv ("TERM"))
2029                 && !STREQ (t, "dumb"))
2030               color_option = 1;
2031             else
2032               color_option = 0;
2033           }
2034         break;
2035
2036       case EXCLUDE_OPTION:
2037         if (!excluded_patterns)
2038           excluded_patterns = new_exclude ();
2039         add_exclude (excluded_patterns, optarg, EXCLUDE_WILDCARDS);
2040         break;
2041       case EXCLUDE_FROM_OPTION:
2042         if (!excluded_patterns)
2043           excluded_patterns = new_exclude ();
2044         if (add_exclude_file (add_exclude, excluded_patterns, optarg,
2045                               EXCLUDE_WILDCARDS, '\n') != 0)
2046           {
2047             error (EXIT_TROUBLE, errno, "%s", optarg);
2048           }
2049         break;
2050
2051       case EXCLUDE_DIRECTORY_OPTION:
2052         if (!excluded_directory_patterns)
2053           excluded_directory_patterns = new_exclude ();
2054         add_exclude (excluded_directory_patterns, optarg, EXCLUDE_WILDCARDS);
2055         break;
2056
2057       case INCLUDE_OPTION:
2058         if (!included_patterns)
2059           included_patterns = new_exclude ();
2060         add_exclude (included_patterns, optarg,
2061                      EXCLUDE_WILDCARDS | EXCLUDE_INCLUDE);
2062         break;
2063
2064       case GROUP_SEPARATOR_OPTION:
2065         group_separator = optarg;
2066         break;
2067
2068       case LINE_BUFFERED_OPTION:
2069         line_buffered = 1;
2070         break;
2071
2072       case LABEL_OPTION:
2073         label = optarg;
2074         break;
2075
2076       case MMAP_OPTION:
2077       case 0:
2078         /* long options */
2079         break;
2080
2081       default:
2082         usage (EXIT_TROUBLE);
2083         break;
2084
2085       }
2086
2087   /* POSIX.2 says that -q overrides -l, which in turn overrides the
2088      other output options.  */
2089   if (exit_on_match)
2090     list_files = 0;
2091   if (exit_on_match | list_files)
2092     {
2093       count_matches = 0;
2094       done_on_match = 1;
2095     }
2096   out_quiet = count_matches | done_on_match;
2097
2098   if (out_after < 0)
2099     out_after = default_context;
2100   if (out_before < 0)
2101     out_before = default_context;
2102
2103   if (color_option)
2104     {
2105       /* Legacy.  */
2106       char *userval = getenv ("GREP_COLOR");
2107       if (userval != NULL && *userval != '\0')
2108         selected_match_color = context_match_color = userval;
2109
2110       /* New GREP_COLORS has priority.  */
2111       parse_grep_colors();
2112     }
2113
2114   if (show_version)
2115     {
2116       version_etc (stdout, program_name, PACKAGE_NAME, VERSION, AUTHORS, \
2117                    (char *) NULL);                                      \
2118       exit (EXIT_SUCCESS);                                              \
2119     }
2120
2121   if (show_help)
2122     usage (EXIT_SUCCESS);
2123
2124   if (keys)
2125     {
2126       if (keycc == 0)
2127         {
2128           /* No keys were specified (e.g. -f /dev/null).  Match nothing.  */
2129           out_invert ^= 1;
2130           match_lines = match_words = 0;
2131         }
2132       else
2133         /* Strip trailing newline. */
2134         --keycc;
2135     }
2136   else
2137     if (optind < argc)
2138       {
2139         /* A copy must be made in case of an xrealloc() or free() later.  */
2140         keycc = strlen(argv[optind]);
2141         keys = xmalloc(keycc + 1);
2142         strcpy(keys, argv[optind++]);
2143       }
2144     else
2145       usage (EXIT_TROUBLE);
2146
2147   set_limits();
2148   compile(keys, keycc);
2149   free (keys);
2150
2151   if ((argc - optind > 1 && !no_filenames) || with_filenames)
2152     out_file = 1;
2153
2154 #ifdef SET_BINARY
2155   /* Output is set to binary mode because we shouldn't convert
2156      NL to CR-LF pairs, especially when grepping binary files.  */
2157   if (!isatty (1))
2158     SET_BINARY (1);
2159 #endif
2160
2161   if (max_count == 0)
2162     exit (EXIT_FAILURE);
2163
2164   if (optind < argc)
2165     {
2166         status = 1;
2167         do
2168         {
2169           char *file = argv[optind];
2170           if ((included_patterns || excluded_patterns)
2171               && !isdir (file))
2172             {
2173               if (included_patterns
2174                   && excluded_file_name (included_patterns, file))
2175                 continue;
2176               if (excluded_patterns
2177                   && excluded_file_name (excluded_patterns, file))
2178                 continue;
2179             }
2180           status &= grepfile (STREQ (file, "-") ? (char *) NULL : file,
2181                               &stats_base);
2182         }
2183         while ( ++optind < argc);
2184     }
2185   else
2186     status = grepfile ((char *) NULL, &stats_base);
2187
2188   /* We register via atexit() to test stdout.  */
2189   exit (errseen ? EXIT_TROUBLE : status);
2190 }
2191 /* vim:set shiftwidth=2: */