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