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

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