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