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