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