2 * Copyright 2010 Nexenta Systems, Inc. All rights reserved.
3 * Copyright (c) 1992 Diomidis Spinellis.
4 * Copyright (c) 1992, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Diomidis Spinellis of Imperial College, University of London.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 4. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 #include <sys/types.h>
55 #define LHMASK (LHSZ - 1)
56 static struct labhash
{
57 struct labhash
*lh_next
;
59 struct s_command
*lh_cmd
;
63 static char *compile_addr(char *, struct s_addr
*);
64 static char *compile_ccl(char **, char *);
65 static char *compile_delimited(char *, char *, int);
66 static char *compile_flags(char *, struct s_subst
*);
67 static regex_t
*compile_re(char *, int);
68 static char *compile_subst(char *, struct s_subst
*);
69 static char *compile_text(void);
70 static char *compile_tr(char *, struct s_tr
**);
71 static struct s_command
72 **compile_stream(struct s_command
**);
73 static char *duptoeol(char *, const char *);
74 static void enterlabel(struct s_command
*);
75 static struct s_command
77 static void fixuplabel(struct s_command
*, struct s_command
*);
78 static void uselabel(void);
81 * Command specification. This is used to drive the command parser.
84 char code
; /* Command code */
85 int naddr
; /* Number of address args */
86 enum e_args args
; /* Argument type */
89 static struct s_format cmd_fmts
[] = {
121 /* The compiled program. */
122 struct s_command
*prog
;
125 * Compile the program into prog.
126 * Initialise appends.
131 *compile_stream(&prog
) = NULL
;
132 fixuplabel(prog
, NULL
);
136 else if ((appends
= malloc(sizeof (struct s_appends
) * appendnum
)) ==
139 if ((match
= malloc((maxnsub
+ 1) * sizeof (regmatch_t
))) == NULL
)
143 #define EATSPACE() do { \
145 while (*p && isspace((unsigned char)*p)) \
150 static struct s_command
**
151 compile_stream(struct s_command
**link
)
154 static char lbuf
[_POSIX2_LINE_MAX
+ 1]; /* To save stack */
155 struct s_command
*cmd
, *cmd2
, *stack
;
157 char re
[_POSIX2_LINE_MAX
+ 1];
158 int naddr
; /* Number of addresses */
162 if ((p
= cu_fgets(lbuf
, sizeof (lbuf
), NULL
)) == NULL
) {
164 fatal(_("unexpected EOF (pending }'s)"));
168 semicolon
: EATSPACE();
170 if (*p
== '#' || *p
== '\0')
172 else if (*p
== ';') {
177 if ((*link
= cmd
= malloc(sizeof (struct s_command
))) == NULL
)
180 cmd
->startline
= cmd
->nonsel
= 0;
181 /* First parse the addresses */
184 /* Valid characters to start an address */
185 #define addrchar(c) (strchr("0123456789/\\$", (c)))
188 if ((cmd
->a1
= malloc(sizeof (struct s_addr
))) == NULL
)
190 p
= compile_addr(p
, cmd
->a1
);
191 EATSPACE(); /* EXTENSION */
194 EATSPACE(); /* EXTENSION */
196 if ((cmd
->a2
= malloc(sizeof (struct s_addr
)))
199 p
= compile_addr(p
, cmd
->a2
);
204 cmd
->a1
= cmd
->a2
= 0;
206 nonsel
: /* Now parse the command */
208 fatal(_("command expected"));
210 for (fp
= cmd_fmts
; fp
->code
; fp
++)
214 fatal(_("invalid command code %c"), *p
);
215 if (naddr
> fp
->naddr
)
216 fatal(_("command %c expects up to %d address(es), "
217 "found %d"), *p
, fp
->naddr
, naddr
);
235 * Short-circuit command processing, since end of
236 * group is really just a noop.
240 fatal(_("unexpected }"));
245 case EMPTY
: /* d D g G h H l n N p P q x = \0 */
254 fatal(_("extra characters at the end of %c "
255 "command"), cmd
->code
);
257 case TEXT
: /* a c i */
261 fatal(_("command %c expects \\ "
262 "followed by text"), cmd
->code
);
266 fatal(_("extra characters after \\ "
267 "at the end of %c command"),
269 cmd
->t
= compile_text();
271 case COMMENT
: /* \0 # */
277 fatal(_("filename expected"));
278 cmd
->t
= duptoeol(p
, "w command");
281 else if ((cmd
->u
.fd
= open(p
,
282 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
, 0666)) == -1)
289 fatal(_("filename expected"));
291 cmd
->t
= duptoeol(p
, "read command");
293 case BRANCH
: /* b t */
299 cmd
->t
= duptoeol(p
, "branch");
304 cmd
->t
= duptoeol(p
, "label");
306 fatal(_("empty label"));
311 if (*p
== '\0' || *p
== '\\')
312 fatal(_("substitute pattern can not "
313 "be delimited by newline or backslash"));
314 if ((cmd
->u
.s
= calloc(1, sizeof (struct s_subst
))) ==
317 p
= compile_delimited(p
, re
, 0);
319 fatal(_("unterminated substitute pattern"));
321 /* Compile RE with no case sensitivity temporarily */
325 cmd
->u
.s
->re
= compile_re(re
, 0);
327 p
= compile_subst(p
, cmd
->u
.s
);
328 p
= compile_flags(p
, cmd
->u
.s
);
330 /* Recompile RE with case sens. from "I" flag if any */
334 cmd
->u
.s
->re
= compile_re(re
, cmd
->u
.s
->icase
);
344 p
= compile_tr(p
, &cmd
->u
.y
);
352 fatal(_("extra text at the end of a "
353 "transform command"));
360 * Get a delimited string. P points to the delimeter of the string; d points
361 * to a buffer area. Newline and delimiter escapes are processed; other
362 * escapes are ignored.
364 * Returns a pointer to the first character after the final delimiter or NULL
365 * in the case of a non-terminated string. The character array d is filled
366 * with the processed string.
369 compile_delimited(char *p
, char *d
, int is_tr
)
377 fatal(_("\\ can not be used as a string delimiter"));
379 fatal(_("newline can not be used as a string delimiter"));
381 if (*p
== '[' && *p
!= c
) {
382 if ((d
= compile_ccl(&p
, d
)) == NULL
)
383 fatal(_("unbalanced brackets ([])"));
385 } else if (*p
== '\\' && p
[1] == '[') {
387 } else if (*p
== '\\' && p
[1] == c
)
389 else if (*p
== '\\' && p
[1] == 'n') {
393 } else if (*p
== '\\' && p
[1] == '\\') {
398 } else if (*p
== c
) {
408 /* compile_ccl: expand a POSIX character class */
410 compile_ccl(char **sp
, char *t
)
420 for (; *s
&& (*t
= *s
) != ']'; s
++, t
++)
422 ((d
= *(s
+1)) == '.' || d
== ':' || d
== '=')) {
423 *++t
= *++s
, t
++, s
++;
424 for (c
= *s
; (*t
= *s
) != ']' || c
!= d
; s
++, t
++)
425 if ((c
= *s
) == '\0')
428 return ((*s
== ']') ? *sp
= ++s
, ++t
: NULL
);
432 * Compiles the regular expression in RE and returns a pointer to the compiled
433 * regular expression.
434 * Cflags are passed to regcomp.
437 compile_re(char *re
, int case_insensitive
)
444 if (case_insensitive
)
446 if ((rep
= malloc(sizeof (regex_t
))) == NULL
)
448 if ((eval
= regcomp(rep
, re
, flags
)) != 0)
449 fatal(_("RE error: %s"), strregerror(eval
, rep
));
450 if (maxnsub
< rep
->re_nsub
)
451 maxnsub
= rep
->re_nsub
;
456 * Compile the substitution string of a regular expression and set res to
457 * point to a saved copy of it. Nsub is the number of parenthesized regular
461 compile_subst(char *p
, struct s_subst
*s
)
463 static char lbuf
[_POSIX2_LINE_MAX
+ 1];
467 char c
, *text
, *op
, *sp
;
468 int more
= 1, sawesc
= 0;
470 c
= *p
++; /* Terminator character */
475 s
->linenum
= linenum
;
476 asize
= 2 * _POSIX2_LINE_MAX
+ 1;
477 if ((text
= malloc(asize
)) == NULL
)
481 op
= sp
= text
+ size
;
483 if (*p
== '\\' || sawesc
) {
485 * If this is a continuation from the last
486 * buffer, we won't have a character to
496 * This escaped character is continued
497 * in the next part of the line. Note
498 * this fact, then cause the loop to
499 * exit w/ normal EOL case and reenter
500 * above with the new buffer.
505 } else if (strchr("123456789", *p
) != NULL
) {
509 ref
> s
->re
->re_nsub
)
510 fatal(_("not defined in "
511 "the RE: \\%c"), *p
);
512 if (s
->maxbref
< ref
)
514 } else if (*p
== '&' || *p
== '\\')
516 } else if (*p
== c
) {
517 if (*++p
== '\0' && more
) {
518 if (cu_fgets(lbuf
, sizeof (lbuf
),
523 size
+= (uintptr_t)sp
- (uintptr_t)op
;
524 if ((s
->new = realloc(text
, size
)) == NULL
)
527 } else if (*p
== '\n') {
528 fatal(_("unescaped newline inside "
529 "substitute pattern"));
534 size
+= (uintptr_t)sp
- (uintptr_t)op
;
535 if (asize
- size
< _POSIX2_LINE_MAX
+ 1) {
537 if ((text
= realloc(text
, asize
)) == NULL
)
540 } while (cu_fgets(p
= lbuf
, sizeof (lbuf
), &more
));
541 fatal(_("unterminated substitute in regular expression"));
546 * Compile the flags of the s command
549 compile_flags(char *p
, struct s_subst
*s
)
551 int gn
; /* True if we have seen g or n */
553 char wfile
[_POSIX2_LINE_MAX
+ 1], *q
;
555 s
->n
= 1; /* Default */
562 EATSPACE(); /* EXTENSION */
566 fatal(_("more than one number or "
567 "'g' in substitute flags"));
581 case '1': case '2': case '3':
582 case '4': case '5': case '6':
583 case '7': case '8': case '9':
585 fatal(_("more than one number or "
586 "'g' in substitute flags"));
589 nval
= strtol(p
, &p
, 10);
590 if (errno
== ERANGE
|| nval
> INT_MAX
)
591 fatal(_("overflow in the 'N' substitute flag"));
597 #ifdef HISTORIC_PRACTICE
599 fatal(_("space missing before w wfile"));
612 fatal(_("no wfile specified"));
613 s
->wfile
= strdup(wfile
);
614 if (!aflag
&& (s
->wfd
= open(wfile
,
615 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
, 0666)) == -1)
619 fatal(_("bad flag in substitute command: '%c'"), *p
);
627 * Compile a translation set of strings into a lookup table.
630 compile_tr(char *p
, struct s_tr
**py
)
635 char old
[_POSIX2_LINE_MAX
+ 1];
636 char new[_POSIX2_LINE_MAX
+ 1];
637 size_t oclen
, oldlen
, nclen
, newlen
;
638 mbstate_t mbs1
, mbs2
;
640 if ((*py
= y
= malloc(sizeof (*y
))) == NULL
)
645 if (*p
== '\0' || *p
== '\\')
646 fatal(_("transform pattern can not be delimited by "
647 "newline or backslash"));
648 p
= compile_delimited(p
, old
, 1);
650 fatal(_("unterminated transform source string"));
651 p
= compile_delimited(p
- 1, new, 1);
653 fatal(_("unterminated transform target string"));
656 oldlen
= mbsrtowcs(NULL
, &op
, 0, NULL
);
657 if (oldlen
== (size_t)-1)
660 newlen
= mbsrtowcs(NULL
, &np
, 0, NULL
);
661 if (newlen
== (size_t)-1)
663 if (newlen
!= oldlen
)
664 fatal(_("transform strings are not the same length"));
665 if (MB_CUR_MAX
== 1) {
667 * The single-byte encoding case is easy: generate a
670 for (i
= 0; i
<= UCHAR_MAX
; i
++)
671 y
->bytetab
[i
] = (char)i
;
672 for (; *op
; op
++, np
++)
673 y
->bytetab
[(uchar_t
)*op
] = *np
;
676 * Multi-byte encoding case: generate a lookup table as
677 * above, but only for single-byte characters. The first
678 * bytes of multi-byte characters have their lookup table
679 * entries set to 0, which causes do_tr() to search through
680 * an auxiliary vector of multi-byte mappings.
682 (void) memset(&mbs1
, 0, sizeof (mbs1
));
683 (void) memset(&mbs2
, 0, sizeof (mbs2
));
684 for (i
= 0; i
<= UCHAR_MAX
; i
++)
685 y
->bytetab
[i
] = (btowc(i
) != WEOF
) ? (uchar_t
)i
: 0;
686 while (*op
!= '\0') {
687 oclen
= mbrlen(op
, MB_LEN_MAX
, &mbs1
);
688 if (oclen
== (size_t)-1 || oclen
== (size_t)-2)
689 errx(1, "%s", strerror(EILSEQ
));
690 nclen
= mbrlen(np
, MB_LEN_MAX
, &mbs2
);
691 if (nclen
== (size_t)-1 || nclen
== (size_t)-2)
692 errx(1, "%s", strerror(EILSEQ
));
693 if (oclen
== 1 && nclen
== 1)
694 y
->bytetab
[(uchar_t
)*op
] = *np
;
696 y
->bytetab
[(uchar_t
)*op
] = 0;
697 y
->multis
= realloc(y
->multis
,
698 (y
->nmultis
+ 1) * sizeof (*y
->multis
));
699 if (y
->multis
== NULL
)
702 y
->multis
[i
].fromlen
= oclen
;
703 (void) memcpy(y
->multis
[i
].from
, op
, oclen
);
704 y
->multis
[i
].tolen
= nclen
;
705 (void) memcpy(y
->multis
[i
].to
, np
, nclen
);
715 * Compile the text following an a or i command.
721 uintptr_t size
, asize
;
722 char *text
, *p
, *op
, *s
;
723 char lbuf
[_POSIX2_LINE_MAX
+ 1];
725 asize
= 2 * _POSIX2_LINE_MAX
+ 1;
726 if ((text
= malloc(asize
)) == NULL
)
729 while (cu_fgets(lbuf
, sizeof (lbuf
), NULL
)) {
730 op
= s
= text
+ size
;
733 for (esc_nl
= 0; *p
!= '\0'; p
++) {
734 if (*p
== '\\' && p
[1] != '\0' && *++p
== '\n')
738 size
+= (uintptr_t)s
- (uintptr_t)op
;
743 if (asize
- size
< _POSIX2_LINE_MAX
+ 1) {
745 if ((text
= realloc(text
, asize
)) == NULL
)
750 if ((p
= realloc(text
, size
+ 1)) == NULL
)
756 * Get an address and return a pointer to the first character after
757 * it. Fill the structure pointed to according to the address.
760 compile_addr(char *p
, struct s_addr
*a
)
762 char *end
, re
[_POSIX2_LINE_MAX
+ 1];
769 case '\\': /* Context address */
772 case '/': /* Context address */
773 p
= compile_delimited(p
, re
, 0);
775 fatal(_("unterminated regular expression"));
777 /* Check for case insensitive regexp flag */
785 a
->u
.r
= compile_re(re
, icase
);
789 case '$': /* Last line */
793 case '+': /* Relative line number */
794 a
->type
= AT_RELLINE
;
798 case '0': case '1': case '2': case '3': case '4':
799 case '5': case '6': case '7': case '8': case '9':
802 a
->u
.l
= strtol(p
, &end
, 10);
805 fatal(_("expected context address"));
812 * Return a copy of all the characters up to \n or \0.
815 duptoeol(char *s
, const char *ctype
)
822 for (start
= s
; *s
!= '\0' && *s
!= '\n'; ++s
)
823 ws
= isspace((unsigned char)*s
);
826 warnx(_("%lu: %s: whitespace after %s"), linenum
, fname
, ctype
);
827 len
= (uintptr_t)s
- (uintptr_t)start
+ 1;
828 if ((p
= malloc(len
)) == NULL
)
830 return (memmove(p
, start
, len
));
834 * Convert goto label names to addresses, and count a and r commands, in
835 * the given subset of the script. Free the memory used by labels in b
836 * and t commands (but not by :).
838 * TODO: Remove } nodes
841 fixuplabel(struct s_command
*cp
, struct s_command
*end
)
844 for (; cp
!= end
; cp
= cp
->next
)
852 /* Resolve branch target. */
857 if ((cp
->u
.c
= findlabel(cp
->t
)) == NULL
)
858 fatal(_("undefined label '%s'"), cp
->t
);
862 /* Do interior commands. */
863 fixuplabel(cp
->u
.c
, cp
->next
);
869 * Associate the given command label for later lookup.
872 enterlabel(struct s_command
*cp
)
874 struct labhash
**lhp
, *lh
;
878 for (h
= 0, p
= (uchar_t
*)cp
->t
; (c
= *p
) != 0; p
++)
879 h
= (h
<< 5) + h
+ c
;
880 lhp
= &labels
[h
& LHMASK
];
881 for (lh
= *lhp
; lh
!= NULL
; lh
= lh
->lh_next
)
882 if (lh
->lh_hash
== h
&& strcmp(cp
->t
, lh
->lh_cmd
->t
) == 0)
883 fatal(_("duplicate label '%s'"), cp
->t
);
884 if ((lh
= malloc(sizeof (*lh
))) == NULL
)
894 * Find the label contained in the command l in the command linked
895 * list cp. L is excluded from the search. Return NULL if not found.
897 static struct s_command
*
898 findlabel(char *name
)
904 for (h
= 0, p
= (uchar_t
*)name
; (c
= *p
) != 0; p
++)
905 h
= (h
<< 5) + h
+ c
;
906 for (lh
= labels
[h
& LHMASK
]; lh
!= NULL
; lh
= lh
->lh_next
) {
907 if (lh
->lh_hash
== h
&& strcmp(name
, lh
->lh_cmd
->t
) == 0) {
916 * Warn about any unused labels. As a side effect, release the label hash
922 struct labhash
*lh
, *next
;
925 for (i
= 0; i
< LHSZ
; i
++) {
926 for (lh
= labels
[i
]; lh
!= NULL
; lh
= next
) {
929 warnx(_("%lu: %s: unused label '%s'"),
930 linenum
, fname
, lh
->lh_cmd
->t
);