1 /* $OpenBSD: compile.c,v 1.42 2017/08/01 18:05:53 martijn Exp $ */
5 * mirabilos <m@mirbsd.org>
6 * Copyright (c) 1992 Diomidis Spinellis.
7 * Copyright (c) 1992, 1993
8 * The Regents of the University of California. All rights reserved.
10 * This code is derived from software contributed to Berkeley by
11 * Diomidis Spinellis of Imperial College, University of London.
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 * 3. 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.
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
38 #include <sys/types.h>
53 __RCSID("$MirOS: src/usr.bin/sed/compile.c,v 1.3 2017/11/20 01:23:56 tg Exp $");
56 #define LHMASK (LHSZ - 1)
57 static struct labhash
{
58 struct labhash
*lh_next
;
60 struct s_command
*lh_cmd
;
64 static char *compile_addr(char *, struct s_addr
*);
65 static char *compile_ccl(char **, char *);
66 static char *compile_delimited(char *, char *, int);
67 static char *compile_flags(char *, struct s_subst
*);
68 static char *compile_re(char *, regex_t
**);
69 static char *compile_subst(char *, struct s_subst
*);
70 static char *compile_text(void);
71 static char *compile_tr(char *, char **);
72 static struct s_command
73 **compile_stream(struct s_command
**);
74 static char *duptoeol(char *, const char *, char **);
75 static void enterlabel(struct s_command
*);
76 static struct s_command
78 static void fixuplabel(struct s_command
*, struct s_command
*);
79 static void uselabel(void);
82 * Command specification. This is used to drive the command parser.
85 char code
; /* Command code */
86 int naddr
; /* Number of address args */
87 enum e_args args
; /* Argument type */
90 static struct s_format cmd_fmts
[] = {
122 /* The compiled program. */
123 struct s_command
*prog
;
126 * Compile the program into prog.
127 * Initialise appends.
132 *compile_stream(&prog
) = NULL
;
133 fixuplabel(prog
, NULL
);
135 appends
= xreallocarray(NULL
, appendnum
, sizeof(struct s_appends
));
136 match
= xreallocarray(NULL
, maxnsub
+ 1, sizeof(regmatch_t
));
139 #define EATSPACE() do { \
141 while (isascii((unsigned char)*p) && \
142 isspace((unsigned char)*p)) \
146 static struct s_command
**
147 compile_stream(struct s_command
**link
)
150 static char *lbuf
; /* To avoid excessive malloc calls */
151 static size_t bufsize
;
152 struct s_command
*cmd
, *cmd2
, *stack
;
154 int naddr
; /* Number of addresses */
158 if ((p
= cu_fgets(&lbuf
, &bufsize
)) == NULL
) {
160 error(COMPILE
, "unexpected EOF (pending }'s)");
164 semicolon
: EATSPACE();
165 if (*p
== '#' || *p
== '\0')
171 *link
= cmd
= xmalloc(sizeof(struct s_command
));
173 cmd
->nonsel
= cmd
->inrange
= 0;
174 /* First parse the addresses */
177 /* Valid characters to start an address */
178 #define addrchar(c) (strchr("0123456789/\\$", (c)))
181 cmd
->a1
= xmalloc(sizeof(struct s_addr
));
182 p
= compile_addr(p
, cmd
->a1
);
183 EATSPACE(); /* EXTENSION */
186 EATSPACE(); /* EXTENSION */
188 cmd
->a2
= xmalloc(sizeof(struct s_addr
));
189 p
= compile_addr(p
, cmd
->a2
);
195 cmd
->a1
= cmd
->a2
= 0;
198 nonsel
: /* Now parse the command */
200 error(COMPILE
, "command expected");
202 for (fp
= cmd_fmts
; fp
->code
; fp
++)
206 error(COMPILE
, "invalid command code %c", *p
);
207 if (naddr
> fp
->naddr
)
209 "command %c expects up to %d address(es), found %d",
210 *p
, fp
->naddr
, naddr
);
228 * Short-circuit command processing, since end of
229 * group is really just a noop.
233 error(COMPILE
, "unexpected }");
238 case EMPTY
: /* d D g G h H l n N p P q x = \0 */
248 "extra characters at the end of %c command", cmd
->code
);
250 case TEXT
: /* a c i */
254 error(COMPILE
, "command %c expects \\ followed by"
259 error(COMPILE
, "extra characters after \\ at the"
260 " end of %c command", cmd
->code
);
261 cmd
->t
= compile_text();
263 case COMMENT
: /* \0 # */
269 error(COMPILE
, "filename expected");
270 cmd
->t
= duptoeol(p
, "w command", NULL
);
275 else if ((cmd
->u
.fd
= open(p
,
276 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
,
278 error(FATAL
, "%s: %s", p
, strerror(errno
));
284 cmd
->t
= duptoeol(p
, "read command", NULL
);
286 case BRANCH
: /* b t */
292 cmd
->t
= duptoeol(p
, "branch", &p
);
301 cmd
->t
= duptoeol(p
, "label", &p
);
302 if (strlen(cmd
->t
) == 0)
303 error(COMPILE
, "empty label");
312 if (*p
== '\0' || *p
== '\\')
313 error(COMPILE
, "substitute pattern can not be"
314 " delimited by newline or backslash");
315 cmd
->u
.s
= xmalloc(sizeof(struct s_subst
));
316 p
= compile_re(p
, &cmd
->u
.s
->re
);
318 error(COMPILE
, "unterminated substitute pattern");
320 p
= compile_subst(p
, cmd
->u
.s
);
321 p
= compile_flags(p
, cmd
->u
.s
);
331 p
= compile_tr(p
, (char **)&cmd
->u
.y
);
339 error(COMPILE
, "extra text at the end of a"
340 " transform command");
347 * Get a delimited string. P points to the delimeter of the string; d points
348 * to a buffer area. Newline and delimiter escapes are processed; other
349 * escapes are ignored.
351 * Returns a pointer to the first character after the final delimiter or NULL
352 * in the case of a non-terminated string. The character array d is filled
353 * with the processed string.
356 compile_delimited(char *p
, char *d
, int is_tr
)
364 error(COMPILE
, "\\ can not be used as a string delimiter");
366 error(COMPILE
, "newline can not be used as a string delimiter");
368 if (*p
== '[' && *p
!= c
) {
369 if ((d
= compile_ccl(&p
, d
)) == NULL
)
370 error(COMPILE
, "unbalanced brackets ([])");
372 } else if (*p
== '\\' && p
[1] == '[') {
374 } else if (*p
== '\\' && p
[1] == c
) {
376 } else if (*p
== '\\' && p
[1] == 'n') {
380 } else if (*p
== '\\' && p
[1] == '\\') {
385 } else if (*p
== c
) {
395 /* compile_ccl: expand a POSIX character class */
397 compile_ccl(char **sp
, char *t
)
407 for (; *s
&& (*t
= *s
) != ']'; s
++, t
++)
408 if (*s
== '[' && ((d
= *(s
+1)) == '.' || d
== ':' || d
== '=')) {
409 *++t
= *++s
, t
++, s
++;
410 for (c
= *s
; (*t
= *s
) != ']' || c
!= d
; s
++, t
++)
411 if ((c
= *s
) == '\0')
413 } else if (*s
== '\\' && s
[1] == 'n') {
426 * Get a regular expression. P points to the delimiter of the regular
427 * expression; repp points to the address of a regexp pointer. Newline
428 * and delimiter escapes are processed; other escapes are ignored.
429 * Returns a pointer to the first character after the final delimiter
430 * or NULL in the case of a non terminated regular expression. The regexp
431 * pointer is set to the compiled regular expression.
432 * Cflags are passed to regcomp.
435 compile_re(char *p
, regex_t
**repp
)
440 re
= xmalloc(strlen(p
) + 1); /* strlen(re) <= strlen(p) */
441 p
= compile_delimited(p
, re
, 0);
442 if (p
&& strlen(re
) == 0) {
447 *repp
= xmalloc(sizeof(regex_t
));
448 if (p
&& (eval
= regcomp(*repp
, re
, Eflag
? REG_EXTENDED
: 0)) != 0)
449 error(COMPILE
, "RE error: %s", strregerror(eval
, *repp
));
450 if (maxnsub
< (*repp
)->re_nsub
)
451 maxnsub
= (*repp
)->re_nsub
;
457 * Compile the substitution string of a regular expression and set res to
458 * point to a saved copy of it. Nsub is the number of parenthesized regular
462 compile_subst(char *p
, struct s_subst
*s
)
465 static size_t bufsize
;
466 size_t asize
, ref
, size
;
467 char c
, *text
, *op
, *sp
;
470 c
= *p
++; /* Terminator character */
475 s
->linenum
= linenum
;
479 size_t len
= ROUNDLEN(strlen(p
) + 1);
480 if (asize
- size
< len
) {
483 } while (asize
- size
< len
);
484 text
= xrealloc(text
, asize
);
486 op
= sp
= text
+ size
;
488 if (*p
== '\\' || sawesc
) {
490 * If this is a continuation from the last
491 * buffer, we won't have a character to
501 * This escaped character is continued
502 * in the next part of the line. Note
503 * this fact, then cause the loop to
504 * exit w/ normal EOL case and reenter
505 * above with the new buffer.
510 } else if (strchr("123456789", *p
) != NULL
) {
514 ref
> s
->re
->re_nsub
)
516 "\\%c not defined in the RE", *p
);
517 if (s
->maxbref
< ref
)
519 } else if (*p
== '&' || *p
== '\\')
521 } else if (*p
== c
) {
525 s
->new = xrealloc(text
, size
);
527 } else if (*p
== '\n') {
529 "unescaped newline inside substitute pattern");
534 } while ((p
= cu_fgets(&lbuf
, &bufsize
)));
535 error(COMPILE
, "unterminated substitute in regular expression");
539 * Compile the flags of the s command
542 compile_flags(char *p
, struct s_subst
*s
)
544 int gn
; /* True if we have seen g or n */
546 char wfile
[PATH_MAX
], *q
, *eq
;
548 s
->n
= 1; /* Default */
553 EATSPACE(); /* EXTENSION */
557 error(COMPILE
, "more than one number or 'g' in"
558 " substitute flags");
569 case '1': case '2': case '3':
570 case '4': case '5': case '6':
571 case '7': case '8': case '9':
573 error(COMPILE
, "more than one number or 'g' in"
574 " substitute flags");
576 l
= strtol(p
, &p
, 10);
577 if (l
<= 0 || l
>= INT_MAX
)
579 "number in substitute flags out of range");
584 #ifdef HISTORIC_PRACTICE
586 warning("space missing before w wfile");
592 eq
= wfile
+ sizeof(wfile
) - 1;
597 error(COMPILE
, "wfile too long");
602 error(COMPILE
, "no wfile specified");
603 s
->wfile
= strdup(wfile
);
606 else if ((s
->wfd
= open(wfile
,
607 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
,
609 error(FATAL
, "%s: %s", wfile
, strerror(errno
));
613 "bad flag in substitute command: '%c'", *p
);
621 * Compile a translation set of strings into a lookup table.
624 compile_tr(char *p
, char **transtab
)
628 char *old
= NULL
, *new = NULL
;
630 if (*p
== '\0' || *p
== '\\')
632 "transform pattern can not be delimited by newline or backslash");
633 old
= xmalloc(strlen(p
) + 1);
634 p
= compile_delimited(p
, old
, 1);
636 error(COMPILE
, "unterminated transform source string");
639 new = xmalloc(strlen(p
) + 1);
640 p
= compile_delimited(--p
, new, 1);
642 error(COMPILE
, "unterminated transform target string");
646 if (strlen(new) != strlen(old
)) {
647 error(COMPILE
, "transform strings are not the same length");
650 /* We assume characters are 8 bits */
651 lt
= xmalloc(UCHAR_MAX
+ 1);
652 for (i
= 0; i
<= UCHAR_MAX
; i
++)
654 for (op
= old
, np
= new; *op
; op
++, np
++)
655 lt
[(u_char
)*op
] = *np
;
667 * Compile the text following an a, c, or i command.
674 char *lbuf
, *text
, *p
, *op
, *s
;
679 while ((p
= cu_fgets(&lbuf
, &bufsize
))) {
680 size_t len
= ROUNDLEN(strlen(p
) + 1);
681 if (asize
- size
< len
) {
684 } while (asize
- size
< len
);
685 text
= xrealloc(text
, asize
);
687 op
= s
= text
+ size
;
688 for (esc_nl
= 0; *p
!= '\0'; p
++) {
689 if (*p
== '\\' && p
[1] != '\0' && *++p
== '\n')
700 text
= xrealloc(text
, size
+ 1);
706 * Get an address and return a pointer to the first character after
707 * it. Fill the structure pointed to according to the address.
710 compile_addr(char *p
, struct s_addr
*a
)
715 case '\\': /* Context address */
718 case '/': /* Context address */
719 p
= compile_re(p
, &a
->u
.r
);
721 error(COMPILE
, "unterminated regular expression");
725 case '$': /* Last line */
729 case '0': case '1': case '2': case '3': case '4':
730 case '5': case '6': case '7': case '8': case '9':
732 a
->u
.l
= strtoul(p
, &end
, 10);
735 error(COMPILE
, "expected context address");
742 * Return a copy of all the characters up to \n or \0.
745 duptoeol(char *s
, const char *ctype
, char **semi
)
753 for (start
= s
; *s
!= '\0' && *s
!= '\n' && *s
!= ';'; ++s
)
754 ws
= isspace((unsigned char)*s
);
756 for (start
= s
; *s
!= '\0' && *s
!= '\n'; ++s
)
757 ws
= isspace((unsigned char)*s
);
761 warning("whitespace after %s", ctype
);
766 strlcpy(s
, start
, len
);
771 * Convert goto label names to addresses, and count a and r commands, in
772 * the given subset of the script. Free the memory used by labels in b
773 * and t commands (but not by :).
775 * TODO: Remove } nodes
778 fixuplabel(struct s_command
*cp
, struct s_command
*end
)
781 for (; cp
!= end
; cp
= cp
->next
)
789 /* Resolve branch target. */
794 if ((cp
->u
.c
= findlabel(cp
->t
)) == NULL
)
795 error(COMPILE
, "undefined label '%s'", cp
->t
);
799 /* Do interior commands. */
800 fixuplabel(cp
->u
.c
, cp
->next
);
806 * Associate the given command label for later lookup.
809 enterlabel(struct s_command
*cp
)
811 struct labhash
**lhp
, *lh
;
815 for (h
= 0, p
= (u_char
*)cp
->t
; (c
= *p
) != 0; p
++)
816 h
= (h
<< 5) + h
+ c
;
817 lhp
= &labels
[h
& LHMASK
];
818 for (lh
= *lhp
; lh
!= NULL
; lh
= lh
->lh_next
)
819 if (lh
->lh_hash
== h
&& strcmp(cp
->t
, lh
->lh_cmd
->t
) == 0)
820 error(COMPILE
, "duplicate label '%s'", cp
->t
);
821 lh
= xmalloc(sizeof *lh
);
830 * Find the label contained in the command l in the command linked
831 * list cp. L is excluded from the search. Return NULL if not found.
833 static struct s_command
*
834 findlabel(char *name
)
840 for (h
= 0, p
= (u_char
*)name
; (c
= *p
) != 0; p
++)
841 h
= (h
<< 5) + h
+ c
;
842 for (lh
= labels
[h
& LHMASK
]; lh
!= NULL
; lh
= lh
->lh_next
) {
843 if (lh
->lh_hash
== h
&& strcmp(name
, lh
->lh_cmd
->t
) == 0) {
852 * Warn about any unused labels. As a side effect, release the label hash
858 struct labhash
*lh
, *next
;
861 for (i
= 0; i
< LHSZ
; i
++) {
862 for (lh
= labels
[i
]; lh
!= NULL
; lh
= next
) {
865 warning("unused label '%s'",