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