[BACK]Return to grep.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / grep

Annotation of src/usr.bin/grep/grep.c, Revision 1.31

1.31    ! otto        1: /*     $OpenBSD: grep.c,v 1.30 2004/09/28 20:51:15 jmc Exp $   */
1.6       deraadt     2:
1.1       deraadt     3: /*-
1.3       deraadt     4:  * Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
                      5:  * All rights reserved.
1.1       deraadt     6:  *
                      7:  * Redistribution and use in source and binary forms, with or without
                      8:  * modification, are permitted provided that the following conditions
                      9:  * are met:
                     10:  * 1. Redistributions of source code must retain the above copyright
                     11:  *    notice, this list of conditions and the following disclaimer.
                     12:  * 2. Redistributions in binary form must reproduce the above copyright
                     13:  *    notice, this list of conditions and the following disclaimer in the
                     14:  *    documentation and/or other materials provided with the distribution.
                     15:  *
                     16:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
                     17:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
                     18:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
                     19:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
                     20:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
                     21:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
                     22:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
                     23:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
                     24:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
                     25:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
                     26:  * SUCH DAMAGE.
                     27:  */
                     28:
1.3       deraadt    29: #include <sys/types.h>
1.9       tedu       30: #include <sys/limits.h>
1.3       deraadt    31: #include <sys/stat.h>
1.1       deraadt    32:
1.18      millert    33: #include <ctype.h>
1.3       deraadt    34: #include <err.h>
                     35: #include <errno.h>
                     36: #include <getopt.h>
                     37: #include <regex.h>
1.1       deraadt    38: #include <stdio.h>
                     39: #include <stdlib.h>
1.3       deraadt    40: #include <string.h>
1.1       deraadt    41: #include <unistd.h>
                     42:
1.3       deraadt    43: #include "grep.h"
                     44:
                     45: /* Flags passed to regcomp() and regexec() */
                     46: int     cflags;
                     47: int     eflags = REG_STARTEND;
                     48:
                     49: int     matchall;      /* shortcut */
                     50: int     patterns, pattern_sz;
                     51: char   **pattern;
                     52: regex_t        *r_pattern;
1.13      tedu       53: fastgrep_t *fg_pattern;
1.3       deraadt    54:
                     55: /* For regex errors  */
                     56: char    re_error[RE_ERROR_BUF + 1];
                     57:
                     58: /* Command-line flags */
                     59: int     Aflag;         /* -A x: print x lines trailing each match */
                     60: int     Bflag;         /* -B x: print x lines leading each match */
                     61: int     Eflag;         /* -E: interpret pattern as extended regexp */
                     62: int     Fflag;         /* -F: interpret pattern as list of fixed strings */
                     63: int     Gflag;         /* -G: interpret pattern as basic regexp */
                     64: int     Hflag;         /* -H: if -R, follow explicitly listed symlinks */
                     65: int     Lflag;         /* -L: only show names of files with no matches */
                     66: int     Pflag;         /* -P: if -R, no symlinks are followed */
                     67: int     Rflag;         /* -R: recursively search directory trees */
                     68: int     Sflag;         /* -S: if -R, follow all symlinks */
                     69: int     Vflag;         /* -V: display version information */
1.5       deraadt    70: #ifndef NOZ
1.3       deraadt    71: int     Zflag;         /* -Z: decompress input before processing */
1.5       deraadt    72: #endif
1.3       deraadt    73: int     bflag;         /* -b: show block numbers for each match */
                     74: int     cflag;         /* -c: only show a count of matching lines */
                     75: int     hflag;         /* -h: don't print filename headers */
                     76: int     iflag;         /* -i: ignore case */
                     77: int     lflag;         /* -l: only show names of files with matches */
                     78: int     nflag;         /* -n: show line numbers in front of matching lines */
                     79: int     oflag;         /* -o: always print file name */
                     80: int     qflag;         /* -q: quiet mode (don't output anything) */
                     81: int     sflag;         /* -s: silent mode (ignore errors) */
                     82: int     vflag;         /* -v: only show non-matching lines */
                     83: int     wflag;         /* -w: pattern must start and end on word boundaries */
                     84: int     xflag;         /* -x: pattern must match entire line */
1.27      otto       85: int     lbflag;        /* --line-buffered */
1.3       deraadt    86:
1.9       tedu       87: int binbehave = BIN_FILE_BIN;
                     88:
                     89: enum {
                     90:        BIN_OPT = CHAR_MAX + 1,
                     91:        HELP_OPT,
1.27      otto       92:        MMAP_OPT,
                     93:        LINEBUF_OPT
1.9       tedu       94: };
                     95:
1.3       deraadt    96: /* Housekeeping */
1.10      tedu       97: int     first;         /* flag whether or not this is our first match */
1.3       deraadt    98: int     tail;          /* lines left to print */
                     99: int     lead;          /* number of lines in leading context queue */
                    100:
1.8       tedu      101: extern char *__progname;
1.3       deraadt   102:
                    103: static void
                    104: usage(void)
                    105: {
1.5       deraadt   106:        fprintf(stderr,
                    107: #ifdef NOZ
1.30      jmc       108:            "usage: %s [-abcEFGHhIiLlnoPqRSsUVvwx] [-A num] [-B num] [-C[num]]\n"
1.5       deraadt   109: #else
1.30      jmc       110:            "usage: %s [-abcEFGHhIiLlnoPqRSsUVvwxZ] [-A num] [-B num] [-C[num]]\n"
1.5       deraadt   111: #endif
1.30      jmc       112:            "\t[-e pattern] [-f file] [--binary-files=value] [--context[=num]]\n"
                    113:            "\t[--line-buffered] [pattern] [file ...]\n", __progname);
1.3       deraadt   114:        exit(2);
                    115: }
                    116:
1.5       deraadt   117: #ifdef NOZ
1.9       tedu      118: static char *optstr = "0123456789A:B:CEFGHILPSRUVabce:f:hilnoqrsuvwxy";
1.5       deraadt   119: #else
1.9       tedu      120: static char *optstr = "0123456789A:B:CEFGHILPSRUVZabce:f:hilnoqrsuvwxy";
1.5       deraadt   121: #endif
1.3       deraadt   122:
1.5       deraadt   123: struct option long_options[] =
1.3       deraadt   124: {
1.19      deraadt   125:        {"binary-files",        required_argument,      NULL, BIN_OPT},
                    126:        {"help",                no_argument,            NULL, HELP_OPT},
                    127:        {"mmap",                no_argument,            NULL, MMAP_OPT},
1.27      otto      128:        {"line-buffered",       no_argument,            NULL, LINEBUF_OPT},
1.19      deraadt   129:        {"after-context",       required_argument,      NULL, 'A'},
                    130:        {"before-context",      required_argument,      NULL, 'B'},
                    131:        {"context",             optional_argument,      NULL, 'C'},
                    132:        {"devices",             required_argument,      NULL, 'D'},
                    133:        {"extended-regexp",     no_argument,            NULL, 'E'},
                    134:        {"fixed-strings",       no_argument,            NULL, 'F'},
                    135:        {"basic-regexp",        no_argument,            NULL, 'G'},
                    136:        {"binary",              no_argument,            NULL, 'U'},
                    137:        {"version",             no_argument,            NULL, 'V'},
                    138:        {"text",                no_argument,            NULL, 'a'},
                    139:        {"byte-offset",         no_argument,            NULL, 'b'},
                    140:        {"count",               no_argument,            NULL, 'c'},
                    141:        {"regexp",              required_argument,      NULL, 'e'},
                    142:        {"file",                required_argument,      NULL, 'f'},
                    143:        {"no-filename",         no_argument,            NULL, 'h'},
                    144:        {"ignore-case",         no_argument,            NULL, 'i'},
                    145:        {"files-without-match", no_argument,            NULL, 'L'},
                    146:        {"files-with-matches",  no_argument,            NULL, 'l'},
                    147:        {"line-number",         no_argument,            NULL, 'n'},
                    148:        {"quiet",               no_argument,            NULL, 'q'},
                    149:        {"silent",              no_argument,            NULL, 'q'},
                    150:        {"recursive",           no_argument,            NULL, 'r'},
                    151:        {"no-messages",         no_argument,            NULL, 's'},
                    152:        {"revert-match",        no_argument,            NULL, 'v'},
                    153:        {"word-regexp",         no_argument,            NULL, 'w'},
                    154:        {"line-regexp",         no_argument,            NULL, 'x'},
                    155:        {"unix-byte-offsets",   no_argument,            NULL, 'u'},
1.5       deraadt   156: #ifndef NOZ
1.19      deraadt   157:        {"decompress",          no_argument,            NULL, 'Z'},
1.5       deraadt   158: #endif
1.19      deraadt   159:        {NULL,                  no_argument,            NULL, 0}
1.3       deraadt   160: };
                    161:
1.1       deraadt   162:
1.3       deraadt   163: static void
                    164: add_pattern(char *pat, size_t len)
                    165: {
                    166:        if (len == 0 || matchall) {
                    167:                matchall = 1;
                    168:                return;
                    169:        }
                    170:        if (patterns == pattern_sz) {
                    171:                pattern_sz *= 2;
1.22      millert   172:                pattern = grep_realloc(pattern, ++pattern_sz * sizeof(*pattern));
1.3       deraadt   173:        }
1.11      tedu      174:        if (pat[len - 1] == '\n')
1.3       deraadt   175:                --len;
1.15      tedu      176:        /* pat may not be NUL-terminated */
1.28      millert   177:        if (wflag && !Fflag) {
1.26      millert   178:                int bol = 0, eol = 0;
                    179:                if (pat[0] == '^')
                    180:                        bol = 1;
                    181:                if (pat[len - 1] == '$')
                    182:                        eol = 1;
1.25      millert   183:                pattern[patterns] = grep_malloc(len + 15);
1.26      millert   184:                snprintf(pattern[patterns], len + 15, "%s[[:<:]]%.*s[[:>:]]%s",
                    185:                    bol ? "^" : "", (int)len - bol - eol, pat + bol,
                    186:                    eol ? "$" : "");
                    187:                len += 14;
1.25      millert   188:        } else {
                    189:                pattern[patterns] = grep_malloc(len + 1);
                    190:                memcpy(pattern[patterns], pat, len);
                    191:                pattern[patterns][len] = '\0';
                    192:        }
1.3       deraadt   193:        ++patterns;
                    194: }
1.1       deraadt   195:
1.3       deraadt   196: static void
                    197: read_patterns(char *fn)
                    198: {
                    199:        FILE *f;
                    200:        char *line;
                    201:        size_t len;
                    202:        int nl;
                    203:
                    204:        if ((f = fopen(fn, "r")) == NULL)
1.20      millert   205:                err(2, "%s", fn);
1.3       deraadt   206:        nl = 0;
                    207:        while ((line = fgetln(f, &len)) != NULL) {
                    208:                if (*line == '\n') {
                    209:                        ++nl;
                    210:                        continue;
                    211:                }
                    212:                if (nl) {
                    213:                        matchall = 1;
                    214:                        break;
                    215:                }
                    216:                nl = 0;
                    217:                add_pattern(line, len);
                    218:        }
                    219:        if (ferror(f))
1.20      millert   220:                err(2, "%s", fn);
1.3       deraadt   221:        fclose(f);
                    222: }
1.1       deraadt   223:
                    224: int
1.3       deraadt   225: main(int argc, char *argv[])
1.1       deraadt   226: {
1.23      millert   227:        int c, lastc, prevoptind, newarg, i;
1.21      millert   228:        long l;
                    229:        char *ep;
1.3       deraadt   230:
1.16      tedu      231:        switch (__progname[0]) {
                    232:        case 'e':
                    233:                Eflag++;
                    234:                break;
                    235:        case 'f':
                    236:                Fflag++;
                    237:                break;
                    238:        case 'g':
                    239:                Gflag++;
                    240:                break;
                    241: #ifndef NOZ
                    242:        case 'z':
                    243:                Zflag++;
                    244:                switch(__progname[1]) {
                    245:                case 'e':
                    246:                        Eflag++;
                    247:                        break;
                    248:                case 'f':
                    249:                        Fflag++;
                    250:                        break;
                    251:                case 'g':
                    252:                        Gflag++;
                    253:                        break;
                    254:                }
                    255:                break;
                    256: #endif
                    257:        }
                    258:
1.18      millert   259:        lastc = '\0';
1.23      millert   260:        newarg = 1;
                    261:        prevoptind = 1;
1.5       deraadt   262:        while ((c = getopt_long(argc, argv, optstr,
1.17      millert   263:                                long_options, NULL)) != -1) {
1.3       deraadt   264:                switch (c) {
                    265:                case '0': case '1': case '2': case '3': case '4':
                    266:                case '5': case '6': case '7': case '8': case '9':
1.23      millert   267:                        if (newarg || !isdigit(lastc))
                    268:                                Aflag = 0;
                    269:                        else if (Aflag > INT_MAX / 10)
                    270:                                errx(2, "context out of range");
                    271:                        Aflag = Bflag = (Aflag * 10) + (c - '0');
1.3       deraadt   272:                        break;
                    273:                case 'A':
                    274:                case 'B':
1.21      millert   275:                        l = strtol(optarg, &ep, 10);
                    276:                        if (ep == optarg || *ep != '\0' ||
                    277:                            l <= 0 || l >= INT_MAX)
                    278:                                errx(2, "context out of range");
                    279:                        if (c == 'A')
                    280:                                Aflag = (int)l;
                    281:                        else
                    282:                                Bflag = (int)l;
1.3       deraadt   283:                        break;
                    284:                case 'C':
1.5       deraadt   285:                        if (optarg == NULL)
1.3       deraadt   286:                                Aflag = Bflag = 2;
1.21      millert   287:                        else {
                    288:                                l = strtol(optarg, &ep, 10);
                    289:                                if (ep == optarg || *ep != '\0' ||
                    290:                                    l <= 0 || l >= INT_MAX)
                    291:                                        errx(2, "context out of range");
                    292:                                Aflag = Bflag = (int)l;
                    293:                        }
1.1       deraadt   294:                        break;
                    295:                case 'E':
1.16      tedu      296:                        Fflag = Gflag = 0;
1.3       deraadt   297:                        Eflag++;
1.1       deraadt   298:                        break;
                    299:                case 'F':
1.16      tedu      300:                        Eflag = Gflag = 0;
1.3       deraadt   301:                        Fflag++;
                    302:                        break;
                    303:                case 'G':
1.16      tedu      304:                        Eflag = Fflag = 0;
1.3       deraadt   305:                        Gflag++;
1.1       deraadt   306:                        break;
                    307:                case 'H':
1.3       deraadt   308:                        Hflag++;
1.1       deraadt   309:                        break;
1.9       tedu      310:                case 'I':
                    311:                        binbehave = BIN_FILE_SKIP;
                    312:                        break;
1.1       deraadt   313:                case 'L':
1.3       deraadt   314:                        lflag = 0;
                    315:                        Lflag = qflag = 1;
1.1       deraadt   316:                        break;
                    317:                case 'P':
1.3       deraadt   318:                        Pflag++;
                    319:                        break;
                    320:                case 'S':
                    321:                        Sflag++;
1.1       deraadt   322:                        break;
                    323:                case 'R':
1.3       deraadt   324:                case 'r':
                    325:                        Rflag++;
                    326:                        oflag++;
                    327:                        break;
                    328:                case 'U':
1.9       tedu      329:                        binbehave = BIN_FILE_BIN;
1.3       deraadt   330:                        break;
                    331:                case 'V':
                    332:                        fprintf(stderr, "grep version %u.%u\n", VER_MAJ, VER_MIN);
1.9       tedu      333:                        exit(0);
1.1       deraadt   334:                        break;
1.5       deraadt   335: #ifndef NOZ
1.3       deraadt   336:                case 'Z':
                    337:                        Zflag++;
1.1       deraadt   338:                        break;
1.5       deraadt   339: #endif
1.1       deraadt   340:                case 'a':
1.9       tedu      341:                        binbehave = BIN_FILE_TEXT;
1.1       deraadt   342:                        break;
                    343:                case 'b':
1.3       deraadt   344:                        bflag = 1;
1.1       deraadt   345:                        break;
                    346:                case 'c':
1.3       deraadt   347:                        cflag = 1;
1.1       deraadt   348:                        break;
                    349:                case 'e':
1.3       deraadt   350:                        add_pattern(optarg, strlen(optarg));
1.1       deraadt   351:                        break;
                    352:                case 'f':
1.3       deraadt   353:                        read_patterns(optarg);
1.1       deraadt   354:                        break;
                    355:                case 'h':
1.3       deraadt   356:                        oflag = 0;
                    357:                        hflag = 1;
1.1       deraadt   358:                        break;
                    359:                case 'i':
1.3       deraadt   360:                case 'y':
1.13      tedu      361:                        iflag = 1;
1.1       deraadt   362:                        cflags |= REG_ICASE;
                    363:                        break;
                    364:                case 'l':
1.3       deraadt   365:                        Lflag = 0;
                    366:                        lflag = qflag = 1;
1.1       deraadt   367:                        break;
                    368:                case 'n':
1.3       deraadt   369:                        nflag = 1;
                    370:                        break;
                    371:                case 'o':
                    372:                        hflag = 0;
                    373:                        oflag = 1;
1.1       deraadt   374:                        break;
                    375:                case 'q':
1.3       deraadt   376:                        qflag = 1;
1.1       deraadt   377:                        break;
                    378:                case 's':
1.3       deraadt   379:                        sflag = 1;
1.1       deraadt   380:                        break;
                    381:                case 'v':
1.3       deraadt   382:                        vflag = 1;
1.1       deraadt   383:                        break;
                    384:                case 'w':
1.3       deraadt   385:                        wflag = 1;
1.1       deraadt   386:                        break;
                    387:                case 'x':
1.3       deraadt   388:                        xflag = 1;
1.1       deraadt   389:                        break;
1.9       tedu      390:                case BIN_OPT:
                    391:                        if (strcmp("binary", optarg) == 0)
                    392:                                binbehave = BIN_FILE_BIN;
                    393:                        else if (strcmp("without-match", optarg) == 0)
                    394:                                binbehave = BIN_FILE_SKIP;
                    395:                        else if (strcmp("text", optarg) == 0)
                    396:                                binbehave = BIN_FILE_TEXT;
                    397:                        else
                    398:                                errx(2, "Unknown binary-files option");
                    399:                        break;
                    400:                case 'u':
                    401:                case MMAP_OPT:
                    402:                        /* default, compatibility */
                    403:                        break;
1.27      otto      404:                case LINEBUF_OPT:
                    405:                        lbflag = 1;
                    406:                        break;
1.9       tedu      407:                case HELP_OPT:
1.1       deraadt   408:                default:
                    409:                        usage();
                    410:                }
1.18      millert   411:                lastc = c;
1.23      millert   412:                newarg = optind != prevoptind;
1.18      millert   413:                prevoptind = optind;
1.1       deraadt   414:        }
1.3       deraadt   415:        argc -= optind;
                    416:        argv += optind;
                    417:
                    418:        if (argc == 0 && patterns == 0)
1.1       deraadt   419:                usage();
                    420:
1.3       deraadt   421:        if (patterns == 0) {
                    422:                add_pattern(*argv, strlen(*argv));
                    423:                --argc;
                    424:                ++argv;
                    425:        }
1.5       deraadt   426:
1.16      tedu      427:        if (Eflag)
                    428:                cflags |= REG_EXTENDED;
1.13      tedu      429:        fg_pattern = grep_malloc(patterns * sizeof(*fg_pattern));
1.22      millert   430:        r_pattern = grep_malloc(patterns * sizeof(*r_pattern));
1.3       deraadt   431:        for (i = 0; i < patterns; ++i) {
1.28      millert   432:                /* Check if cheating is allowed (always is for fgrep). */
                    433:                if (Fflag) {
                    434:                        fgrepcomp(&fg_pattern[i], pattern[i]);
                    435:                } else {
                    436:                        if (fastcomp(&fg_pattern[i], pattern[i])) {
                    437:                                /* Fall back to full regex library */
                    438:                                c = regcomp(&r_pattern[i], pattern[i], cflags);
                    439:                                if (c != 0) {
                    440:                                        regerror(c, &r_pattern[i], re_error,
                    441:                                            RE_ERROR_BUF);
                    442:                                        errx(2, "%s", re_error);
                    443:                                }
1.13      tedu      444:                        }
1.1       deraadt   445:                }
                    446:        }
1.29      deraadt   447:
1.27      otto      448:        if (lbflag)
                    449:                setlinebuf(stdout);
1.1       deraadt   450:
1.3       deraadt   451:        if ((argc == 0 || argc == 1) && !oflag)
                    452:                hflag = 1;
1.1       deraadt   453:
1.3       deraadt   454:        if (argc == 0)
                    455:                exit(!procfile(NULL));
1.5       deraadt   456:
1.3       deraadt   457:        if (Rflag)
                    458:                c = grep_tree(argv);
1.1       deraadt   459:        else
1.3       deraadt   460:                for (c = 0; argc--; ++argv)
                    461:                        c += procfile(*argv);
1.1       deraadt   462:
1.3       deraadt   463:        exit(!c);
1.1       deraadt   464: }