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