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