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