2 * SPDX-License-Identifier: BSD-3-Clause
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
35 * @(#)compile.c 8.1 (Berkeley) 6/6/93
36 * $FreeBSD: head/usr.bin/sed/compile.c 361884 2020-06-07 04:32:38Z kevans $
39 #include <sys/cdefs.h>
41 #include <sys/types.h>
60 #define LHMASK (LHSZ - 1)
61 static struct labhash
{
62 struct labhash
*lh_next
;
64 struct s_command
*lh_cmd
;
68 static char *compile_addr(char *, struct s_addr
*);
69 static char *compile_ccl(char **, char *);
70 static char *compile_delimited(char *, char *, int);
71 static char *compile_flags(char *, struct s_subst
*);
72 static regex_t
*compile_re(char *, int);
73 static char *compile_subst(char *, struct s_subst
*);
74 static char *compile_text(void);
75 static char *compile_tr(char *, struct s_tr
**);
76 static struct s_command
77 **compile_stream(struct s_command
**);
78 static char *duptoeol(char *, const char *);
79 static void enterlabel(struct s_command
*);
80 static struct s_command
82 static void fixuplabel(struct s_command
*, struct s_command
*);
83 static void uselabel(void);
86 * Command specification. This is used to drive the command parser.
89 char code
; /* Command code */
90 int naddr
; /* Number of address args */
91 enum e_args args
; /* Argument type */
94 static struct s_format cmd_fmts
[] = {
126 /* The compiled program. */
127 struct s_command
*prog
;
130 * Compile the program into prog.
131 * Initialise appends.
136 *compile_stream(&prog
) = NULL
;
137 fixuplabel(prog
, NULL
);
141 else if ((appends
= malloc(sizeof(struct s_appends
) * appendnum
)) ==
144 if ((match
= malloc((maxnsub
+ 1) * sizeof(regmatch_t
))) == NULL
)
148 #define EATSPACE() do { \
150 while (*p && isspace((unsigned char)*p)) \
154 static struct s_command
**
155 compile_stream(struct s_command
**link
)
158 static char lbuf
[_POSIX2_LINE_MAX
+ 1]; /* To save stack */
159 struct s_command
*cmd
, *cmd2
, *stack
;
161 char re
[_POSIX2_LINE_MAX
+ 1];
162 int naddr
; /* Number of addresses */
166 if ((p
= cu_fgets(lbuf
, sizeof(lbuf
), NULL
)) == NULL
) {
168 errx(1, "%lu: %s: unexpected EOF (pending }'s)",
173 semicolon
: EATSPACE();
175 if (*p
== '#' || *p
== '\0')
177 else if (*p
== ';') {
182 if ((*link
= cmd
= malloc(sizeof(struct s_command
))) == NULL
)
185 cmd
->startline
= cmd
->nonsel
= 0;
186 /* First parse the addresses */
189 /* Valid characters to start an address */
190 #define addrchar(c) (strchr("0123456789/\\$", (c)))
193 if ((cmd
->a1
= malloc(sizeof(struct s_addr
))) == NULL
)
195 p
= compile_addr(p
, cmd
->a1
);
196 EATSPACE(); /* EXTENSION */
199 EATSPACE(); /* EXTENSION */
201 if ((cmd
->a2
= malloc(sizeof(struct s_addr
)))
204 p
= compile_addr(p
, cmd
->a2
);
209 cmd
->a1
= cmd
->a2
= NULL
;
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
);
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 */
260 errx(1, "%lu: %s: extra characters at the end of %c command",
261 linenum
, fname
, cmd
->code
);
263 case TEXT
: /* a c i */
268 "%lu: %s: command %c expects \\ followed by text", linenum
, fname
, cmd
->code
);
273 "%lu: %s: extra characters after \\ at the end of %c command",
274 linenum
, fname
, cmd
->code
);
275 cmd
->t
= compile_text();
277 case COMMENT
: /* \0 # */
283 errx(1, "%lu: %s: filename expected", linenum
, fname
);
284 cmd
->t
= duptoeol(p
, "w command");
287 else if ((cmd
->u
.fd
= open(p
,
288 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
,
296 errx(1, "%lu: %s: filename expected", linenum
, fname
);
298 cmd
->t
= duptoeol(p
, "read command");
300 case BRANCH
: /* b t */
306 cmd
->t
= duptoeol(p
, "branch");
311 cmd
->t
= duptoeol(p
, "label");
313 errx(1, "%lu: %s: empty label", linenum
, fname
);
318 if (*p
== '\0' || *p
== '\\')
320 "%lu: %s: substitute pattern can not be delimited by newline or backslash",
322 if ((cmd
->u
.s
= calloc(1, sizeof(struct s_subst
))) == NULL
)
324 p
= compile_delimited(p
, re
, 0);
327 "%lu: %s: unterminated substitute pattern", linenum
, fname
);
329 /* Compile RE with no case sensitivity temporarily */
333 cmd
->u
.s
->re
= compile_re(re
, 0);
335 p
= compile_subst(p
, cmd
->u
.s
);
336 p
= compile_flags(p
, cmd
->u
.s
);
338 /* Recompile RE with case sensitivity from "I" flag if any */
342 cmd
->u
.s
->re
= compile_re(re
, cmd
->u
.s
->icase
);
352 p
= compile_tr(p
, &cmd
->u
.y
);
361 "%lu: %s: extra text at the end of a transform command", linenum
, fname
);
368 hex2char(const char *in
, char *out
, int len
)
371 char *endptr
, hexbuf
[3];
374 hexbuf
[1] = len
> 1 ? in
[1] : '\0';
378 ord
= strtol(hexbuf
, &endptr
, 16);
379 if (*endptr
!= '\0' || errno
!= 0)
391 return isdigit(lc
) || (lc
>= 'a' && lc
<= 'f');
395 dohex(const char *in
, char *out
, int *len
)
399 if (!hexdigit(in
[0]))
404 if (hex2char(in
, out
, tmplen
) == 0) {
413 * Get a delimited string. P points to the delimiter of the string; d points
414 * to a buffer area. Newline and delimiter escapes are processed; other
415 * escapes are ignored.
417 * Returns a pointer to the first character after the final delimiter or NULL
418 * in the case of a non-terminated string. The character array d is filled
419 * with the processed string.
422 compile_delimited(char *p
, char *d
, int is_tr
)
431 errx(1, "%lu: %s: \\ can not be used as a string delimiter",
434 errx(1, "%lu: %s: newline can not be used as a string delimiter",
437 if (*p
== '[' && *p
!= c
) {
438 if ((d
= compile_ccl(&p
, d
)) == NULL
)
439 errx(1, "%lu: %s: unbalanced brackets ([])", linenum
, fname
);
441 } else if (*p
== '\\' && p
[1] == '[') {
443 } else if (*p
== '\\' && p
[1] == c
) {
445 } else if (*p
== '\\' &&
446 (p
[1] == 'n' || p
[1] == 'r' || p
[1] == 't')) {
460 } else if (*p
== '\\' && p
[1] == 'x') {
461 if (dohex(&p
[2], d
, &hexlen
)) {
466 } else if (*p
== '\\' && p
[1] == '\\') {
471 } else if (*p
== c
) {
481 /* compile_ccl: expand a POSIX character class */
483 compile_ccl(char **sp
, char *t
)
493 for (; *s
&& (*t
= *s
) != ']'; s
++, t
++) {
494 if (*s
== '[' && ((d
= *(s
+1)) == '.' || d
== ':' || d
== '=')) {
495 *++t
= *++s
, t
++, s
++;
496 for (c
= *s
; (*t
= *s
) != ']' || c
!= d
; s
++, t
++)
497 if ((c
= *s
) == '\0')
499 } else if (*s
== '\\') {
514 if (dohex(&s
[2], t
, &hexlen
))
520 return (*s
== ']') ? *sp
= ++s
, ++t
: NULL
;
524 * Compiles the regular expression in RE and returns a pointer to the compiled
525 * regular expression.
526 * Cflags are passed to regcomp.
529 compile_re(char *re
, int case_insensitive
)
536 if (case_insensitive
)
538 if ((rep
= malloc(sizeof(regex_t
))) == NULL
)
540 if ((eval
= regcomp(rep
, re
, flags
)) != 0)
541 errx(1, "%lu: %s: RE error: %s",
542 linenum
, fname
, strregerror(eval
, rep
));
543 if (maxnsub
< rep
->re_nsub
)
544 maxnsub
= rep
->re_nsub
;
549 * Compile the substitution string of a regular expression and set res to
550 * point to a saved copy of it. Nsub is the number of parenthesized regular
554 compile_subst(char *p
, struct s_subst
*s
)
556 static char lbuf
[_POSIX2_LINE_MAX
+ 1];
557 int asize
, hexlen
, size
;
559 char c
, *text
, *op
, *sp
;
560 int more
= 1, sawesc
= 0;
562 c
= *p
++; /* Terminator character */
567 s
->linenum
= linenum
;
568 asize
= 2 * _POSIX2_LINE_MAX
+ 1;
569 if ((text
= malloc(asize
)) == NULL
)
573 op
= sp
= text
+ size
;
575 if (*p
== '\\' || sawesc
) {
577 * If this is a continuation from the last
578 * buffer, we won't have a character to
588 * This escaped character is continued
589 * in the next part of the line. Note
590 * this fact, then cause the loop to
591 * exit w/ normal EOL case and reenter
592 * above with the new buffer.
597 } else if (strchr("123456789", *p
) != NULL
) {
601 ref
> s
->re
->re_nsub
)
602 errx(1, "%lu: %s: \\%c not defined in the RE",
604 if (s
->maxbref
< ref
)
622 #define ADVANCE_N(s, n) \
625 while (*(adv + (n) - 1) != '\0') { \
626 *adv = *(adv + (n)); \
631 if (dohex(&p
[1], p
, &hexlen
)) {
638 } else if (*p
== c
) {
639 if (*++p
== '\0' && more
) {
640 if (cu_fgets(lbuf
, sizeof(lbuf
), &more
))
645 if ((s
->new = realloc(text
, size
)) == NULL
)
648 } else if (*p
== '\n') {
650 "%lu: %s: unescaped newline inside substitute pattern", linenum
, fname
);
656 if (asize
- size
< _POSIX2_LINE_MAX
+ 1) {
658 if ((text
= realloc(text
, asize
)) == NULL
)
661 } while (cu_fgets(p
= lbuf
, sizeof(lbuf
), &more
) != NULL
);
662 errx(1, "%lu: %s: unterminated substitute in regular expression",
668 * Compile the flags of the s command
671 compile_flags(char *p
, struct s_subst
*s
)
673 int gn
; /* True if we have seen g or n */
675 char wfile
[_POSIX2_LINE_MAX
+ 1], *q
, *eq
;
677 s
->n
= 1; /* Default */
683 EATSPACE(); /* EXTENSION */
688 "%lu: %s: more than one number or 'g' in substitute flags", linenum
, fname
);
703 case '1': case '2': case '3':
704 case '4': case '5': case '6':
705 case '7': case '8': case '9':
708 "%lu: %s: more than one number or 'g' in substitute flags", linenum
, fname
);
711 nval
= strtol(p
, &p
, 10);
712 if (errno
== ERANGE
|| nval
> INT_MAX
)
714 "%lu: %s: overflow in the 'N' substitute flag", linenum
, fname
);
720 #ifdef HISTORIC_PRACTICE
722 warnx("%lu: %s: space missing before w wfile", linenum
, fname
);
728 eq
= wfile
+ sizeof(wfile
) - 1;
733 err(1, "wfile too long");
738 errx(1, "%lu: %s: no wfile specified", linenum
, fname
);
739 s
->wfile
= strdup(wfile
);
740 if (!aflag
&& (s
->wfd
= open(wfile
,
741 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
,
746 errx(1, "%lu: %s: bad flag in substitute command: '%c'",
755 * Compile a translation set of strings into a lookup table.
758 compile_tr(char *p
, struct s_tr
**py
)
763 char old
[_POSIX2_LINE_MAX
+ 1];
764 char new[_POSIX2_LINE_MAX
+ 1];
765 size_t oclen
, oldlen
, nclen
, newlen
;
766 mbstate_t mbs1
, mbs2
;
768 if ((*py
= y
= malloc(sizeof(*y
))) == NULL
)
773 if (*p
== '\0' || *p
== '\\')
775 "%lu: %s: transform pattern can not be delimited by newline or backslash",
777 p
= compile_delimited(p
, old
, 1);
779 errx(1, "%lu: %s: unterminated transform source string",
781 p
= compile_delimited(p
- 1, new, 1);
783 errx(1, "%lu: %s: unterminated transform target string",
787 oldlen
= mbsrtowcs(NULL
, &op
, 0, NULL
);
788 if (oldlen
== (size_t)-1)
791 newlen
= mbsrtowcs(NULL
, &np
, 0, NULL
);
792 if (newlen
== (size_t)-1)
794 if (newlen
!= oldlen
)
795 errx(1, "%lu: %s: transform strings are not the same length",
797 if (MB_CUR_MAX
== 1) {
799 * The single-byte encoding case is easy: generate a
802 for (i
= 0; i
<= UCHAR_MAX
; i
++)
803 y
->bytetab
[i
] = (char)i
;
804 for (; *op
; op
++, np
++)
805 y
->bytetab
[(u_char
)*op
] = *np
;
808 * Multi-byte encoding case: generate a lookup table as
809 * above, but only for single-byte characters. The first
810 * bytes of multi-byte characters have their lookup table
811 * entries set to 0, which causes do_tr() to search through
812 * an auxiliary vector of multi-byte mappings.
814 memset(&mbs1
, 0, sizeof(mbs1
));
815 memset(&mbs2
, 0, sizeof(mbs2
));
816 for (i
= 0; i
<= UCHAR_MAX
; i
++)
817 y
->bytetab
[i
] = (btowc(i
) != WEOF
) ? i
: 0;
818 while (*op
!= '\0') {
819 oclen
= mbrlen(op
, MB_LEN_MAX
, &mbs1
);
820 if (oclen
== (size_t)-1 || oclen
== (size_t)-2)
821 errc(1, EILSEQ
, NULL
);
822 nclen
= mbrlen(np
, MB_LEN_MAX
, &mbs2
);
823 if (nclen
== (size_t)-1 || nclen
== (size_t)-2)
824 errc(1, EILSEQ
, NULL
);
825 if (oclen
== 1 && nclen
== 1)
826 y
->bytetab
[(u_char
)*op
] = *np
;
828 y
->bytetab
[(u_char
)*op
] = 0;
829 y
->multis
= realloc(y
->multis
,
830 (y
->nmultis
+ 1) * sizeof(*y
->multis
));
831 if (y
->multis
== NULL
)
834 y
->multis
[i
].fromlen
= oclen
;
835 memcpy(y
->multis
[i
].from
, op
, oclen
);
836 y
->multis
[i
].tolen
= nclen
;
837 memcpy(y
->multis
[i
].to
, np
, nclen
);
847 * Compile the text following an a, c, or i command.
852 int asize
, esc_nl
, size
;
853 char *text
, *p
, *op
, *s
;
854 char lbuf
[_POSIX2_LINE_MAX
+ 1];
856 asize
= 2 * _POSIX2_LINE_MAX
+ 1;
857 if ((text
= malloc(asize
)) == NULL
)
860 while (cu_fgets(lbuf
, sizeof(lbuf
), NULL
) != NULL
) {
861 op
= s
= text
+ size
;
863 #ifdef LEGACY_BSDSED_COMPAT
866 for (esc_nl
= 0; *p
!= '\0'; p
++) {
867 if (*p
== '\\' && p
[1] != '\0' && *++p
== '\n')
876 if (asize
- size
< _POSIX2_LINE_MAX
+ 1) {
878 if ((text
= realloc(text
, asize
)) == NULL
)
883 if ((p
= realloc(text
, size
+ 1)) == NULL
)
889 * Get an address and return a pointer to the first character after
890 * it. Fill the structure pointed to according to the address.
893 compile_addr(char *p
, struct s_addr
*a
)
895 char *end
, re
[_POSIX2_LINE_MAX
+ 1];
902 case '\\': /* Context address */
905 case '/': /* Context address */
906 p
= compile_delimited(p
, re
, 0);
908 errx(1, "%lu: %s: unterminated regular expression", linenum
, fname
);
909 /* Check for case insensitive regexp flag */
917 a
->u
.r
= compile_re(re
, icase
);
921 case '$': /* Last line */
925 case '+': /* Relative line number */
926 a
->type
= AT_RELLINE
;
930 case '0': case '1': case '2': case '3': case '4':
931 case '5': case '6': case '7': case '8': case '9':
934 a
->u
.l
= strtol(p
, &end
, 10);
937 errx(1, "%lu: %s: expected context address", linenum
, fname
);
944 * Return a copy of all the characters up to \n or \0.
947 duptoeol(char *s
, const char *ctype
)
954 for (start
= s
; *s
!= '\0' && *s
!= '\n'; ++s
)
955 ws
= isspace((unsigned char)*s
);
958 warnx("%lu: %s: whitespace after %s", linenum
, fname
, ctype
);
960 if ((p
= malloc(len
)) == NULL
)
962 return (memmove(p
, start
, len
));
966 * Convert goto label names to addresses, and count a and r commands, in
967 * the given subset of the script. Free the memory used by labels in b
968 * and t commands (but not by :).
970 * TODO: Remove } nodes
973 fixuplabel(struct s_command
*cp
, struct s_command
*end
)
976 for (; cp
!= end
; cp
= cp
->next
)
984 /* Resolve branch target. */
989 if ((cp
->u
.c
= findlabel(cp
->t
)) == NULL
)
990 errx(1, "%lu: %s: undefined label '%s'", linenum
, fname
, cp
->t
);
994 /* Do interior commands. */
995 fixuplabel(cp
->u
.c
, cp
->next
);
1001 * Associate the given command label for later lookup.
1004 enterlabel(struct s_command
*cp
)
1006 struct labhash
**lhp
, *lh
;
1010 for (h
= 0, p
= (u_char
*)cp
->t
; (c
= *p
) != 0; p
++)
1011 h
= (h
<< 5) + h
+ c
;
1012 lhp
= &labels
[h
& LHMASK
];
1013 for (lh
= *lhp
; lh
!= NULL
; lh
= lh
->lh_next
)
1014 if (lh
->lh_hash
== h
&& strcmp(cp
->t
, lh
->lh_cmd
->t
) == 0)
1015 errx(1, "%lu: %s: duplicate label '%s'", linenum
, fname
, cp
->t
);
1016 if ((lh
= malloc(sizeof *lh
)) == NULL
)
1026 * Find the label contained in the command l in the command linked
1027 * list cp. L is excluded from the search. Return NULL if not found.
1029 static struct s_command
*
1030 findlabel(char *name
)
1036 for (h
= 0, p
= (u_char
*)name
; (c
= *p
) != 0; p
++)
1037 h
= (h
<< 5) + h
+ c
;
1038 for (lh
= labels
[h
& LHMASK
]; lh
!= NULL
; lh
= lh
->lh_next
) {
1039 if (lh
->lh_hash
== h
&& strcmp(name
, lh
->lh_cmd
->t
) == 0) {
1041 return (lh
->lh_cmd
);
1048 * Warn about any unused labels. As a side effect, release the label hash
1054 struct labhash
*lh
, *next
;
1057 for (i
= 0; i
< LHSZ
; i
++) {
1058 for (lh
= labels
[i
]; lh
!= NULL
; lh
= next
) {
1061 warnx("%lu: %s: unused label '%s'",
1062 linenum
, fname
, lh
->lh_cmd
->t
);