1 /* $NetBSD: compile.c,v 1.46 2015/03/12 12:40:41 christos Exp $ */
4 * Copyright (c) 1992 Diomidis Spinellis.
5 * Copyright (c) 1992, 1993
6 * The Regents of the University of California. All rights reserved.
8 * This code is derived from software contributed to Berkeley by
9 * Diomidis Spinellis of Imperial College, University of London.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
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.
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
36 #if HAVE_NBTOOL_CONFIG_H
37 #include "nbtool_config.h"
40 #include <sys/cdefs.h>
41 __RCSID("$NetBSD: compile.c,v 1.46 2015/03/12 12:40:41 christos Exp $");
43 __FBSDID("$FreeBSD: head/usr.bin/sed/compile.c 259132 2013-12-09 18:57:20Z eadler $");
47 static const char sccsid
[] = "@(#)compile.c 8.1 (Berkeley) 6/6/93";
50 #include <sys/types.h>
68 #define LHMASK (LHSZ - 1)
69 static struct labhash
{
70 struct labhash
*lh_next
;
72 struct s_command
*lh_cmd
;
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
90 static void fixuplabel(struct s_command
*, struct s_command
*);
91 static void uselabel(void);
94 * Command specification. This is used to drive the command parser.
97 char code
; /* Command code */
98 int naddr
; /* Number of address args */
99 enum e_args args
; /* Argument type */
102 static struct s_format cmd_fmts
[] = {
134 /* The compiled program. */
135 struct s_command
*prog
;
138 * Compile the program into prog.
139 * Initialise appends.
144 *compile_stream(&prog
) = NULL
;
145 fixuplabel(prog
, NULL
);
148 appends
= xmalloc(sizeof(struct s_appends
) * appendnum
);
149 match
= xmalloc((maxnsub
+ 1) * sizeof(regmatch_t
));
152 #define EATSPACE() do { \
154 while (*p && isspace((unsigned char)*p)) \
158 static struct s_command
**
159 compile_stream(struct s_command
**link
)
162 static char lbuf
[_POSIX2_LINE_MAX
+ 1]; /* To save stack */
163 struct s_command
*cmd
, *cmd2
, *stack
;
165 char re
[_POSIX2_LINE_MAX
+ 1];
166 int naddr
; /* Number of addresses */
170 if ((p
= cu_fgets(lbuf
, sizeof(lbuf
), NULL
)) == NULL
) {
172 errx(1, "%lu: %s: unexpected EOF (pending }'s)",
177 semicolon
: EATSPACE();
179 if (*p
== '#' || *p
== '\0')
181 else if (*p
== ';') {
186 *link
= cmd
= xmalloc(sizeof(struct s_command
));
188 cmd
->startline
= cmd
->nonsel
= 0;
189 /* First parse the addresses */
192 /* Valid characters to start an address */
193 #define addrchar(c) (strchr("0123456789/\\$", (c)))
196 cmd
->a1
= xmalloc(sizeof(struct s_addr
));
197 p
= compile_addr(p
, cmd
->a1
);
198 EATSPACE(); /* EXTENSION */
201 EATSPACE(); /* EXTENSION */
203 cmd
->a2
= xmalloc(sizeof(struct s_addr
));
204 p
= compile_addr(p
, cmd
->a2
);
209 cmd
->a1
= cmd
->a2
= 0;
211 nonsel
: /* Now parse the command */
213 errx(1, "%lu: %s: command expected", linenum
, fname
);
215 for (fp
= cmd_fmts
; fp
->code
; fp
++)
219 errx(1, "%lu: %s: invalid command code %c", linenum
, fname
, *p
);
220 if (naddr
> fp
->naddr
)
222 "%lu: %s: command %c expects up to %d address(es), found %d",
223 linenum
, fname
, *p
, fp
->naddr
, naddr
);
228 cmd
->nonsel
= ! cmd
->nonsel
;
241 * Short-circuit command processing, since end of
242 * group is really just a noop.
246 errx(1, "%lu: %s: unexpected }", linenum
, fname
);
251 case EMPTY
: /* d D g G h H l n N p P q x = \0 */
264 errx(1, "%lu: %s: extra characters at the end of %c command",
265 linenum
, fname
, cmd
->code
);
268 case TEXT
: /* a c i */
273 "%lu: %s: command %c expects \\ followed by text", linenum
, fname
, cmd
->code
);
278 "%lu: %s: extra characters after \\ at the end of %c command",
279 linenum
, fname
, cmd
->code
);
280 cmd
->t
= compile_text();
282 case COMMENT
: /* \0 # */
288 errx(1, "%lu: %s: filename expected", linenum
, fname
);
289 cmd
->t
= duptoeol(p
, "w command");
292 else if ((cmd
->u
.fd
= open(p
,
293 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
,
301 errx(1, "%lu: %s: filename expected", linenum
, fname
);
303 cmd
->t
= duptoeol(p
, "read command");
305 case BRANCH
: /* b t */
311 cmd
->t
= duptoeol(p
, "branch");
316 cmd
->t
= duptoeol(p
, "label");
318 errx(1, "%lu: %s: empty label", linenum
, fname
);
323 if (*p
== '\0' || *p
== '\\')
325 "%lu: %s: substitute pattern can not be delimited by newline or backslash",
327 cmd
->u
.s
= xcalloc(1, sizeof(struct s_subst
));
328 p
= compile_delimited(p
, re
, 0);
331 "%lu: %s: unterminated substitute pattern", linenum
, fname
);
333 /* Compile RE with no case sensitivity temporarily */
337 cmd
->u
.s
->re
= compile_re(re
, 0);
339 p
= compile_subst(p
, cmd
->u
.s
);
340 p
= compile_flags(p
, cmd
->u
.s
);
342 /* Recompile RE with case sensitivity from "I" flag if any */
346 cmd
->u
.s
->re
= compile_re(re
, cmd
->u
.s
->icase
);
356 p
= compile_tr(p
, &cmd
->u
.y
);
369 "%lu: %s: extra text at the end of a transform command", linenum
, fname
);
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.
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.
387 compile_delimited(char *p
, char *d
, int is_tr
)
395 errx(1, "%lu: %s: \\ can not be used as a string delimiter",
398 errx(1, "%lu: %s: newline can not be used as a string delimiter",
401 if (*p
== '[' && *p
!= c
) {
402 if ((d
= compile_ccl(&p
, d
)) == NULL
)
403 errx(1, "%lu: %s: unbalanced brackets ([])", linenum
, fname
);
405 } else if (*p
== '\\' && p
[1] == '[') {
407 } else if (*p
== '\\' && p
[1] == c
)
409 else if (*p
== '\\' && p
[1] == 'n') {
413 } else if (*p
== '\\' && p
[1] == '\\') {
418 } else if (*p
== c
) {
428 /* compile_ccl: expand a POSIX character class */
430 compile_ccl(char **sp
, char *t
)
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')
447 return (*s
== ']') ? *sp
= ++s
, ++t
: NULL
;
451 * Compiles the regular expression in RE and returns a pointer to the compiled
452 * regular expression.
453 * Cflags are passed to regcomp.
456 compile_re(char *re
, int case_insensitive
)
463 if (case_insensitive
)
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
;
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
480 compile_subst(char *p
, struct s_subst
*s
)
482 static char lbuf
[_POSIX2_LINE_MAX
+ 1];
485 char c
, *text
, *op
, *sp
;
486 int more
= 1, sawesc
= 0;
488 c
= *p
++; /* Terminator character */
493 s
->linenum
= linenum
;
494 asize
= 2 * _POSIX2_LINE_MAX
+ 1;
495 text
= xmalloc(asize
);
498 op
= sp
= text
+ size
;
500 if (*p
== '\\' || sawesc
) {
502 * If this is a continuation from the last
503 * buffer, we won't have a character to
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.
522 } else if (strchr("123456789", *p
) != NULL
) {
524 ref
= (u_char
)(*p
- '0');
526 ref
> s
->re
->re_nsub
)
527 errx(1, "%lu: %s: \\%c not defined in the RE",
529 if (s
->maxbref
< ref
)
531 } else if (*p
== '&' || *p
== '\\')
533 } else if (*p
== c
) {
534 if (*++p
== '\0' && more
) {
535 if (cu_fgets(lbuf
, sizeof(lbuf
), &more
))
539 size
+= (size_t)(sp
- op
);
540 s
->new = xrealloc(text
, size
);
542 } else if (*p
== '\n') {
544 "%lu: %s: unescaped newline inside substitute pattern", linenum
, fname
);
549 size
+= (size_t)(sp
- op
);
550 if (asize
- size
< _POSIX2_LINE_MAX
+ 1) {
552 text
= xrealloc(text
, asize
);
554 } while (cu_fgets(p
= lbuf
, sizeof(lbuf
), &more
));
555 errx(1, "%lu: %s: unterminated substitute in regular expression",
561 * Compile the flags of the s command
564 compile_flags(char *p
, struct s_subst
*s
)
566 int gn
; /* True if we have seen g or n */
568 char wfile
[_POSIX2_LINE_MAX
+ 1], *q
;
570 s
->n
= 1; /* Default */
576 EATSPACE(); /* EXTENSION */
581 "%lu: %s: more than one number or 'g' in substitute flags", linenum
, fname
);
596 case '1': case '2': case '3':
597 case '4': case '5': case '6':
598 case '7': case '8': case '9':
601 "%lu: %s: more than one number or 'g' in substitute flags", linenum
, fname
);
604 nval
= strtoul(p
, &p
, 10);
605 if (errno
== ERANGE
|| nval
> INT_MAX
)
607 "%lu: %s: overflow in the 'N' substitute flag", linenum
, fname
);
613 #ifdef HISTORIC_PRACTICE
615 warnx("%lu: %s: space missing before w wfile", linenum
, fname
);
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
,
636 errx(1, "%lu: %s: bad flag in substitute command: '%c'",
645 * Compile a translation set of strings into a lookup table.
648 compile_tr(char *p
, struct s_tr
**py
)
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
;
658 *py
= y
= xmalloc(sizeof(*y
));
662 if (*p
== '\0' || *p
== '\\')
664 "%lu: %s: transform pattern can not be delimited by newline or backslash",
666 p
= compile_delimited(p
, old
, 1);
668 errx(1, "%lu: %s: unterminated transform source string",
670 p
= compile_delimited(p
- 1, new, 1);
672 errx(1, "%lu: %s: unterminated transform target string",
676 oldlen
= mbsrtowcs(NULL
, &op
, 0, NULL
);
677 if (oldlen
== (size_t)-1)
680 newlen
= mbsrtowcs(NULL
, &np
, 0, NULL
);
681 if (newlen
== (size_t)-1)
683 if (newlen
!= oldlen
)
684 errx(1, "%lu: %s: transform strings are not the same length",
686 if (MB_CUR_MAX
== 1) {
688 * The single-byte encoding case is easy: generate a
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
;
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.
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
;
717 y
->bytetab
[(u_char
)*op
] = 0;
718 y
->multis
= xrealloc(y
->multis
,
719 (y
->nmultis
+ 1) * sizeof(*y
->multis
));
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
);
734 * Compile the text following an a or i command.
741 char *text
, *p
, *op
, *s
;
742 char lbuf
[_POSIX2_LINE_MAX
+ 1];
744 asize
= 2 * _POSIX2_LINE_MAX
+ 1;
745 text
= xmalloc(asize
);
747 while (cu_fgets(lbuf
, sizeof(lbuf
), NULL
)) {
748 op
= s
= text
+ size
;
751 for (esc_nl
= 0; *p
!= '\0'; p
++) {
752 if (*p
== '\\' && p
[1] != '\0' && *++p
== '\n')
756 size
+= (size_t)(s
- op
);
761 if (asize
- size
< _POSIX2_LINE_MAX
+ 1) {
763 text
= xrealloc(text
, asize
);
767 p
= xrealloc(text
, size
+ 1);
772 * Get an address and return a pointer to the first character after
773 * it. Fill the structure pointed to according to the address.
776 compile_addr(char *p
, struct s_addr
*a
)
778 char *end
, re
[_POSIX2_LINE_MAX
+ 1];
785 case '\\': /* Context address */
788 case '/': /* Context address */
789 p
= compile_delimited(p
, re
, 0);
791 errx(1, "%lu: %s: unterminated regular expression", linenum
, fname
);
792 /* Check for case insensitive regexp flag */
800 a
->u
.r
= compile_re(re
, icase
);
804 case '$': /* Last line */
808 case '+': /* Relative line number */
809 a
->type
= AT_RELLINE
;
813 case '0': case '1': case '2': case '3': case '4':
814 case '5': case '6': case '7': case '8': case '9':
817 a
->u
.l
= strtoul(p
, &end
, 10);
820 errx(1, "%lu: %s: expected context address", linenum
, fname
);
827 * Return a copy of all the characters up to \n or \0.
830 duptoeol(char *s
, const char *ctype
)
837 for (start
= s
; *s
!= '\0' && *s
!= '\n'; ++s
)
838 ws
= isspace((unsigned char)*s
);
841 warnx("%lu: %s: whitespace after %s", linenum
, fname
, ctype
);
842 len
= (size_t)(s
- start
+ 1);
844 return (memmove(p
, start
, len
));
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 :).
852 * TODO: Remove } nodes
855 fixuplabel(struct s_command
*cp
, struct s_command
*end
)
858 for (; cp
!= end
; cp
= cp
->next
)
866 /* Resolve branch target. */
871 if ((cp
->u
.c
= findlabel(cp
->t
)) == NULL
)
872 errx(1, "%lu: %s: undefined label '%s'", linenum
, fname
, cp
->t
);
876 /* Do interior commands. */
877 fixuplabel(cp
->u
.c
, cp
->next
);
883 * Associate the given command label for later lookup.
886 enterlabel(struct s_command
*cp
)
888 struct labhash
**lhp
, *lh
;
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
);
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.
910 static struct s_command
*
911 findlabel(char *name
)
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) {
929 * Warn about any unused labels. As a side effect, release the label hash
935 struct labhash
*lh
, *next
;
938 for (i
= 0; i
< LHSZ
; i
++) {
939 for (lh
= labels
[i
]; lh
!= NULL
; lh
= next
) {
942 warnx("%lu: %s: unused label '%s'",
943 linenum
, fname
, lh
->lh_cmd
->t
);