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