2 * Copyright (c) 1992 Diomidis Spinellis.
3 * Copyright (c) 1992, 1993, 1994
4 * The Regents of the University of California. All rights reserved.
6 * This code is derived from software contributed to Berkeley by
7 * Diomidis Spinellis of Imperial College, University of London.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
38 static const char sccsid[] = "@(#)process.c 8.6 (Berkeley) 4/20/94";
41 #include <sys/types.h>
43 #include <sys/ioctl.h>
62 static SPACE HS, PS, SS, YS;
66 #define psanl PS.append_newline
70 static inline int applies(struct s_command *);
71 static void do_tr(struct s_tr *);
72 static void flush_appends(void);
73 static void lputs(char *, size_t);
74 static int regexec_e(regex_t *, const char *, int, int, size_t);
75 static void regsub(SPACE *, char *, char *);
76 static int substitute(struct s_command *);
78 struct s_appends *appends; /* Array of pointers to strings to append. */
79 static int appendx; /* Index into appends array. */
80 int appendnum; /* Size of appends array. */
82 static int lastaddr; /* Set by applies if last address of a range. */
83 static int sdone; /* If any substitutes since last line input. */
84 /* Iov structure for 'w' commands. */
85 static regex_t *defpreg;
90 fwrite(ps, 1, psl, outfile); \
91 if (psanl) fputc('\n', outfile); \
105 for (linenum = 0; mf_fgets(&PS, REPLACE);) {
120 if (appendx >= appendnum)
121 if ((appends = realloc(appends,
122 sizeof(struct s_appends) *
123 (appendnum *= 2))) == NULL)
125 appends[appendx].type = AP_STRING;
126 appends[appendx].s = cp->t;
127 appends[appendx].len = strlen(cp->t);
136 if (cp->a2 == NULL || lastaddr || lastline())
137 (void)fprintf(outfile, "%s", cp->t);
146 (p = memchr(ps, '\n', psl)) == NULL) {
151 memmove(ps, p + 1, psl);
155 cspace(&PS, hs, hsl, REPLACE);
158 cspace(&PS, "\n", 1, APPEND);
159 cspace(&PS, hs, hsl, APPEND);
162 cspace(&HS, ps, psl, REPLACE);
165 cspace(&HS, "\n", 1, APPEND);
166 cspace(&HS, ps, psl, APPEND);
169 (void)fprintf(outfile, "%s", cp->t);
178 if (!mf_fgets(&PS, REPLACE))
184 cspace(&PS, "\n", 1, APPEND);
185 if (!mf_fgets(&PS, APPEND))
196 if ((p = memchr(ps, '\n', psl)) != NULL) {
214 if (appendx >= appendnum)
215 if ((appends = realloc(appends,
216 sizeof(struct s_appends) *
217 (appendnum *= 2))) == NULL)
219 appends[appendx].type = AP_FILE;
220 appends[appendx].s = cp->t;
221 appends[appendx].len = strlen(cp->t);
225 sdone |= substitute(cp);
237 if (cp->u.fd == -1 && (cp->u.fd = open(cp->t,
238 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
241 if (write(cp->u.fd, ps, psl) != (ssize_t)psl ||
242 write(cp->u.fd, "\n", 1) != 1)
247 * If the hold space is null, make it empty
248 * but not null. Otherwise the pattern space
249 * will become null after the swap, which is
250 * an abnormal condition.
253 cspace(&HS, "", 0, REPLACE);
256 psanl = tspace.append_newline;
268 (void)fprintf(outfile, "%lu\n", linenum);
273 new: if (!nflag && !pd)
276 } /* for all lines */
280 * TRUE if the address passed matches the current program state
281 * (lastline, linenumber, ps).
284 ((a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, psl) : \
285 (a)->type == AT_LINE ? linenum == (a)->u.l : lastline())
288 * Return TRUE if the command applies to the current line. Sets the start
289 * line for process ranges. Interprets the non-select (``!'') flag.
292 applies(struct s_command *cp)
297 if (cp->a1 == NULL && cp->a2 == NULL)
300 if (cp->startline > 0) {
301 switch (cp->a2->type) {
303 if (linenum - cp->startline <= cp->a2->u.l)
315 } else if (cp->a2->type == AT_LINE &&
316 linenum > cp->a2->u.l) {
318 * We missed the 2nd address due to a
319 * branch, so just close the range and
327 } else if (cp->a1 && MATCH(cp->a1)) {
329 * If the second address is a number less than or
330 * equal to the line number first selected, only
331 * one line shall be selected.
333 * Likewise if the relative second line address is zero.
335 if ((cp->a2->type == AT_LINE &&
336 linenum >= cp->a2->u.l) ||
337 (cp->a2->type == AT_RELLINE && cp->a2->u.l == 0))
340 cp->startline = linenum;
347 return (cp->nonsel ? ! r : r);
351 * Reset the sed processor to its initial state.
356 struct s_command *cp;
359 * Reset all in-range markers.
361 for (cp = prog; cp; cp = cp->code == '{' ? cp->u.c : cp->next)
366 * Clear out the hold space.
368 cspace(&HS, "", 0, REPLACE);
373 * Do substitutions in the pattern space. Currently, we build a
374 * copy of the new pattern space in the substitute space structure
375 * and then swap them.
378 substitute(struct s_command *cp)
382 regoff_t re_off, slen;
389 if (defpreg != NULL && cp->u.s->maxbref > defpreg->re_nsub) {
390 linenum = cp->u.s->linenum;
391 errx(1, "%lu: %s: \\%u not defined in the RE",
392 linenum, fname, cp->u.s->maxbref);
395 if (!regexec_e(re, s, 0, 0, psl))
398 SS.len = 0; /* Clean substitute space. */
406 if (lastempty || match[0].rm_so != match[0].rm_eo) {
407 /* Locate start of replaced string. */
408 re_off = match[0].rm_so;
409 /* Copy leading retained string. */
410 cspace(&SS, s, re_off, APPEND);
411 /* Add in regular expression. */
412 regsub(&SS, s, cp->u.s->new);
415 /* Move past this match. */
416 if (match[0].rm_so != match[0].rm_eo) {
418 slen -= match[0].rm_eo;
421 if (match[0].rm_so < slen)
422 cspace(&SS, s + match[0].rm_so, 1,
424 s += match[0].rm_so + 1;
425 slen -= match[0].rm_so + 1;
428 } while (slen >= 0 && regexec_e(re, s, REG_NOTBOL, 0, slen));
429 /* Copy trailing retained string. */
431 cspace(&SS, s, slen, APPEND);
433 default: /* Nth occurrence */
435 if (match[0].rm_eo == match[0].rm_so)
436 match[0].rm_eo = match[0].rm_so + 1;
438 slen -= match[0].rm_eo;
441 if (!regexec_e(re, s, REG_NOTBOL, 0, slen))
445 case 1: /* 1st occurrence */
446 /* Locate start of replaced string. */
447 re_off = match[0].rm_so + (s - ps);
448 /* Copy leading retained string. */
449 cspace(&SS, ps, re_off, APPEND);
450 /* Add in regular expression. */
451 regsub(&SS, s, cp->u.s->new);
452 /* Copy trailing retained string. */
454 slen -= match[0].rm_eo;
455 cspace(&SS, s, slen, APPEND);
460 * Swap the substitute space and the pattern space, and make sure
461 * that any leftover pointers into stdio memory get lost.
465 psanl = tspace.append_newline;
469 /* Handle the 'p' flag. */
473 /* Handle the 'w' flag. */
474 if (cp->u.s->wfile && !pd) {
475 if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile,
476 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1)
477 err(1, "%s", cp->u.s->wfile);
478 if (write(cp->u.s->wfd, ps, psl) != (ssize_t)psl ||
479 write(cp->u.s->wfd, "\n", 1) != 1)
480 err(1, "%s", cp->u.s->wfile);
487 * Perform translation ('y' command) in the pattern space.
490 do_tr(struct s_tr *y)
497 if (MB_CUR_MAX == 1) {
499 * Single-byte encoding: perform in-place translation
500 * of the pattern space.
502 for (p = ps; p < &ps[psl]; p++)
503 *p = y->bytetab[(u_char)*p];
506 * Multi-byte encoding: perform translation into the
507 * translation space, then swap the translation and
510 /* Clean translation space. */
512 for (p = ps, left = psl; left > 0; p += clen, left -= clen) {
513 if ((c = y->bytetab[(u_char)*p]) != '\0') {
514 cspace(&YS, &c, 1, APPEND);
518 for (i = 0; i < y->nmultis; i++)
519 if (left >= y->multis[i].fromlen &&
520 memcmp(p, y->multis[i].from,
521 y->multis[i].fromlen) == 0)
523 if (i < y->nmultis) {
524 cspace(&YS, y->multis[i].to,
525 y->multis[i].tolen, APPEND);
526 clen = y->multis[i].fromlen;
528 cspace(&YS, p, 1, APPEND);
532 /* Swap the translation space and the pattern space. */
535 psanl = tmp.append_newline;
542 * Flush append requests. Always called before reading a line,
543 * therefore it also resets the substitution done (sdone) flag.
552 for (i = 0; i < appendx; i++)
553 switch (appends[i].type) {
555 fwrite(appends[i].s, sizeof(char), appends[i].len,
560 * Read files probably shouldn't be cached. Since
561 * it's not an error to read a non-existent file,
562 * it's possible that another program is interacting
563 * with the sed script through the filesystem. It
564 * would be truly bizarre, but possible. It's probably
565 * not that big a performance win, anyhow.
567 if ((f = fopen(appends[i].s, "r")) == NULL)
569 while ((count = fread(buf, sizeof(char), sizeof(buf), f)))
570 (void)fwrite(buf, sizeof(char), count, outfile);
575 errx(1, "%s: %s", outfname, strerror(errno ? errno : EIO));
580 lputs(char *s, size_t len)
582 static const char escapes[] = "\\\a\b\f\r\t\v";
586 static int termwidth = -1;
591 if (outfile != stdout)
593 if (termwidth == -1) {
594 if ((p = getenv("COLUMNS")) && *p != '\0')
596 else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
598 termwidth = win.ws_col;
605 memset(&mbs, 0, sizeof(mbs));
608 clen = mbrtowc(&wc, s, len, &mbs);
611 if (clen == (size_t)-1 || clen == (size_t)-2) {
612 wc = (unsigned char)*s;
614 memset(&mbs, 0, sizeof(mbs));
617 if (col + 1 >= termwidth)
618 fprintf(outfile, "\\\n");
620 fputc('\n', outfile);
622 } else if (iswprint(wc)) {
624 if (col + width >= termwidth) {
625 fprintf(outfile, "\\\n");
628 fwrite(s, 1, clen, outfile);
630 } else if (wc != L'\0' && (c = wctob(wc)) != EOF &&
631 (p = strchr(escapes, c)) != NULL) {
632 if (col + 2 >= termwidth) {
633 fprintf(outfile, "\\\n");
636 fprintf(outfile, "\\%c", "\\abfrtv"[p - escapes]);
639 if (col + 4 * clen >= (unsigned)termwidth) {
640 fprintf(outfile, "\\\n");
643 for (i = 0; i < clen; i++)
644 fprintf(outfile, "\\%03o",
645 (int)(unsigned char)s[i]);
651 if (col + 1 >= termwidth)
652 fprintf(outfile, "\\\n");
653 (void)fputc('$', outfile);
654 (void)fputc('\n', outfile);
656 errx(1, "%s: %s", outfname, strerror(errno ? errno : EIO));
660 regexec_e(regex_t *preg, const char *string, int eflags, int nomatch,
667 errx(1, "first RE may not be empty");
673 match[0].rm_eo = slen;
675 eval = regexec(defpreg, string,
676 nomatch ? 0 : maxnsub + 1, match, eflags | REG_STARTEND);
683 errx(1, "RE error: %s", strregerror(eval, defpreg));
688 * regsub - perform substitutions after a regexp match
689 * Based on a routine by Henry Spencer
692 regsub(SPACE *sp, char *string, char *src)
697 #define NEEDSP(reqlen) \
698 /* XXX What is the +1 for? */ \
699 if (sp->len + (reqlen) + 1 >= sp->blen) { \
700 sp->blen += (reqlen) + 1024; \
701 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) \
704 dst = sp->space + sp->len; \
707 dst = sp->space + sp->len;
708 while ((c = *src++) != '\0') {
711 else if (c == '\\' && isdigit((unsigned char)*src))
715 if (no < 0) { /* Ordinary character. */
716 if (c == '\\' && (*src == '\\' || *src == '&'))
721 } else if (match[no].rm_so != -1 && match[no].rm_eo != -1) {
722 len = match[no].rm_eo - match[no].rm_so;
724 memmove(dst, string + match[no].rm_so, len);
735 * Concatenate space: append the source space to the destination space,
736 * allocating new space as necessary.
739 cspace(SPACE *sp, const char *p, size_t len, enum e_spflag spflag)
743 /* Make sure SPACE has enough memory and ramp up quickly. */
744 tlen = sp->len + len + 1;
745 if (tlen > sp->blen) {
746 sp->blen = tlen + 1024;
747 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) ==
752 if (spflag == REPLACE)
755 memmove(sp->space + sp->len, p, len);
757 sp->space[sp->len += len] = '\0';
761 * Close all cached opened files and report any errors
764 cfclose(struct s_command *cp, struct s_command *end)
767 for (; cp != end; cp = cp->next)
770 if (cp->u.s->wfd != -1 && close(cp->u.s->wfd))
771 err(1, "%s", cp->u.s->wfile);
775 if (cp->u.fd != -1 && close(cp->u.fd))
780 cfclose(cp->u.c, cp->next);