grep.c revision 126435
1/* grep.c - main driver file for grep. 2 Copyright 1992, 1997-1999, 2000 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 2, 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., 59 Temple Place - Suite 330, Boston, MA 17 02111-1307, USA. */ 18 19/* Written July 1992 by Mike Haertel. */ 20/* Builtin decompression 1997 by Wolfram Schneider <wosch@FreeBSD.org>. */ 21 22/* $FreeBSD: head/gnu/usr.bin/grep/grep.c 126435 2004-03-01 08:37:20Z ache $ */ 23 24#ifdef HAVE_CONFIG_H 25# include <config.h> 26#endif 27#include <sys/types.h> 28#include <sys/stat.h> 29#if defined(HAVE_MMAP) 30# include <sys/mman.h> 31#endif 32#if defined(HAVE_SETRLIMIT) 33# include <sys/time.h> 34# include <sys/resource.h> 35#endif 36#include <stdio.h> 37#include "system.h" 38#include "getopt.h" 39#include "getpagesize.h" 40#include "grep.h" 41#include "savedir.h" 42 43#undef MAX 44#define MAX(A,B) ((A) > (B) ? (A) : (B)) 45 46struct stats 47{ 48 struct stats *parent; 49 struct stat stat; 50}; 51 52/* base of chain of stat buffers, used to detect directory loops */ 53static struct stats stats_base; 54 55/* if non-zero, display usage information and exit */ 56static int show_help; 57 58/* If non-zero, print the version on standard output and exit. */ 59static int show_version; 60 61/* If nonzero, use mmap if possible. */ 62static int mmap_option; 63 64/* If zero, output nulls after filenames. */ 65static int filename_mask; 66 67/* Short options. */ 68static char const short_options[] = 69"0123456789A:B:C::EFGHIJRUVX:abcd:e:f:hiLlnqrsuvwxyZz"; 70 71/* Non-boolean long options that have no corresponding short equivalents. */ 72enum 73{ 74 BINARY_FILES_OPTION = CHAR_MAX + 1 75}; 76 77/* Long options equivalences. */ 78static struct option long_options[] = 79{ 80 {"after-context", required_argument, NULL, 'A'}, 81 {"basic-regexp", no_argument, NULL, 'G'}, 82 {"before-context", required_argument, NULL, 'B'}, 83 {"binary-files", required_argument, NULL, BINARY_FILES_OPTION}, 84 {"byte-offset", no_argument, NULL, 'b'}, 85 {"context", optional_argument, NULL, 'C'}, 86 {"count", no_argument, NULL, 'c'}, 87 {"directories", required_argument, NULL, 'd'}, 88 {"extended-regexp", no_argument, NULL, 'E'}, 89 {"file", required_argument, NULL, 'f'}, 90 {"files-with-matches", no_argument, NULL, 'l'}, 91 {"files-without-match", no_argument, NULL, 'L'}, 92 {"fixed-regexp", no_argument, NULL, 'F'}, 93 {"fixed-strings", no_argument, NULL, 'F'}, 94 {"help", no_argument, &show_help, 1}, 95 {"ignore-case", no_argument, NULL, 'i'}, 96 {"line-number", no_argument, NULL, 'n'}, 97 {"line-regexp", no_argument, NULL, 'x'}, 98 {"mmap", no_argument, &mmap_option, 1}, 99 {"no-filename", no_argument, NULL, 'h'}, 100 {"no-messages", no_argument, NULL, 's'}, 101 {"bz2decompress", no_argument, NULL, 'J'}, 102#if HAVE_LIBZ > 0 103 {"decompress", no_argument, NULL, 'Z'}, 104 {"null", no_argument, &filename_mask, 0}, 105#else 106 {"null", no_argument, NULL, 'Z'}, 107#endif 108 {"null-data", no_argument, NULL, 'z'}, 109 {"quiet", no_argument, NULL, 'q'}, 110 {"recursive", no_argument, NULL, 'r'}, 111 {"regexp", required_argument, NULL, 'e'}, 112 {"invert-match", no_argument, NULL, 'v'}, 113 {"silent", no_argument, NULL, 'q'}, 114 {"text", no_argument, NULL, 'a'}, 115 {"binary", no_argument, NULL, 'U'}, 116 {"unix-byte-offsets", no_argument, NULL, 'u'}, 117 {"version", no_argument, NULL, 'V'}, 118 {"with-filename", no_argument, NULL, 'H'}, 119 {"word-regexp", no_argument, NULL, 'w'}, 120 {0, 0, 0, 0} 121}; 122 123/* Define flags declared in grep.h. */ 124int match_icase; 125int match_words; 126int match_lines; 127unsigned char eolbyte; 128 129/* For error messages. */ 130static char *prog; 131static char const *filename; 132static int errseen; 133 134/* How to handle directories. */ 135static enum 136 { 137 READ_DIRECTORIES, 138 RECURSE_DIRECTORIES, 139 SKIP_DIRECTORIES 140 } directories; 141 142static int ck_atoi PARAMS ((char const *, int *)); 143static void usage PARAMS ((int)) __attribute__((noreturn)); 144static void error PARAMS ((const char *, int)); 145static void setmatcher PARAMS ((char const *)); 146static int install_matcher PARAMS ((char const *)); 147static int prepend_args PARAMS ((char const *, char *, char **)); 148static void prepend_default_options PARAMS ((char const *, int *, char ***)); 149static char *page_alloc PARAMS ((size_t, char **)); 150static int reset PARAMS ((int, char const *, struct stats *)); 151static int fillbuf PARAMS ((size_t, struct stats *)); 152static int grepbuf PARAMS ((char *, char *)); 153static void prtext PARAMS ((char *, char *, int *)); 154static void prpending PARAMS ((char *)); 155static void prline PARAMS ((char *, char *, int)); 156static void print_offset_sep PARAMS ((off_t, int)); 157static void nlscan PARAMS ((char *)); 158static int grep PARAMS ((int, char const *, struct stats *)); 159static int grepdir PARAMS ((char const *, struct stats *)); 160static int grepfile PARAMS ((char const *, struct stats *)); 161#if O_BINARY 162static inline int undossify_input PARAMS ((register char *, size_t)); 163#endif 164 165/* Functions we'll use to search. */ 166static void (*compile) PARAMS ((char *, size_t)); 167static char *(*execute) PARAMS ((char *, size_t, char **)); 168 169/* Print a message and possibly an error string. Remember 170 that something awful happened. */ 171static void 172error (const char *mesg, int errnum) 173{ 174 if (errnum) 175 fprintf (stderr, "%s: %s: %s\n", prog, mesg, strerror (errnum)); 176 else 177 fprintf (stderr, "%s: %s\n", prog, mesg); 178 errseen = 1; 179} 180 181/* Like error (), but die horribly after printing. */ 182void 183fatal (const char *mesg, int errnum) 184{ 185 error (mesg, errnum); 186 exit (2); 187} 188 189/* Interface to handle errors and fix library lossage. */ 190char * 191xmalloc (size_t size) 192{ 193 char *result; 194 195 result = malloc (size); 196 if (size && !result) 197 fatal (_("memory exhausted"), 0); 198 return result; 199} 200 201/* Interface to handle errors and fix some library lossage. */ 202char * 203xrealloc (char *ptr, size_t size) 204{ 205 char *result; 206 207 if (ptr) 208 result = realloc (ptr, size); 209 else 210 result = malloc (size); 211 if (size && !result) 212 fatal (_("memory exhausted"), 0); 213 return result; 214} 215 216/* Convert STR to a positive integer, storing the result in *OUT. 217 If STR is not a valid integer, return -1 (otherwise 0). */ 218static int 219ck_atoi (char const *str, int *out) 220{ 221 char const *p; 222 for (p = str; *p; p++) 223 if (*p < '0' || *p > '9') 224 return -1; 225 226 *out = atoi (optarg); 227 return 0; 228} 229 230 231/* Hairy buffering mechanism for grep. The intent is to keep 232 all reads aligned on a page boundary and multiples of the 233 page size. */ 234 235static char *ubuffer; /* Unaligned base of buffer. */ 236static char *buffer; /* Base of buffer. */ 237static size_t bufsalloc; /* Allocated size of buffer save region. */ 238static size_t bufalloc; /* Total buffer size. */ 239#define PREFERRED_SAVE_FACTOR 5 /* Preferred value of bufalloc / bufsalloc. */ 240static int bufdesc; /* File descriptor. */ 241static char *bufbeg; /* Beginning of user-visible stuff. */ 242static char *buflim; /* Limit of user-visible stuff. */ 243static size_t pagesize; /* alignment of memory pages */ 244static off_t bufoffset; /* Read offset; defined on regular files. */ 245 246#if defined(HAVE_MMAP) 247static int bufmapped; /* True if buffer is memory-mapped. */ 248static off_t initial_bufoffset; /* Initial value of bufoffset. */ 249#endif 250 251#include <bzlib.h> 252static BZFILE* bzbufdesc; /* libbz2 file handle. */ 253static int BZflag; /* uncompress before searching. */ 254#if HAVE_LIBZ > 0 255#include <zlib.h> 256static gzFile gzbufdesc; /* zlib file descriptor. */ 257static int Zflag; /* uncompress before searching. */ 258#endif 259 260/* Return VAL aligned to the next multiple of ALIGNMENT. VAL can be 261 an integer or a pointer. Both args must be free of side effects. */ 262#define ALIGN_TO(val, alignment) \ 263 ((size_t) (val) % (alignment) == 0 \ 264 ? (val) \ 265 : (val) + ((alignment) - (size_t) (val) % (alignment))) 266 267/* Return the address of a page-aligned buffer of size SIZE, 268 reallocating it from *UP. Set *UP to the newly allocated (but 269 possibly unaligned) buffer used to build the aligned buffer. To 270 free the buffer, free (*UP). */ 271static char * 272page_alloc (size_t size, char **up) 273{ 274 size_t asize = size + pagesize - 1; 275 if (size <= asize) 276 { 277 char *p = *up ? realloc (*up, asize) : malloc (asize); 278 if (p) 279 { 280 *up = p; 281 return ALIGN_TO (p, pagesize); 282 } 283 } 284 return NULL; 285} 286 287/* Reset the buffer for a new file, returning zero if we should skip it. 288 Initialize on the first time through. */ 289static int 290reset (int fd, char const *file, struct stats *stats) 291{ 292 if (pagesize) 293 bufsalloc = ALIGN_TO (bufalloc / PREFERRED_SAVE_FACTOR, pagesize); 294 else 295 { 296 size_t ubufsalloc; 297 pagesize = getpagesize (); 298 if (pagesize == 0) 299 abort (); 300#ifndef BUFSALLOC 301 ubufsalloc = MAX (8192, pagesize); 302#else 303 ubufsalloc = BUFSALLOC; 304#endif 305 bufsalloc = ALIGN_TO (ubufsalloc, pagesize); 306 bufalloc = PREFERRED_SAVE_FACTOR * bufsalloc; 307 /* The 1 byte of overflow is a kludge for dfaexec(), which 308 inserts a sentinel newline at the end of the buffer 309 being searched. There's gotta be a better way... */ 310 if (bufsalloc < ubufsalloc 311 || bufalloc / PREFERRED_SAVE_FACTOR != bufsalloc 312 || bufalloc + 1 < bufalloc 313 || ! (buffer = page_alloc (bufalloc + 1, &ubuffer))) 314 fatal (_("memory exhausted"), 0); 315 } 316 if (BZflag) 317 { 318 bzbufdesc = BZ2_bzdopen(fd, "r"); 319 if (bzbufdesc == NULL) 320 fatal(_("memory exhausted"), 0); 321 } 322#if HAVE_LIBZ > 0 323 if (Zflag) 324 { 325 gzbufdesc = gzdopen(fd, "r"); 326 if (gzbufdesc == NULL) 327 fatal(_("memory exhausted"), 0); 328 } 329#endif 330 331 buflim = buffer; 332 bufdesc = fd; 333 334 if (fstat (fd, &stats->stat) != 0) 335 { 336 error ("fstat", errno); 337 return 0; 338 } 339 if (directories == SKIP_DIRECTORIES && S_ISDIR (stats->stat.st_mode)) 340 return 0; 341 if ( 342 BZflag || 343#if HAVE_LIBZ > 0 344 Zflag || 345#endif 346 S_ISREG (stats->stat.st_mode)) 347 { 348 if (file) 349 bufoffset = 0; 350 else 351 { 352 bufoffset = lseek (fd, 0, SEEK_CUR); 353 if (bufoffset < 0) 354 { 355 error ("lseek", errno); 356 return 0; 357 } 358 } 359#ifdef HAVE_MMAP 360 initial_bufoffset = bufoffset; 361 bufmapped = mmap_option && bufoffset % pagesize == 0; 362#endif 363 } 364 else 365 { 366#ifdef HAVE_MMAP 367 bufmapped = 0; 368#endif 369 } 370 return 1; 371} 372 373/* Read new stuff into the buffer, saving the specified 374 amount of old stuff. When we're done, 'bufbeg' points 375 to the beginning of the buffer contents, and 'buflim' 376 points just after the end. Return zero if there's an error. */ 377static int 378fillbuf (size_t save, struct stats *stats) 379{ 380 size_t fillsize = 0; 381 int cc = 1; 382 size_t readsize; 383 384 /* Offset from start of unaligned buffer to start of old stuff 385 that we want to save. */ 386 size_t saved_offset = buflim - ubuffer - save; 387 388 if (bufsalloc < save) 389 { 390 size_t aligned_save = ALIGN_TO (save, pagesize); 391 size_t maxalloc = (size_t) -1; 392 size_t newalloc; 393 394 if (S_ISREG (stats->stat.st_mode)) 395 { 396 /* Calculate an upper bound on how much memory we should allocate. 397 We can't use ALIGN_TO here, since off_t might be longer than 398 size_t. Watch out for arithmetic overflow. */ 399 off_t to_be_read = stats->stat.st_size - bufoffset; 400 size_t slop = to_be_read % pagesize; 401 off_t aligned_to_be_read = to_be_read + (slop ? pagesize - slop : 0); 402 off_t maxalloc_off = aligned_save + aligned_to_be_read; 403 if (0 <= maxalloc_off && maxalloc_off == (size_t) maxalloc_off) 404 maxalloc = maxalloc_off; 405 } 406 407 /* Grow bufsalloc until it is at least as great as `save'; but 408 if there is an overflow, just grow it to the next page boundary. */ 409 while (bufsalloc < save) 410 if (bufsalloc < bufsalloc * 2) 411 bufsalloc *= 2; 412 else 413 { 414 bufsalloc = aligned_save; 415 break; 416 } 417 418 /* Grow the buffer size to be PREFERRED_SAVE_FACTOR times 419 bufsalloc.... */ 420 newalloc = PREFERRED_SAVE_FACTOR * bufsalloc; 421 if (maxalloc < newalloc) 422 { 423 /* ... except don't grow it more than a pagesize past the 424 file size, as that might cause unnecessary memory 425 exhaustion if the file is large. */ 426 newalloc = maxalloc; 427 bufsalloc = aligned_save; 428 } 429 430 /* Check that the above calculations made progress, which might 431 not occur if there is arithmetic overflow. If there's no 432 progress, or if the new buffer size is larger than the old 433 and buffer reallocation fails, report memory exhaustion. */ 434 if (bufsalloc < save || newalloc < save 435 || (newalloc == save && newalloc != maxalloc) 436 || (bufalloc < newalloc 437 && ! (buffer 438 = page_alloc ((bufalloc = newalloc) + 1, &ubuffer)))) 439 fatal (_("memory exhausted"), 0); 440 } 441 442 bufbeg = buffer + bufsalloc - save; 443 memmove (bufbeg, ubuffer + saved_offset, save); 444 readsize = bufalloc - bufsalloc; 445 446#if defined(HAVE_MMAP) 447 if (bufmapped) 448 { 449 size_t mmapsize = readsize; 450 451 /* Don't mmap past the end of the file; some hosts don't allow this. 452 Use `read' on the last page. */ 453 if (stats->stat.st_size - bufoffset < mmapsize) 454 { 455 mmapsize = stats->stat.st_size - bufoffset; 456 mmapsize -= mmapsize % pagesize; 457 } 458 459 if (mmapsize 460 && (mmap ((caddr_t) (buffer + bufsalloc), mmapsize, 461 PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED, 462 bufdesc, bufoffset) 463 != (caddr_t) -1)) 464 { 465 /* Do not bother to use madvise with MADV_SEQUENTIAL or 466 MADV_WILLNEED on the mmapped memory. One might think it 467 would help, but it slows us down about 30% on SunOS 4.1. */ 468 fillsize = mmapsize; 469 } 470 else 471 { 472 /* Stop using mmap on this file. Synchronize the file 473 offset. Do not warn about mmap failures. On some hosts 474 (e.g. Solaris 2.5) mmap can fail merely because some 475 other process has an advisory read lock on the file. 476 There's no point alarming the user about this misfeature. */ 477 bufmapped = 0; 478 if (bufoffset != initial_bufoffset 479 && lseek (bufdesc, bufoffset, SEEK_SET) < 0) 480 { 481 error ("lseek", errno); 482 cc = 0; 483 } 484 } 485 } 486#endif /*HAVE_MMAP*/ 487 488 if (! fillsize) 489 { 490 ssize_t bytesread; 491 do 492 if (BZflag && bzbufdesc) 493 { 494 int bzerr; 495 bytesread = BZ2_bzRead (&bzerr, bzbufdesc, buffer + bufsalloc, readsize); 496 497 switch (bzerr) 498 { 499 case BZ_OK: 500 case BZ_STREAM_END: 501 /* ok */ 502 break; 503 case BZ_DATA_ERROR_MAGIC: 504 BZ2_bzReadClose (&bzerr, bzbufdesc); bzbufdesc = NULL; 505 lseek (bufdesc, 0, SEEK_SET); 506 bytesread = read (bufdesc, buffer + bufsalloc, readsize); 507 break; 508 default: 509 bytesread = 0; 510 break; 511 } 512 } 513 else 514#if HAVE_LIBZ > 0 515 if (Zflag) 516 bytesread = gzread (gzbufdesc, buffer + bufsalloc, readsize); 517 else 518#endif 519 bytesread = read (bufdesc, buffer + bufsalloc, readsize); 520 while (bytesread < 0 && errno == EINTR); 521 if (bytesread < 0) 522 cc = 0; 523 else 524 fillsize = bytesread; 525 } 526 527 bufoffset += fillsize; 528#if O_BINARY 529 if (fillsize) 530 fillsize = undossify_input (buffer + bufsalloc, fillsize); 531#endif 532 buflim = buffer + bufsalloc + fillsize; 533 return cc; 534} 535 536/* Flags controlling the style of output. */ 537static enum 538 { 539 BINARY_BINARY_FILES, 540 TEXT_BINARY_FILES, 541 WITHOUT_MATCH_BINARY_FILES 542 } binary_files; /* How to handle binary files. */ 543static int out_quiet; /* Suppress all normal output. */ 544static int out_invert; /* Print nonmatching stuff. */ 545static int out_file; /* Print filenames. */ 546static int out_line; /* Print line numbers. */ 547static int out_byte; /* Print byte offsets. */ 548static int out_before; /* Lines of leading context. */ 549static int out_after; /* Lines of trailing context. */ 550static int count_matches; /* Count matching lines. */ 551static int list_files; /* List matching files. */ 552static int no_filenames; /* Suppress file names. */ 553static int suppress_errors; /* Suppress diagnostics. */ 554 555/* Internal variables to keep track of byte count, context, etc. */ 556static off_t totalcc; /* Total character count before bufbeg. */ 557static char *lastnl; /* Pointer after last newline counted. */ 558static char *lastout; /* Pointer after last character output; 559 NULL if no character has been output 560 or if it's conceptually before bufbeg. */ 561static off_t totalnl; /* Total newline count before lastnl. */ 562static int pending; /* Pending lines of output. */ 563static int done_on_match; /* Stop scanning file on first match */ 564 565#if O_BINARY 566# include "dosbuf.c" 567#endif 568 569static void 570nlscan (char *lim) 571{ 572 char *beg; 573 for (beg = lastnl; (beg = memchr (beg, eolbyte, lim - beg)); beg++) 574 totalnl++; 575 lastnl = lim; 576} 577 578static void 579print_offset_sep (off_t pos, int sep) 580{ 581 /* Do not rely on printf to print pos, since off_t may be longer than long, 582 and long long is not portable. */ 583 584 char buf[sizeof pos * CHAR_BIT]; 585 char *p = buf + sizeof buf - 1; 586 *p = sep; 587 588 do 589 *--p = '0' + pos % 10; 590 while ((pos /= 10) != 0); 591 592 fwrite (p, 1, buf + sizeof buf - p, stdout); 593} 594 595static void 596prline (char *beg, char *lim, int sep) 597{ 598 if (out_file) 599 printf ("%s%c", filename, sep & filename_mask); 600 if (out_line) 601 { 602 nlscan (beg); 603 print_offset_sep (++totalnl, sep); 604 lastnl = lim; 605 } 606 if (out_byte) 607 { 608 off_t pos = totalcc + (beg - bufbeg); 609#if O_BINARY 610 pos = dossified_pos (pos); 611#endif 612 print_offset_sep (pos, sep); 613 } 614 fwrite (beg, 1, lim - beg, stdout); 615 if (ferror (stdout)) 616 error (_("writing output"), errno); 617 lastout = lim; 618} 619 620/* Print pending lines of trailing context prior to LIM. */ 621static void 622prpending (char *lim) 623{ 624 char *nl; 625 626 if (!lastout) 627 lastout = bufbeg; 628 while (pending > 0 && lastout < lim) 629 { 630 --pending; 631 if ((nl = memchr (lastout, eolbyte, lim - lastout)) != 0) 632 ++nl; 633 else 634 nl = lim; 635 prline (lastout, nl, '-'); 636 } 637} 638 639/* Print the lines between BEG and LIM. Deal with context crap. 640 If NLINESP is non-null, store a count of lines between BEG and LIM. */ 641static void 642prtext (char *beg, char *lim, int *nlinesp) 643{ 644 static int used; /* avoid printing "--" before any output */ 645 char *bp, *p, *nl; 646 char eol = eolbyte; 647 int i, n; 648 649 if (!out_quiet && pending > 0) 650 prpending (beg); 651 652 p = beg; 653 654 if (!out_quiet) 655 { 656 /* Deal with leading context crap. */ 657 658 bp = lastout ? lastout : bufbeg; 659 for (i = 0; i < out_before; ++i) 660 if (p > bp) 661 do 662 --p; 663 while (p > bp && p[-1] != eol); 664 665 /* We only print the "--" separator if our output is 666 discontiguous from the last output in the file. */ 667 if ((out_before || out_after) && used && p != lastout) 668 puts ("--"); 669 670 while (p < beg) 671 { 672 nl = memchr (p, eol, beg - p); 673 prline (p, nl + 1, '-'); 674 p = nl + 1; 675 } 676 } 677 678 if (nlinesp) 679 { 680 /* Caller wants a line count. */ 681 for (n = 0; p < lim; ++n) 682 { 683 if ((nl = memchr (p, eol, lim - p)) != 0) 684 ++nl; 685 else 686 nl = lim; 687 if (!out_quiet) 688 prline (p, nl, ':'); 689 p = nl; 690 } 691 *nlinesp = n; 692 } 693 else 694 if (!out_quiet) 695 prline (beg, lim, ':'); 696 697 pending = out_quiet ? 0 : out_after; 698 used = 1; 699} 700 701/* Scan the specified portion of the buffer, matching lines (or 702 between matching lines if OUT_INVERT is true). Return a count of 703 lines printed. */ 704static int 705grepbuf (char *beg, char *lim) 706{ 707 int nlines, n; 708 register char *p, *b; 709 char *endp; 710 char eol = eolbyte; 711 712 nlines = 0; 713 p = beg; 714 while ((b = (*execute)(p, lim - p, &endp)) != 0) 715 { 716 /* Avoid matching the empty line at the end of the buffer. */ 717 if (b == lim && ((b > beg && b[-1] == eol) || b == beg)) 718 break; 719 if (!out_invert) 720 { 721 prtext (b, endp, (int *) 0); 722 nlines += 1; 723 if (done_on_match) 724 return nlines; 725 } 726 else if (p < b) 727 { 728 prtext (p, b, &n); 729 nlines += n; 730 } 731 p = endp; 732 } 733 if (out_invert && p < lim) 734 { 735 prtext (p, lim, &n); 736 nlines += n; 737 } 738 return nlines; 739} 740 741/* Search a given file. Normally, return a count of lines printed; 742 but if the file is a directory and we search it recursively, then 743 return -2 if there was a match, and -1 otherwise. */ 744static int 745grep (int fd, char const *file, struct stats *stats) 746{ 747 int nlines, i; 748 int not_text; 749 size_t residue, save; 750 char *beg, *lim; 751 char eol = eolbyte; 752 753 if (!reset (fd, file, stats)) 754 return 0; 755 756 if (file && directories == RECURSE_DIRECTORIES 757 && S_ISDIR (stats->stat.st_mode)) 758 { 759 /* Close fd now, so that we don't open a lot of file descriptors 760 when we recurse deeply. */ 761 if (BZflag && bzbufdesc) 762 BZ2_bzclose(bzbufdesc); 763 else 764#if HAVE_LIBZ > 0 765 if (Zflag) 766 gzclose(gzbufdesc); 767 else 768#endif 769 if (close (fd) != 0) 770 error (file, errno); 771 return grepdir (file, stats) - 2; 772 } 773 774 totalcc = 0; 775 lastout = 0; 776 totalnl = 0; 777 pending = 0; 778 779 nlines = 0; 780 residue = 0; 781 save = 0; 782 783 if (! fillbuf (save, stats)) 784 { 785 if (! (is_EISDIR (errno, file) && suppress_errors)) 786 error (filename, errno); 787 return 0; 788 } 789 790 not_text = (((binary_files == BINARY_BINARY_FILES && !out_quiet) 791 || binary_files == WITHOUT_MATCH_BINARY_FILES) 792 && memchr (bufbeg, eol ? '\0' : '\200', buflim - bufbeg)); 793 if (not_text && binary_files == WITHOUT_MATCH_BINARY_FILES) 794 return 0; 795 done_on_match += not_text; 796 out_quiet += not_text; 797 798 for (;;) 799 { 800 lastnl = bufbeg; 801 if (lastout) 802 lastout = bufbeg; 803 if (buflim - bufbeg == save) 804 break; 805 beg = bufbeg + save - residue; 806 for (lim = buflim; lim > beg && lim[-1] != eol; --lim) 807 ; 808 residue = buflim - lim; 809 if (beg < lim) 810 { 811 nlines += grepbuf (beg, lim); 812 if (pending) 813 prpending (lim); 814 if (nlines && done_on_match && !out_invert) 815 goto finish_grep; 816 } 817 i = 0; 818 beg = lim; 819 while (i < out_before && beg > bufbeg && beg != lastout) 820 { 821 ++i; 822 do 823 --beg; 824 while (beg > bufbeg && beg[-1] != eol); 825 } 826 if (beg != lastout) 827 lastout = 0; 828 save = residue + lim - beg; 829 totalcc += buflim - bufbeg - save; 830 if (out_line) 831 nlscan (beg); 832 if (! fillbuf (save, stats)) 833 { 834 if (! (is_EISDIR (errno, file) && suppress_errors)) 835 error (filename, errno); 836 goto finish_grep; 837 } 838 } 839 if (residue) 840 { 841 *buflim++ = eol; 842 nlines += grepbuf (bufbeg + save - residue, buflim); 843 if (pending) 844 prpending (buflim); 845 } 846 847 finish_grep: 848 done_on_match -= not_text; 849 out_quiet -= not_text; 850 if ((not_text & ~out_quiet) && nlines != 0) 851 printf (_("Binary file %s matches\n"), filename); 852 return nlines; 853} 854 855static int 856grepfile (char const *file, struct stats *stats) 857{ 858 int desc; 859 int count; 860 int status; 861 862 if (! file) 863 { 864 desc = 0; 865 filename = _("(standard input)"); 866 } 867 else 868 { 869 while ((desc = open (file, O_RDONLY)) < 0 && errno == EINTR) 870 continue; 871 872 if (desc < 0) 873 { 874 int e = errno; 875 876 if (is_EISDIR (e, file) && directories == RECURSE_DIRECTORIES) 877 { 878 if (stat (file, &stats->stat) != 0) 879 { 880 error (file, errno); 881 return 1; 882 } 883 884 return grepdir (file, stats); 885 } 886 887 if (!suppress_errors) 888 { 889 if (directories == SKIP_DIRECTORIES) 890 switch (e) 891 { 892#ifdef EISDIR 893 case EISDIR: 894 return 1; 895#endif 896 case EACCES: 897 /* When skipping directories, don't worry about 898 directories that can't be opened. */ 899 if (stat (file, &stats->stat) == 0 900 && S_ISDIR (stats->stat.st_mode)) 901 return 1; 902 break; 903 } 904 905 error (file, e); 906 } 907 908 return 1; 909 } 910 911 filename = file; 912 } 913 914#if O_BINARY 915 /* Set input to binary mode. Pipes are simulated with files 916 on DOS, so this includes the case of "foo | grep bar". */ 917 if (!isatty (desc)) 918 SET_BINARY (desc); 919#endif 920 921 count = grep (desc, file, stats); 922 if (count < 0) 923 status = count + 2; 924 else 925 { 926 if (count_matches) 927 { 928 if (out_file) 929 printf ("%s%c", filename, ':' & filename_mask); 930 printf ("%d\n", count); 931 } 932 933 status = !count; 934 if (list_files == 1 - 2 * status) 935 printf ("%s%c", filename, '\n' & filename_mask); 936 937 if (BZflag && bzbufdesc) 938 BZ2_bzclose(bzbufdesc); 939 else 940#if HAVE_LIBZ > 0 941 if (Zflag) 942 gzclose(gzbufdesc); 943 else 944#endif 945 if (file) 946 while (close (desc) != 0) 947 if (errno != EINTR) 948 { 949 error (file, errno); 950 break; 951 } 952 } 953 954 return status; 955} 956 957static int 958grepdir (char const *dir, struct stats *stats) 959{ 960 int status = 1; 961 struct stats *ancestor; 962 char *name_space; 963 964 for (ancestor = stats; (ancestor = ancestor->parent) != 0; ) 965 if (ancestor->stat.st_ino == stats->stat.st_ino 966 && ancestor->stat.st_dev == stats->stat.st_dev) 967 { 968 if (!suppress_errors) 969 fprintf (stderr, _("%s: warning: %s: %s\n"), prog, dir, 970 _("recursive directory loop")); 971 return 1; 972 } 973 974 name_space = savedir (dir, (unsigned) stats->stat.st_size); 975 976 if (! name_space) 977 { 978 if (errno) 979 { 980 if (!suppress_errors) 981 error (dir, errno); 982 } 983 else 984 fatal (_("Memory exhausted"), 0); 985 } 986 else 987 { 988 size_t dirlen = strlen (dir); 989 int needs_slash = ! (dirlen == FILESYSTEM_PREFIX_LEN (dir) 990 || IS_SLASH (dir[dirlen - 1])); 991 char *file = NULL; 992 char *namep = name_space; 993 struct stats child; 994 child.parent = stats; 995 out_file += !no_filenames; 996 while (*namep) 997 { 998 size_t namelen = strlen (namep); 999 file = xrealloc (file, dirlen + 1 + namelen + 1); 1000 strcpy (file, dir); 1001 file[dirlen] = '/'; 1002 strcpy (file + dirlen + needs_slash, namep); 1003 namep += namelen + 1; 1004 status &= grepfile (file, &child); 1005 } 1006 out_file -= !no_filenames; 1007 if (file) 1008 free (file); 1009 free (name_space); 1010 } 1011 1012 return status; 1013} 1014 1015static void 1016usage (int status) 1017{ 1018 if (status != 0) 1019 { 1020 fprintf (stderr, _("Usage: %s [OPTION]... PATTERN [FILE]...\n"), prog); 1021 fprintf (stderr, _("Try `%s --help' for more information.\n"), prog); 1022 } 1023 else 1024 { 1025 printf (_("Usage: %s [OPTION]... PATTERN [FILE] ...\n"), prog); 1026 printf (_("\ 1027Search for PATTERN in each FILE or standard input.\n\ 1028Example: %s -i 'hello world' menu.h main.c\n\ 1029\n\ 1030Regexp selection and interpretation:\n"), prog); 1031 printf (_("\ 1032 -E, --extended-regexp PATTERN is an extended regular expression\n\ 1033 -F, --fixed-strings PATTERN is a set of newline-separated strings\n\ 1034 -G, --basic-regexp PATTERN is a basic regular expression\n")); 1035 printf (_("\ 1036 -e, --regexp=PATTERN use PATTERN as a regular expression\n\ 1037 -f, --file=FILE obtain PATTERN from FILE\n\ 1038 -i, --ignore-case ignore case distinctions\n\ 1039 -w, --word-regexp force PATTERN to match only whole words\n\ 1040 -x, --line-regexp force PATTERN to match only whole lines\n\ 1041 -z, --null-data a data line ends in 0 byte, not newline\n")); 1042 printf (_("\ 1043\n\ 1044Miscellaneous:\n\ 1045 -s, --no-messages suppress error messages\n\ 1046 -v, --invert-match select non-matching lines\n\ 1047 -V, --version print version information and exit\n\ 1048 --help display this help and exit\n\ 1049 -J, --bz2decompress decompress bzip2'ed input before searching\n\ 1050 -Z, --decompress decompress input before searching (HAVE_LIBZ=1)\n\ 1051 --mmap use memory-mapped input if possible\n")); 1052 printf (_("\ 1053\n\ 1054Output control:\n\ 1055 -b, --byte-offset print the byte offset with output lines\n\ 1056 -n, --line-number print line number with output lines\n\ 1057 -H, --with-filename print the filename for each match\n\ 1058 -h, --no-filename suppress the prefixing filename on output\n\ 1059 -q, --quiet, --silent suppress all normal output\n\ 1060 --binary-files=TYPE assume that binary files are TYPE\n\ 1061 TYPE is 'binary', 'text', or 'without-match'.\n\ 1062 -a, --text equivalent to --binary-files=text\n\ 1063 -I equivalent to --binary-files=without-match\n\ 1064 -d, --directories=ACTION how to handle directories\n\ 1065 ACTION is 'read', 'recurse', or 'skip'.\n\ 1066 -r, --recursive equivalent to --directories=recurse.\n\ 1067 -L, --files-without-match only print FILE names containing no match\n\ 1068 -l, --files-with-matches only print FILE names containing matches\n\ 1069 -c, --count only print a count of matching lines per FILE\n\ 1070 --null print 0 byte after FILE name\n")); 1071 printf (_("\ 1072\n\ 1073Context control:\n\ 1074 -B, --before-context=NUM print NUM lines of leading context\n\ 1075 -A, --after-context=NUM print NUM lines of trailing context\n\ 1076 -C, --context[=NUM] print NUM (default 2) lines of output context\n\ 1077 unless overridden by -A or -B\n\ 1078 -NUM same as --context=NUM\n\ 1079 -U, --binary do not strip CR characters at EOL (MSDOS)\n\ 1080 -u, --unix-byte-offsets report offsets as if CRs were not there (MSDOS)\n\ 1081\n\ 1082`egrep' means `grep -E'. `fgrep' means `grep -F'.\n\ 1083With no FILE, or when FILE is -, read standard input. If less than\n\ 1084two FILEs given, assume -h. Exit status is 0 if match, 1 if no match,\n\ 1085and 2 if trouble.\n")); 1086 printf (_("\nReport bugs to <bug-gnu-utils@gnu.org>.\n")); 1087 } 1088 exit (status); 1089} 1090 1091/* Set the matcher to M, reporting any conflicts. */ 1092static void 1093setmatcher (char const *m) 1094{ 1095 if (matcher && strcmp (matcher, m) != 0) 1096 fatal (_("conflicting matchers specified"), 0); 1097 matcher = m; 1098} 1099 1100/* Go through the matchers vector and look for the specified matcher. 1101 If we find it, install it in compile and execute, and return 1. */ 1102static int 1103install_matcher (char const *name) 1104{ 1105 int i; 1106#ifdef HAVE_SETRLIMIT 1107 struct rlimit rlim; 1108#endif 1109 1110 for (i = 0; matchers[i].name; ++i) 1111 if (strcmp (name, matchers[i].name) == 0) 1112 { 1113 compile = matchers[i].compile; 1114 execute = matchers[i].execute; 1115#if HAVE_SETRLIMIT && defined(RLIMIT_STACK) 1116 /* I think every platform needs to do this, so that regex.c 1117 doesn't oveflow the stack. The default value of 1118 `re_max_failures' is too large for some platforms: it needs 1119 more than 3MB-large stack. 1120 1121 The test for HAVE_SETRLIMIT should go into `configure'. */ 1122 if (!getrlimit (RLIMIT_STACK, &rlim)) 1123 { 1124 long newlim; 1125 extern long int re_max_failures; /* from regex.c */ 1126 1127 /* Approximate the amount regex.c needs, plus some more. */ 1128 newlim = re_max_failures * 2 * 20 * sizeof (char *); 1129 if (newlim > rlim.rlim_max) 1130 { 1131 newlim = rlim.rlim_max; 1132 re_max_failures = newlim / (2 * 20 * sizeof (char *)); 1133 } 1134 if (rlim.rlim_cur < newlim) 1135 rlim.rlim_cur = newlim; 1136 1137 setrlimit (RLIMIT_STACK, &rlim); 1138 } 1139#endif 1140 return 1; 1141 } 1142 return 0; 1143} 1144 1145/* Find the white-space-separated options specified by OPTIONS, and 1146 using BUF to store copies of these options, set ARGV[0], ARGV[1], 1147 etc. to the option copies. Return the number N of options found. 1148 Do not set ARGV[N] to NULL. If ARGV is NULL, do not store ARGV[0] 1149 etc. Backslash can be used to escape whitespace (and backslashes). */ 1150static int 1151prepend_args (char const *options, char *buf, char **argv) 1152{ 1153 char const *o = options; 1154 char *b = buf; 1155 int n = 0; 1156 1157 for (;;) 1158 { 1159 while (ISSPACE ((unsigned char) *o)) 1160 o++; 1161 if (!*o) 1162 return n; 1163 if (argv) 1164 argv[n] = b; 1165 n++; 1166 1167 do 1168 if ((*b++ = *o++) == '\\' && *o) 1169 b[-1] = *o++; 1170 while (*o && ! ISSPACE ((unsigned char) *o)); 1171 1172 *b++ = '\0'; 1173 } 1174} 1175 1176/* Prepend the whitespace-separated options in OPTIONS to the argument 1177 vector of a main program with argument count *PARGC and argument 1178 vector *PARGV. */ 1179static void 1180prepend_default_options (char const *options, int *pargc, char ***pargv) 1181{ 1182 if (options) 1183 { 1184 char *buf = xmalloc (strlen (options) + 1); 1185 int prepended = prepend_args (options, buf, (char **) NULL); 1186 int argc = *pargc; 1187 char * const *argv = *pargv; 1188 char **pp = (char **) xmalloc ((prepended + argc + 1) * sizeof *pp); 1189 *pargc = prepended + argc; 1190 *pargv = pp; 1191 *pp++ = *argv++; 1192 pp += prepend_args (options, buf, pp); 1193 while ((*pp++ = *argv++)) 1194 continue; 1195 } 1196} 1197 1198int 1199main (int argc, char **argv) 1200{ 1201 char *keys; 1202 size_t keycc, oldcc, keyalloc; 1203 int with_filenames; 1204 int opt, cc, status; 1205 int default_context; 1206 unsigned digit_args_val; 1207 FILE *fp; 1208 extern char *optarg; 1209 extern int optind; 1210 1211 initialize_main (&argc, &argv); 1212 prog = argv[0]; 1213 if (prog && strrchr (prog, '/')) 1214 prog = strrchr (prog, '/') + 1; 1215 1216#if HAVE_LIBZ > 0 1217 if (prog[0] == 'z') { 1218 Zflag = 1; 1219 ++prog; 1220 } 1221#endif 1222 if (prog[0] == 'b') { 1223 BZflag = 1; 1224 ++prog; 1225 } 1226 1227#if defined(__MSDOS__) || defined(_WIN32) 1228 /* DOS and MS-Windows use backslashes as directory separators, and usually 1229 have an .exe suffix. They also have case-insensitive filesystems. */ 1230 if (prog) 1231 { 1232 char *p = prog; 1233 char *bslash = strrchr (argv[0], '\\'); 1234 1235 if (bslash && bslash >= prog) /* for mixed forward/backslash case */ 1236 prog = bslash + 1; 1237 else if (prog == argv[0] 1238 && argv[0][0] && argv[0][1] == ':') /* "c:progname" */ 1239 prog = argv[0] + 2; 1240 1241 /* Collapse the letter-case, so `strcmp' could be used hence. */ 1242 for ( ; *p; p++) 1243 if (*p >= 'A' && *p <= 'Z') 1244 *p += 'a' - 'A'; 1245 1246 /* Remove the .exe extension, if any. */ 1247 if ((p = strrchr (prog, '.')) && strcmp (p, ".exe") == 0) 1248 *p = '\0'; 1249 } 1250#endif 1251 1252 keys = NULL; 1253 keycc = 0; 1254 with_filenames = 0; 1255 eolbyte = '\n'; 1256 filename_mask = ~0; 1257 1258 /* The value -1 means to use DEFAULT_CONTEXT. */ 1259 out_after = out_before = -1; 1260 /* Default before/after context: chaged by -C/-NUM options */ 1261 default_context = 0; 1262 /* Accumulated value of individual digits in a -NUM option */ 1263 digit_args_val = 0; 1264 1265 1266/* Internationalization. */ 1267#if HAVE_SETLOCALE 1268 setlocale (LC_ALL, ""); 1269#endif 1270#if ENABLE_NLS 1271 bindtextdomain (PACKAGE, LOCALEDIR); 1272 textdomain (PACKAGE); 1273#endif 1274 1275 prepend_default_options (getenv ("GREP_OPTIONS"), &argc, &argv); 1276 1277 while ((opt = getopt_long (argc, argv, short_options, long_options, NULL)) 1278 != -1) 1279 switch (opt) 1280 { 1281 case '0': 1282 case '1': 1283 case '2': 1284 case '3': 1285 case '4': 1286 case '5': 1287 case '6': 1288 case '7': 1289 case '8': 1290 case '9': 1291 digit_args_val = 10 * digit_args_val + opt - '0'; 1292 default_context = digit_args_val; 1293 break; 1294 case 'A': 1295 if (optarg) 1296 { 1297 if (ck_atoi (optarg, &out_after)) 1298 fatal (_("invalid context length argument"), 0); 1299 } 1300 break; 1301 case 'B': 1302 if (optarg) 1303 { 1304 if (ck_atoi (optarg, &out_before)) 1305 fatal (_("invalid context length argument"), 0); 1306 } 1307 break; 1308 case 'C': 1309 /* Set output match context, but let any explicit leading or 1310 trailing amount specified with -A or -B stand. */ 1311 if (optarg) 1312 { 1313 if (ck_atoi (optarg, &default_context)) 1314 fatal (_("invalid context length argument"), 0); 1315 } 1316 else 1317 default_context = 2; 1318 break; 1319 case 'E': 1320 setmatcher ("egrep"); 1321 break; 1322 case 'F': 1323 setmatcher ("fgrep"); 1324 break; 1325 case 'G': 1326 setmatcher ("grep"); 1327 break; 1328 case 'H': 1329 with_filenames = 1; 1330 break; 1331 case 'I': 1332 binary_files = WITHOUT_MATCH_BINARY_FILES; 1333 break; 1334 case 'J': 1335 if (Zflag) 1336 { 1337 printf (_("Cannot mix -Z and -J.\n")); 1338 usage (2); 1339 } 1340 BZflag = 1; 1341 break; 1342 case 'U': 1343#if O_BINARY 1344 dos_use_file_type = DOS_BINARY; 1345#endif 1346 break; 1347 case 'u': 1348#if O_BINARY 1349 dos_report_unix_offset = 1; 1350#endif 1351 break; 1352 case 'V': 1353 show_version = 1; 1354 break; 1355 case 'X': 1356 setmatcher (optarg); 1357 break; 1358 case 'a': 1359 binary_files = TEXT_BINARY_FILES; 1360 break; 1361 case 'b': 1362 out_byte = 1; 1363 break; 1364 case 'c': 1365 out_quiet = 1; 1366 count_matches = 1; 1367 break; 1368 case 'd': 1369 if (strcmp (optarg, "read") == 0) 1370 directories = READ_DIRECTORIES; 1371 else if (strcmp (optarg, "skip") == 0) 1372 directories = SKIP_DIRECTORIES; 1373 else if (strcmp (optarg, "recurse") == 0) 1374 directories = RECURSE_DIRECTORIES; 1375 else 1376 fatal (_("unknown directories method"), 0); 1377 break; 1378 case 'e': 1379 cc = strlen (optarg); 1380 keys = xrealloc (keys, keycc + cc + 1); 1381 strcpy (&keys[keycc], optarg); 1382 keycc += cc; 1383 keys[keycc++] = '\n'; 1384 break; 1385 case 'f': 1386 fp = strcmp (optarg, "-") != 0 ? fopen (optarg, "r") : stdin; 1387 if (!fp) 1388 fatal (optarg, errno); 1389 for (keyalloc = 1; keyalloc <= keycc + 1; keyalloc *= 2) 1390 ; 1391 keys = xrealloc (keys, keyalloc); 1392 oldcc = keycc; 1393 while (!feof (fp) 1394 && (cc = fread (keys + keycc, 1, keyalloc - 1 - keycc, fp)) > 0) 1395 { 1396 keycc += cc; 1397 if (keycc == keyalloc - 1) 1398 keys = xrealloc (keys, keyalloc *= 2); 1399 } 1400 if (fp != stdin) 1401 fclose(fp); 1402 /* Append final newline if file ended in non-newline. */ 1403 if (oldcc != keycc && keys[keycc - 1] != '\n') 1404 keys[keycc++] = '\n'; 1405 break; 1406 case 'h': 1407 no_filenames = 1; 1408 break; 1409 case 'i': 1410 case 'y': /* For old-timers . . . */ 1411 match_icase = 1; 1412 break; 1413 case 'L': 1414 /* Like -l, except list files that don't contain matches. 1415 Inspired by the same option in Hume's gre. */ 1416 out_quiet = 1; 1417 list_files = -1; 1418 done_on_match = 1; 1419 break; 1420 case 'l': 1421 out_quiet = 1; 1422 list_files = 1; 1423 done_on_match = 1; 1424 break; 1425 case 'n': 1426 out_line = 1; 1427 break; 1428 case 'q': 1429 done_on_match = 1; 1430 out_quiet = 1; 1431 break; 1432 case 'R': 1433 case 'r': 1434 directories = RECURSE_DIRECTORIES; 1435 break; 1436 case 's': 1437 suppress_errors = 1; 1438 break; 1439 case 'v': 1440 out_invert = 1; 1441 break; 1442 case 'w': 1443 match_words = 1; 1444 break; 1445 case 'x': 1446 match_lines = 1; 1447 break; 1448 case 'Z': 1449#if HAVE_LIBZ > 0 1450 if (BZflag) 1451 { 1452 printf (_("Cannot mix -J and -Z.\n")); 1453 usage (2); 1454 } 1455 Zflag = 1; 1456#else 1457 filename_mask = 0; 1458#endif 1459 break; 1460 case 'z': 1461 eolbyte = '\0'; 1462 break; 1463 case BINARY_FILES_OPTION: 1464 if (strcmp (optarg, "binary") == 0) 1465 binary_files = BINARY_BINARY_FILES; 1466 else if (strcmp (optarg, "text") == 0) 1467 binary_files = TEXT_BINARY_FILES; 1468 else if (strcmp (optarg, "without-match") == 0) 1469 binary_files = WITHOUT_MATCH_BINARY_FILES; 1470 else 1471 fatal (_("unknown binary-files type"), 0); 1472 break; 1473 case 0: 1474 /* long options */ 1475 break; 1476 default: 1477 usage (2); 1478 break; 1479 } 1480 1481 if (out_after < 0) 1482 out_after = default_context; 1483 if (out_before < 0) 1484 out_before = default_context; 1485 1486 if (! matcher) 1487 matcher = prog; 1488 1489 if (show_version) 1490 { 1491 printf (_("%s (GNU grep) %s\n"), matcher, VERSION); 1492 printf ("\n"); 1493 printf (_("\ 1494Copyright 1988, 1992-1999, 2000 Free Software Foundation, Inc.\n")); 1495 printf (_("\ 1496This is free software; see the source for copying conditions. There is NO\n\ 1497warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n")); 1498 printf ("\n"); 1499 exit (0); 1500 } 1501 1502 if (show_help) 1503 usage (0); 1504 1505 if (keys) 1506 { 1507 if (keycc == 0) 1508 /* No keys were specified (e.g. -f /dev/null). Match nothing. */ 1509 out_invert ^= 1; 1510 else 1511 /* Strip trailing newline. */ 1512 --keycc; 1513 } 1514 else 1515 if (optind < argc) 1516 { 1517 keys = argv[optind++]; 1518 keycc = strlen (keys); 1519 } 1520 else 1521 usage (2); 1522 1523 if (!install_matcher (matcher) && !install_matcher ("default")) 1524 abort (); 1525 1526 (*compile)(keys, keycc); 1527 1528 if ((argc - optind > 1 && !no_filenames) || with_filenames) 1529 out_file = 1; 1530 1531#if O_BINARY 1532 /* Output is set to binary mode because we shouldn't convert 1533 NL to CR-LF pairs, especially when grepping binary files. */ 1534 if (!isatty (1)) 1535 SET_BINARY (1); 1536#endif 1537 1538 1539 if (optind < argc) 1540 { 1541 status = 1; 1542 do 1543 { 1544 char *file = argv[optind]; 1545 status &= grepfile (strcmp (file, "-") == 0 ? (char *) NULL : file, 1546 &stats_base); 1547 } 1548 while ( ++optind < argc); 1549 } 1550 else 1551 status = grepfile ((char *) NULL, &stats_base); 1552 1553 if (fclose (stdout) == EOF) 1554 error (_("writing output"), errno); 1555 1556 exit (errseen ? 2 : status); 1557} 1558