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