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