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

Annotation of src/usr.bin/sed/compile.c, Revision 1.21

1.21    ! deraadt     1: /*     $OpenBSD: compile.c,v 1.20 2004/07/10 11:41:26 otto Exp $       */
1.2       deraadt     2:
1.1       deraadt     3: /*-
                      4:  * Copyright (c) 1992 Diomidis Spinellis.
                      5:  * Copyright (c) 1992, 1993
                      6:  *     The Regents of the University of California.  All rights reserved.
                      7:  *
                      8:  * This code is derived from software contributed to Berkeley by
                      9:  * Diomidis Spinellis of Imperial College, University of London.
                     10:  *
                     11:  * Redistribution and use in source and binary forms, with or without
                     12:  * modification, are permitted provided that the following conditions
                     13:  * are met:
                     14:  * 1. Redistributions of source code must retain the above copyright
                     15:  *    notice, this list of conditions and the following disclaimer.
                     16:  * 2. Redistributions in binary form must reproduce the above copyright
                     17:  *    notice, this list of conditions and the following disclaimer in the
                     18:  *    documentation and/or other materials provided with the distribution.
1.14      millert    19:  * 3. Neither the name of the University nor the names of its contributors
1.1       deraadt    20:  *    may be used to endorse or promote products derived from this software
                     21:  *    without specific prior written permission.
                     22:  *
                     23:  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
                     24:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
                     25:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
                     26:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
                     27:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
                     28:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
                     29:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
                     30:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
                     31:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
                     32:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
                     33:  * SUCH DAMAGE.
                     34:  */
                     35:
                     36: #ifndef lint
1.9       millert    37: /* from: static char sccsid[] = "@(#)compile.c 8.2 (Berkeley) 4/28/95"; */
1.21    ! deraadt    38: static char *rcsid = "$OpenBSD: compile.c,v 1.20 2004/07/10 11:41:26 otto Exp $";
1.1       deraadt    39: #endif /* not lint */
                     40:
                     41: #include <sys/types.h>
                     42: #include <sys/stat.h>
                     43:
                     44: #include <ctype.h>
                     45: #include <errno.h>
                     46: #include <fcntl.h>
                     47: #include <limits.h>
                     48: #include <regex.h>
                     49: #include <stdio.h>
                     50: #include <stdlib.h>
                     51: #include <string.h>
                     52:
                     53: #include "defs.h"
                     54: #include "extern.h"
                     55:
                     56: #define LHSZ   128
                     57: #define        LHMASK  (LHSZ - 1)
                     58: static struct labhash {
                     59:        struct  labhash *lh_next;
                     60:        u_int   lh_hash;
                     61:        struct  s_command *lh_cmd;
                     62:        int     lh_ref;
                     63: } *labels[LHSZ];
                     64:
1.11      millert    65: static char     *compile_addr(char *, struct s_addr *);
                     66: static char     *compile_ccl(char **, char *);
                     67: static char     *compile_delimited(char *, char *);
                     68: static char     *compile_flags(char *, struct s_subst *);
                     69: static char     *compile_re(char *, regex_t **);
                     70: static char     *compile_subst(char *, struct s_subst *);
                     71: static char     *compile_text(void);
                     72: static char     *compile_tr(char *, char **);
1.1       deraadt    73: static struct s_command
1.11      millert    74:                **compile_stream(struct s_command **);
1.16      deraadt    75: static char     *duptoeol(char *, char *, char **);
1.11      millert    76: static void      enterlabel(struct s_command *);
1.1       deraadt    77: static struct s_command
1.11      millert    78:                 *findlabel(char *);
                     79: static void      fixuplabel(struct s_command *, struct s_command *);
                     80: static void      uselabel(void);
1.1       deraadt    81:
                     82: /*
                     83:  * Command specification.  This is used to drive the command parser.
                     84:  */
                     85: struct s_format {
                     86:        char code;                              /* Command code */
                     87:        int naddr;                              /* Number of address args */
                     88:        enum e_args args;                       /* Argument type */
                     89: };
                     90:
                     91: static struct s_format cmd_fmts[] = {
                     92:        {'{', 2, GROUP},
                     93:        {'}', 0, ENDGROUP},
                     94:        {'a', 1, TEXT},
                     95:        {'b', 2, BRANCH},
                     96:        {'c', 2, TEXT},
                     97:        {'d', 2, EMPTY},
                     98:        {'D', 2, EMPTY},
                     99:        {'g', 2, EMPTY},
                    100:        {'G', 2, EMPTY},
                    101:        {'h', 2, EMPTY},
                    102:        {'H', 2, EMPTY},
                    103:        {'i', 1, TEXT},
                    104:        {'l', 2, EMPTY},
                    105:        {'n', 2, EMPTY},
                    106:        {'N', 2, EMPTY},
                    107:        {'p', 2, EMPTY},
                    108:        {'P', 2, EMPTY},
                    109:        {'q', 1, EMPTY},
                    110:        {'r', 1, RFILE},
                    111:        {'s', 2, SUBST},
                    112:        {'t', 2, BRANCH},
                    113:        {'w', 2, WFILE},
                    114:        {'x', 2, EMPTY},
                    115:        {'y', 2, TR},
                    116:        {'!', 2, NONSEL},
                    117:        {':', 0, LABEL},
                    118:        {'#', 0, COMMENT},
                    119:        {'=', 1, EMPTY},
                    120:        {'\0', 0, COMMENT},
                    121: };
                    122:
                    123: /* The compiled program. */
                    124: struct s_command *prog;
                    125:
                    126: /*
                    127:  * Compile the program into prog.
                    128:  * Initialise appends.
                    129:  */
                    130: void
1.15      deraadt   131: compile(void)
1.1       deraadt   132: {
                    133:        *compile_stream(&prog) = NULL;
                    134:        fixuplabel(prog, NULL);
                    135:        uselabel();
                    136:        appends = xmalloc(sizeof(struct s_appends) * appendnum);
                    137:        match = xmalloc((maxnsub + 1) * sizeof(regmatch_t));
                    138: }
                    139:
                    140: #define EATSPACE() do {                                                        \
                    141:        if (p)                                                          \
                    142:                while (*p && isascii(*p) && isspace(*p))                \
                    143:                        p++;                                            \
                    144:        } while (0)
                    145:
                    146: static struct s_command **
1.15      deraadt   147: compile_stream(struct s_command **link)
1.1       deraadt   148: {
1.10      mpech     149:        char *p;
1.1       deraadt   150:        static char lbuf[_POSIX2_LINE_MAX + 1]; /* To save stack */
                    151:        struct s_command *cmd, *cmd2, *stack;
                    152:        struct s_format *fp;
                    153:        int naddr;                              /* Number of addresses */
                    154:
                    155:        stack = 0;
                    156:        for (;;) {
                    157:                if ((p = cu_fgets(lbuf, sizeof(lbuf))) == NULL) {
                    158:                        if (stack != 0)
                    159:                                err(COMPILE, "unexpected EOF (pending }'s)");
                    160:                        return (link);
                    161:                }
                    162:
                    163: semicolon:     EATSPACE();
                    164:                if (p && (*p == '#' || *p == '\0'))
                    165:                        continue;
                    166:                *link = cmd = xmalloc(sizeof(struct s_command));
                    167:                link = &cmd->next;
                    168:                cmd->nonsel = cmd->inrange = 0;
                    169:                /* First parse the addresses */
                    170:                naddr = 0;
                    171:
                    172: /* Valid characters to start an address */
                    173: #define        addrchar(c)     (strchr("0123456789/\\$", (c)))
                    174:                if (addrchar(*p)) {
                    175:                        naddr++;
                    176:                        cmd->a1 = xmalloc(sizeof(struct s_addr));
                    177:                        p = compile_addr(p, cmd->a1);
                    178:                        EATSPACE();                             /* EXTENSION */
                    179:                        if (*p == ',') {
                    180:                                p++;
                    181:                                EATSPACE();                     /* EXTENSION */
                    182:                                naddr++;
                    183:                                cmd->a2 = xmalloc(sizeof(struct s_addr));
                    184:                                p = compile_addr(p, cmd->a2);
                    185:                                EATSPACE();
                    186:                        } else
                    187:                                cmd->a2 = 0;
                    188:                } else
                    189:                        cmd->a1 = cmd->a2 = 0;
                    190:
                    191: nonsel:                /* Now parse the command */
                    192:                if (!*p)
                    193:                        err(COMPILE, "command expected");
                    194:                cmd->code = *p;
                    195:                for (fp = cmd_fmts; fp->code; fp++)
                    196:                        if (fp->code == *p)
                    197:                                break;
                    198:                if (!fp->code)
                    199:                        err(COMPILE, "invalid command code %c", *p);
                    200:                if (naddr > fp->naddr)
                    201:                        err(COMPILE,
                    202: "command %c expects up to %d address(es), found %d", *p, fp->naddr, naddr);
                    203:                switch (fp->args) {
                    204:                case NONSEL:                    /* ! */
                    205:                        p++;
                    206:                        EATSPACE();
                    207:                        cmd->nonsel = ! cmd->nonsel;
                    208:                        goto nonsel;
                    209:                case GROUP:                     /* { */
                    210:                        p++;
                    211:                        EATSPACE();
                    212:                        cmd->next = stack;
                    213:                        stack = cmd;
                    214:                        link = &cmd->u.c;
                    215:                        if (*p)
                    216:                                goto semicolon;
                    217:                        break;
                    218:                case ENDGROUP:
                    219:                        /*
                    220:                         * Short-circuit command processing, since end of
                    221:                         * group is really just a noop.
                    222:                         */
                    223:                        cmd->nonsel = 1;
                    224:                        if (stack == 0)
                    225:                                err(COMPILE, "unexpected }");
                    226:                        cmd2 = stack;
                    227:                        stack = cmd2->next;
                    228:                        cmd2->next = cmd;
                    229:                        /*FALLTHROUGH*/
                    230:                case EMPTY:             /* d D g G h H l n N p P q x = \0 */
                    231:                        p++;
                    232:                        EATSPACE();
                    233:                        if (*p == ';') {
                    234:                                p++;
                    235:                                link = &cmd->next;
                    236:                                goto semicolon;
                    237:                        }
                    238:                        if (*p)
                    239:                                err(COMPILE,
                    240: "extra characters at the end of %c command", cmd->code);
                    241:                        break;
                    242:                case TEXT:                      /* a c i */
                    243:                        p++;
                    244:                        EATSPACE();
                    245:                        if (*p != '\\')
                    246:                                err(COMPILE,
                    247: "command %c expects \\ followed by text", cmd->code);
                    248:                        p++;
                    249:                        EATSPACE();
                    250:                        if (*p)
                    251:                                err(COMPILE,
                    252: "extra characters after \\ at the end of %c command", cmd->code);
                    253:                        cmd->t = compile_text();
                    254:                        break;
                    255:                case COMMENT:                   /* \0 # */
                    256:                        break;
                    257:                case WFILE:                     /* w */
                    258:                        p++;
                    259:                        EATSPACE();
                    260:                        if (*p == '\0')
                    261:                                err(COMPILE, "filename expected");
1.16      deraadt   262:                        cmd->t = duptoeol(p, "w command", NULL);
1.1       deraadt   263:                        if (aflag)
                    264:                                cmd->u.fd = -1;
1.21    ! deraadt   265:                        else if ((cmd->u.fd = open(p,
1.1       deraadt   266:                            O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
                    267:                            DEFFILEMODE)) == -1)
1.12      jsyn      268:                                err(FATAL, "%s: %s", p, strerror(errno));
1.1       deraadt   269:                        break;
                    270:                case RFILE:                     /* r */
                    271:                        p++;
                    272:                        EATSPACE();
1.16      deraadt   273:                        cmd->t = duptoeol(p, "read command", NULL);
1.1       deraadt   274:                        break;
                    275:                case BRANCH:                    /* b t */
                    276:                        p++;
                    277:                        EATSPACE();
                    278:                        if (*p == '\0')
                    279:                                cmd->t = NULL;
                    280:                        else
1.16      deraadt   281:                                cmd->t = duptoeol(p, "branch", &p);
                    282:                        if (*p == ';') {
                    283:                                p++;
                    284:                                goto semicolon;
                    285:                        }
1.1       deraadt   286:                        break;
                    287:                case LABEL:                     /* : */
                    288:                        p++;
                    289:                        EATSPACE();
1.16      deraadt   290:                        cmd->t = duptoeol(p, "label", &p);
                    291:                        if (strlen(cmd->t) == 0)
1.1       deraadt   292:                                err(COMPILE, "empty label");
                    293:                        enterlabel(cmd);
1.16      deraadt   294:                        if (*p == ';') {
                    295:                                p++;
                    296:                                goto semicolon;
                    297:                        }
1.1       deraadt   298:                        break;
                    299:                case SUBST:                     /* s */
                    300:                        p++;
                    301:                        if (*p == '\0' || *p == '\\')
                    302:                                err(COMPILE,
                    303: "substitute pattern can not be delimited by newline or backslash");
                    304:                        cmd->u.s = xmalloc(sizeof(struct s_subst));
                    305:                        p = compile_re(p, &cmd->u.s->re);
                    306:                        if (p == NULL)
                    307:                                err(COMPILE, "unterminated substitute pattern");
                    308:                        --p;
                    309:                        p = compile_subst(p, cmd->u.s);
                    310:                        p = compile_flags(p, cmd->u.s);
                    311:                        EATSPACE();
                    312:                        if (*p == ';') {
                    313:                                p++;
                    314:                                link = &cmd->next;
                    315:                                goto semicolon;
                    316:                        }
                    317:                        break;
                    318:                case TR:                        /* y */
                    319:                        p++;
                    320:                        p = compile_tr(p, (char **)&cmd->u.y);
                    321:                        EATSPACE();
                    322:                        if (*p == ';') {
                    323:                                p++;
                    324:                                link = &cmd->next;
                    325:                                goto semicolon;
                    326:                        }
                    327:                        if (*p)
                    328:                                err(COMPILE,
                    329: "extra text at the end of a transform command");
                    330:                        break;
                    331:                }
                    332:        }
                    333: }
                    334:
                    335: /*
                    336:  * Get a delimited string.  P points to the delimeter of the string; d points
                    337:  * to a buffer area.  Newline and delimiter escapes are processed; other
                    338:  * escapes are ignored.
                    339:  *
                    340:  * Returns a pointer to the first character after the final delimiter or NULL
                    341:  * in the case of a non-terminated string.  The character array d is filled
                    342:  * with the processed string.
                    343:  */
                    344: static char *
1.15      deraadt   345: compile_delimited(char *p, char *d)
1.1       deraadt   346: {
                    347:        char c;
                    348:
                    349:        c = *p++;
                    350:        if (c == '\0')
                    351:                return (NULL);
                    352:        else if (c == '\\')
                    353:                err(COMPILE, "\\ can not be used as a string delimiter");
                    354:        else if (c == '\n')
                    355:                err(COMPILE, "newline can not be used as a string delimiter");
                    356:        while (*p) {
                    357:                if (*p == '[') {
                    358:                        if ((d = compile_ccl(&p, d)) == NULL)
                    359:                                err(COMPILE, "unbalanced brackets ([])");
                    360:                        continue;
                    361:                } else if (*p == '\\' && p[1] == '[') {
                    362:                        *d++ = *p++;
                    363:                } else if (*p == '\\' && p[1] == c)
                    364:                        p++;
                    365:                else if (*p == '\\' && p[1] == 'n') {
                    366:                        *d++ = '\n';
                    367:                        p += 2;
                    368:                        continue;
                    369:                } else if (*p == '\\' && p[1] == '\\')
                    370:                        *d++ = *p++;
                    371:                else if (*p == c) {
                    372:                        *d = '\0';
                    373:                        return (p + 1);
                    374:                }
                    375:                *d++ = *p++;
                    376:        }
                    377:        return (NULL);
                    378: }
                    379:
                    380:
                    381: /* compile_ccl: expand a POSIX character class */
                    382: static char *
1.15      deraadt   383: compile_ccl(char **sp, char *t)
1.1       deraadt   384: {
                    385:        int c, d;
                    386:        char *s = *sp;
                    387:
                    388:        *t++ = *s++;
                    389:        if (*s == '^')
                    390:                *t++ = *s++;
                    391:        if (*s == ']')
                    392:                *t++ = *s++;
                    393:        for (; *s && (*t = *s) != ']'; s++, t++)
                    394:                if (*s == '[' && ((d = *(s+1)) == '.' || d == ':' || d == '=')) {
                    395:                        *++t = *++s, t++, s++;
                    396:                        for (c = *s; (*t = *s) != ']' || c != d; s++, t++)
                    397:                                if ((c = *s) == '\0')
                    398:                                        return NULL;
                    399:                } else if (*s == '\\' && s[1] == 'n')
                    400:                            *t = '\n', s++;
                    401:        return (*s == ']') ? *sp = ++s, ++t : NULL;
                    402: }
                    403:
                    404: /*
                    405:  * Get a regular expression.  P points to the delimiter of the regular
                    406:  * expression; repp points to the address of a regexp pointer.  Newline
                    407:  * and delimiter escapes are processed; other escapes are ignored.
                    408:  * Returns a pointer to the first character after the final delimiter
                    409:  * or NULL in the case of a non terminated regular expression.  The regexp
                    410:  * pointer is set to the compiled regular expression.
                    411:  * Cflags are passed to regcomp.
                    412:  */
                    413: static char *
1.15      deraadt   414: compile_re(char *p, regex_t **repp)
1.1       deraadt   415: {
                    416:        int eval;
                    417:        char re[_POSIX2_LINE_MAX + 1];
                    418:
                    419:        p = compile_delimited(p, re);
                    420:        if (p && strlen(re) == 0) {
                    421:                *repp = NULL;
                    422:                return (p);
                    423:        }
                    424:        *repp = xmalloc(sizeof(regex_t));
1.6       millert   425:        if (p && (eval = regcomp(*repp, re, 0)) != 0)
1.1       deraadt   426:                err(COMPILE, "RE error: %s", strregerror(eval, *repp));
                    427:        if (maxnsub < (*repp)->re_nsub)
                    428:                maxnsub = (*repp)->re_nsub;
                    429:        return (p);
                    430: }
                    431:
                    432: /*
                    433:  * Compile the substitution string of a regular expression and set res to
                    434:  * point to a saved copy of it.  Nsub is the number of parenthesized regular
                    435:  * expressions.
                    436:  */
                    437: static char *
1.15      deraadt   438: compile_subst(char *p, struct s_subst *s)
1.1       deraadt   439: {
                    440:        static char lbuf[_POSIX2_LINE_MAX + 1];
                    441:        int asize, ref, size;
                    442:        char c, *text, *op, *sp;
1.19      otto      443:        int sawesc = 0;
1.1       deraadt   444:
                    445:        c = *p++;                       /* Terminator character */
                    446:        if (c == '\0')
                    447:                return (NULL);
                    448:
                    449:        s->maxbref = 0;
                    450:        s->linenum = linenum;
                    451:        asize = 2 * _POSIX2_LINE_MAX + 1;
                    452:        text = xmalloc(asize);
                    453:        size = 0;
                    454:        do {
                    455:                op = sp = text + size;
                    456:                for (; *p; p++) {
1.19      otto      457:                        if (*p == '\\' || sawesc) {
                    458:                                /*
                    459:                                 * If this is a continuation from the last
                    460:                                 * buffer, we won't have a character to
                    461:                                 * skip over.
                    462:                                 */
                    463:                                if (sawesc)
                    464:                                        sawesc = 0;
                    465:                                else
                    466:                                        p++;
                    467:
                    468:                                if (*p == '\0') {
                    469:                                        /*
                    470:                                         * This escaped character is continued
                    471:                                         * in the next part of the line.  Note
                    472:                                         * this fact, then cause the loop to
                    473:                                         * exit w/ normal EOL case and reenter
                    474:                                         * above with the new buffer.
                    475:                                         */
                    476:                                        sawesc = 1;
                    477:                                        p--;
                    478:                                        continue;
                    479:                                } else if (strchr("123456789", *p) != NULL) {
1.1       deraadt   480:                                        *sp++ = '\\';
                    481:                                        ref = *p - '0';
                    482:                                        if (s->re != NULL &&
                    483:                                            ref > s->re->re_nsub)
                    484:                                                err(COMPILE,
                    485: "\\%c not defined in the RE", *p);
                    486:                                        if (s->maxbref < ref)
                    487:                                                s->maxbref = ref;
                    488:                                } else if (*p == '&' || *p == '\\')
                    489:                                        *sp++ = '\\';
                    490:                        } else if (*p == c) {
                    491:                                p++;
                    492:                                *sp++ = '\0';
                    493:                                size += sp - op;
                    494:                                s->new = xrealloc(text, size);
                    495:                                return (p);
                    496:                        } else if (*p == '\n') {
                    497:                                err(COMPILE,
                    498: "unescaped newline inside substitute pattern");
                    499:                                /* NOTREACHED */
                    500:                        }
                    501:                        *sp++ = *p;
                    502:                }
                    503:                size += sp - op;
                    504:                if (asize - size < _POSIX2_LINE_MAX + 1) {
                    505:                        asize *= 2;
1.20      otto      506:                        text = xrealloc(text, asize);
1.1       deraadt   507:                }
                    508:        } while (cu_fgets(p = lbuf, sizeof(lbuf)));
                    509:        err(COMPILE, "unterminated substitute in regular expression");
                    510:        /* NOTREACHED */
                    511: }
                    512:
                    513: /*
                    514:  * Compile the flags of the s command
                    515:  */
                    516: static char *
1.15      deraadt   517: compile_flags(char *p, struct s_subst *s)
1.1       deraadt   518: {
                    519:        int gn;                 /* True if we have seen g or n */
1.17      otto      520:        long l;
1.1       deraadt   521:        char wfile[_POSIX2_LINE_MAX + 1], *q;
                    522:
                    523:        s->n = 1;                               /* Default */
                    524:        s->p = 0;
                    525:        s->wfile = NULL;
                    526:        s->wfd = -1;
                    527:        for (gn = 0;;) {
                    528:                EATSPACE();                     /* EXTENSION */
                    529:                switch (*p) {
                    530:                case 'g':
                    531:                        if (gn)
                    532:                                err(COMPILE,
                    533: "more than one number or 'g' in substitute flags");
                    534:                        gn = 1;
                    535:                        s->n = 0;
                    536:                        break;
                    537:                case '\0':
                    538:                case '\n':
                    539:                case ';':
                    540:                        return (p);
                    541:                case 'p':
                    542:                        s->p = 1;
                    543:                        break;
                    544:                case '1': case '2': case '3':
                    545:                case '4': case '5': case '6':
                    546:                case '7': case '8': case '9':
                    547:                        if (gn)
                    548:                                err(COMPILE,
                    549: "more than one number or 'g' in substitute flags");
                    550:                        gn = 1;
1.17      otto      551:                        l = strtol(p, &p, 10);
                    552:                        if (l <= 0 || l >= INT_MAX)
                    553:                                err(COMPILE,
                    554:                                    "number in substitute flags out of range");
                    555:                        s->n = (int)l;
                    556:                        continue;
1.1       deraadt   557:                case 'w':
                    558:                        p++;
                    559: #ifdef HISTORIC_PRACTICE
                    560:                        if (*p != ' ') {
                    561:                                err(WARNING, "space missing before w wfile");
                    562:                                return (p);
                    563:                        }
                    564: #endif
                    565:                        EATSPACE();
                    566:                        q = wfile;
                    567:                        while (*p) {
                    568:                                if (*p == '\n')
                    569:                                        break;
                    570:                                *q++ = *p++;
                    571:                        }
                    572:                        *q = '\0';
                    573:                        if (q == wfile)
                    574:                                err(COMPILE, "no wfile specified");
                    575:                        s->wfile = strdup(wfile);
                    576:                        if (!aflag && (s->wfd = open(wfile,
                    577:                            O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
                    578:                            DEFFILEMODE)) == -1)
1.12      jsyn      579:                                err(FATAL, "%s: %s", wfile, strerror(errno));
1.1       deraadt   580:                        return (p);
                    581:                default:
                    582:                        err(COMPILE,
                    583:                            "bad flag in substitute command: '%c'", *p);
                    584:                        break;
                    585:                }
                    586:                p++;
                    587:        }
                    588: }
                    589:
                    590: /*
                    591:  * Compile a translation set of strings into a lookup table.
                    592:  */
                    593: static char *
1.15      deraadt   594: compile_tr(char *p, char **transtab)
1.1       deraadt   595: {
                    596:        int i;
                    597:        char *lt, *op, *np;
                    598:        char old[_POSIX2_LINE_MAX + 1];
                    599:        char new[_POSIX2_LINE_MAX + 1];
                    600:
                    601:        if (*p == '\0' || *p == '\\')
                    602:                err(COMPILE,
                    603: "transform pattern can not be delimited by newline or backslash");
                    604:        p = compile_delimited(p, old);
                    605:        if (p == NULL) {
                    606:                err(COMPILE, "unterminated transform source string");
                    607:                return (NULL);
                    608:        }
                    609:        p = compile_delimited(--p, new);
                    610:        if (p == NULL) {
                    611:                err(COMPILE, "unterminated transform target string");
                    612:                return (NULL);
                    613:        }
                    614:        EATSPACE();
                    615:        if (strlen(new) != strlen(old)) {
                    616:                err(COMPILE, "transform strings are not the same length");
                    617:                return (NULL);
                    618:        }
                    619:        /* We assume characters are 8 bits */
1.18      deraadt   620:        lt = xmalloc(UCHAR_MAX + 1);
1.1       deraadt   621:        for (i = 0; i <= UCHAR_MAX; i++)
                    622:                lt[i] = (char)i;
                    623:        for (op = old, np = new; *op; op++, np++)
                    624:                lt[(u_char)*op] = *np;
                    625:        *transtab = lt;
                    626:        return (p);
                    627: }
                    628:
                    629: /*
1.7       deraadt   630:  * Compile the text following an a, c, or i command.
1.1       deraadt   631:  */
                    632: static char *
1.15      deraadt   633: compile_text(void)
1.1       deraadt   634: {
1.4       deraadt   635:        int asize, esc_nl, size;
1.1       deraadt   636:        char *text, *p, *op, *s;
                    637:        char lbuf[_POSIX2_LINE_MAX + 1];
                    638:
                    639:        asize = 2 * _POSIX2_LINE_MAX + 1;
                    640:        text = xmalloc(asize);
                    641:        size = 0;
                    642:        while (cu_fgets(lbuf, sizeof(lbuf))) {
                    643:                op = s = text + size;
                    644:                p = lbuf;
                    645:                EATSPACE();
1.4       deraadt   646:                for (esc_nl = 0; *p != '\0'; p++) {
                    647:                        if (*p == '\\' && p[1] != '\0' && *++p == '\n')
                    648:                                esc_nl = 1;
1.1       deraadt   649:                        *s++ = *p;
                    650:                }
                    651:                size += s - op;
1.4       deraadt   652:                if (!esc_nl) {
1.1       deraadt   653:                        *s = '\0';
                    654:                        break;
                    655:                }
                    656:                if (asize - size < _POSIX2_LINE_MAX + 1) {
                    657:                        asize *= 2;
                    658:                        text = xmalloc(asize);
                    659:                }
                    660:        }
1.8       brian     661:        text[size] = '\0';
1.1       deraadt   662:        return (xrealloc(text, size + 1));
                    663: }
                    664:
                    665: /*
                    666:  * Get an address and return a pointer to the first character after
                    667:  * it.  Fill the structure pointed to according to the address.
                    668:  */
                    669: static char *
1.15      deraadt   670: compile_addr(char *p, struct s_addr *a)
1.1       deraadt   671: {
                    672:        char *end;
                    673:
                    674:        switch (*p) {
                    675:        case '\\':                              /* Context address */
                    676:                ++p;
                    677:                /* FALLTHROUGH */
                    678:        case '/':                               /* Context address */
                    679:                p = compile_re(p, &a->u.r);
                    680:                if (p == NULL)
                    681:                        err(COMPILE, "unterminated regular expression");
                    682:                a->type = AT_RE;
                    683:                return (p);
                    684:
                    685:        case '$':                               /* Last line */
                    686:                a->type = AT_LAST;
                    687:                return (p + 1);
                    688:                                                /* Line number */
1.21    ! deraadt   689:        case '0': case '1': case '2': case '3': case '4':
1.1       deraadt   690:        case '5': case '6': case '7': case '8': case '9':
                    691:                a->type = AT_LINE;
1.3       millert   692:                a->u.l = strtoul(p, &end, 10);
1.1       deraadt   693:                return (end);
                    694:        default:
                    695:                err(COMPILE, "expected context address");
                    696:                return (NULL);
                    697:        }
                    698: }
                    699:
                    700: /*
                    701:  * duptoeol --
                    702:  *     Return a copy of all the characters up to \n or \0.
                    703:  */
                    704: static char *
1.16      deraadt   705: duptoeol(char *s, char *ctype, char **semi)
1.1       deraadt   706: {
                    707:        size_t len;
                    708:        int ws;
                    709:        char *start;
                    710:
                    711:        ws = 0;
1.16      deraadt   712:        if (semi) {
                    713:                for (start = s; *s != '\0' && *s != '\n' && *s != ';'; ++s)
                    714:                        ws = isspace(*s);
                    715:        } else {
                    716:                for (start = s; *s != '\0' && *s != '\n'; ++s)
                    717:                        ws = isspace(*s);
                    718:                *s = '\0';
                    719:        }
1.1       deraadt   720:        if (ws)
                    721:                err(WARNING, "whitespace after %s", ctype);
                    722:        len = s - start + 1;
1.16      deraadt   723:        if (semi)
                    724:                *semi = s;
                    725:        s = xmalloc(len);
                    726:        strlcpy(s, start, len);
                    727:        return (s);
1.1       deraadt   728: }
                    729:
                    730: /*
                    731:  * Convert goto label names to addresses, and count a and r commands, in
                    732:  * the given subset of the script.  Free the memory used by labels in b
                    733:  * and t commands (but not by :).
                    734:  *
                    735:  * TODO: Remove } nodes
                    736:  */
                    737: static void
1.15      deraadt   738: fixuplabel(struct s_command *cp, struct s_command *end)
1.1       deraadt   739: {
                    740:
                    741:        for (; cp != end; cp = cp->next)
                    742:                switch (cp->code) {
                    743:                case 'a':
                    744:                case 'r':
                    745:                        appendnum++;
                    746:                        break;
                    747:                case 'b':
                    748:                case 't':
                    749:                        /* Resolve branch target. */
                    750:                        if (cp->t == NULL) {
                    751:                                cp->u.c = NULL;
                    752:                                break;
                    753:                        }
                    754:                        if ((cp->u.c = findlabel(cp->t)) == NULL)
                    755:                                err(COMPILE2, "undefined label '%s'", cp->t);
                    756:                        free(cp->t);
                    757:                        break;
                    758:                case '{':
                    759:                        /* Do interior commands. */
                    760:                        fixuplabel(cp->u.c, cp->next);
                    761:                        break;
                    762:                }
                    763: }
                    764:
                    765: /*
                    766:  * Associate the given command label for later lookup.
                    767:  */
                    768: static void
1.15      deraadt   769: enterlabel(struct s_command *cp)
1.1       deraadt   770: {
1.10      mpech     771:        struct labhash **lhp, *lh;
                    772:        u_char *p;
                    773:        u_int h, c;
1.1       deraadt   774:
                    775:        for (h = 0, p = (u_char *)cp->t; (c = *p) != 0; p++)
                    776:                h = (h << 5) + h + c;
                    777:        lhp = &labels[h & LHMASK];
                    778:        for (lh = *lhp; lh != NULL; lh = lh->lh_next)
                    779:                if (lh->lh_hash == h && strcmp(cp->t, lh->lh_cmd->t) == 0)
                    780:                        err(COMPILE2, "duplicate label '%s'", cp->t);
                    781:        lh = xmalloc(sizeof *lh);
                    782:        lh->lh_next = *lhp;
                    783:        lh->lh_hash = h;
                    784:        lh->lh_cmd = cp;
                    785:        lh->lh_ref = 0;
                    786:        *lhp = lh;
                    787: }
                    788:
                    789: /*
                    790:  * Find the label contained in the command l in the command linked
                    791:  * list cp.  L is excluded from the search.  Return NULL if not found.
                    792:  */
                    793: static struct s_command *
1.15      deraadt   794: findlabel(char *name)
1.1       deraadt   795: {
1.10      mpech     796:        struct labhash *lh;
                    797:        u_char *p;
                    798:        u_int h, c;
1.1       deraadt   799:
                    800:        for (h = 0, p = (u_char *)name; (c = *p) != 0; p++)
                    801:                h = (h << 5) + h + c;
                    802:        for (lh = labels[h & LHMASK]; lh != NULL; lh = lh->lh_next) {
                    803:                if (lh->lh_hash == h && strcmp(name, lh->lh_cmd->t) == 0) {
                    804:                        lh->lh_ref = 1;
                    805:                        return (lh->lh_cmd);
                    806:                }
                    807:        }
                    808:        return (NULL);
                    809: }
                    810:
1.21    ! deraadt   811: /*
1.1       deraadt   812:  * Warn about any unused labels.  As a side effect, release the label hash
                    813:  * table space.
                    814:  */
                    815: static void
1.15      deraadt   816: uselabel(void)
1.1       deraadt   817: {
1.10      mpech     818:        struct labhash *lh, *next;
                    819:        int i;
1.1       deraadt   820:
                    821:        for (i = 0; i < LHSZ; i++) {
                    822:                for (lh = labels[i]; lh != NULL; lh = next) {
                    823:                        next = lh->lh_next;
                    824:                        if (!lh->lh_ref)
                    825:                                err(WARNING, "unused label '%s'",
                    826:                                    lh->lh_cmd->t);
                    827:                        free(lh);
                    828:                }
                    829:        }
                    830: }