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>
37 __FBSDID("$FreeBSD$");
40 static const char sccsid[] = "@(#)compile.c 8.1 (Berkeley) 6/6/93";
43 #include <sys/types.h>
62 #define LHMASK (LHSZ - 1)
63 static struct labhash {
64 struct labhash *lh_next;
66 struct s_command *lh_cmd;
70 static char *compile_addr(char *, struct s_addr *);
71 static char *compile_ccl(char **, char *);
72 static char *compile_delimited(char *, char *, int);
73 static char *compile_flags(char *, struct s_subst *);
74 static regex_t *compile_re(char *, int);
75 static char *compile_subst(char *, struct s_subst *);
76 static char *compile_text(void);
77 static char *compile_tr(char *, struct s_tr **);
78 static struct s_command
79 **compile_stream(struct s_command **);
80 static char *duptoeol(char *, const char *);
81 static void enterlabel(struct s_command *);
82 static struct s_command
84 static void fixuplabel(struct s_command *, struct s_command *);
85 static void uselabel(void);
88 * Command specification. This is used to drive the command parser.
91 char code; /* Command code */
92 int naddr; /* Number of address args */
93 enum e_args args; /* Argument type */
96 static struct s_format cmd_fmts[] = {
128 /* The compiled program. */
129 struct s_command *prog;
132 * Compile the program into prog.
133 * Initialise appends.
138 *compile_stream(&prog) = NULL;
139 fixuplabel(prog, NULL);
143 else if ((appends = malloc(sizeof(struct s_appends) * appendnum)) ==
146 if ((match = malloc((maxnsub + 1) * sizeof(regmatch_t))) == NULL)
150 #define EATSPACE() do { \
152 while (*p && isspace((unsigned char)*p)) \
156 static struct s_command **
157 compile_stream(struct s_command **link)
160 static char lbuf[_POSIX2_LINE_MAX + 1]; /* To save stack */
161 struct s_command *cmd, *cmd2, *stack;
163 char re[_POSIX2_LINE_MAX + 1];
164 int naddr; /* Number of addresses */
168 if ((p = cu_fgets(lbuf, sizeof(lbuf), NULL)) == NULL) {
170 errx(1, "%lu: %s: unexpected EOF (pending }'s)",
175 semicolon: EATSPACE();
177 if (*p == '#' || *p == '\0')
179 else if (*p == ';') {
184 if ((*link = cmd = malloc(sizeof(struct s_command))) == NULL)
187 cmd->startline = cmd->nonsel = 0;
188 /* First parse the addresses */
191 /* Valid characters to start an address */
192 #define addrchar(c) (strchr("0123456789/\\$", (c)))
195 if ((cmd->a1 = malloc(sizeof(struct s_addr))) == NULL)
197 p = compile_addr(p, cmd->a1);
198 EATSPACE(); /* EXTENSION */
201 EATSPACE(); /* EXTENSION */
203 if ((cmd->a2 = malloc(sizeof(struct s_addr)))
206 p = compile_addr(p, cmd->a2);
211 cmd->a1 = cmd->a2 = NULL;
213 nonsel: /* Now parse the command */
215 errx(1, "%lu: %s: command expected", linenum, fname);
217 for (fp = cmd_fmts; fp->code; fp++)
221 errx(1, "%lu: %s: invalid command code %c", linenum, fname, *p);
222 if (naddr > fp->naddr)
224 "%lu: %s: command %c expects up to %d address(es), found %d",
225 linenum, fname, *p, fp->naddr, naddr);
243 * Short-circuit command processing, since end of
244 * group is really just a noop.
248 errx(1, "%lu: %s: unexpected }", linenum, fname);
253 case EMPTY: /* d D g G h H l n N p P q x = \0 */
262 errx(1, "%lu: %s: extra characters at the end of %c command",
263 linenum, fname, cmd->code);
265 case TEXT: /* a c i */
270 "%lu: %s: command %c expects \\ followed by text", linenum, fname, cmd->code);
275 "%lu: %s: extra characters after \\ at the end of %c command",
276 linenum, fname, cmd->code);
277 cmd->t = compile_text();
279 case COMMENT: /* \0 # */
285 errx(1, "%lu: %s: filename expected", linenum, fname);
286 cmd->t = duptoeol(p, "w command");
289 else if ((cmd->u.fd = open(p,
290 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
298 errx(1, "%lu: %s: filename expected", linenum, fname);
300 cmd->t = duptoeol(p, "read command");
302 case BRANCH: /* b t */
308 cmd->t = duptoeol(p, "branch");
313 cmd->t = duptoeol(p, "label");
315 errx(1, "%lu: %s: empty label", linenum, fname);
320 if (*p == '\0' || *p == '\\')
322 "%lu: %s: substitute pattern can not be delimited by newline or backslash",
324 if ((cmd->u.s = calloc(1, sizeof(struct s_subst))) == NULL)
326 p = compile_delimited(p, re, 0);
329 "%lu: %s: unterminated substitute pattern", linenum, fname);
331 /* Compile RE with no case sensitivity temporarily */
335 cmd->u.s->re = compile_re(re, 0);
337 p = compile_subst(p, cmd->u.s);
338 p = compile_flags(p, cmd->u.s);
340 /* Recompile RE with case sensitivity from "I" flag if any */
344 cmd->u.s->re = compile_re(re, cmd->u.s->icase);
354 p = compile_tr(p, &cmd->u.y);
363 "%lu: %s: extra text at the end of a transform command", linenum, fname);
370 hex2char(const char *in, char *out, int len)
373 char *endptr, hexbuf[3];
376 hexbuf[1] = len > 1 ? in[1] : '\0';
380 ord = strtol(hexbuf, &endptr, 16);
381 if (*endptr != '\0' || errno != 0)
393 return isdigit(lc) || (lc >= 'a' && lc <= 'f');
397 dohex(const char *in, char *out, int *len)
401 if (!hexdigit(in[0]))
406 if (hex2char(in, out, tmplen) == 0) {
415 * Get a delimited string. P points to the delimiter of the string; d points
416 * to a buffer area. Newline and delimiter escapes are processed; other
417 * escapes are ignored.
419 * Returns a pointer to the first character after the final delimiter or NULL
420 * in the case of a non-terminated string. The character array d is filled
421 * with the processed string.
424 compile_delimited(char *p, char *d, int is_tr)
433 errx(1, "%lu: %s: \\ can not be used as a string delimiter",
436 errx(1, "%lu: %s: newline can not be used as a string delimiter",
439 if (*p == '[' && *p != c) {
440 if ((d = compile_ccl(&p, d)) == NULL)
441 errx(1, "%lu: %s: unbalanced brackets ([])", linenum, fname);
443 } else if (*p == '\\' && p[1] == '[') {
445 } else if (*p == '\\' && p[1] == c) {
447 } else if (*p == '\\' &&
448 (p[1] == 'n' || p[1] == 'r' || p[1] == 't')) {
462 } else if (*p == '\\' && p[1] == 'x') {
463 if (dohex(&p[2], d, &hexlen)) {
468 } else if (*p == '\\' && p[1] == '\\') {
473 } else if (*p == c) {
483 /* compile_ccl: expand a POSIX character class */
485 compile_ccl(char **sp, char *t)
495 for (; *s && (*t = *s) != ']'; s++, t++) {
496 if (*s == '[' && ((d = *(s+1)) == '.' || d == ':' || d == '=')) {
497 *++t = *++s, t++, s++;
498 for (c = *s; (*t = *s) != ']' || c != d; s++, t++)
499 if ((c = *s) == '\0')
501 } else if (*s == '\\') {
516 if (dohex(&s[2], t, &hexlen))
522 return (*s == ']') ? *sp = ++s, ++t : NULL;
526 * Compiles the regular expression in RE and returns a pointer to the compiled
527 * regular expression.
528 * Cflags are passed to regcomp.
531 compile_re(char *re, int case_insensitive)
538 if (case_insensitive)
540 if ((rep = malloc(sizeof(regex_t))) == NULL)
542 if ((eval = regcomp(rep, re, flags)) != 0)
543 errx(1, "%lu: %s: RE error: %s",
544 linenum, fname, strregerror(eval, rep));
545 if (maxnsub < rep->re_nsub)
546 maxnsub = rep->re_nsub;
551 * Compile the substitution string of a regular expression and set res to
552 * point to a saved copy of it. Nsub is the number of parenthesized regular
556 compile_subst(char *p, struct s_subst *s)
558 static char lbuf[_POSIX2_LINE_MAX + 1];
559 int asize, hexlen, size;
561 char c, *text, *op, *sp;
562 int more = 1, sawesc = 0;
564 c = *p++; /* Terminator character */
569 s->linenum = linenum;
570 asize = 2 * _POSIX2_LINE_MAX + 1;
571 if ((text = malloc(asize)) == NULL)
575 op = sp = text + size;
577 if (*p == '\\' || sawesc) {
579 * If this is a continuation from the last
580 * buffer, we won't have a character to
590 * This escaped character is continued
591 * in the next part of the line. Note
592 * this fact, then cause the loop to
593 * exit w/ normal EOL case and reenter
594 * above with the new buffer.
599 } else if (strchr("123456789", *p) != NULL) {
603 ref > s->re->re_nsub)
604 errx(1, "%lu: %s: \\%c not defined in the RE",
606 if (s->maxbref < ref)
624 #define ADVANCE_N(s, n) \
627 while (*(adv + (n) - 1) != '\0') { \
628 *adv = *(adv + (n)); \
633 if (dohex(&p[1], p, &hexlen)) {
640 } else if (*p == c) {
641 if (*++p == '\0' && more) {
642 if (cu_fgets(lbuf, sizeof(lbuf), &more))
647 if ((s->new = realloc(text, size)) == NULL)
650 } else if (*p == '\n') {
652 "%lu: %s: unescaped newline inside substitute pattern", linenum, fname);
658 if (asize - size < _POSIX2_LINE_MAX + 1) {
660 if ((text = realloc(text, asize)) == NULL)
663 } while (cu_fgets(p = lbuf, sizeof(lbuf), &more) != NULL);
664 errx(1, "%lu: %s: unterminated substitute in regular expression",
670 * Compile the flags of the s command
673 compile_flags(char *p, struct s_subst *s)
675 int gn; /* True if we have seen g or n */
677 char wfile[_POSIX2_LINE_MAX + 1], *q, *eq;
679 s->n = 1; /* Default */
685 EATSPACE(); /* EXTENSION */
690 "%lu: %s: more than one number or 'g' in substitute flags", linenum, fname);
705 case '1': case '2': case '3':
706 case '4': case '5': case '6':
707 case '7': case '8': case '9':
710 "%lu: %s: more than one number or 'g' in substitute flags", linenum, fname);
713 nval = strtol(p, &p, 10);
714 if (errno == ERANGE || nval > INT_MAX)
716 "%lu: %s: overflow in the 'N' substitute flag", linenum, fname);
722 #ifdef HISTORIC_PRACTICE
724 warnx("%lu: %s: space missing before w wfile", linenum, fname);
730 eq = wfile + sizeof(wfile) - 1;
735 err(1, "wfile too long");
740 errx(1, "%lu: %s: no wfile specified", linenum, fname);
741 s->wfile = strdup(wfile);
742 if (!aflag && (s->wfd = open(wfile,
743 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
748 errx(1, "%lu: %s: bad flag in substitute command: '%c'",
757 * Compile a translation set of strings into a lookup table.
760 compile_tr(char *p, struct s_tr **py)
765 char old[_POSIX2_LINE_MAX + 1];
766 char new[_POSIX2_LINE_MAX + 1];
767 size_t oclen, oldlen, nclen, newlen;
768 mbstate_t mbs1, mbs2;
770 if ((*py = y = malloc(sizeof(*y))) == NULL)
775 if (*p == '\0' || *p == '\\')
777 "%lu: %s: transform pattern can not be delimited by newline or backslash",
779 p = compile_delimited(p, old, 1);
781 errx(1, "%lu: %s: unterminated transform source string",
783 p = compile_delimited(p - 1, new, 1);
785 errx(1, "%lu: %s: unterminated transform target string",
789 oldlen = mbsrtowcs(NULL, &op, 0, NULL);
790 if (oldlen == (size_t)-1)
793 newlen = mbsrtowcs(NULL, &np, 0, NULL);
794 if (newlen == (size_t)-1)
796 if (newlen != oldlen)
797 errx(1, "%lu: %s: transform strings are not the same length",
799 if (MB_CUR_MAX == 1) {
801 * The single-byte encoding case is easy: generate a
804 for (i = 0; i <= UCHAR_MAX; i++)
805 y->bytetab[i] = (char)i;
806 for (; *op; op++, np++)
807 y->bytetab[(u_char)*op] = *np;
810 * Multi-byte encoding case: generate a lookup table as
811 * above, but only for single-byte characters. The first
812 * bytes of multi-byte characters have their lookup table
813 * entries set to 0, which causes do_tr() to search through
814 * an auxiliary vector of multi-byte mappings.
816 memset(&mbs1, 0, sizeof(mbs1));
817 memset(&mbs2, 0, sizeof(mbs2));
818 for (i = 0; i <= UCHAR_MAX; i++)
819 y->bytetab[i] = (btowc(i) != WEOF) ? i : 0;
820 while (*op != '\0') {
821 oclen = mbrlen(op, MB_LEN_MAX, &mbs1);
822 if (oclen == (size_t)-1 || oclen == (size_t)-2)
823 errc(1, EILSEQ, NULL);
824 nclen = mbrlen(np, MB_LEN_MAX, &mbs2);
825 if (nclen == (size_t)-1 || nclen == (size_t)-2)
826 errc(1, EILSEQ, NULL);
827 if (oclen == 1 && nclen == 1)
828 y->bytetab[(u_char)*op] = *np;
830 y->bytetab[(u_char)*op] = 0;
831 y->multis = realloc(y->multis,
832 (y->nmultis + 1) * sizeof(*y->multis));
833 if (y->multis == NULL)
836 y->multis[i].fromlen = oclen;
837 memcpy(y->multis[i].from, op, oclen);
838 y->multis[i].tolen = nclen;
839 memcpy(y->multis[i].to, np, nclen);
849 * Compile the text following an a, c, or i command.
854 int asize, esc_nl, size;
855 char *text, *p, *op, *s;
856 char lbuf[_POSIX2_LINE_MAX + 1];
858 asize = 2 * _POSIX2_LINE_MAX + 1;
859 if ((text = malloc(asize)) == NULL)
862 while (cu_fgets(lbuf, sizeof(lbuf), NULL) != NULL) {
863 op = s = text + size;
865 #ifdef LEGACY_BSDSED_COMPAT
868 for (esc_nl = 0; *p != '\0'; p++) {
869 if (*p == '\\' && p[1] != '\0' && *++p == '\n')
878 if (asize - size < _POSIX2_LINE_MAX + 1) {
880 if ((text = realloc(text, asize)) == NULL)
885 if ((p = realloc(text, size + 1)) == NULL)
891 * Get an address and return a pointer to the first character after
892 * it. Fill the structure pointed to according to the address.
895 compile_addr(char *p, struct s_addr *a)
897 char *end, re[_POSIX2_LINE_MAX + 1];
904 case '\\': /* Context address */
907 case '/': /* Context address */
908 p = compile_delimited(p, re, 0);
910 errx(1, "%lu: %s: unterminated regular expression", linenum, fname);
911 /* Check for case insensitive regexp flag */
919 a->u.r = compile_re(re, icase);
923 case '$': /* Last line */
927 case '+': /* Relative line number */
928 a->type = AT_RELLINE;
932 case '0': case '1': case '2': case '3': case '4':
933 case '5': case '6': case '7': case '8': case '9':
936 a->u.l = strtol(p, &end, 10);
939 errx(1, "%lu: %s: expected context address", linenum, fname);
946 * Return a copy of all the characters up to \n or \0.
949 duptoeol(char *s, const char *ctype)
956 for (start = s; *s != '\0' && *s != '\n'; ++s)
957 ws = isspace((unsigned char)*s);
960 warnx("%lu: %s: whitespace after %s", linenum, fname, ctype);
962 if ((p = malloc(len)) == NULL)
964 return (memmove(p, start, len));
968 * Convert goto label names to addresses, and count a and r commands, in
969 * the given subset of the script. Free the memory used by labels in b
970 * and t commands (but not by :).
972 * TODO: Remove } nodes
975 fixuplabel(struct s_command *cp, struct s_command *end)
978 for (; cp != end; cp = cp->next)
986 /* Resolve branch target. */
991 if ((cp->u.c = findlabel(cp->t)) == NULL)
992 errx(1, "%lu: %s: undefined label '%s'", linenum, fname, cp->t);
996 /* Do interior commands. */
997 fixuplabel(cp->u.c, cp->next);
1003 * Associate the given command label for later lookup.
1006 enterlabel(struct s_command *cp)
1008 struct labhash **lhp, *lh;
1012 for (h = 0, p = (u_char *)cp->t; (c = *p) != 0; p++)
1013 h = (h << 5) + h + c;
1014 lhp = &labels[h & LHMASK];
1015 for (lh = *lhp; lh != NULL; lh = lh->lh_next)
1016 if (lh->lh_hash == h && strcmp(cp->t, lh->lh_cmd->t) == 0)
1017 errx(1, "%lu: %s: duplicate label '%s'", linenum, fname, cp->t);
1018 if ((lh = malloc(sizeof *lh)) == NULL)
1028 * Find the label contained in the command l in the command linked
1029 * list cp. L is excluded from the search. Return NULL if not found.
1031 static struct s_command *
1032 findlabel(char *name)
1038 for (h = 0, p = (u_char *)name; (c = *p) != 0; p++)
1039 h = (h << 5) + h + c;
1040 for (lh = labels[h & LHMASK]; lh != NULL; lh = lh->lh_next) {
1041 if (lh->lh_hash == h && strcmp(name, lh->lh_cmd->t) == 0) {
1043 return (lh->lh_cmd);
1050 * Warn about any unused labels. As a side effect, release the label hash
1056 struct labhash *lh, *next;
1059 for (i = 0; i < LHSZ; i++) {
1060 for (lh = labels[i]; lh != NULL; lh = next) {
1063 warnx("%lu: %s: unused label '%s'",
1064 linenum, fname, lh->lh_cmd->t);