xref: /openbsd-src/usr.bin/sed/compile.c (revision 4c1e55dc91edd6e69ccc60ce855900fbc12cf34f)
1 /*	$OpenBSD: compile.c,v 1.34 2010/11/15 20:26:00 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 #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 = 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, int is_tr)
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 			if (is_tr)
374 				p++;
375 			else
376 				*d++ = *p++;
377 		} else if (*p == c) {
378 			*d = '\0';
379 			return (p + 1);
380 		}
381 		*d++ = *p++;
382 	}
383 	return (NULL);
384 }
385 
386 
387 /* compile_ccl: expand a POSIX character class */
388 static char *
389 compile_ccl(char **sp, char *t)
390 {
391 	int c, d;
392 	char *s = *sp;
393 
394 	*t++ = *s++;
395 	if (*s == '^')
396 		*t++ = *s++;
397 	if (*s == ']')
398 		*t++ = *s++;
399 	for (; *s && (*t = *s) != ']'; s++, t++)
400 		if (*s == '[' && ((d = *(s+1)) == '.' || d == ':' || d == '=')) {
401 			*++t = *++s, t++, s++;
402 			for (c = *s; (*t = *s) != ']' || c != d; s++, t++)
403 				if ((c = *s) == '\0')
404 					return NULL;
405 		} else if (*s == '\\' && s[1] == 'n') {
406 			*t = '\n';
407 			s++;
408 		}
409 	if (*s == ']') {
410 		*sp = ++s;
411 		return (++t);
412 	} else {
413 		return (NULL);
414 	}
415 }
416 
417 /*
418  * Get a regular expression.  P points to the delimiter of the regular
419  * expression; repp points to the address of a regexp pointer.  Newline
420  * and delimiter escapes are processed; other escapes are ignored.
421  * Returns a pointer to the first character after the final delimiter
422  * or NULL in the case of a non terminated regular expression.  The regexp
423  * pointer is set to the compiled regular expression.
424  * Cflags are passed to regcomp.
425  */
426 static char *
427 compile_re(char *p, regex_t **repp)
428 {
429 	int eval;
430 	char *re;
431 
432 	re = xmalloc(strlen(p) + 1); /* strlen(re) <= strlen(p) */
433 	p = compile_delimited(p, re, 0);
434 	if (p && strlen(re) == 0) {
435 		*repp = NULL;
436 		free(re);
437 		return (p);
438 	}
439 	*repp = xmalloc(sizeof(regex_t));
440 	if (p && (eval = regcomp(*repp, re, Eflag ? REG_EXTENDED : 0)) != 0)
441 		err(COMPILE, "RE error: %s", strregerror(eval, *repp));
442 	if (maxnsub < (*repp)->re_nsub)
443 		maxnsub = (*repp)->re_nsub;
444 	free(re);
445 	return (p);
446 }
447 
448 /*
449  * Compile the substitution string of a regular expression and set res to
450  * point to a saved copy of it.  Nsub is the number of parenthesized regular
451  * expressions.
452  */
453 static char *
454 compile_subst(char *p, struct s_subst *s)
455 {
456 	static char *lbuf;
457 	static size_t bufsize;
458 	int asize, ref, size;
459 	char c, *text, *op, *sp;
460 	int sawesc = 0;
461 
462 	c = *p++;			/* Terminator character */
463 	if (c == '\0')
464 		return (NULL);
465 
466 	s->maxbref = 0;
467 	s->linenum = linenum;
468 	text = NULL;
469 	asize = size = 0;
470 	do {
471 		size_t len = ROUNDLEN(strlen(p) + 1);
472 		if (asize - size < len) {
473 			do {
474 				asize += len;
475 			} while (asize - size < len);
476 			text = xrealloc(text, asize);
477 		}
478 		op = sp = text + size;
479 		for (; *p; p++) {
480 			if (*p == '\\' || sawesc) {
481 				/*
482 				 * If this is a continuation from the last
483 				 * buffer, we won't have a character to
484 				 * skip over.
485 				 */
486 				if (sawesc)
487 					sawesc = 0;
488 				else
489 					p++;
490 
491 				if (*p == '\0') {
492 					/*
493 					 * This escaped character is continued
494 					 * in the next part of the line.  Note
495 					 * this fact, then cause the loop to
496 					 * exit w/ normal EOL case and reenter
497 					 * above with the new buffer.
498 					 */
499 					sawesc = 1;
500 					p--;
501 					continue;
502 				} else if (strchr("123456789", *p) != NULL) {
503 					*sp++ = '\\';
504 					ref = *p - '0';
505 					if (s->re != NULL &&
506 					    ref > s->re->re_nsub)
507 						err(COMPILE,
508 "\\%c not defined in the RE", *p);
509 					if (s->maxbref < ref)
510 						s->maxbref = ref;
511 				} else if (*p == '&' || *p == '\\')
512 					*sp++ = '\\';
513 			} else if (*p == c) {
514 				p++;
515 				*sp++ = '\0';
516 				size += sp - op;
517 				s->new = xrealloc(text, size);
518 				return (p);
519 			} else if (*p == '\n') {
520 				err(COMPILE,
521 "unescaped newline inside substitute pattern");
522 				/* NOTREACHED */
523 			}
524 			*sp++ = *p;
525 		}
526 		size += sp - op;
527 	} while ((p = cu_fgets(&lbuf, &bufsize)));
528 	err(COMPILE, "unterminated substitute in regular expression");
529 	/* NOTREACHED */
530 }
531 
532 /*
533  * Compile the flags of the s command
534  */
535 static char *
536 compile_flags(char *p, struct s_subst *s)
537 {
538 	int gn;			/* True if we have seen g or n */
539 	long l;
540 	char wfile[PATH_MAX], *q;
541 
542 	s->n = 1;				/* Default */
543 	s->p = 0;
544 	s->wfile = NULL;
545 	s->wfd = -1;
546 	for (gn = 0;;) {
547 		EATSPACE();			/* EXTENSION */
548 		switch (*p) {
549 		case 'g':
550 			if (gn)
551 				err(COMPILE, "more than one number or 'g' in"
552 				    " substitute flags");
553 			gn = 1;
554 			s->n = 0;
555 			break;
556 		case '\0':
557 		case '\n':
558 		case ';':
559 			return (p);
560 		case 'p':
561 			s->p = 1;
562 			break;
563 		case '1': case '2': case '3':
564 		case '4': case '5': case '6':
565 		case '7': case '8': case '9':
566 			if (gn)
567 				err(COMPILE, "more than one number or 'g' in"
568 				    " substitute flags");
569 			gn = 1;
570 			l = strtol(p, &p, 10);
571 			if (l <= 0 || l >= INT_MAX)
572 				err(COMPILE,
573 				    "number in substitute flags out of range");
574 			s->n = (int)l;
575 			continue;
576 		case 'w':
577 			p++;
578 #ifdef HISTORIC_PRACTICE
579 			if (*p != ' ') {
580 				err(WARNING, "space missing before w wfile");
581 				return (p);
582 			}
583 #endif
584 			EATSPACE();
585 			q = wfile;
586 			while (*p) {
587 				if (*p == '\n')
588 					break;
589 				*q++ = *p++;
590 			}
591 			*q = '\0';
592 			if (q == wfile)
593 				err(COMPILE, "no wfile specified");
594 			s->wfile = strdup(wfile);
595 			if (!aflag && (s->wfd = open(wfile,
596 			    O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
597 			    DEFFILEMODE)) == -1)
598 				err(FATAL, "%s: %s", wfile, strerror(errno));
599 			return (p);
600 		default:
601 			err(COMPILE,
602 			    "bad flag in substitute command: '%c'", *p);
603 			break;
604 		}
605 		p++;
606 	}
607 }
608 
609 /*
610  * Compile a translation set of strings into a lookup table.
611  */
612 static char *
613 compile_tr(char *p, char **transtab)
614 {
615 	int i;
616 	char *lt, *op, *np;
617 	char *old = NULL, *new = NULL;
618 
619 	if (*p == '\0' || *p == '\\')
620 		err(COMPILE,
621 "transform pattern can not be delimited by newline or backslash");
622 	old = xmalloc(strlen(p) + 1);
623 	p = compile_delimited(p, old, 1);
624 	if (p == NULL) {
625 		err(COMPILE, "unterminated transform source string");
626 		goto bad;
627 	}
628 	new = xmalloc(strlen(p) + 1);
629 	p = compile_delimited(--p, new, 1);
630 	if (p == NULL) {
631 		err(COMPILE, "unterminated transform target string");
632 		goto bad;
633 	}
634 	EATSPACE();
635 	if (strlen(new) != strlen(old)) {
636 		err(COMPILE, "transform strings are not the same length");
637 		goto bad;
638 	}
639 	/* We assume characters are 8 bits */
640 	lt = xmalloc(UCHAR_MAX + 1);
641 	for (i = 0; i <= UCHAR_MAX; i++)
642 		lt[i] = (char)i;
643 	for (op = old, np = new; *op; op++, np++)
644 		lt[(u_char)*op] = *np;
645 	*transtab = lt;
646 	free(old);
647 	free(new);
648 	return (p);
649 bad:
650 	free(old);
651 	free(new);
652 	return (NULL);
653 }
654 
655 /*
656  * Compile the text following an a, c, or i command.
657  */
658 static char *
659 compile_text(void)
660 {
661 	int asize, esc_nl, size;
662 	char *lbuf, *text, *p, *op, *s;
663 	size_t bufsize;
664 
665 	lbuf = text = NULL;
666 	asize = size = 0;
667 	while ((p = cu_fgets(&lbuf, &bufsize))) {
668 		size_t len = ROUNDLEN(strlen(p) + 1);
669 		if (asize - size < len) {
670 			do {
671 				asize += len;
672 			} while (asize - size < len);
673 			text = xrealloc(text, asize);
674 		}
675 		op = s = text + size;
676 		for (esc_nl = 0; *p != '\0'; p++) {
677 			if (*p == '\\' && p[1] != '\0' && *++p == '\n')
678 				esc_nl = 1;
679 			*s++ = *p;
680 		}
681 		size += s - op;
682 		if (!esc_nl) {
683 			*s = '\0';
684 			break;
685 		}
686 	}
687 	free(lbuf);
688 	text = xrealloc(text, size + 1);
689 	text[size] = '\0';
690 	return (text);
691 }
692 
693 /*
694  * Get an address and return a pointer to the first character after
695  * it.  Fill the structure pointed to according to the address.
696  */
697 static char *
698 compile_addr(char *p, struct s_addr *a)
699 {
700 	char *end;
701 
702 	switch (*p) {
703 	case '\\':				/* Context address */
704 		++p;
705 		/* FALLTHROUGH */
706 	case '/':				/* Context address */
707 		p = compile_re(p, &a->u.r);
708 		if (p == NULL)
709 			err(COMPILE, "unterminated regular expression");
710 		a->type = AT_RE;
711 		return (p);
712 
713 	case '$':				/* Last line */
714 		a->type = AT_LAST;
715 		return (p + 1);
716 						/* Line number */
717 	case '0': case '1': case '2': case '3': case '4':
718 	case '5': case '6': case '7': case '8': case '9':
719 		a->type = AT_LINE;
720 		a->u.l = strtoul(p, &end, 10);
721 		return (end);
722 	default:
723 		err(COMPILE, "expected context address");
724 		return (NULL);
725 	}
726 }
727 
728 /*
729  * duptoeol --
730  *	Return a copy of all the characters up to \n or \0.
731  */
732 static char *
733 duptoeol(char *s, char *ctype, char **semi)
734 {
735 	size_t len;
736 	int ws;
737 	char *start;
738 
739 	ws = 0;
740 	if (semi) {
741 		for (start = s; *s != '\0' && *s != '\n' && *s != ';'; ++s)
742 			ws = isspace(*s);
743 	} else {
744 		for (start = s; *s != '\0' && *s != '\n'; ++s)
745 			ws = isspace(*s);
746 		*s = '\0';
747 	}
748 	if (ws)
749 		err(WARNING, "whitespace after %s", ctype);
750 	len = s - start + 1;
751 	if (semi)
752 		*semi = s;
753 	s = xmalloc(len);
754 	strlcpy(s, start, len);
755 	return (s);
756 }
757 
758 /*
759  * Convert goto label names to addresses, and count a and r commands, in
760  * the given subset of the script.  Free the memory used by labels in b
761  * and t commands (but not by :).
762  *
763  * TODO: Remove } nodes
764  */
765 static void
766 fixuplabel(struct s_command *cp, struct s_command *end)
767 {
768 
769 	for (; cp != end; cp = cp->next)
770 		switch (cp->code) {
771 		case 'a':
772 		case 'r':
773 			appendnum++;
774 			break;
775 		case 'b':
776 		case 't':
777 			/* Resolve branch target. */
778 			if (cp->t == NULL) {
779 				cp->u.c = NULL;
780 				break;
781 			}
782 			if ((cp->u.c = findlabel(cp->t)) == NULL)
783 				err(COMPILE2, "undefined label '%s'", cp->t);
784 			free(cp->t);
785 			break;
786 		case '{':
787 			/* Do interior commands. */
788 			fixuplabel(cp->u.c, cp->next);
789 			break;
790 		}
791 }
792 
793 /*
794  * Associate the given command label for later lookup.
795  */
796 static void
797 enterlabel(struct s_command *cp)
798 {
799 	struct labhash **lhp, *lh;
800 	u_char *p;
801 	u_int h, c;
802 
803 	for (h = 0, p = (u_char *)cp->t; (c = *p) != 0; p++)
804 		h = (h << 5) + h + c;
805 	lhp = &labels[h & LHMASK];
806 	for (lh = *lhp; lh != NULL; lh = lh->lh_next)
807 		if (lh->lh_hash == h && strcmp(cp->t, lh->lh_cmd->t) == 0)
808 			err(COMPILE2, "duplicate label '%s'", cp->t);
809 	lh = xmalloc(sizeof *lh);
810 	lh->lh_next = *lhp;
811 	lh->lh_hash = h;
812 	lh->lh_cmd = cp;
813 	lh->lh_ref = 0;
814 	*lhp = lh;
815 }
816 
817 /*
818  * Find the label contained in the command l in the command linked
819  * list cp.  L is excluded from the search.  Return NULL if not found.
820  */
821 static struct s_command *
822 findlabel(char *name)
823 {
824 	struct labhash *lh;
825 	u_char *p;
826 	u_int h, c;
827 
828 	for (h = 0, p = (u_char *)name; (c = *p) != 0; p++)
829 		h = (h << 5) + h + c;
830 	for (lh = labels[h & LHMASK]; lh != NULL; lh = lh->lh_next) {
831 		if (lh->lh_hash == h && strcmp(name, lh->lh_cmd->t) == 0) {
832 			lh->lh_ref = 1;
833 			return (lh->lh_cmd);
834 		}
835 	}
836 	return (NULL);
837 }
838 
839 /*
840  * Warn about any unused labels.  As a side effect, release the label hash
841  * table space.
842  */
843 static void
844 uselabel(void)
845 {
846 	struct labhash *lh, *next;
847 	int i;
848 
849 	for (i = 0; i < LHSZ; i++) {
850 		for (lh = labels[i]; lh != NULL; lh = next) {
851 			next = lh->lh_next;
852 			if (!lh->lh_ref)
853 				err(WARNING, "unused label '%s'",
854 				    lh->lh_cmd->t);
855 			free(lh);
856 		}
857 	}
858 }
859