[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.42

1.42    ! tedu        1: /*     $OpenBSD: grep.c,v 1.41 2010/04/20 15:58:08 jacekm 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.33      jaredy     32: #include <sys/queue.h>
1.1       deraadt    33:
1.18      millert    34: #include <ctype.h>
1.3       deraadt    35: #include <err.h>
                     36: #include <errno.h>
                     37: #include <getopt.h>
                     38: #include <regex.h>
1.1       deraadt    39: #include <stdio.h>
                     40: #include <stdlib.h>
1.3       deraadt    41: #include <string.h>
1.1       deraadt    42: #include <unistd.h>
                     43:
1.3       deraadt    44: #include "grep.h"
                     45:
                     46: /* Flags passed to regcomp() and regexec() */
                     47: int     cflags;
                     48: int     eflags = REG_STARTEND;
                     49:
                     50: int     matchall;      /* shortcut */
                     51: int     patterns, pattern_sz;
                     52: char   **pattern;
                     53: regex_t        *r_pattern;
1.13      tedu       54: fastgrep_t *fg_pattern;
1.3       deraadt    55:
                     56: /* For regex errors  */
                     57: char    re_error[RE_ERROR_BUF + 1];
                     58:
                     59: /* Command-line flags */
                     60: int     Aflag;         /* -A x: print x lines trailing each match */
                     61: int     Bflag;         /* -B x: print x lines leading each match */
                     62: int     Eflag;         /* -E: interpret pattern as extended regexp */
                     63: int     Fflag;         /* -F: interpret pattern as list of fixed strings */
                     64: int     Gflag;         /* -G: interpret pattern as basic regexp */
                     65: int     Lflag;         /* -L: only show names of files with no matches */
                     66: int     Rflag;         /* -R: recursively search directory trees */
1.5       deraadt    67: #ifndef NOZ
1.3       deraadt    68: int     Zflag;         /* -Z: decompress input before processing */
1.5       deraadt    69: #endif
1.3       deraadt    70: int     bflag;         /* -b: show block numbers for each match */
                     71: int     cflag;         /* -c: only show a count of matching lines */
                     72: int     hflag;         /* -h: don't print filename headers */
                     73: int     iflag;         /* -i: ignore case */
                     74: int     lflag;         /* -l: only show names of files with matches */
                     75: int     nflag;         /* -n: show line numbers in front of matching lines */
                     76: int     qflag;         /* -q: quiet mode (don't output anything) */
                     77: int     sflag;         /* -s: silent mode (ignore errors) */
                     78: int     vflag;         /* -v: only show non-matching lines */
                     79: int     wflag;         /* -w: pattern must start and end on word boundaries */
                     80: int     xflag;         /* -x: pattern must match entire line */
1.27      otto       81: int     lbflag;        /* --line-buffered */
1.3       deraadt    82:
1.9       tedu       83: int binbehave = BIN_FILE_BIN;
                     84:
                     85: enum {
                     86:        BIN_OPT = CHAR_MAX + 1,
                     87:        HELP_OPT,
1.27      otto       88:        MMAP_OPT,
                     89:        LINEBUF_OPT
1.9       tedu       90: };
                     91:
1.3       deraadt    92: /* Housekeeping */
1.10      tedu       93: int     first;         /* flag whether or not this is our first match */
1.3       deraadt    94: int     tail;          /* lines left to print */
                     95:
1.33      jaredy     96: struct patfile {
                     97:        const char              *pf_file;
                     98:        SLIST_ENTRY(patfile)     pf_next;
                     99: };
                    100: SLIST_HEAD(, patfile)           patfilelh;
                    101:
1.8       tedu      102: extern char *__progname;
1.3       deraadt   103:
                    104: static void
                    105: usage(void)
                    106: {
1.5       deraadt   107:        fprintf(stderr,
                    108: #ifdef NOZ
1.40      tedu      109:            "usage: %s [-abcEFGhIiLlnqRsUVvwx] [-A num] [-B num] [-C[num]]\n"
1.5       deraadt   110: #else
1.40      tedu      111:            "usage: %s [-abcEFGhIiLlnqRsUVvwxZ] [-A num] [-B num] [-C[num]]\n"
1.5       deraadt   112: #endif
1.30      jmc       113:            "\t[-e pattern] [-f file] [--binary-files=value] [--context[=num]]\n"
                    114:            "\t[--line-buffered] [pattern] [file ...]\n", __progname);
1.3       deraadt   115:        exit(2);
                    116: }
                    117:
1.5       deraadt   118: #ifdef NOZ
1.40      tedu      119: static char *optstr = "0123456789A:B:CEFGILRUVabce:f:hilnqrsuvwxy";
1.5       deraadt   120: #else
1.40      tedu      121: static char *optstr = "0123456789A:B:CEFGILRUVZabce:f:hilnqrsuvwxy";
1.5       deraadt   122: #endif
1.3       deraadt   123:
1.5       deraadt   124: struct option long_options[] =
1.3       deraadt   125: {
1.19      deraadt   126:        {"binary-files",        required_argument,      NULL, BIN_OPT},
                    127:        {"help",                no_argument,            NULL, HELP_OPT},
                    128:        {"mmap",                no_argument,            NULL, MMAP_OPT},
1.27      otto      129:        {"line-buffered",       no_argument,            NULL, LINEBUF_OPT},
1.19      deraadt   130:        {"after-context",       required_argument,      NULL, 'A'},
                    131:        {"before-context",      required_argument,      NULL, 'B'},
                    132:        {"context",             optional_argument,      NULL, 'C'},
                    133:        {"devices",             required_argument,      NULL, 'D'},
                    134:        {"extended-regexp",     no_argument,            NULL, 'E'},
                    135:        {"fixed-strings",       no_argument,            NULL, 'F'},
                    136:        {"basic-regexp",        no_argument,            NULL, 'G'},
                    137:        {"binary",              no_argument,            NULL, 'U'},
                    138:        {"version",             no_argument,            NULL, 'V'},
                    139:        {"text",                no_argument,            NULL, 'a'},
                    140:        {"byte-offset",         no_argument,            NULL, 'b'},
                    141:        {"count",               no_argument,            NULL, 'c'},
                    142:        {"regexp",              required_argument,      NULL, 'e'},
                    143:        {"file",                required_argument,      NULL, 'f'},
                    144:        {"no-filename",         no_argument,            NULL, 'h'},
                    145:        {"ignore-case",         no_argument,            NULL, 'i'},
                    146:        {"files-without-match", no_argument,            NULL, 'L'},
                    147:        {"files-with-matches",  no_argument,            NULL, 'l'},
                    148:        {"line-number",         no_argument,            NULL, 'n'},
                    149:        {"quiet",               no_argument,            NULL, 'q'},
                    150:        {"silent",              no_argument,            NULL, 'q'},
                    151:        {"recursive",           no_argument,            NULL, 'r'},
                    152:        {"no-messages",         no_argument,            NULL, 's'},
                    153:        {"revert-match",        no_argument,            NULL, 'v'},
                    154:        {"word-regexp",         no_argument,            NULL, 'w'},
                    155:        {"line-regexp",         no_argument,            NULL, 'x'},
                    156:        {"unix-byte-offsets",   no_argument,            NULL, 'u'},
1.5       deraadt   157: #ifndef NOZ
1.19      deraadt   158:        {"decompress",          no_argument,            NULL, 'Z'},
1.5       deraadt   159: #endif
1.19      deraadt   160:        {NULL,                  no_argument,            NULL, 0}
1.3       deraadt   161: };
                    162:
1.1       deraadt   163:
1.3       deraadt   164: static void
                    165: add_pattern(char *pat, size_t len)
                    166: {
1.36      jaredy    167:        if (!xflag && (len == 0 || matchall)) {
1.3       deraadt   168:                matchall = 1;
                    169:                return;
                    170:        }
                    171:        if (patterns == pattern_sz) {
                    172:                pattern_sz *= 2;
1.22      millert   173:                pattern = grep_realloc(pattern, ++pattern_sz * sizeof(*pattern));
1.3       deraadt   174:        }
1.37      ray       175:        if (len > 0 && pat[len - 1] == '\n')
1.3       deraadt   176:                --len;
1.15      tedu      177:        /* pat may not be NUL-terminated */
1.28      millert   178:        if (wflag && !Fflag) {
1.32      otto      179:                int bol = 0, eol = 0, extra;
1.26      millert   180:                if (pat[0] == '^')
                    181:                        bol = 1;
1.36      jaredy    182:                if (len > 0 && pat[len - 1] == '$')
1.26      millert   183:                        eol = 1;
1.32      otto      184:                extra = Eflag ? 2 : 4;
                    185:                pattern[patterns] = grep_malloc(len + 15 + extra);
                    186:                snprintf(pattern[patterns], len + 15 + extra,
                    187:                   "%s[[:<:]]%s%.*s%s[[:>:]]%s",
                    188:                    bol ? "^" : "",
                    189:                    Eflag ? "(" : "\\(",
                    190:                    (int)len - bol - eol, pat + bol,
                    191:                    Eflag ? ")" : "\\)",
1.26      millert   192:                    eol ? "$" : "");
1.32      otto      193:                len += 14 + extra;
1.25      millert   194:        } else {
                    195:                pattern[patterns] = grep_malloc(len + 1);
                    196:                memcpy(pattern[patterns], pat, len);
                    197:                pattern[patterns][len] = '\0';
                    198:        }
1.3       deraadt   199:        ++patterns;
                    200: }
1.1       deraadt   201:
1.3       deraadt   202: static void
1.35      otto      203: add_patterns(char *pats)
                    204: {
                    205:        char *nl;
                    206:
                    207:        while ((nl = strchr(pats, '\n')) != NULL) {
                    208:                add_pattern(pats, nl - pats);
                    209:                pats = nl + 1;
                    210:        }
                    211:        add_pattern(pats, strlen(pats));
                    212: }
                    213:
                    214: static void
1.33      jaredy    215: read_patterns(const char *fn)
1.3       deraadt   216: {
                    217:        FILE *f;
                    218:        char *line;
                    219:        size_t len;
                    220:
                    221:        if ((f = fopen(fn, "r")) == NULL)
1.20      millert   222:                err(2, "%s", fn);
1.38      kili      223:        while ((line = fgetln(f, &len)) != NULL)
                    224:                add_pattern(line, *line == '\n' ? 0 : len);
1.3       deraadt   225:        if (ferror(f))
1.20      millert   226:                err(2, "%s", fn);
1.3       deraadt   227:        fclose(f);
                    228: }
1.1       deraadt   229:
                    230: int
1.3       deraadt   231: main(int argc, char *argv[])
1.1       deraadt   232: {
1.41      jacekm    233:        int c, lastc, prevoptind, newarg, i, needpattern, exprs, expr_sz;
1.33      jaredy    234:        struct patfile *patfile, *pf_next;
1.21      millert   235:        long l;
1.41      jacekm    236:        char *ep, **expr;
1.3       deraadt   237:
1.33      jaredy    238:        SLIST_INIT(&patfilelh);
1.16      tedu      239:        switch (__progname[0]) {
                    240:        case 'e':
                    241:                Eflag++;
                    242:                break;
                    243:        case 'f':
                    244:                Fflag++;
                    245:                break;
                    246:        case 'g':
                    247:                Gflag++;
                    248:                break;
                    249: #ifndef NOZ
                    250:        case 'z':
                    251:                Zflag++;
                    252:                switch(__progname[1]) {
                    253:                case 'e':
                    254:                        Eflag++;
                    255:                        break;
                    256:                case 'f':
                    257:                        Fflag++;
                    258:                        break;
                    259:                case 'g':
                    260:                        Gflag++;
                    261:                        break;
                    262:                }
                    263:                break;
                    264: #endif
                    265:        }
                    266:
1.18      millert   267:        lastc = '\0';
1.23      millert   268:        newarg = 1;
                    269:        prevoptind = 1;
1.38      kili      270:        needpattern = 1;
1.41      jacekm    271:        expr_sz = exprs = 0;
                    272:        expr = NULL;
1.5       deraadt   273:        while ((c = getopt_long(argc, argv, optstr,
1.17      millert   274:                                long_options, NULL)) != -1) {
1.3       deraadt   275:                switch (c) {
                    276:                case '0': case '1': case '2': case '3': case '4':
                    277:                case '5': case '6': case '7': case '8': case '9':
1.23      millert   278:                        if (newarg || !isdigit(lastc))
                    279:                                Aflag = 0;
                    280:                        else if (Aflag > INT_MAX / 10)
                    281:                                errx(2, "context out of range");
                    282:                        Aflag = Bflag = (Aflag * 10) + (c - '0');
1.3       deraadt   283:                        break;
                    284:                case 'A':
                    285:                case 'B':
1.21      millert   286:                        l = strtol(optarg, &ep, 10);
                    287:                        if (ep == optarg || *ep != '\0' ||
                    288:                            l <= 0 || l >= INT_MAX)
                    289:                                errx(2, "context out of range");
                    290:                        if (c == 'A')
                    291:                                Aflag = (int)l;
                    292:                        else
                    293:                                Bflag = (int)l;
1.3       deraadt   294:                        break;
                    295:                case 'C':
1.5       deraadt   296:                        if (optarg == NULL)
1.3       deraadt   297:                                Aflag = Bflag = 2;
1.21      millert   298:                        else {
                    299:                                l = strtol(optarg, &ep, 10);
                    300:                                if (ep == optarg || *ep != '\0' ||
                    301:                                    l <= 0 || l >= INT_MAX)
                    302:                                        errx(2, "context out of range");
                    303:                                Aflag = Bflag = (int)l;
                    304:                        }
1.1       deraadt   305:                        break;
                    306:                case 'E':
1.16      tedu      307:                        Fflag = Gflag = 0;
1.3       deraadt   308:                        Eflag++;
1.1       deraadt   309:                        break;
                    310:                case 'F':
1.16      tedu      311:                        Eflag = Gflag = 0;
1.3       deraadt   312:                        Fflag++;
                    313:                        break;
                    314:                case 'G':
1.16      tedu      315:                        Eflag = Fflag = 0;
1.3       deraadt   316:                        Gflag++;
1.1       deraadt   317:                        break;
1.9       tedu      318:                case 'I':
                    319:                        binbehave = BIN_FILE_SKIP;
                    320:                        break;
1.1       deraadt   321:                case 'L':
1.3       deraadt   322:                        lflag = 0;
                    323:                        Lflag = qflag = 1;
1.1       deraadt   324:                        break;
                    325:                case 'R':
1.3       deraadt   326:                case 'r':
                    327:                        Rflag++;
                    328:                        break;
                    329:                case 'U':
1.9       tedu      330:                        binbehave = BIN_FILE_BIN;
1.3       deraadt   331:                        break;
                    332:                case 'V':
                    333:                        fprintf(stderr, "grep version %u.%u\n", VER_MAJ, VER_MIN);
1.9       tedu      334:                        exit(0);
1.1       deraadt   335:                        break;
1.5       deraadt   336: #ifndef NOZ
1.3       deraadt   337:                case 'Z':
                    338:                        Zflag++;
1.1       deraadt   339:                        break;
1.5       deraadt   340: #endif
1.1       deraadt   341:                case 'a':
1.9       tedu      342:                        binbehave = BIN_FILE_TEXT;
1.1       deraadt   343:                        break;
                    344:                case 'b':
1.3       deraadt   345:                        bflag = 1;
1.1       deraadt   346:                        break;
                    347:                case 'c':
1.3       deraadt   348:                        cflag = 1;
1.1       deraadt   349:                        break;
                    350:                case 'e':
1.41      jacekm    351:                        /* defer adding of expressions until all arguments are parsed */
                    352:                        if (exprs == expr_sz) {
                    353:                                expr_sz *= 2;
                    354:                                expr = grep_realloc(expr, ++expr_sz * sizeof(*expr));
                    355:                        }
1.38      kili      356:                        needpattern = 0;
1.41      jacekm    357:                        expr[exprs] = optarg;
                    358:                        ++exprs;
1.1       deraadt   359:                        break;
                    360:                case 'f':
1.33      jaredy    361:                        patfile = grep_malloc(sizeof(*patfile));
                    362:                        patfile->pf_file = optarg;
                    363:                        SLIST_INSERT_HEAD(&patfilelh, patfile, pf_next);
1.38      kili      364:                        needpattern = 0;
1.1       deraadt   365:                        break;
                    366:                case 'h':
1.3       deraadt   367:                        hflag = 1;
1.1       deraadt   368:                        break;
                    369:                case 'i':
1.3       deraadt   370:                case 'y':
1.13      tedu      371:                        iflag = 1;
1.1       deraadt   372:                        cflags |= REG_ICASE;
                    373:                        break;
                    374:                case 'l':
1.3       deraadt   375:                        Lflag = 0;
                    376:                        lflag = qflag = 1;
1.1       deraadt   377:                        break;
                    378:                case 'n':
1.3       deraadt   379:                        nflag = 1;
                    380:                        break;
1.1       deraadt   381:                case 'q':
1.3       deraadt   382:                        qflag = 1;
1.1       deraadt   383:                        break;
                    384:                case 's':
1.3       deraadt   385:                        sflag = 1;
1.1       deraadt   386:                        break;
                    387:                case 'v':
1.3       deraadt   388:                        vflag = 1;
1.1       deraadt   389:                        break;
                    390:                case 'w':
1.3       deraadt   391:                        wflag = 1;
1.1       deraadt   392:                        break;
                    393:                case 'x':
1.3       deraadt   394:                        xflag = 1;
1.1       deraadt   395:                        break;
1.9       tedu      396:                case BIN_OPT:
                    397:                        if (strcmp("binary", optarg) == 0)
                    398:                                binbehave = BIN_FILE_BIN;
                    399:                        else if (strcmp("without-match", optarg) == 0)
                    400:                                binbehave = BIN_FILE_SKIP;
                    401:                        else if (strcmp("text", optarg) == 0)
                    402:                                binbehave = BIN_FILE_TEXT;
                    403:                        else
                    404:                                errx(2, "Unknown binary-files option");
                    405:                        break;
                    406:                case 'u':
                    407:                case MMAP_OPT:
                    408:                        /* default, compatibility */
                    409:                        break;
1.27      otto      410:                case LINEBUF_OPT:
                    411:                        lbflag = 1;
                    412:                        break;
1.9       tedu      413:                case HELP_OPT:
1.1       deraadt   414:                default:
                    415:                        usage();
                    416:                }
1.18      millert   417:                lastc = c;
1.23      millert   418:                newarg = optind != prevoptind;
1.18      millert   419:                prevoptind = optind;
1.1       deraadt   420:        }
1.3       deraadt   421:        argc -= optind;
                    422:        argv += optind;
1.41      jacekm    423:
                    424:        for (i = 0; i < exprs; i++)
                    425:                add_patterns(expr[i]);
                    426:        free(expr);
                    427:        expr = NULL;
1.33      jaredy    428:
                    429:        for (patfile = SLIST_FIRST(&patfilelh); patfile != NULL;
                    430:            patfile = pf_next) {
                    431:                pf_next = SLIST_NEXT(patfile, pf_next);
                    432:                read_patterns(patfile->pf_file);
                    433:                free(patfile);
                    434:        }
1.3       deraadt   435:
1.38      kili      436:        if (argc == 0 && needpattern)
1.1       deraadt   437:                usage();
                    438:
1.38      kili      439:        if (argc != 0 && needpattern) {
1.35      otto      440:                add_patterns(*argv);
1.3       deraadt   441:                --argc;
                    442:                ++argv;
                    443:        }
1.5       deraadt   444:
1.16      tedu      445:        if (Eflag)
                    446:                cflags |= REG_EXTENDED;
1.42    ! tedu      447:        if (Fflag)
        !           448:                cflags |= REG_NOSPEC;
        !           449: #ifdef SMALL
        !           450:        /* Sorry, this won't work */
        !           451:        if (Fflag && wflag)
        !           452:                errx(1, "Can't use small fgrep with -w");
        !           453: #endif
1.39      deraadt   454:        fg_pattern = grep_calloc(patterns, sizeof(*fg_pattern));
                    455:        r_pattern = grep_calloc(patterns, sizeof(*r_pattern));
1.3       deraadt   456:        for (i = 0; i < patterns; ++i) {
1.28      millert   457:                /* Check if cheating is allowed (always is for fgrep). */
1.42    ! tedu      458: #ifndef SMALL
1.28      millert   459:                if (Fflag) {
                    460:                        fgrepcomp(&fg_pattern[i], pattern[i]);
1.42    ! tedu      461:                } else
        !           462: #endif
        !           463:                {
1.28      millert   464:                        if (fastcomp(&fg_pattern[i], pattern[i])) {
                    465:                                /* Fall back to full regex library */
                    466:                                c = regcomp(&r_pattern[i], pattern[i], cflags);
                    467:                                if (c != 0) {
                    468:                                        regerror(c, &r_pattern[i], re_error,
                    469:                                            RE_ERROR_BUF);
                    470:                                        errx(2, "%s", re_error);
                    471:                                }
1.13      tedu      472:                        }
1.1       deraadt   473:                }
                    474:        }
1.29      deraadt   475:
1.27      otto      476:        if (lbflag)
                    477:                setlinebuf(stdout);
1.1       deraadt   478:
1.40      tedu      479:        if ((argc == 0 || argc == 1) && !Rflag)
1.3       deraadt   480:                hflag = 1;
1.1       deraadt   481:
1.3       deraadt   482:        if (argc == 0)
                    483:                exit(!procfile(NULL));
1.5       deraadt   484:
1.3       deraadt   485:        if (Rflag)
                    486:                c = grep_tree(argv);
1.1       deraadt   487:        else
1.3       deraadt   488:                for (c = 0; argc--; ++argv)
                    489:                        c += procfile(*argv);
1.1       deraadt   490:
1.3       deraadt   491:        exit(!c);
1.1       deraadt   492: }