xref: /freebsd/usr.bin/sed/compile.c (revision 2c8d04d0228871c24017509cf039e7c5d97d97be)
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 const char	 *compile_addr(const char *, struct s_addr *);
68 static       char	 *compile_ccl(const char **, char *);
69 static const char	 *compile_delimited(const char *, char *, int);
70 static const char	 *compile_flags(const char *, struct s_subst *);
71 static const regex_t	 *compile_re(const char *, int);
72 static const char	 *compile_subst(const char *, struct s_subst *);
73 static       char	 *compile_text(size_t *);
74 static const char	 *compile_tr(const char *, struct s_tr **);
75 static struct s_command
76 		**compile_stream(struct s_command **);
77 static char	 *duptoeol(const char *, const char *, size_t *);
78 static void	  enterlabel(struct s_command *);
79 static struct s_command
80 		 *findlabel(const char *);
81 static void	  fixuplabel(struct s_command *, const 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 	while (*p && isspace((unsigned char)*p))		\
149 		p++;						\
150 	} while (0)
151 
152 #define	EATSPACEN() do {					\
153 	while (*p && *p != '\n' && isspace((unsigned char)*p))  \
154 		p++;						\
155 	} while (0)
156 
157 static struct s_command **
158 compile_stream(struct s_command **link)
159 {
160 	const char *p;
161 	struct s_command *cmd, *cmd2, *stack;
162 	struct s_format *fp;
163 	char re[_POSIX2_LINE_MAX + 1];
164 	int naddr;				/* Number of addresses */
165 
166 	stack = NULL;
167 	for (;;) {
168 		if ((p = cu_fgets(NULL)) == NULL) {
169 			if (stack != NULL)
170 				errx(1, "%lu: %s: unexpected EOF (pending }'s)",
171 							linenum, fname);
172 			return (link);
173 		}
174 
175 semicolon:	EATSPACEN();
176 		switch (*p) {
177 		case '#': case '\0': case '\n':
178 			continue;	/* to next command-unit */
179 		case ';':
180 			p++;
181 			goto semicolon;
182 		}
183 
184 		if ((*link = cmd = malloc(sizeof(struct s_command))) == NULL)
185 			err(1, "malloc");
186 		link = &cmd->next;
187 		cmd->startline = cmd->nonsel = 0;
188 		/* First parse the addresses */
189 		naddr = 0;
190 
191 /* Valid characters to start an address */
192 #define	addrchar(c)	(strchr("0123456789/\\$", (c)))
193 		if (addrchar(*p)) {
194 			naddr++;
195 			if ((cmd->a1 = malloc(sizeof(struct s_addr))) == NULL)
196 				err(1, "malloc");
197 			p = compile_addr(p, cmd->a1);
198 			EATSPACE();				/* EXTENSION */
199 			if (*p == ',') {
200 				p++;
201 				EATSPACE();			/* EXTENSION */
202 				naddr++;
203 				if ((cmd->a2 = malloc(sizeof(struct s_addr)))
204 				    == NULL)
205 					err(1, "malloc");
206 				p = compile_addr(p, cmd->a2);
207 				EATSPACE();
208 			} else
209 				cmd->a2 = NULL;
210 		} else
211 			cmd->a1 = cmd->a2 = NULL;
212 
213 nonsel:		/* Now parse the command */
214 		if (*p == '\0' || *p == '\n')
215 			errx(1, "%lu: %s: command expected", linenum, fname);
216 		cmd->code = *p;
217 		for (fp = cmd_fmts; fp->code; fp++)
218 			if (fp->code == *p)
219 				break;
220 		if (!fp->code)
221 			errx(1, "%lu: %s: invalid command code %c (%s)", linenum, fname, *p, p);
222 		if (naddr > fp->naddr)
223 			errx(1,
224 				"%lu: %s: command %c expects up to %d address(es), found %d",
225 				linenum, fname, *p, fp->naddr, naddr);
226 		switch (fp->args) {
227 		case NONSEL:			/* ! */
228 			p++;
229 			EATSPACE();
230 			cmd->nonsel = 1;
231 			goto nonsel;
232 		case GROUP:			/* { */
233 			p++;
234 			EATSPACEN();
235 			cmd->next = stack;
236 			stack = cmd;
237 			link = &cmd->u.c;
238 			if (*p != '\0' && *p != '\n')
239 				goto semicolon;
240 			break;
241 		case ENDGROUP:
242 			/*
243 			 * Short-circuit command processing, since end of
244 			 * group is really just a noop.
245 			 */
246 			cmd->nonsel = 1;
247 			if (stack == NULL)
248 				errx(1, "%lu: %s: unexpected }", linenum, fname);
249 			cmd2 = stack;
250 			stack = cmd2->next;
251 			cmd2->next = cmd;
252 			/*FALLTHROUGH*/
253 		case EMPTY:		/* d D g G h H l n N p P q x = \0 */
254 			p++;
255 			EATSPACEN();
256 			if (*p == ';') {
257 				p++;
258 				link = &cmd->next;
259 				goto semicolon;
260 			}
261 			if (*p != '\0' && *p != '\n')
262 				errx(1, "%lu: %s: extra characters at the end of %c command",
263 						linenum, fname, cmd->code);
264 			break;
265 		case TEXT:			/* a c i */
266 			p++;
267 			EATSPACE();
268 			if (*p != '\\')
269 				errx(1,
270 "%lu: %s: command %c expects \\ followed by text", linenum, fname, cmd->code);
271 			p++;
272 			EATSPACEN();
273 			if (*p != '\n')
274 				errx(1,
275 				"%lu: %s: extra characters (%c) after \\ at the end of %c command",
276 				linenum, fname, *p, cmd->code);
277 			cmd->t = compile_text(&cmd->tlen);
278 			break;
279 		case COMMENT:			/* \0 # */
280 			break;
281 		case WFILE:			/* w */
282 			p++;
283 			EATSPACE();
284 			if (*p == '\0')
285 				errx(1, "%lu: %s: filename expected", linenum, fname);
286 			cmd->t = duptoeol(p, "w command", &cmd->tlen);
287 			if (aflag)
288 				cmd->u.fd = -1;
289 			else if ((cmd->u.fd = open(cmd->t,
290 			    O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
291 			    DEFFILEMODE)) == -1)
292 				err(1, "%s", p);
293 			break;
294 		case RFILE:			/* r */
295 			p++;
296 			EATSPACE();
297 			if (*p == '\0')
298 				errx(1, "%lu: %s: filename expected", linenum, fname);
299 			else
300 				cmd->t = duptoeol(p, "read command", &cmd->tlen);
301 			break;
302 		case BRANCH:			/* b t */
303 			p++;
304 			EATSPACEN();
305 			if (*p == '\0' || *p == '\n')
306 				cmd->t = NULL;
307 			else
308 				cmd->t = duptoeol(p, "branch", &cmd->tlen);
309 			break;
310 		case LABEL:			/* : */
311 			p++;
312 			EATSPACE();
313 			cmd->t = duptoeol(p, "label", &cmd->tlen);
314 			if (cmd->t[0] == '\0')
315 				errx(1, "%lu: %s: empty label", linenum, fname);
316 			enterlabel(cmd);
317 			break;
318 		case SUBST:			/* s */
319 			p++;
320 			if (*p == '\0' || *p == '\\' || *p == '\n')
321 				errx(1,
322 "%lu: %s: substitute pattern can not be delimited by newline or backslash",
323 					linenum, fname);
324 			if ((cmd->u.s = calloc(1, sizeof(struct s_subst))) == NULL)
325 				err(1, "malloc");
326 			p = compile_delimited(p, re, 0);
327 			if (p == NULL)
328 				errx(1,
329 				"%lu: %s: unterminated substitute pattern", linenum, fname);
330 
331 			--p;
332 			p = compile_subst(p, cmd->u.s);
333 			p = compile_flags(p, cmd->u.s);
334 
335 			if (*re != '\0')
336 				cmd->u.s->re = compile_re(re, cmd->u.s->icase);
337 
338 			EATSPACE();
339 
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 delimiter 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 const char *
373 compile_delimited(const char *p, char *d, int is_tr)
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 == '[' && *p != c) {
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 			if (is_tr)
401 				p++;
402 			else
403 				*d++ = *p++;
404 		} else if (*p == c) {
405 			*d = '\0';
406 			return (p + 1);
407 		}
408 		*d++ = *p++;
409 	}
410 	return (NULL);
411 }
412 
413 
414 /* compile_ccl: expand a POSIX character class */
415 static char *
416 compile_ccl(const char **sp, char *t)
417 {
418 	int c, d;
419 	const char *s = *sp;
420 
421 	*t++ = *s++;
422 	if (*s == '^')
423 		*t++ = *s++;
424 	if (*s == ']')
425 		*t++ = *s++;
426 	for (; *s && (*t = *s) != ']'; s++, t++)
427 		if (*s == '[' && ((d = *(s+1)) == '.' || d == ':' || d == '=')) {
428 			*++t = *++s, t++, s++;
429 			for (c = *s; (*t = *s) != ']' || c != d; s++, t++)
430 				if ((c = *s) == '\0')
431 					return NULL;
432 		}
433 	return (*s == ']') ? *sp = ++s, ++t : NULL;
434 }
435 
436 /*
437  * Compiles the regular expression in RE and returns a pointer to the compiled
438  * regular expression.
439  * Cflags are passed to regcomp.
440  */
441 static const regex_t *
442 compile_re(const char *re, int case_insensitive)
443 {
444 	regex_t *rep;
445 	int eval, flags;
446 
447 
448 	flags = rflags;
449 	if (case_insensitive)
450 		flags |= REG_ICASE;
451 	if ((rep = malloc(sizeof(regex_t))) == NULL)
452 		err(1, "malloc");
453 	if ((eval = regcomp(rep, re, flags)) != 0)
454 		errx(1, "%lu: %s: RE error: %s",
455 				linenum, fname, strregerror(eval, rep));
456 	if (maxnsub < rep->re_nsub)
457 		maxnsub = rep->re_nsub;
458 	return (rep);
459 }
460 
461 /*
462  * Compile the substitution string of a regular expression and set res to
463  * point to a saved copy of it.  Nsub is the number of parenthesized regular
464  * expressions.
465  */
466 static const char *
467 compile_subst(const char *p, struct s_subst *s)
468 {
469 	int asize, size;
470 	u_char ref;
471 	char c, *text, *op, *sp;
472 	int more = 0, sawesc = 0;
473 
474 	c = *p++;			/* Terminator character */
475 	if (c == '\0')
476 		return (NULL);
477 
478 	s->maxbref = 0;
479 	s->linenum = linenum;
480 	asize = 2 * _POSIX2_LINE_MAX + 1;
481 	if ((text = malloc(asize)) == NULL)
482 		err(1, "malloc");
483 	size = 0;
484 	do {
485 		op = sp = text + size;
486 		for (; *p != '\0' && *p != '\n'; p++) {
487 			if (*p == '\\' || sawesc) {
488 				/*
489 				 * If this is a continuation from the last
490 				 * buffer, we won't have a character to
491 				 * skip over.
492 				 */
493 				if (sawesc)
494 					sawesc = 0;
495 				else
496 					p++;
497 
498 				if (*p == '\0') {
499 					/*
500 					 * This escaped character is continued
501 					 * in the next part of the line.  Note
502 					 * this fact, then cause the loop to
503 					 * exit w/ normal EOL case and reenter
504 					 * above with the new buffer.
505 					 */
506 					sawesc = 1;
507 					p--;
508 					break;
509 				} else if (*p == '\n') {
510 					*sp++ = '\n';
511 					break;
512 				} else if (strchr("123456789", *p) != NULL) {
513 					*sp++ = '\\';
514 					ref = *p - '0';
515 					if (s->re != NULL &&
516 					    ref > s->re->re_nsub)
517 						errx(1, "%lu: %s: \\%c not defined in the RE",
518 								linenum, fname, *p);
519 					if (s->maxbref < ref)
520 						s->maxbref = ref;
521 				} else if (*p == '&' || *p == '\\')
522 					*sp++ = '\\';
523 			} else if (*p == c) {
524 				if (*++p == '\0' && more) {
525 					const char *nextp;
526 
527 					nextp = cu_fgets(&more);
528 					if (nextp != NULL)
529 						p = nextp;
530 				}
531 				*sp++ = '\0';
532 				size += sp - op;
533 				if ((s->new = realloc(text, size)) == NULL)
534 					err(1, "realloc");
535 				return (p);
536 			} else if (*p == '\n') {
537 				errx(1,
538 "%lu: %s: unescaped newline inside substitute pattern", linenum, fname);
539 				/* NOTREACHED */
540 			}
541 			*sp++ = *p;
542 		}
543 		size += sp - op;
544 		if (asize - size < _POSIX2_LINE_MAX + 1) {
545 			asize *= 2;
546 			if ((text = realloc(text, asize)) == NULL)
547 				err(1, "realloc");
548 		}
549 	} while ((p = cu_fgets(&more)));
550 	errx(1, "%lu: %s: unterminated substitute in regular expression",
551 			linenum, fname);
552 	/* NOTREACHED */
553 }
554 
555 /*
556  * Compile the flags of the s command
557  */
558 static const char *
559 compile_flags(const char *p, struct s_subst *s)
560 {
561 	int gn;			/* True if we have seen g or n */
562 	unsigned long nval;
563 	char *q;
564 
565 	s->n = 1;				/* Default */
566 	s->p = 0;
567 	s->wfile = NULL;
568 	s->wfd = -1;
569 	s->icase = 0;
570 	for (gn = 0;;) {
571 		EATSPACEN();			/* EXTENSION */
572 		switch (*p) {
573 		case 'g':
574 			if (gn)
575 				errx(1,
576 "%lu: %s: more than one number or 'g' in substitute flags", linenum, fname);
577 			gn = 1;
578 			s->n = 0;
579 			break;
580 		case '\0':
581 		case '\n':
582 		case ';':
583 			return (p);
584 		case 'p':
585 			s->p = 1;
586 			break;
587 		case 'i':
588 		case 'I':
589 			s->icase = 1;
590 			break;
591 		case '1': case '2': case '3':
592 		case '4': case '5': case '6':
593 		case '7': case '8': case '9':
594 			if (gn)
595 				errx(1,
596 "%lu: %s: more than one number or 'g' in substitute flags", linenum, fname);
597 			gn = 1;
598 			errno = 0;
599 			nval = strtol(p, &q, 10);
600 			if (errno == ERANGE || nval > INT_MAX)
601 				errx(1,
602 "%lu: %s: overflow in the 'N' substitute flag", linenum, fname);
603 			s->n = nval;
604 			p = q;
605 			continue;
606 		case 'w':
607 			p++;
608 #ifdef HISTORIC_PRACTICE
609 			if (*p != ' ') {
610 				warnx("%lu: %s: space missing before w wfile", linenum, fname);
611 				return (p);
612 			}
613 #endif
614 			EATSPACE();
615 			s->wfile = duptoeol(p, "w flag", NULL);
616 			if (!aflag && (s->wfd = open(s->wfile,
617 			    O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
618 			    DEFFILEMODE)) == -1)
619 				err(1, "%s", s->wfile);
620 			return (p);
621 		default:
622 			errx(1, "%lu: %s: bad flag in substitute command: '%c' (%.10s)",
623 					linenum, fname, *p, p);
624 			break;
625 		}
626 		p++;
627 	}
628 }
629 
630 /*
631  * Compile a translation set of strings into a lookup table.
632  */
633 static const char *
634 compile_tr(const 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, "malloc");
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, 1);
654 	if (p == NULL)
655 		errx(1, "%lu: %s: unterminated transform source string",
656 				linenum, fname);
657 	p = compile_delimited(p - 1, new, 1);
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, "mbsrtowcs");
666 	np = new;
667 	newlen = mbsrtowcs(NULL, &np, 0, NULL);
668 	if (newlen == (size_t)-1)
669 		err(1, "mbsrtowcs");
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, "realloc");
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, c, or i command.
724  */
725 static char *
726 compile_text(size_t *ptlen)
727 {
728 	int asize, esc_nl, size;
729 	char *text, *s;
730 	const char *p, *op;
731 
732 	asize = 2 * _POSIX2_LINE_MAX + 1;
733 	if ((text = malloc(asize)) == NULL)
734 		err(1, "malloc");
735 	size = 0;
736 	while ((p = cu_fgets(NULL))) {
737 		op = s = text + size;
738 		for (esc_nl = 0; *p != '\0'; p++) {
739 			if (*p == '\\' && p[1] != '\0' && *++p == '\n')
740 				esc_nl = 1;
741 			*s++ = *p;
742 			if (*p == '\n')
743 				break;
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 ((text = realloc(text, size + 1)) == NULL)
758 		err(1, "realloc");
759 	*ptlen = size;
760 	return (text);
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 const char *
768 compile_addr(const 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, 0);
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(const char *s, const char *ctype, size_t *ptlen)
823 {
824 	size_t len;
825 	int ws;
826 	char *p;
827 	const char *start;
828 
829 	ws = 0;
830 	for (start = s; *s != '\0' && *s != '\n'; ++s)
831 		ws = isspace((unsigned char)*s);
832 	if (ws)
833 		warnx("%lu: %s: whitespace after %s", linenum, fname, ctype);
834 	len = s - start;
835 	if ((p = malloc(len + 1)) == NULL)
836 		err(1, "malloc");
837 	memmove(p, start, len);
838 	p[len] = '\0';
839 	if (ptlen != NULL)
840 		*ptlen = len;
841 	return p;
842 }
843 
844 /*
845  * Convert goto label names to addresses, and count a and r commands, in
846  * the given subset of the script.  Free the memory used by labels in b
847  * and t commands (but not by :).
848  *
849  * TODO: Remove } nodes
850  */
851 static void
852 fixuplabel(struct s_command *cp, const struct s_command *end)
853 {
854 
855 	for (; cp != end; cp = cp->next)
856 		switch (cp->code) {
857 		case 'a':
858 		case 'r':
859 			appendnum++;
860 			break;
861 		case 'b':
862 		case 't':
863 			/* Resolve branch target. */
864 			if (cp->t == NULL) {
865 				cp->u.c = NULL;
866 				break;
867 			}
868 			if ((cp->u.c = findlabel(cp->t)) == NULL)
869 				errx(1, "%lu: %s: %c: undefined label '%s'", linenum, fname, cp->code, cp->t);
870 			free(cp->t);
871 			break;
872 		case '{':
873 			/* Do interior commands. */
874 			fixuplabel(cp->u.c, cp->next);
875 			break;
876 		}
877 }
878 
879 /*
880  * Associate the given command label for later lookup.
881  */
882 static void
883 enterlabel(struct s_command *cp)
884 {
885 	struct labhash **lhp, *lh;
886 	u_char *p;
887 	u_int h, c;
888 
889 	for (h = 0, p = (u_char *)cp->t; (c = *p) != 0; p++)
890 		h = (h << 5) + h + c;
891 	lhp = &labels[h & LHMASK];
892 	for (lh = *lhp; lh != NULL; lh = lh->lh_next)
893 		if (lh->lh_hash == h && strcmp(cp->t, lh->lh_cmd->t) == 0)
894 			errx(1, "%lu: %s: duplicate label '%s'", linenum, fname, cp->t);
895 	if ((lh = malloc(sizeof *lh)) == NULL)
896 		err(1, "malloc");
897 	lh->lh_next = *lhp;
898 	lh->lh_hash = h;
899 	lh->lh_cmd = cp;
900 	lh->lh_ref = 0;
901 	*lhp = lh;
902 }
903 
904 /*
905  * Find the label contained in the command l in the command linked
906  * list cp.  L is excluded from the search.  Return NULL if not found.
907  */
908 static struct s_command *
909 findlabel(const char *name)
910 {
911 	struct labhash *lh;
912 	const u_char *p;
913 	u_int h, c;
914 
915 	for (h = 0, p = (const u_char *)name; (c = *p) != 0; p++)
916 		h = (h << 5) + h + c;
917 	for (lh = labels[h & LHMASK]; lh != NULL; lh = lh->lh_next) {
918 		if (lh->lh_hash == h && strcmp(name, lh->lh_cmd->t) == 0) {
919 			lh->lh_ref = 1;
920 			return (lh->lh_cmd);
921 		}
922 	}
923 	return (NULL);
924 }
925 
926 /*
927  * Warn about any unused labels.  As a side effect, release the label hash
928  * table space.
929  */
930 static void
931 uselabel(void)
932 {
933 	struct labhash *lh, *next;
934 	int i;
935 
936 	for (i = 0; i < LHSZ; i++) {
937 		for (lh = labels[i]; lh != NULL; lh = next) {
938 			next = lh->lh_next;
939 			if (!lh->lh_ref)
940 				warnx("%lu: %s: unused label '%s'",
941 				    linenum, fname, lh->lh_cmd->t);
942 			free(lh);
943 		}
944 	}
945 }
946