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