1 /* $NetBSD: compile.c,v 1.35 2007/04/17 20:30:29 christos Exp $ */
4 * Copyright (c) 1992, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Diomidis Spinellis of Imperial College, University of London.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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
36 * Copyright (c) 1992 Diomidis Spinellis.
38 * This code is derived from software contributed to Berkeley by
39 * Diomidis Spinellis of Imperial College, University of London.
41 * Redistribution and use in source and binary forms, with or without
42 * modification, are permitted provided that the following conditions
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.
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
70 #if HAVE_NBTOOL_CONFIG_H
71 #include "nbtool_config.h"
74 #include <sys/cdefs.h>
77 static char sccsid
[] = "@(#)compile.c 8.2 (Berkeley) 4/28/95";
79 __RCSID("$NetBSD: compile.c,v 1.35 2007/04/17 20:30:29 christos Exp $");
83 #include <sys/types.h>
98 #ifndef _POSIX2_LINE_MAX
99 #define _POSIX2_LINE_MAX (2 * BUFSIZ)
103 #define LHMASK (LHSZ - 1)
104 static struct labhash
{
105 struct labhash
*lh_next
;
107 struct s_command
*lh_cmd
;
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
125 static void fixuplabel(struct s_command
*, struct s_command
*);
126 static void uselabel(void);
129 * Command specification. This is used to drive the command parser.
132 char code
; /* Command code */
133 int naddr
; /* Number of address args */
134 enum e_args args
; /* Argument type */
137 static struct s_format cmd_fmts
[] = {
169 /* The compiled program. */
170 struct s_command
*prog
;
173 * Compile the program into prog.
174 * Initialise appends.
179 *compile_stream(&prog
) = NULL
;
180 fixuplabel(prog
, NULL
);
183 appends
= xmalloc(sizeof(struct s_appends
) * appendnum
);
184 match
= xmalloc((maxnsub
+ 1) * sizeof(regmatch_t
));
188 while (*p && isascii((unsigned char)*p) && \
189 isspace((unsigned char)*p)) \
192 static struct s_command **
193 compile_stream(struct s_command
**link
)
196 static char lbuf
[_POSIX2_LINE_MAX
+ 1]; /* To save stack */
197 struct s_command
*cmd
, *cmd2
, *stack
;
199 int naddr
; /* Number of addresses */
203 if ((p
= cu_fgets(lbuf
, sizeof(lbuf
))) == NULL
) {
205 err(COMPILE
, "unexpected EOF (pending }'s)");
209 semicolon
: EATSPACE();
210 if (*p
== '#' || *p
== '\0')
212 else if (*p
== ';') {
216 *link
= cmd
= xmalloc(sizeof(struct s_command
));
218 cmd
->nonsel
= cmd
->inrange
= 0;
219 /* First parse the addresses */
222 /* Valid characters to start an address */
223 #define addrchar(c) (strchr("0123456789/\\$", (c)))
226 cmd
->a1
= xmalloc(sizeof(struct s_addr
));
227 p
= compile_addr(p
, cmd
->a1
);
228 EATSPACE(); /* EXTENSION */
231 EATSPACE(); /* EXTENSION */
233 cmd
->a2
= xmalloc(sizeof(struct s_addr
));
234 p
= compile_addr(p
, cmd
->a2
);
239 cmd
->a1
= cmd
->a2
= 0;
241 nonsel
: /* Now parse the command */
243 err(COMPILE
, "command expected");
245 for (fp
= cmd_fmts
; fp
->code
; fp
++)
249 err(COMPILE
, "invalid command code %c", *p
);
250 if (naddr
> fp
->naddr
)
252 "command %c expects up to %d address(es), found %d", *p
, fp
->naddr
, naddr
);
257 cmd
->nonsel
= ! cmd
->nonsel
;
270 * Short-circuit command processing, since end of
271 * group is really just a noop.
275 err(COMPILE
, "unexpected }");
280 case EMPTY
: /* d D g G h H l n N p P q x = \0 */
290 "extra characters at the end of %c command", cmd
->code
);
292 case TEXT
: /* a c i */
297 "command %c expects \\ followed by text", cmd
->code
);
302 "extra characters after \\ at the end of %c command", cmd
->code
);
303 cmd
->t
= compile_text();
305 case COMMENT
: /* \0 # */
311 err(COMPILE
, "filename expected");
312 cmd
->t
= duptoeol(p
, "w command");
315 else if ((cmd
->u
.fd
= open(p
,
316 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
,
318 err(FATAL
, "%s: %s", p
, strerror(errno
));
324 err(COMPILE
, "filename expected");
326 cmd
->t
= duptoeol(p
, "read command");
328 case BRANCH
: /* b t */
334 cmd
->t
= duptoeol(p
, "branch");
339 cmd
->t
= duptoeol(p
, "label");
341 err(COMPILE
, "empty label");
346 if (*p
== '\0' || *p
== '\\')
348 "substitute pattern can not be delimited by newline or backslash");
349 cmd
->u
.s
= xmalloc(sizeof(struct s_subst
));
350 p
= compile_re(p
, &cmd
->u
.s
->re
);
352 err(COMPILE
, "unterminated substitute pattern");
354 p
= compile_subst(p
, cmd
->u
.s
);
355 p
= compile_flags(p
, cmd
->u
.s
);
365 p
= compile_tr(p
, (char **)(void *)&cmd
->u
.y
);
374 "extra text at the end of a transform command");
381 * Get a delimited string. P points to the delimiter of the string; d points
382 * to a buffer area. Newline and delimiter escapes are processed; other
383 * escapes are ignored.
385 * Returns a pointer to the first character after the final delimiter or NULL
386 * in the case of a non-terminated string. The character array d is filled
387 * with the processed string.
390 compile_delimited(char *p
, char *d
)
398 err(COMPILE
, "\\ can not be used as a string delimiter");
400 err(COMPILE
, "newline can not be used as a string delimiter");
403 if ((d
= compile_ccl(&p
, d
)) == NULL
)
404 err(COMPILE
, "unbalanced brackets ([])");
406 } else if (*p
== '\\' && p
[1] == '[') {
408 } else if (*p
== '\\' && p
[1] == c
)
410 else if (*p
== '\\' && p
[1] == 'n') {
414 } else if (*p
== '\\' && p
[1] == '\\')
426 /* compile_ccl: expand a POSIX character class */
428 compile_ccl(char **sp
, char *t
)
438 for (; *s
&& (*t
= *s
) != ']'; s
++, t
++)
439 if (*s
== '[' && ((d
= *(s
+1)) == '.' || d
== ':' || d
== '=')) {
440 *++t
= *++s
, t
++, s
++;
441 for (c
= *s
; (*t
= *s
) != ']' || c
!= d
; s
++, t
++)
442 if ((c
= *s
) == '\0')
444 } else if (*s
== '\\' && s
[1] == 'n')
446 return (*s
== ']') ? *sp
= ++s
, ++t
: NULL
;
450 * Get a regular expression. P points to the delimiter of the regular
451 * expression; repp points to the address of a regexp pointer. Newline
452 * and delimiter escapes are processed; other escapes are ignored.
453 * Returns a pointer to the first character after the final delimiter
454 * or NULL in the case of a non terminated regular expression. The regexp
455 * pointer is set to the compiled regular expression.
456 * Cflags are passed to regcomp.
459 compile_re(char *p
, regex_t
**repp
)
462 char re
[_POSIX2_LINE_MAX
+ 1];
464 p
= compile_delimited(p
, re
);
465 if (p
&& strlen(re
) == 0) {
469 *repp
= xmalloc(sizeof(regex_t
));
470 if (p
&& (eval
= regcomp(*repp
, re
, ere
)) != 0)
471 err(COMPILE
, "RE error: %s", strregerror(eval
, *repp
));
472 if (maxnsub
< (*repp
)->re_nsub
)
473 maxnsub
= (*repp
)->re_nsub
;
478 * Compile the substitution string of a regular expression and set res to
479 * point to a saved copy of it. Nsub is the number of parenthesized regular
483 compile_subst(char *p
, struct s_subst
*s
)
485 static char lbuf
[_POSIX2_LINE_MAX
+ 1];
486 int asize
, ref
, size
;
487 char c
, *text
, *op
, *sp
;
490 c
= *p
++; /* Terminator character */
495 s
->linenum
= linenum
;
496 asize
= 2 * _POSIX2_LINE_MAX
+ 1;
497 text
= xmalloc(asize
);
500 op
= sp
= text
+ size
;
502 if (*p
== '\\' || sawesc
) {
504 * If this is a continuation from the last
505 * buffer, we won't have a character to
515 * This escaped character is continued
516 * in the next part of the line. Note
517 * this fact, then cause the loop to
518 * exit w/ normal EOL case and reenter
519 * above with the new buffer.
524 } else if (strchr("123456789", *p
) != NULL
) {
528 (size_t)ref
> s
->re
->re_nsub
)
530 "\\%c not defined in the RE", *p
);
531 if (s
->maxbref
< ref
)
533 } else if (*p
== '&' || *p
== '\\')
535 } else if (*p
== c
) {
539 s
->new = xrealloc(text
, size
);
541 } else if (*p
== '\n') {
543 "unescaped newline inside substitute pattern");
549 if (asize
- size
< _POSIX2_LINE_MAX
+ 1) {
551 text
= xrealloc(text
, asize
);
553 } while (cu_fgets(p
= lbuf
, sizeof(lbuf
)));
554 err(COMPILE
, "unterminated substitute in regular expression");
560 * Compile the flags of the s command
563 compile_flags(char *p
, struct s_subst
*s
)
565 int gn
; /* True if we have seen g or n */
566 char wfile
[_POSIX2_LINE_MAX
+ 1], *q
;
568 s
->n
= 1; /* Default */
573 EATSPACE(); /* EXTENSION */
578 "more than one number or 'g' in substitute flags");
589 case '1': case '2': case '3':
590 case '4': case '5': case '6':
591 case '7': case '8': case '9':
594 "more than one number or 'g' in substitute flags");
596 /* XXX Check for overflow */
597 s
->n
= (int)strtol(p
, &p
, 10);
602 #ifdef HISTORIC_PRACTICE
604 err(WARNING
, "space missing before w wfile");
617 err(COMPILE
, "no wfile specified");
618 s
->wfile
= strdup(wfile
);
619 if (!aflag
&& (s
->wfd
= open(wfile
,
620 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
,
622 err(FATAL
, "%s: %s", wfile
, strerror(errno
));
626 "bad flag in substitute command: '%c'", *p
);
634 * Compile a translation set of strings into a lookup table.
637 compile_tr(char *p
, char **transtab
)
641 char old
[_POSIX2_LINE_MAX
+ 1];
642 char new[_POSIX2_LINE_MAX
+ 1];
644 if (*p
== '\0' || *p
== '\\')
646 "transform pattern can not be delimited by newline or backslash");
647 p
= compile_delimited(p
, old
);
649 err(COMPILE
, "unterminated transform source string");
652 p
= compile_delimited(--p
, new);
654 err(COMPILE
, "unterminated transform target string");
658 if (strlen(new) != strlen(old
)) {
659 err(COMPILE
, "transform strings are not the same length");
662 /* We assume characters are 8 bits */
663 lt
= xmalloc(UCHAR_MAX
+1);
664 for (i
= 0; i
<= UCHAR_MAX
; i
++)
666 for (op
= old
, np
= new; *op
; op
++, np
++)
667 lt
[(u_char
)*op
] = *np
;
673 * Compile the text following an a, c, or i command.
679 char *text
, *p
, *op
, *s
;
680 char lbuf
[_POSIX2_LINE_MAX
+ 1];
682 asize
= 2 * _POSIX2_LINE_MAX
+ 1;
683 text
= xmalloc(asize
);
685 while (cu_fgets(lbuf
, sizeof(lbuf
))) {
686 op
= s
= text
+ size
;
698 if (asize
- size
< _POSIX2_LINE_MAX
+ 1) {
700 text
= xrealloc(text
, asize
);
703 return (xrealloc(text
, size
+ 1));
707 * Get an address and return a pointer to the first character after
708 * it. Fill the structure pointed to according to the address.
711 compile_addr(char *p
, struct s_addr
*a
)
716 case '\\': /* Context address */
719 case '/': /* Context address */
720 p
= compile_re(p
, &a
->u
.r
);
722 err(COMPILE
, "unterminated regular expression");
726 case '$': /* Last line */
730 case '0': case '1': case '2': case '3': case '4':
731 case '5': case '6': case '7': case '8': case '9':
733 a
->u
.l
= strtol(p
, &end
, 10);
736 err(COMPILE
, "expected context address");
743 * Return a copy of all the characters up to \n or \0.
746 duptoeol(char *s
, const char *ctype
)
753 for (start
= s
; *s
!= '\0' && *s
!= '\n'; ++s
)
754 ws
= isspace((unsigned char)*s
);
757 err(WARNING
, "whitespace after %s", ctype
);
759 return (memmove(xmalloc(len
), start
, len
));
763 * Convert goto label names to addresses, and count a and r commands, in
764 * the given subset of the script. Free the memory used by labels in b
765 * and t commands (but not by :).
767 * TODO: Remove } nodes
770 fixuplabel(struct s_command
*cp
, struct s_command
*end
)
773 for (; cp
!= end
; cp
= cp
->next
)
781 /* Resolve branch target. */
786 if ((cp
->u
.c
= findlabel(cp
->t
)) == NULL
)
787 err(COMPILE2
, "undefined label '%s'", cp
->t
);
791 /* Do interior commands. */
792 fixuplabel(cp
->u
.c
, cp
->next
);
798 * Associate the given command label for later lookup.
801 enterlabel(struct s_command
*cp
)
803 struct labhash
**lhp
, *lh
;
807 for (h
= 0, p
= (u_char
*)cp
->t
; (c
= *p
) != 0; p
++)
808 h
= (h
<< 5) + h
+ c
;
809 lhp
= &labels
[h
& LHMASK
];
810 for (lh
= *lhp
; lh
!= NULL
; lh
= lh
->lh_next
)
811 if (lh
->lh_hash
== h
&& strcmp(cp
->t
, lh
->lh_cmd
->t
) == 0)
812 err(COMPILE2
, "duplicate label '%s'", cp
->t
);
813 lh
= xmalloc(sizeof *lh
);
822 * Find the label contained in the command l in the command linked
823 * list cp. L is excluded from the search. Return NULL if not found.
825 static struct s_command
*
826 findlabel(char *name
)
832 for (h
= 0, p
= (u_char
*)name
; (c
= *p
) != 0; p
++)
833 h
= (h
<< 5) + h
+ c
;
834 for (lh
= labels
[h
& LHMASK
]; lh
!= NULL
; lh
= lh
->lh_next
) {
835 if (lh
->lh_hash
== h
&& strcmp(name
, lh
->lh_cmd
->t
) == 0) {
844 * Warn about any unused labels. As a side effect, release the label hash
850 struct labhash
*lh
, *next
;
853 for (i
= 0; i
< LHSZ
; i
++) {
854 for (lh
= labels
[i
]; lh
!= NULL
; lh
= next
) {
857 err(WARNING
, "unused label '%s'",