1 /* $NetBSD: compile.c,v 1.37 2010/02/19 16:35:27 tnn 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.37 2010/02/19 16:35:27 tnn 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
; /* To avoid excessive malloc calls */
197 static size_t bufsize
;
198 struct s_command
*cmd
, *cmd2
, *stack
;
200 int naddr
; /* Number of addresses */
204 if ((p
= cu_fgets(&lbuf
, &bufsize
)) == NULL
) {
206 err(COMPILE
, "unexpected EOF (pending }'s)");
210 semicolon
: EATSPACE();
211 if (*p
== '#' || *p
== '\0')
213 else if (*p
== ';') {
217 *link
= cmd
= xmalloc(sizeof(struct s_command
));
219 cmd
->nonsel
= cmd
->inrange
= 0;
220 /* First parse the addresses */
223 /* Valid characters to start an address */
224 #define addrchar(c) (strchr("0123456789/\\$", (c)))
227 cmd
->a1
= xmalloc(sizeof(struct s_addr
));
228 p
= compile_addr(p
, cmd
->a1
);
229 EATSPACE(); /* EXTENSION */
232 EATSPACE(); /* EXTENSION */
234 cmd
->a2
= xmalloc(sizeof(struct s_addr
));
235 p
= compile_addr(p
, cmd
->a2
);
240 cmd
->a1
= cmd
->a2
= 0;
242 nonsel
: /* Now parse the command */
244 err(COMPILE
, "command expected");
246 for (fp
= cmd_fmts
; fp
->code
; fp
++)
250 err(COMPILE
, "invalid command code %c", *p
);
251 if (naddr
> fp
->naddr
)
253 "command %c expects up to %d address(es), found %d", *p
, fp
->naddr
, naddr
);
258 cmd
->nonsel
= ! cmd
->nonsel
;
271 * Short-circuit command processing, since end of
272 * group is really just a noop.
276 err(COMPILE
, "unexpected }");
281 case EMPTY
: /* d D g G h H l n N p P q x = \0 */
291 "extra characters at the end of %c command", cmd
->code
);
293 case TEXT
: /* a c i */
298 "command %c expects \\ followed by text", cmd
->code
);
303 "extra characters after \\ at the end of %c command", cmd
->code
);
304 cmd
->t
= compile_text();
306 case COMMENT
: /* \0 # */
312 err(COMPILE
, "filename expected");
313 cmd
->t
= duptoeol(p
, "w command");
316 else if ((cmd
->u
.fd
= open(p
,
317 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
,
319 err(FATAL
, "%s: %s", p
, strerror(errno
));
325 err(COMPILE
, "filename expected");
327 cmd
->t
= duptoeol(p
, "read command");
329 case BRANCH
: /* b t */
335 cmd
->t
= duptoeol(p
, "branch");
340 cmd
->t
= duptoeol(p
, "label");
342 err(COMPILE
, "empty label");
347 if (*p
== '\0' || *p
== '\\')
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
);
353 err(COMPILE
, "unterminated substitute pattern");
355 p
= compile_subst(p
, cmd
->u
.s
);
356 p
= compile_flags(p
, cmd
->u
.s
);
366 p
= compile_tr(p
, (char **)(void *)&cmd
->u
.y
);
375 "extra text at the end of a transform command");
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.
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.
391 compile_delimited(char *p
, char *d
)
399 err(COMPILE
, "\\ can not be used as a string delimiter");
401 err(COMPILE
, "newline can not be used as a string delimiter");
404 if ((d
= compile_ccl(&p
, d
)) == NULL
)
405 err(COMPILE
, "unbalanced brackets ([])");
407 } else if (*p
== '\\' && p
[1] == '[') {
409 } else if (*p
== '\\' && p
[1] == c
)
411 else if (*p
== '\\' && p
[1] == 'n') {
415 } else if (*p
== '\\' && p
[1] == '\\')
427 /* compile_ccl: expand a POSIX character class */
429 compile_ccl(char **sp
, char *t
)
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')
445 } else if (*s
== '\\' && s
[1] == 'n')
447 return (*s
== ']') ? *sp
= ++s
, ++t
: NULL
;
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.
460 compile_re(char *p
, regex_t
**repp
)
465 re
= xmalloc(strlen(p
) + 1); /* strlen(re) <= strlen(p) */
466 p
= compile_delimited(p
, re
);
467 if (p
&& strlen(re
) == 0) {
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
;
481 * Compile the substitution string of a regular expression and set res to
482 * point to a saved copy of it. Nsub is the number of parenthesized regular
486 compile_subst(char *p
, struct s_subst
*s
)
489 static size_t bufsize
;
490 int asize
, ref
, size
, len
;
491 char c
, *text
, *op
, *sp
;
494 c
= *p
++; /* Terminator character */
499 s
->linenum
= linenum
;
503 len
= ROUNDLEN(strlen(p
) + 1);
504 if (asize
- size
< len
) {
507 } while (asize
- size
< len
);
508 text
= xrealloc(text
, asize
);
510 op
= sp
= text
+ size
;
512 if (*p
== '\\' || sawesc
) {
514 * If this is a continuation from the last
515 * buffer, we won't have a character to
525 * This escaped character is continued
526 * in the next part of the line. Note
527 * this fact, then cause the loop to
528 * exit w/ normal EOL case and reenter
529 * above with the new buffer.
534 } else if (strchr("123456789", *p
) != NULL
) {
538 (size_t)ref
> s
->re
->re_nsub
)
540 "\\%c not defined in the RE", *p
);
541 if (s
->maxbref
< ref
)
543 } else if (*p
== '&' || *p
== '\\')
545 } else if (*p
== c
) {
549 s
->new = xrealloc(text
, size
);
551 } else if (*p
== '\n') {
553 "unescaped newline inside substitute pattern");
559 } while ((p
= cu_fgets(&lbuf
, &bufsize
)));
560 err(COMPILE
, "unterminated substitute in regular expression");
566 * Compile the flags of the s command
569 compile_flags(char *p
, struct s_subst
*s
)
571 int gn
; /* True if we have seen g or n */
572 char wfile
[PATH_MAX
], *q
;
574 s
->n
= 1; /* Default */
579 EATSPACE(); /* EXTENSION */
584 "more than one number or 'g' in substitute flags");
595 case '1': case '2': case '3':
596 case '4': case '5': case '6':
597 case '7': case '8': case '9':
600 "more than one number or 'g' in substitute flags");
602 /* XXX Check for overflow */
603 s
->n
= (int)strtol(p
, &p
, 10);
608 #ifdef HISTORIC_PRACTICE
610 err(WARNING
, "space missing before w wfile");
623 err(COMPILE
, "no wfile specified");
624 s
->wfile
= strdup(wfile
);
625 if (!aflag
&& (s
->wfd
= open(wfile
,
626 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
,
628 err(FATAL
, "%s: %s", wfile
, strerror(errno
));
632 "bad flag in substitute command: '%c'", *p
);
640 * Compile a translation set of strings into a lookup table.
643 compile_tr(char *p
, char **transtab
)
647 char *old
= NULL
, *new = NULL
;
649 if (*p
== '\0' || *p
== '\\')
651 "transform pattern can not be delimited by newline or backslash");
652 old
= xmalloc(strlen(p
) + 1);
653 p
= compile_delimited(p
, old
);
655 err(COMPILE
, "unterminated transform source string");
658 new = xmalloc(strlen(p
) + 1);
659 p
= compile_delimited(--p
, new);
661 err(COMPILE
, "unterminated transform target string");
665 if (strlen(new) != strlen(old
)) {
666 err(COMPILE
, "transform strings are not the same length");
669 /* We assume characters are 8 bits */
670 lt
= xmalloc(UCHAR_MAX
+1);
671 for (i
= 0; i
<= UCHAR_MAX
; i
++)
673 for (op
= old
, np
= new; *op
; op
++, np
++)
674 lt
[(u_char
)*op
] = *np
;
686 * Compile the text following an a, c, or i command.
691 int asize
, size
, len
;
692 char *lbuf
, *text
, *p
, *op
, *s
;
697 while ((p
= cu_fgets(&lbuf
, &bufsize
))) {
698 len
= ROUNDLEN(strlen(p
) + 1);
699 if (asize
- size
< len
) {
702 } while (asize
- size
< len
);
703 text
= xrealloc(text
, asize
);
705 op
= s
= text
+ size
;
718 return (xrealloc(text
, size
+ 1));
722 * Get an address and return a pointer to the first character after
723 * it. Fill the structure pointed to according to the address.
726 compile_addr(char *p
, struct s_addr
*a
)
731 case '\\': /* Context address */
734 case '/': /* Context address */
735 p
= compile_re(p
, &a
->u
.r
);
737 err(COMPILE
, "unterminated regular expression");
741 case '$': /* Last line */
745 case '0': case '1': case '2': case '3': case '4':
746 case '5': case '6': case '7': case '8': case '9':
748 a
->u
.l
= strtol(p
, &end
, 10);
751 err(COMPILE
, "expected context address");
758 * Return a copy of all the characters up to \n or \0.
761 duptoeol(char *s
, const char *ctype
)
768 for (start
= s
; *s
!= '\0' && *s
!= '\n'; ++s
)
769 ws
= isspace((unsigned char)*s
);
772 err(WARNING
, "whitespace after %s", ctype
);
774 return (memmove(xmalloc(len
), start
, len
));
778 * Convert goto label names to addresses, and count a and r commands, in
779 * the given subset of the script. Free the memory used by labels in b
780 * and t commands (but not by :).
782 * TODO: Remove } nodes
785 fixuplabel(struct s_command
*cp
, struct s_command
*end
)
788 for (; cp
!= end
; cp
= cp
->next
)
796 /* Resolve branch target. */
801 if ((cp
->u
.c
= findlabel(cp
->t
)) == NULL
)
802 err(COMPILE2
, "undefined label '%s'", cp
->t
);
806 /* Do interior commands. */
807 fixuplabel(cp
->u
.c
, cp
->next
);
813 * Associate the given command label for later lookup.
816 enterlabel(struct s_command
*cp
)
818 struct labhash
**lhp
, *lh
;
822 for (h
= 0, p
= (u_char
*)cp
->t
; (c
= *p
) != 0; p
++)
823 h
= (h
<< 5) + h
+ c
;
824 lhp
= &labels
[h
& LHMASK
];
825 for (lh
= *lhp
; lh
!= NULL
; lh
= lh
->lh_next
)
826 if (lh
->lh_hash
== h
&& strcmp(cp
->t
, lh
->lh_cmd
->t
) == 0)
827 err(COMPILE2
, "duplicate label '%s'", cp
->t
);
828 lh
= xmalloc(sizeof *lh
);
837 * Find the label contained in the command l in the command linked
838 * list cp. L is excluded from the search. Return NULL if not found.
840 static struct s_command
*
841 findlabel(char *name
)
847 for (h
= 0, p
= (u_char
*)name
; (c
= *p
) != 0; p
++)
848 h
= (h
<< 5) + h
+ c
;
849 for (lh
= labels
[h
& LHMASK
]; lh
!= NULL
; lh
= lh
->lh_next
) {
850 if (lh
->lh_hash
== h
&& strcmp(name
, lh
->lh_cmd
->t
) == 0) {
859 * Warn about any unused labels. As a side effect, release the label hash
865 struct labhash
*lh
, *next
;
868 for (i
= 0; i
< LHSZ
; i
++) {
869 for (lh
= labels
[i
]; lh
!= NULL
; lh
= next
) {
872 err(WARNING
, "unused label '%s'",