2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1992 Diomidis Spinellis.
5 * Copyright (c) 1992, 1993, 1994
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[] = "@(#)process.c 8.6 (Berkeley) 4/20/94";
43 #include <sys/types.h>
45 #include <sys/ioctl.h>
64 static SPACE HS, PS, SS, YS;
68 #define psanl PS.append_newline
72 static inline int applies(struct s_command *);
73 static void do_tr(struct s_tr *);
74 static void flush_appends(void);
75 static void lputs(char *, size_t);
76 static int regexec_e(regex_t *, const char *, int, int, size_t,
78 static void regsub(SPACE *, char *, char *);
79 static int substitute(struct s_command *);
81 struct s_appends *appends; /* Array of pointers to strings to append. */
82 static int appendx; /* Index into appends array. */
83 int appendnum; /* Size of appends array. */
85 static int lastaddr; /* Set by applies if last address of a range. */
86 static int sdone; /* If any substitutes since last line input. */
87 /* Iov structure for 'w' commands. */
88 static regex_t *defpreg;
93 fwrite(ps, 1, psl, outfile); \
94 if (psanl) fputc('\n', outfile); \
100 struct s_command *cp;
107 oldpsanl = oldpsl = 0;
109 for (linenum = 0; mf_fgets(&PS, REPLACE);) {
124 if (appendx >= appendnum)
125 if ((appends = realloc(appends,
126 sizeof(struct s_appends) *
127 (appendnum *= 2))) == NULL)
129 appends[appendx].type = AP_STRING;
130 appends[appendx].s = cp->t;
131 appends[appendx].len = strlen(cp->t);
140 if (cp->a2 == NULL || lastaddr || lastline())
141 (void)fprintf(outfile, "%s", cp->t);
150 (p = memchr(ps, '\n', psl)) == NULL) {
155 memmove(ps, p + 1, psl);
159 cspace(&PS, hs, hsl, REPLACE);
162 cspace(&PS, "\n", 1, APPEND);
163 cspace(&PS, hs, hsl, APPEND);
166 cspace(&HS, ps, psl, REPLACE);
169 cspace(&HS, "\n", 1, APPEND);
170 cspace(&HS, ps, psl, APPEND);
173 (void)fprintf(outfile, "%s", cp->t);
182 if (!mf_fgets(&PS, REPLACE))
188 cspace(&PS, "\n", 1, APPEND);
189 if (!mf_fgets(&PS, APPEND))
200 if ((p = memchr(ps, '\n', psl)) != NULL) {
218 if (appendx >= appendnum)
219 if ((appends = realloc(appends,
220 sizeof(struct s_appends) *
221 (appendnum *= 2))) == NULL)
223 appends[appendx].type = AP_FILE;
224 appends[appendx].s = cp->t;
225 appends[appendx].len = strlen(cp->t);
229 sdone |= substitute(cp);
241 if (cp->u.fd == -1 && (cp->u.fd = open(cp->t,
242 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
245 if (write(cp->u.fd, ps, psl) != (ssize_t)psl ||
246 write(cp->u.fd, "\n", 1) != 1)
251 * If the hold space is null, make it empty
252 * but not null. Otherwise the pattern space
253 * will become null after the swap, which is
254 * an abnormal condition.
257 cspace(&HS, "", 0, REPLACE);
260 psanl = tspace.append_newline;
272 (void)fprintf(outfile, "%lu\n", linenum);
277 new: if (!nflag && !pd)
280 } /* for all lines */
284 * TRUE if the address passed matches the current program state
285 * (lastline, linenumber, ps).
288 ((a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, 0, psl) : \
289 (a)->type == AT_LINE ? linenum == (a)->u.l : lastline())
292 * Return TRUE if the command applies to the current line. Sets the start
293 * line for process ranges. Interprets the non-select (``!'') flag.
296 applies(struct s_command *cp)
301 if (cp->a1 == NULL && cp->a2 == NULL)
304 if (cp->startline > 0) {
305 switch (cp->a2->type) {
307 if (linenum - cp->startline <= cp->a2->u.l)
319 } else if (cp->a2->type == AT_LINE &&
320 linenum > cp->a2->u.l) {
322 * We missed the 2nd address due to a
323 * branch, so just close the range and
331 } else if (cp->a1 && MATCH(cp->a1)) {
333 * If the second address is a number less than or
334 * equal to the line number first selected, only
335 * one line shall be selected.
337 * Likewise if the relative second line address is zero.
339 if ((cp->a2->type == AT_LINE &&
340 linenum >= cp->a2->u.l) ||
341 (cp->a2->type == AT_RELLINE && cp->a2->u.l == 0))
344 cp->startline = linenum;
351 return (cp->nonsel ? ! r : r);
355 * Reset the sed processor to its initial state.
360 struct s_command *cp;
363 * Reset all in-range markers.
365 for (cp = prog; cp; cp = cp->code == '{' ? cp->u.c : cp->next)
370 * Clear out the hold space.
372 cspace(&HS, "", 0, REPLACE);
377 * Do substitutions in the pattern space. Currently, we build a
378 * copy of the new pattern space in the substitute space structure
379 * and then swap them.
382 substitute(struct s_command *cp)
394 if (defpreg != NULL && cp->u.s->maxbref > defpreg->re_nsub) {
395 linenum = cp->u.s->linenum;
396 errx(1, "%lu: %s: \\%u not defined in the RE",
397 linenum, fname, cp->u.s->maxbref);
400 if (!regexec_e(re, ps, 0, 0, 0, psl))
403 SS.len = 0; /* Clean substitute space. */
409 /* Copy the leading retained string. */
410 if (n <= 1 && (match[0].rm_so > le))
411 cspace(&SS, s, match[0].rm_so - le, APPEND);
413 /* Skip zero-length matches right after other matches. */
414 if (lastempty || (match[0].rm_so - le) ||
415 match[0].rm_so != match[0].rm_eo) {
417 /* Want this match: append replacement. */
418 regsub(&SS, ps, cp->u.s->new);
422 /* Want a later match: append original. */
423 if (match[0].rm_eo - le)
424 cspace(&SS, s, match[0].rm_eo - le,
430 /* Move past this match. */
431 s = ps + match[0].rm_eo;
432 slen = psl - match[0].rm_eo;
436 * After a zero-length match, advance one byte,
437 * and at the end of the line, terminate.
439 if (match[0].rm_so == match[0].rm_eo) {
440 if (*s == '\0' || *s == '\n')
445 cspace(&SS, s++, 1, APPEND);
452 } while (n >= 0 && slen >= 0 &&
453 regexec_e(re, ps, REG_NOTBOL, 0, le, psl));
455 /* Did not find the requested number of matches. */
459 /* Copy the trailing retained string. */
461 cspace(&SS, s, slen, APPEND);
464 * Swap the substitute space and the pattern space, and make sure
465 * that any leftover pointers into stdio memory get lost.
469 psanl = tspace.append_newline;
473 /* Handle the 'p' flag. */
477 /* Handle the 'w' flag. */
478 if (cp->u.s->wfile && !pd) {
479 if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile,
480 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1)
481 err(1, "%s", cp->u.s->wfile);
482 if (write(cp->u.s->wfd, ps, psl) != (ssize_t)psl ||
483 write(cp->u.s->wfd, "\n", 1) != 1)
484 err(1, "%s", cp->u.s->wfile);
491 * Perform translation ('y' command) in the pattern space.
494 do_tr(struct s_tr *y)
501 if (MB_CUR_MAX == 1) {
503 * Single-byte encoding: perform in-place translation
504 * of the pattern space.
506 for (p = ps; p < &ps[psl]; p++)
507 *p = y->bytetab[(u_char)*p];
510 * Multi-byte encoding: perform translation into the
511 * translation space, then swap the translation and
514 /* Clean translation space. */
516 for (p = ps, left = psl; left > 0; p += clen, left -= clen) {
517 if ((c = y->bytetab[(u_char)*p]) != '\0') {
518 cspace(&YS, &c, 1, APPEND);
522 for (i = 0; i < y->nmultis; i++)
523 if (left >= y->multis[i].fromlen &&
524 memcmp(p, y->multis[i].from,
525 y->multis[i].fromlen) == 0)
527 if (i < y->nmultis) {
528 cspace(&YS, y->multis[i].to,
529 y->multis[i].tolen, APPEND);
530 clen = y->multis[i].fromlen;
532 cspace(&YS, p, 1, APPEND);
536 /* Swap the translation space and the pattern space. */
539 psanl = tmp.append_newline;
546 * Flush append requests. Always called before reading a line,
547 * therefore it also resets the substitution done (sdone) flag.
556 for (i = 0; i < appendx; i++)
557 switch (appends[i].type) {
559 fwrite(appends[i].s, sizeof(char), appends[i].len,
564 * Read files probably shouldn't be cached. Since
565 * it's not an error to read a non-existent file,
566 * it's possible that another program is interacting
567 * with the sed script through the filesystem. It
568 * would be truly bizarre, but possible. It's probably
569 * not that big a performance win, anyhow.
571 if ((f = fopen(appends[i].s, "r")) == NULL)
573 while ((count = fread(buf, sizeof(char), sizeof(buf), f)))
574 (void)fwrite(buf, sizeof(char), count, outfile);
579 errx(1, "%s: %s", outfname, strerror(errno ? errno : EIO));
584 lputs(char *s, size_t len)
586 static const char escapes[] = "\\\a\b\f\r\t\v";
590 static int termwidth = -1;
595 if (outfile != stdout)
597 if (termwidth == -1) {
598 if ((p = getenv("COLUMNS")) && *p != '\0')
600 else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
602 termwidth = win.ws_col;
609 memset(&mbs, 0, sizeof(mbs));
612 clen = mbrtowc(&wc, s, len, &mbs);
615 if (clen == (size_t)-1 || clen == (size_t)-2) {
616 wc = (unsigned char)*s;
618 memset(&mbs, 0, sizeof(mbs));
621 if (col + 1 >= termwidth)
622 fprintf(outfile, "\\\n");
624 fputc('\n', outfile);
626 } else if (iswprint(wc)) {
628 if (col + width >= termwidth) {
629 fprintf(outfile, "\\\n");
632 fwrite(s, 1, clen, outfile);
634 } else if (wc != L'\0' && (c = wctob(wc)) != EOF &&
635 (p = strchr(escapes, c)) != NULL) {
636 if (col + 2 >= termwidth) {
637 fprintf(outfile, "\\\n");
640 fprintf(outfile, "\\%c", "\\abfrtv"[p - escapes]);
643 if (col + 4 * clen >= (unsigned)termwidth) {
644 fprintf(outfile, "\\\n");
647 for (i = 0; i < clen; i++)
648 fprintf(outfile, "\\%03o",
649 (int)(unsigned char)s[i]);
655 if (col + 1 >= termwidth)
656 fprintf(outfile, "\\\n");
657 (void)fputc('$', outfile);
658 (void)fputc('\n', outfile);
660 errx(1, "%s: %s", outfname, strerror(errno ? errno : EIO));
664 regexec_e(regex_t *preg, const char *string, int eflags, int nomatch,
665 size_t start, size_t stop)
671 errx(1, "first RE may not be empty");
676 match[0].rm_so = start;
677 match[0].rm_eo = stop;
679 eval = regexec(defpreg, string,
680 nomatch ? 0 : maxnsub + 1, match, eflags | REG_STARTEND);
687 errx(1, "RE error: %s", strregerror(eval, defpreg));
692 * regsub - perform substitutions after a regexp match
693 * Based on a routine by Henry Spencer
696 regsub(SPACE *sp, char *string, char *src)
701 #define NEEDSP(reqlen) \
702 /* XXX What is the +1 for? */ \
703 if (sp->len + (reqlen) + 1 >= sp->blen) { \
704 sp->blen += (reqlen) + 1024; \
705 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) \
708 dst = sp->space + sp->len; \
711 dst = sp->space + sp->len;
712 while ((c = *src++) != '\0') {
715 else if (c == '\\' && isdigit((unsigned char)*src))
719 if (no < 0) { /* Ordinary character. */
720 if (c == '\\' && (*src == '\\' || *src == '&'))
725 } else if (match[no].rm_so != -1 && match[no].rm_eo != -1) {
726 len = match[no].rm_eo - match[no].rm_so;
728 memmove(dst, string + match[no].rm_so, len);
739 * Concatenate space: append the source space to the destination space,
740 * allocating new space as necessary.
743 cspace(SPACE *sp, const char *p, size_t len, enum e_spflag spflag)
747 /* Make sure SPACE has enough memory and ramp up quickly. */
748 tlen = sp->len + len + 1;
749 if (tlen > sp->blen) {
750 sp->blen = tlen + 1024;
751 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) ==
756 if (spflag == REPLACE)
759 memmove(sp->space + sp->len, p, len);
761 sp->space[sp->len += len] = '\0';
765 * Close all cached opened files and report any errors
768 cfclose(struct s_command *cp, struct s_command *end)
771 for (; cp != end; cp = cp->next)
774 if (cp->u.s->wfd != -1 && close(cp->u.s->wfd))
775 err(1, "%s", cp->u.s->wfile);
779 if (cp->u.fd != -1 && close(cp->u.fd))
784 cfclose(cp->u.c, cp->next);