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