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