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