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