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
36 #include <sys/cdefs.h>
38 static const char sccsid[] = "@(#)compile.c 8.1 (Berkeley) 6/6/93";
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) {
439 if ((d = compile_ccl(&p, d)) == NULL) {
441 "%lu: %s: unbalanced brackets ([])",
446 } else if (*p == '\\' && p[1] == '[') {
451 } else if (*p == '\\' && p[1] == c) {
453 } else if (*p == '\\' &&
454 (p[1] == 'n' || p[1] == 'r' || p[1] == 't')) {
468 } else if (*p == '\\' && p[1] == 'x') {
469 if (dohex(&p[2], d, &hexlen)) {
474 } else if (*p == '\\' && p[1] == '\\') {
479 } else if (*p == c) {
489 /* compile_ccl: expand a POSIX character class */
491 compile_ccl(char **sp, char *t)
501 for (; *s && (*t = *s) != ']'; s++, t++) {
502 if (*s == '[' && ((d = *(s+1)) == '.' || d == ':' || d == '=')) {
503 *++t = *++s, t++, s++;
504 for (c = *s; (*t = *s) != ']' || c != d; s++, t++)
505 if ((c = *s) == '\0')
507 } else if (*s == '\\') {
522 if (dohex(&s[2], t, &hexlen))
528 return (*s == ']') ? *sp = ++s, ++t : NULL;
532 * Compiles the regular expression in RE and returns a pointer to the compiled
533 * regular expression.
534 * Cflags are passed to regcomp.
537 compile_re(char *re, int case_insensitive)
544 if (case_insensitive)
546 if ((rep = malloc(sizeof(regex_t))) == NULL)
548 if ((eval = regcomp(rep, re, flags)) != 0)
549 errx(1, "%lu: %s: RE error: %s",
550 linenum, fname, strregerror(eval, rep));
551 if (maxnsub < rep->re_nsub)
552 maxnsub = rep->re_nsub;
557 * Compile the substitution string of a regular expression and set res to
558 * point to a saved copy of it. Nsub is the number of parenthesized regular
562 compile_subst(char *p, struct s_subst *s)
564 static char lbuf[_POSIX2_LINE_MAX + 1];
565 int asize, hexlen, size;
567 char c, *text, *op, *sp;
568 int more = 1, sawesc = 0;
570 c = *p++; /* Terminator character */
575 s->linenum = linenum;
576 asize = 2 * _POSIX2_LINE_MAX + 1;
577 if ((text = malloc(asize)) == NULL)
581 op = sp = text + size;
583 if (*p == '\\' || sawesc) {
585 * If this is a continuation from the last
586 * buffer, we won't have a character to
596 * This escaped character is continued
597 * in the next part of the line. Note
598 * this fact, then cause the loop to
599 * exit w/ normal EOL case and reenter
600 * above with the new buffer.
605 } else if (strchr("123456789", *p) != NULL) {
609 ref > s->re->re_nsub)
610 errx(1, "%lu: %s: \\%c not defined in the RE",
612 if (s->maxbref < ref)
630 #define ADVANCE_N(s, n) \
633 while (*(adv + (n) - 1) != '\0') { \
634 *adv = *(adv + (n)); \
639 if (dohex(&p[1], p, &hexlen)) {
646 } else if (*p == c) {
647 if (*++p == '\0' && more) {
648 if (cu_fgets(lbuf, sizeof(lbuf), &more))
653 if ((s->new = realloc(text, size)) == NULL)
656 } else if (*p == '\n') {
658 "%lu: %s: unescaped newline inside substitute pattern", linenum, fname);
664 if (asize - size < _POSIX2_LINE_MAX + 1) {
666 if ((text = realloc(text, asize)) == NULL)
669 } while (cu_fgets(p = lbuf, sizeof(lbuf), &more) != NULL);
670 errx(1, "%lu: %s: unterminated substitute in regular expression",
676 * Compile the flags of the s command
679 compile_flags(char *p, struct s_subst *s)
681 int gn; /* True if we have seen g or n */
683 char wfile[_POSIX2_LINE_MAX + 1], *q, *eq;
685 s->n = 1; /* Default */
691 EATSPACE(); /* EXTENSION */
696 "%lu: %s: more than one number or 'g' in substitute flags", linenum, fname);
711 case '1': case '2': case '3':
712 case '4': case '5': case '6':
713 case '7': case '8': case '9':
716 "%lu: %s: more than one number or 'g' in substitute flags", linenum, fname);
719 nval = strtol(p, &p, 10);
720 if (errno == ERANGE || nval > INT_MAX)
722 "%lu: %s: overflow in the 'N' substitute flag", linenum, fname);
728 #ifdef HISTORIC_PRACTICE
730 warnx("%lu: %s: space missing before w wfile", linenum, fname);
736 eq = wfile + sizeof(wfile) - 1;
741 err(1, "wfile too long");
746 errx(1, "%lu: %s: no wfile specified", linenum, fname);
747 s->wfile = strdup(wfile);
748 if (!aflag && (s->wfd = open(wfile,
749 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
754 errx(1, "%lu: %s: bad flag in substitute command: '%c'",
763 * Compile a translation set of strings into a lookup table.
766 compile_tr(char *p, struct s_tr **py)
771 char old[_POSIX2_LINE_MAX + 1];
772 char new[_POSIX2_LINE_MAX + 1];
773 size_t oclen, oldlen, nclen, newlen;
774 mbstate_t mbs1, mbs2;
776 if ((*py = y = malloc(sizeof(*y))) == NULL)
781 if (*p == '\0' || *p == '\\')
783 "%lu: %s: transform pattern can not be delimited by newline or backslash",
785 p = compile_delimited(p, old, 1);
787 errx(1, "%lu: %s: unterminated transform source string",
789 p = compile_delimited(p - 1, new, 1);
791 errx(1, "%lu: %s: unterminated transform target string",
795 oldlen = mbsrtowcs(NULL, &op, 0, NULL);
796 if (oldlen == (size_t)-1)
799 newlen = mbsrtowcs(NULL, &np, 0, NULL);
800 if (newlen == (size_t)-1)
802 if (newlen != oldlen)
803 errx(1, "%lu: %s: transform strings are not the same length",
805 if (MB_CUR_MAX == 1) {
807 * The single-byte encoding case is easy: generate a
810 for (i = 0; i <= UCHAR_MAX; i++)
811 y->bytetab[i] = (char)i;
812 for (; *op; op++, np++)
813 y->bytetab[(u_char)*op] = *np;
816 * Multi-byte encoding case: generate a lookup table as
817 * above, but only for single-byte characters. The first
818 * bytes of multi-byte characters have their lookup table
819 * entries set to 0, which causes do_tr() to search through
820 * an auxiliary vector of multi-byte mappings.
822 memset(&mbs1, 0, sizeof(mbs1));
823 memset(&mbs2, 0, sizeof(mbs2));
824 for (i = 0; i <= UCHAR_MAX; i++)
825 y->bytetab[i] = (btowc(i) != WEOF) ? i : 0;
826 while (*op != '\0') {
827 oclen = mbrlen(op, MB_LEN_MAX, &mbs1);
828 if (oclen == (size_t)-1 || oclen == (size_t)-2)
829 errc(1, EILSEQ, NULL);
830 nclen = mbrlen(np, MB_LEN_MAX, &mbs2);
831 if (nclen == (size_t)-1 || nclen == (size_t)-2)
832 errc(1, EILSEQ, NULL);
833 if (oclen == 1 && nclen == 1)
834 y->bytetab[(u_char)*op] = *np;
836 y->bytetab[(u_char)*op] = 0;
837 y->multis = realloc(y->multis,
838 (y->nmultis + 1) * sizeof(*y->multis));
839 if (y->multis == NULL)
842 y->multis[i].fromlen = oclen;
843 memcpy(y->multis[i].from, op, oclen);
844 y->multis[i].tolen = nclen;
845 memcpy(y->multis[i].to, np, nclen);
855 * Compile the text following an a, c, or i command.
860 int asize, esc_nl, size;
861 char *text, *p, *op, *s;
862 char lbuf[_POSIX2_LINE_MAX + 1];
864 asize = 2 * _POSIX2_LINE_MAX + 1;
865 if ((text = malloc(asize)) == NULL)
868 while (cu_fgets(lbuf, sizeof(lbuf), NULL) != NULL) {
869 op = s = text + size;
871 #ifdef LEGACY_BSDSED_COMPAT
874 for (esc_nl = 0; *p != '\0'; p++) {
875 if (*p == '\\' && p[1] != '\0' && *++p == '\n')
884 if (asize - size < _POSIX2_LINE_MAX + 1) {
886 if ((text = realloc(text, asize)) == NULL)
891 if ((p = realloc(text, size + 1)) == NULL)
897 * Get an address and return a pointer to the first character after
898 * it. Fill the structure pointed to according to the address.
901 compile_addr(char *p, struct s_addr *a)
903 char *end, re[_POSIX2_LINE_MAX + 1];
910 case '\\': /* Context address */
913 case '/': /* Context address */
914 p = compile_delimited(p, re, 0);
916 errx(1, "%lu: %s: unterminated regular expression", linenum, fname);
917 /* Check for case insensitive regexp flag */
925 a->u.r = compile_re(re, icase);
929 case '$': /* Last line */
933 case '+': /* Relative line number */
934 a->type = AT_RELLINE;
938 case '0': case '1': case '2': case '3': case '4':
939 case '5': case '6': case '7': case '8': case '9':
942 a->u.l = strtol(p, &end, 10);
945 errx(1, "%lu: %s: expected context address", linenum, fname);
952 * Return a copy of all the characters up to \n or \0.
955 duptoeol(char *s, const char *ctype)
962 for (start = s; *s != '\0' && *s != '\n'; ++s)
963 ws = isspace((unsigned char)*s);
966 warnx("%lu: %s: whitespace after %s", linenum, fname, ctype);
968 if ((p = malloc(len)) == NULL)
970 return (memmove(p, start, len));
974 * Convert goto label names to addresses, and count a and r commands, in
975 * the given subset of the script. Free the memory used by labels in b
976 * and t commands (but not by :).
978 * TODO: Remove } nodes
981 fixuplabel(struct s_command *cp, struct s_command *end)
984 for (; cp != end; cp = cp->next)
992 /* Resolve branch target. */
997 if ((cp->u.c = findlabel(cp->t)) == NULL)
998 errx(1, "%lu: %s: undefined label '%s'", linenum, fname, cp->t);
1002 /* Do interior commands. */
1003 fixuplabel(cp->u.c, cp->next);
1009 * Associate the given command label for later lookup.
1012 enterlabel(struct s_command *cp)
1014 struct labhash **lhp, *lh;
1018 for (h = 0, p = (u_char *)cp->t; (c = *p) != 0; p++)
1019 h = (h << 5) + h + c;
1020 lhp = &labels[h & LHMASK];
1021 for (lh = *lhp; lh != NULL; lh = lh->lh_next)
1022 if (lh->lh_hash == h && strcmp(cp->t, lh->lh_cmd->t) == 0)
1023 errx(1, "%lu: %s: duplicate label '%s'", linenum, fname, cp->t);
1024 if ((lh = malloc(sizeof *lh)) == NULL)
1034 * Find the label contained in the command l in the command linked
1035 * list cp. L is excluded from the search. Return NULL if not found.
1037 static struct s_command *
1038 findlabel(char *name)
1044 for (h = 0, p = (u_char *)name; (c = *p) != 0; p++)
1045 h = (h << 5) + h + c;
1046 for (lh = labels[h & LHMASK]; lh != NULL; lh = lh->lh_next) {
1047 if (lh->lh_hash == h && strcmp(name, lh->lh_cmd->t) == 0) {
1049 return (lh->lh_cmd);
1056 * Warn about any unused labels. As a side effect, release the label hash
1062 struct labhash *lh, *next;
1065 for (i = 0; i < LHSZ; i++) {
1066 for (lh = labels[i]; lh != NULL; lh = next) {
1069 warnx("%lu: %s: unused label '%s'",
1070 linenum, fname, lh->lh_cmd->t);