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