xref: /minix/usr.bin/sed/compile.c (revision 0a6a1f1d)
1 /*	$NetBSD: compile.c,v 1.46 2015/03/12 12:40:41 christos 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 #if HAVE_NBTOOL_CONFIG_H
37 #include "nbtool_config.h"
38 #endif
39 
40 #include <sys/cdefs.h>
41 __RCSID("$NetBSD: compile.c,v 1.46 2015/03/12 12:40:41 christos Exp $");
42 #ifdef __FBSDID
43 __FBSDID("$FreeBSD: head/usr.bin/sed/compile.c 259132 2013-12-09 18:57:20Z eadler $");
44 #endif
45 
46 #if 0
47 static const char sccsid[] = "@(#)compile.c	8.1 (Berkeley) 6/6/93";
48 #endif
49 
50 #include <sys/types.h>
51 #include <sys/stat.h>
52 
53 #include <ctype.h>
54 #include <err.h>
55 #include <errno.h>
56 #include <fcntl.h>
57 #include <limits.h>
58 #include <regex.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <wchar.h>
63 
64 #include "defs.h"
65 #include "extern.h"
66 
67 #define LHSZ	128
68 #define	LHMASK	(LHSZ - 1)
69 static struct labhash {
70 	struct	labhash *lh_next;
71 	u_int	lh_hash;
72 	struct	s_command *lh_cmd;
73 	int	lh_ref;
74 } *labels[LHSZ];
75 
76 static char	 *compile_addr(char *, struct s_addr *);
77 static char	 *compile_ccl(char **, char *);
78 static char	 *compile_delimited(char *, char *, int);
79 static char	 *compile_flags(char *, struct s_subst *);
80 static regex_t	 *compile_re(char *, int);
81 static char	 *compile_subst(char *, struct s_subst *);
82 static char	 *compile_text(void);
83 static char	 *compile_tr(char *, struct s_tr **);
84 static struct s_command
85 		**compile_stream(struct s_command **);
86 static char	 *duptoeol(char *, const char *);
87 static void	  enterlabel(struct s_command *);
88 static struct s_command
89 		 *findlabel(char *);
90 static void	  fixuplabel(struct s_command *, struct s_command *);
91 static void	  uselabel(void);
92 
93 /*
94  * Command specification.  This is used to drive the command parser.
95  */
96 struct s_format {
97 	char code;				/* Command code */
98 	int naddr;				/* Number of address args */
99 	enum e_args args;			/* Argument type */
100 };
101 
102 static struct s_format cmd_fmts[] = {
103 	{'{', 2, GROUP},
104 	{'}', 0, ENDGROUP},
105 	{'a', 1, TEXT},
106 	{'b', 2, BRANCH},
107 	{'c', 2, TEXT},
108 	{'d', 2, EMPTY},
109 	{'D', 2, EMPTY},
110 	{'g', 2, EMPTY},
111 	{'G', 2, EMPTY},
112 	{'h', 2, EMPTY},
113 	{'H', 2, EMPTY},
114 	{'i', 1, TEXT},
115 	{'l', 2, EMPTY},
116 	{'n', 2, EMPTY},
117 	{'N', 2, EMPTY},
118 	{'p', 2, EMPTY},
119 	{'P', 2, EMPTY},
120 	{'q', 1, EMPTY},
121 	{'r', 1, RFILE},
122 	{'s', 2, SUBST},
123 	{'t', 2, BRANCH},
124 	{'w', 2, WFILE},
125 	{'x', 2, EMPTY},
126 	{'y', 2, TR},
127 	{'!', 2, NONSEL},
128 	{':', 0, LABEL},
129 	{'#', 0, COMMENT},
130 	{'=', 1, EMPTY},
131 	{'\0', 0, COMMENT},
132 };
133 
134 /* The compiled program. */
135 struct s_command *prog;
136 
137 /*
138  * Compile the program into prog.
139  * Initialise appends.
140  */
141 void
compile(void)142 compile(void)
143 {
144 	*compile_stream(&prog) = NULL;
145 	fixuplabel(prog, NULL);
146 	uselabel();
147 	if (appendnum > 0)
148 		appends = xmalloc(sizeof(struct s_appends) * appendnum);
149 	match = xmalloc((maxnsub + 1) * sizeof(regmatch_t));
150 }
151 
152 #define EATSPACE() do {							\
153 	if (p)								\
154 		while (*p && isspace((unsigned char)*p))                \
155 			p++;						\
156 	} while (0)
157 
158 static struct s_command **
compile_stream(struct s_command ** link)159 compile_stream(struct s_command **link)
160 {
161 	char *p;
162 	static char lbuf[_POSIX2_LINE_MAX + 1];	/* To save stack */
163 	struct s_command *cmd, *cmd2, *stack;
164 	struct s_format *fp;
165 	char re[_POSIX2_LINE_MAX + 1];
166 	int naddr;				/* Number of addresses */
167 
168 	stack = 0;
169 	for (;;) {
170 		if ((p = cu_fgets(lbuf, sizeof(lbuf), NULL)) == NULL) {
171 			if (stack != 0)
172 				errx(1, "%lu: %s: unexpected EOF (pending }'s)",
173 							linenum, fname);
174 			return (link);
175 		}
176 
177 semicolon:	EATSPACE();
178 		if (p) {
179 			if (*p == '#' || *p == '\0')
180 				continue;
181 			else if (*p == ';') {
182 				p++;
183 				goto semicolon;
184 			}
185 		}
186 		*link = cmd = xmalloc(sizeof(struct s_command));
187 		link = &cmd->next;
188 		cmd->startline = cmd->nonsel = 0;
189 		/* First parse the addresses */
190 		naddr = 0;
191 
192 /* Valid characters to start an address */
193 #define	addrchar(c)	(strchr("0123456789/\\$", (c)))
194 		if (addrchar(*p)) {
195 			naddr++;
196 			cmd->a1 = xmalloc(sizeof(struct s_addr));
197 			p = compile_addr(p, cmd->a1);
198 			EATSPACE();				/* EXTENSION */
199 			if (*p == ',') {
200 				p++;
201 				EATSPACE();			/* EXTENSION */
202 				naddr++;
203 				cmd->a2 = xmalloc(sizeof(struct s_addr));
204 				p = compile_addr(p, cmd->a2);
205 				EATSPACE();
206 			} else
207 				cmd->a2 = 0;
208 		} else
209 			cmd->a1 = cmd->a2 = 0;
210 
211 nonsel:		/* Now parse the command */
212 		if (!*p)
213 			errx(1, "%lu: %s: command expected", linenum, fname);
214 		cmd->code = *p;
215 		for (fp = cmd_fmts; fp->code; fp++)
216 			if (fp->code == *p)
217 				break;
218 		if (!fp->code)
219 			errx(1, "%lu: %s: invalid command code %c", linenum, fname, *p);
220 		if (naddr > fp->naddr)
221 			errx(1,
222 				"%lu: %s: command %c expects up to %d address(es), found %d",
223 				linenum, fname, *p, fp->naddr, naddr);
224 		switch (fp->args) {
225 		case NONSEL:			/* ! */
226 			p++;
227 			EATSPACE();
228 			cmd->nonsel = ! cmd->nonsel;
229 			goto nonsel;
230 		case GROUP:			/* { */
231 			p++;
232 			EATSPACE();
233 			cmd->next = stack;
234 			stack = cmd;
235 			link = &cmd->u.c;
236 			if (*p)
237 				goto semicolon;
238 			break;
239 		case ENDGROUP:
240 			/*
241 			 * Short-circuit command processing, since end of
242 			 * group is really just a noop.
243 			 */
244 			cmd->nonsel = 1;
245 			if (stack == 0)
246 				errx(1, "%lu: %s: unexpected }", linenum, fname);
247 			cmd2 = stack;
248 			stack = cmd2->next;
249 			cmd2->next = cmd;
250 			/*FALLTHROUGH*/
251 		case EMPTY:		/* d D g G h H l n N p P q x = \0 */
252 			p++;
253 			EATSPACE();
254 			switch (*p) {
255 			case ';':
256 				p++;
257 				link = &cmd->next;
258 				goto semicolon;
259 			case '}':
260 				goto semicolon;
261 			case '\0':
262 				break;
263 			default:
264 				errx(1, "%lu: %s: extra characters at the end of %c command",
265 						linenum, fname, cmd->code);
266 			}
267 			break;
268 		case TEXT:			/* a c i */
269 			p++;
270 			EATSPACE();
271 			if (*p != '\\')
272 				errx(1,
273 "%lu: %s: command %c expects \\ followed by text", linenum, fname, cmd->code);
274 			p++;
275 			EATSPACE();
276 			if (*p)
277 				errx(1,
278 				"%lu: %s: extra characters after \\ at the end of %c command",
279 				linenum, fname, cmd->code);
280 			cmd->t = compile_text();
281 			break;
282 		case COMMENT:			/* \0 # */
283 			break;
284 		case WFILE:			/* w */
285 			p++;
286 			EATSPACE();
287 			if (*p == '\0')
288 				errx(1, "%lu: %s: filename expected", linenum, fname);
289 			cmd->t = duptoeol(p, "w command");
290 			if (aflag)
291 				cmd->u.fd = -1;
292 			else if ((cmd->u.fd = open(p,
293 			    O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
294 			    DEFFILEMODE)) == -1)
295 				err(1, "%s", p);
296 			break;
297 		case RFILE:			/* r */
298 			p++;
299 			EATSPACE();
300 			if (*p == '\0')
301 				errx(1, "%lu: %s: filename expected", linenum, fname);
302 			else
303 				cmd->t = duptoeol(p, "read command");
304 			break;
305 		case BRANCH:			/* b t */
306 			p++;
307 			EATSPACE();
308 			if (*p == '\0')
309 				cmd->t = NULL;
310 			else
311 				cmd->t = duptoeol(p, "branch");
312 			break;
313 		case LABEL:			/* : */
314 			p++;
315 			EATSPACE();
316 			cmd->t = duptoeol(p, "label");
317 			if (strlen(p) == 0)
318 				errx(1, "%lu: %s: empty label", linenum, fname);
319 			enterlabel(cmd);
320 			break;
321 		case SUBST:			/* s */
322 			p++;
323 			if (*p == '\0' || *p == '\\')
324 				errx(1,
325 "%lu: %s: substitute pattern can not be delimited by newline or backslash",
326 					linenum, fname);
327 			cmd->u.s = xcalloc(1, sizeof(struct s_subst));
328 			p = compile_delimited(p, re, 0);
329 			if (p == NULL)
330 				errx(1,
331 				"%lu: %s: unterminated substitute pattern", linenum, fname);
332 
333 			/* Compile RE with no case sensitivity temporarily */
334 			if (*re == '\0')
335 				cmd->u.s->re = NULL;
336 			else
337 				cmd->u.s->re = compile_re(re, 0);
338 			--p;
339 			p = compile_subst(p, cmd->u.s);
340 			p = compile_flags(p, cmd->u.s);
341 
342 			/* Recompile RE with case sensitivity from "I" flag if any */
343 			if (*re == '\0')
344 				cmd->u.s->re = NULL;
345 			else
346 				cmd->u.s->re = compile_re(re, cmd->u.s->icase);
347 			EATSPACE();
348 			if (*p == ';') {
349 				p++;
350 				link = &cmd->next;
351 				goto semicolon;
352 			}
353 			break;
354 		case TR:			/* y */
355 			p++;
356 			p = compile_tr(p, &cmd->u.y);
357 			EATSPACE();
358 			switch (*p) {
359 			case ';':
360 				p++;
361 				link = &cmd->next;
362 				goto semicolon;
363 			case '}':
364 				goto semicolon;
365 			case '\0':
366 				break;
367 			default:
368 				errx(1,
369 "%lu: %s: extra text at the end of a transform command", linenum, fname);
370 			}
371 			if (*p)
372 			break;
373 		}
374 	}
375 }
376 
377 /*
378  * Get a delimited string.  P points to the delimeter of the string; d points
379  * to a buffer area.  Newline and delimiter escapes are processed; other
380  * escapes are ignored.
381  *
382  * Returns a pointer to the first character after the final delimiter or NULL
383  * in the case of a non-terminated string.  The character array d is filled
384  * with the processed string.
385  */
386 static char *
compile_delimited(char * p,char * d,int is_tr)387 compile_delimited(char *p, char *d, int is_tr)
388 {
389 	char c;
390 
391 	c = *p++;
392 	if (c == '\0')
393 		return (NULL);
394 	else if (c == '\\')
395 		errx(1, "%lu: %s: \\ can not be used as a string delimiter",
396 				linenum, fname);
397 	else if (c == '\n')
398 		errx(1, "%lu: %s: newline can not be used as a string delimiter",
399 				linenum, fname);
400 	while (*p) {
401 		if (*p == '[' && *p != c) {
402 			if ((d = compile_ccl(&p, d)) == NULL)
403 				errx(1, "%lu: %s: unbalanced brackets ([])", linenum, fname);
404 			continue;
405 		} else if (*p == '\\' && p[1] == '[') {
406 			*d++ = *p++;
407 		} else if (*p == '\\' && p[1] == c)
408 			p++;
409 		else if (*p == '\\' && p[1] == 'n') {
410 			*d++ = '\n';
411 			p += 2;
412 			continue;
413 		} else if (*p == '\\' && p[1] == '\\') {
414 			if (is_tr)
415 				p++;
416 			else
417 				*d++ = *p++;
418 		} else if (*p == c) {
419 			*d = '\0';
420 			return (p + 1);
421 		}
422 		*d++ = *p++;
423 	}
424 	return (NULL);
425 }
426 
427 
428 /* compile_ccl: expand a POSIX character class */
429 static char *
compile_ccl(char ** sp,char * t)430 compile_ccl(char **sp, char *t)
431 {
432 	int c, d;
433 	char *s = *sp;
434 
435 	*t++ = *s++;
436 	if (*s == '^')
437 		*t++ = *s++;
438 	if (*s == ']')
439 		*t++ = *s++;
440 	for (; *s && (*t = *s) != ']'; s++, t++)
441 		if (*s == '[' && ((d = *(s+1)) == '.' || d == ':' || d == '=')) {
442 			*++t = *++s, t++, s++;
443 			for (c = *s; (*t = *s) != ']' || c != d; s++, t++)
444 				if ((c = *s) == '\0')
445 					return NULL;
446 		}
447 	return (*s == ']') ? *sp = ++s, ++t : NULL;
448 }
449 
450 /*
451  * Compiles the regular expression in RE and returns a pointer to the compiled
452  * regular expression.
453  * Cflags are passed to regcomp.
454  */
455 static regex_t *
compile_re(char * re,int case_insensitive)456 compile_re(char *re, int case_insensitive)
457 {
458 	regex_t *rep;
459 	int eval, flags;
460 
461 
462 	flags = rflags;
463 	if (case_insensitive)
464 		flags |= REG_ICASE;
465 	rep = xmalloc(sizeof(regex_t));
466 	if ((eval = regcomp(rep, re, flags)) != 0)
467 		errx(1, "%lu: %s: RE error: %s",
468 				linenum, fname, strregerror(eval, rep));
469 	if (maxnsub < rep->re_nsub)
470 		maxnsub = rep->re_nsub;
471 	return (rep);
472 }
473 
474 /*
475  * Compile the substitution string of a regular expression and set res to
476  * point to a saved copy of it.  Nsub is the number of parenthesized regular
477  * expressions.
478  */
479 static char *
compile_subst(char * p,struct s_subst * s)480 compile_subst(char *p, struct s_subst *s)
481 {
482 	static char lbuf[_POSIX2_LINE_MAX + 1];
483 	size_t asize, size;
484 	u_char ref;
485 	char c, *text, *op, *sp;
486 	int more = 1, sawesc = 0;
487 
488 	c = *p++;			/* Terminator character */
489 	if (c == '\0')
490 		return (NULL);
491 
492 	s->maxbref = 0;
493 	s->linenum = linenum;
494 	asize = 2 * _POSIX2_LINE_MAX + 1;
495 	text = xmalloc(asize);
496 	size = 0;
497 	do {
498 		op = sp = text + size;
499 		for (; *p; p++) {
500 			if (*p == '\\' || sawesc) {
501 				/*
502 				 * If this is a continuation from the last
503 				 * buffer, we won't have a character to
504 				 * skip over.
505 				 */
506 				if (sawesc)
507 					sawesc = 0;
508 				else
509 					p++;
510 
511 				if (*p == '\0') {
512 					/*
513 					 * This escaped character is continued
514 					 * in the next part of the line.  Note
515 					 * this fact, then cause the loop to
516 					 * exit w/ normal EOL case and reenter
517 					 * above with the new buffer.
518 					 */
519 					sawesc = 1;
520 					p--;
521 					continue;
522 				} else if (strchr("123456789", *p) != NULL) {
523 					*sp++ = '\\';
524 					ref = (u_char)(*p - '0');
525 					if (s->re != NULL &&
526 					    ref > s->re->re_nsub)
527 						errx(1, "%lu: %s: \\%c not defined in the RE",
528 								linenum, fname, *p);
529 					if (s->maxbref < ref)
530 						s->maxbref = ref;
531 				} else if (*p == '&' || *p == '\\')
532 					*sp++ = '\\';
533 			} else if (*p == c) {
534 				if (*++p == '\0' && more) {
535 					if (cu_fgets(lbuf, sizeof(lbuf), &more))
536 						p = lbuf;
537 				}
538 				*sp++ = '\0';
539 				size += (size_t)(sp - op);
540 				s->new = xrealloc(text, size);
541 				return (p);
542 			} else if (*p == '\n') {
543 				errx(1,
544 "%lu: %s: unescaped newline inside substitute pattern", linenum, fname);
545 				/* NOTREACHED */
546 			}
547 			*sp++ = *p;
548 		}
549 		size += (size_t)(sp - op);
550 		if (asize - size < _POSIX2_LINE_MAX + 1) {
551 			asize *= 2;
552 			text = xrealloc(text, asize);
553 		}
554 	} while (cu_fgets(p = lbuf, sizeof(lbuf), &more));
555 	errx(1, "%lu: %s: unterminated substitute in regular expression",
556 			linenum, fname);
557 	/* NOTREACHED */
558 }
559 
560 /*
561  * Compile the flags of the s command
562  */
563 static char *
compile_flags(char * p,struct s_subst * s)564 compile_flags(char *p, struct s_subst *s)
565 {
566 	int gn;			/* True if we have seen g or n */
567 	unsigned long nval;
568 	char wfile[_POSIX2_LINE_MAX + 1], *q;
569 
570 	s->n = 1;				/* Default */
571 	s->p = 0;
572 	s->wfile = NULL;
573 	s->wfd = -1;
574 	s->icase = 0;
575 	for (gn = 0;;) {
576 		EATSPACE();			/* EXTENSION */
577 		switch (*p) {
578 		case 'g':
579 			if (gn)
580 				errx(1,
581 "%lu: %s: more than one number or 'g' in substitute flags", linenum, fname);
582 			gn = 1;
583 			s->n = 0;
584 			break;
585 		case '\0':
586 		case '\n':
587 		case ';':
588 			return (p);
589 		case 'p':
590 			s->p = 1;
591 			break;
592 		case 'i':
593 		case 'I':
594 			s->icase = 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 				errx(1,
601 "%lu: %s: more than one number or 'g' in substitute flags", linenum, fname);
602 			gn = 1;
603 			errno = 0;
604 			nval = strtoul(p, &p, 10);
605 			if (errno == ERANGE || nval > INT_MAX)
606 				errx(1,
607 "%lu: %s: overflow in the 'N' substitute flag", linenum, fname);
608 			s->n = (int)nval;
609 			p--;
610 			break;
611 		case 'w':
612 			p++;
613 #ifdef HISTORIC_PRACTICE
614 			if (*p != ' ') {
615 				warnx("%lu: %s: space missing before w wfile", linenum, fname);
616 				return (p);
617 			}
618 #endif
619 			EATSPACE();
620 			q = wfile;
621 			while (*p) {
622 				if (*p == '\n')
623 					break;
624 				*q++ = *p++;
625 			}
626 			*q = '\0';
627 			if (q == wfile)
628 				errx(1, "%lu: %s: no wfile specified", linenum, fname);
629 			s->wfile = strdup(wfile);
630 			if (!aflag && (s->wfd = open(wfile,
631 			    O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
632 			    DEFFILEMODE)) == -1)
633 				err(1, "%s", wfile);
634 			return (p);
635 		default:
636 			errx(1, "%lu: %s: bad flag in substitute command: '%c'",
637 					linenum, fname, *p);
638 			break;
639 		}
640 		p++;
641 	}
642 }
643 
644 /*
645  * Compile a translation set of strings into a lookup table.
646  */
647 static char *
compile_tr(char * p,struct s_tr ** py)648 compile_tr(char *p, struct s_tr **py)
649 {
650 	struct s_tr *y;
651 	size_t i;
652 	const char *op, *np;
653 	char old[_POSIX2_LINE_MAX + 1];
654 	char new[_POSIX2_LINE_MAX + 1];
655 	size_t oclen, oldlen, nclen, newlen;
656 	mbstate_t mbs1, mbs2;
657 
658 	*py = y = xmalloc(sizeof(*y));
659 	y->multis = NULL;
660 	y->nmultis = 0;
661 
662 	if (*p == '\0' || *p == '\\')
663 		errx(1,
664 	"%lu: %s: transform pattern can not be delimited by newline or backslash",
665 			linenum, fname);
666 	p = compile_delimited(p, old, 1);
667 	if (p == NULL)
668 		errx(1, "%lu: %s: unterminated transform source string",
669 				linenum, fname);
670 	p = compile_delimited(p - 1, new, 1);
671 	if (p == NULL)
672 		errx(1, "%lu: %s: unterminated transform target string",
673 				linenum, fname);
674 	EATSPACE();
675 	op = old;
676 	oldlen = mbsrtowcs(NULL, &op, 0, NULL);
677 	if (oldlen == (size_t)-1)
678 		err(1, NULL);
679 	np = new;
680 	newlen = mbsrtowcs(NULL, &np, 0, NULL);
681 	if (newlen == (size_t)-1)
682 		err(1, NULL);
683 	if (newlen != oldlen)
684 		errx(1, "%lu: %s: transform strings are not the same length",
685 				linenum, fname);
686 	if (MB_CUR_MAX == 1) {
687 		/*
688 		 * The single-byte encoding case is easy: generate a
689 		 * lookup table.
690 		 */
691 		for (i = 0; i <= UCHAR_MAX; i++)
692 			y->bytetab[i] = (u_char)i;
693 		for (; *op; op++, np++)
694 			y->bytetab[(u_char)*op] = (u_char)*np;
695 	} else {
696 		/*
697 		 * Multi-byte encoding case: generate a lookup table as
698 		 * above, but only for single-byte characters. The first
699 		 * bytes of multi-byte characters have their lookup table
700 		 * entries set to 0, which causes do_tr() to search through
701 		 * an auxiliary vector of multi-byte mappings.
702 		 */
703 		memset(&mbs1, 0, sizeof(mbs1));
704 		memset(&mbs2, 0, sizeof(mbs2));
705 		for (i = 0; i <= UCHAR_MAX; i++)
706 			y->bytetab[i] = (u_char)((btowc((int)i) != WEOF) ? i : 0);
707 		while (*op != '\0') {
708 			oclen = mbrlen(op, MB_LEN_MAX, &mbs1);
709 			if (oclen == (size_t)-1 || oclen == (size_t)-2)
710 				errc(1, EILSEQ, NULL);
711 			nclen = mbrlen(np, MB_LEN_MAX, &mbs2);
712 			if (nclen == (size_t)-1 || nclen == (size_t)-2)
713 				errc(1, EILSEQ, NULL);
714 			if (oclen == 1 && nclen == 1)
715 				y->bytetab[(u_char)*op] = (u_char)*np;
716 			else {
717 				y->bytetab[(u_char)*op] = 0;
718 				y->multis = xrealloc(y->multis,
719 				    (y->nmultis + 1) * sizeof(*y->multis));
720 				i = y->nmultis++;
721 				y->multis[i].fromlen = oclen;
722 				memcpy(y->multis[i].from, op, oclen);
723 				y->multis[i].tolen = nclen;
724 				memcpy(y->multis[i].to, np, nclen);
725 			}
726 			op += oclen;
727 			np += nclen;
728 		}
729 	}
730 	return (p);
731 }
732 
733 /*
734  * Compile the text following an a or i command.
735  */
736 static char *
compile_text(void)737 compile_text(void)
738 {
739 	size_t asize, size;
740 	int esc_nl;
741 	char *text, *p, *op, *s;
742 	char lbuf[_POSIX2_LINE_MAX + 1];
743 
744 	asize = 2 * _POSIX2_LINE_MAX + 1;
745 	text = xmalloc(asize);
746 	size = 0;
747 	while (cu_fgets(lbuf, sizeof(lbuf), NULL)) {
748 		op = s = text + size;
749 		p = lbuf;
750 		EATSPACE();
751 		for (esc_nl = 0; *p != '\0'; p++) {
752 			if (*p == '\\' && p[1] != '\0' && *++p == '\n')
753 				esc_nl = 1;
754 			*s++ = *p;
755 		}
756 		size += (size_t)(s - op);
757 		if (!esc_nl) {
758 			*s = '\0';
759 			break;
760 		}
761 		if (asize - size < _POSIX2_LINE_MAX + 1) {
762 			asize *= 2;
763 			text = xrealloc(text, asize);
764 		}
765 	}
766 	text[size] = '\0';
767 	p = xrealloc(text, size + 1);
768 	return (p);
769 }
770 
771 /*
772  * Get an address and return a pointer to the first character after
773  * it.  Fill the structure pointed to according to the address.
774  */
775 static char *
compile_addr(char * p,struct s_addr * a)776 compile_addr(char *p, struct s_addr *a)
777 {
778 	char *end, re[_POSIX2_LINE_MAX + 1];
779 	int icase;
780 
781 	icase = 0;
782 
783 	a->type = 0;
784 	switch (*p) {
785 	case '\\':				/* Context address */
786 		++p;
787 		/* FALLTHROUGH */
788 	case '/':				/* Context address */
789 		p = compile_delimited(p, re, 0);
790 		if (p == NULL)
791 			errx(1, "%lu: %s: unterminated regular expression", linenum, fname);
792 		/* Check for case insensitive regexp flag */
793 		if (*p == 'I') {
794 			icase = 1;
795 			p++;
796 		}
797 		if (*re == '\0')
798 			a->u.r = NULL;
799 		else
800 			a->u.r = compile_re(re, icase);
801 		a->type = AT_RE;
802 		return (p);
803 
804 	case '$':				/* Last line */
805 		a->type = AT_LAST;
806 		return (p + 1);
807 
808 	case '+':				/* Relative line number */
809 		a->type = AT_RELLINE;
810 		p++;
811 		/* FALLTHROUGH */
812 						/* Line number */
813 	case '0': case '1': case '2': case '3': case '4':
814 	case '5': case '6': case '7': case '8': case '9':
815 		if (a->type == 0)
816 			a->type = AT_LINE;
817 		a->u.l = strtoul(p, &end, 10);
818 		return (end);
819 	default:
820 		errx(1, "%lu: %s: expected context address", linenum, fname);
821 		return (NULL);
822 	}
823 }
824 
825 /*
826  * duptoeol --
827  *	Return a copy of all the characters up to \n or \0.
828  */
829 static char *
duptoeol(char * s,const char * ctype)830 duptoeol(char *s, const char *ctype)
831 {
832 	size_t len;
833 	int ws;
834 	char *p, *start;
835 
836 	ws = 0;
837 	for (start = s; *s != '\0' && *s != '\n'; ++s)
838 		ws = isspace((unsigned char)*s);
839 	*s = '\0';
840 	if (ws)
841 		warnx("%lu: %s: whitespace after %s", linenum, fname, ctype);
842 	len = (size_t)(s - start + 1);
843 	p = xmalloc(len);
844 	return (memmove(p, start, len));
845 }
846 
847 /*
848  * Convert goto label names to addresses, and count a and r commands, in
849  * the given subset of the script.  Free the memory used by labels in b
850  * and t commands (but not by :).
851  *
852  * TODO: Remove } nodes
853  */
854 static void
fixuplabel(struct s_command * cp,struct s_command * end)855 fixuplabel(struct s_command *cp, struct s_command *end)
856 {
857 
858 	for (; cp != end; cp = cp->next)
859 		switch (cp->code) {
860 		case 'a':
861 		case 'r':
862 			appendnum++;
863 			break;
864 		case 'b':
865 		case 't':
866 			/* Resolve branch target. */
867 			if (cp->t == NULL) {
868 				cp->u.c = NULL;
869 				break;
870 			}
871 			if ((cp->u.c = findlabel(cp->t)) == NULL)
872 				errx(1, "%lu: %s: undefined label '%s'", linenum, fname, cp->t);
873 			free(cp->t);
874 			break;
875 		case '{':
876 			/* Do interior commands. */
877 			fixuplabel(cp->u.c, cp->next);
878 			break;
879 		}
880 }
881 
882 /*
883  * Associate the given command label for later lookup.
884  */
885 static void
enterlabel(struct s_command * cp)886 enterlabel(struct s_command *cp)
887 {
888 	struct labhash **lhp, *lh;
889 	u_char *p;
890 	u_int h, c;
891 
892 	for (h = 0, p = (u_char *)cp->t; (c = *p) != 0; p++)
893 		h = (h << 5) + h + c;
894 	lhp = &labels[h & LHMASK];
895 	for (lh = *lhp; lh != NULL; lh = lh->lh_next)
896 		if (lh->lh_hash == h && strcmp(cp->t, lh->lh_cmd->t) == 0)
897 			errx(1, "%lu: %s: duplicate label '%s'", linenum, fname, cp->t);
898 	lh = xmalloc(sizeof *lh);
899 	lh->lh_next = *lhp;
900 	lh->lh_hash = h;
901 	lh->lh_cmd = cp;
902 	lh->lh_ref = 0;
903 	*lhp = lh;
904 }
905 
906 /*
907  * Find the label contained in the command l in the command linked
908  * list cp.  L is excluded from the search.  Return NULL if not found.
909  */
910 static struct s_command *
findlabel(char * name)911 findlabel(char *name)
912 {
913 	struct labhash *lh;
914 	u_char *p;
915 	u_int h, c;
916 
917 	for (h = 0, p = (u_char *)name; (c = *p) != 0; p++)
918 		h = (h << 5) + h + c;
919 	for (lh = labels[h & LHMASK]; lh != NULL; lh = lh->lh_next) {
920 		if (lh->lh_hash == h && strcmp(name, lh->lh_cmd->t) == 0) {
921 			lh->lh_ref = 1;
922 			return (lh->lh_cmd);
923 		}
924 	}
925 	return (NULL);
926 }
927 
928 /*
929  * Warn about any unused labels.  As a side effect, release the label hash
930  * table space.
931  */
932 static void
uselabel(void)933 uselabel(void)
934 {
935 	struct labhash *lh, *next;
936 	int i;
937 
938 	for (i = 0; i < LHSZ; i++) {
939 		for (lh = labels[i]; lh != NULL; lh = next) {
940 			next = lh->lh_next;
941 			if (!lh->lh_ref)
942 				warnx("%lu: %s: unused label '%s'",
943 				    linenum, fname, lh->lh_cmd->t);
944 			free(lh);
945 		}
946 	}
947 }
948