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 unsigned int appendx; /* Index into appends array. */
83 unsigned 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) {
213 if (inplace == NULL) {
222 if (appendx >= appendnum)
223 if ((appends = realloc(appends,
224 sizeof(struct s_appends) *
225 (appendnum *= 2))) == NULL)
227 appends[appendx].type = AP_FILE;
228 appends[appendx].s = cp->t;
229 appends[appendx].len = strlen(cp->t);
233 sdone |= substitute(cp);
245 if (cp->u.fd == -1 && (cp->u.fd = open(cp->t,
246 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
249 if (write(cp->u.fd, ps, psl) != (ssize_t)psl ||
250 write(cp->u.fd, "\n", 1) != 1)
255 * If the hold space is null, make it empty
256 * but not null. Otherwise the pattern space
257 * will become null after the swap, which is
258 * an abnormal condition.
261 cspace(&HS, "", 0, REPLACE);
264 psanl = tspace.append_newline;
276 (void)fprintf(outfile, "%lu\n", linenum);
281 new: if (!nflag && !pd)
284 } /* for all lines */
288 * TRUE if the address passed matches the current program state
289 * (lastline, linenumber, ps).
292 ((a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, 0, psl) : \
293 (a)->type == AT_LINE ? linenum == (a)->u.l : lastline())
296 * Return TRUE if the command applies to the current line. Sets the start
297 * line for process ranges. Interprets the non-select (``!'') flag.
300 applies(struct s_command *cp)
305 if (cp->a1 == NULL && cp->a2 == NULL)
308 if (cp->startline > 0) {
309 switch (cp->a2->type) {
311 if (linenum - cp->startline <= cp->a2->u.l)
323 } else if (cp->a2->type == AT_LINE &&
324 linenum > cp->a2->u.l) {
326 * We missed the 2nd address due to a
327 * branch, so just close the range and
335 } else if (cp->a1 && MATCH(cp->a1)) {
337 * If the second address is a number less than or
338 * equal to the line number first selected, only
339 * one line shall be selected.
341 * Likewise if the relative second line address is zero.
343 if ((cp->a2->type == AT_LINE &&
344 linenum >= cp->a2->u.l) ||
345 (cp->a2->type == AT_RELLINE && cp->a2->u.l == 0))
348 cp->startline = linenum;
355 return (cp->nonsel ? ! r : r);
359 * Reset the sed processor to its initial state.
364 struct s_command *cp;
367 * Reset all in-range markers.
369 for (cp = prog; cp; cp = cp->code == '{' ? cp->u.c : cp->next)
374 * Clear out the hold space.
376 cspace(&HS, "", 0, REPLACE);
381 * Do substitutions in the pattern space. Currently, we build a
382 * copy of the new pattern space in the substitute space structure
383 * and then swap them.
386 substitute(struct s_command *cp)
398 if (defpreg != NULL && cp->u.s->maxbref > defpreg->re_nsub) {
399 linenum = cp->u.s->linenum;
400 errx(1, "%lu: %s: \\%u not defined in the RE",
401 linenum, fname, cp->u.s->maxbref);
404 if (!regexec_e(re, ps, 0, 0, 0, psl))
407 SS.len = 0; /* Clean substitute space. */
413 /* Copy the leading retained string. */
414 if (n <= 1 && (match[0].rm_so > le))
415 cspace(&SS, s, match[0].rm_so - le, APPEND);
417 /* Skip zero-length matches right after other matches. */
418 if (lastempty || (match[0].rm_so - le) ||
419 match[0].rm_so != match[0].rm_eo) {
421 /* Want this match: append replacement. */
422 regsub(&SS, ps, cp->u.s->new);
426 /* Want a later match: append original. */
427 if (match[0].rm_eo - le)
428 cspace(&SS, s, match[0].rm_eo - le,
434 /* Move past this match. */
435 s = ps + match[0].rm_eo;
436 slen = psl - match[0].rm_eo;
440 * After a zero-length match, advance one byte,
441 * and at the end of the line, terminate.
443 if (match[0].rm_so == match[0].rm_eo) {
444 if (*s == '\0' || *s == '\n')
449 cspace(&SS, s++, 1, APPEND);
456 } while (n >= 0 && slen >= 0 &&
457 regexec_e(re, ps, REG_NOTBOL, 0, le, psl));
459 /* Did not find the requested number of matches. */
463 /* Copy the trailing retained string. */
465 cspace(&SS, s, slen, APPEND);
468 * Swap the substitute space and the pattern space, and make sure
469 * that any leftover pointers into stdio memory get lost.
473 psanl = tspace.append_newline;
477 /* Handle the 'p' flag. */
481 /* Handle the 'w' flag. */
482 if (cp->u.s->wfile && !pd) {
483 if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile,
484 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1)
485 err(1, "%s", cp->u.s->wfile);
486 if (write(cp->u.s->wfd, ps, psl) != (ssize_t)psl ||
487 write(cp->u.s->wfd, "\n", 1) != 1)
488 err(1, "%s", cp->u.s->wfile);
495 * Perform translation ('y' command) in the pattern space.
498 do_tr(struct s_tr *y)
505 if (MB_CUR_MAX == 1) {
507 * Single-byte encoding: perform in-place translation
508 * of the pattern space.
510 for (p = ps; p < &ps[psl]; p++)
511 *p = y->bytetab[(u_char)*p];
514 * Multi-byte encoding: perform translation into the
515 * translation space, then swap the translation and
518 /* Clean translation space. */
520 for (p = ps, left = psl; left > 0; p += clen, left -= clen) {
521 if ((c = y->bytetab[(u_char)*p]) != '\0') {
522 cspace(&YS, &c, 1, APPEND);
526 for (i = 0; i < y->nmultis; i++)
527 if (left >= y->multis[i].fromlen &&
528 memcmp(p, y->multis[i].from,
529 y->multis[i].fromlen) == 0)
531 if (i < y->nmultis) {
532 cspace(&YS, y->multis[i].to,
533 y->multis[i].tolen, APPEND);
534 clen = y->multis[i].fromlen;
536 cspace(&YS, p, 1, APPEND);
540 /* Swap the translation space and the pattern space. */
543 psanl = tmp.append_newline;
550 * Flush append requests. Always called before reading a line,
551 * therefore it also resets the substitution done (sdone) flag.
557 unsigned int count, idx;
560 for (idx = 0; idx < appendx; idx++)
561 switch (appends[idx].type) {
563 fwrite(appends[idx].s, sizeof(char), appends[idx].len,
568 * Read files probably shouldn't be cached. Since
569 * it's not an error to read a non-existent file,
570 * it's possible that another program is interacting
571 * with the sed script through the filesystem. It
572 * would be truly bizarre, but possible. It's probably
573 * not that big a performance win, anyhow.
575 if ((f = fopen(appends[idx].s, "r")) == NULL)
577 while ((count = fread(buf, sizeof(char), sizeof(buf), f)))
578 (void)fwrite(buf, sizeof(char), count, outfile);
583 errx(1, "%s: %s", outfname, strerror(errno ? errno : EIO));
588 lputs(char *s, size_t len)
590 static const char escapes[] = "\\\a\b\f\r\t\v";
594 static int termwidth = -1;
599 if (outfile != stdout)
601 if (termwidth == -1) {
602 if ((p = getenv("COLUMNS")) && *p != '\0')
604 else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
606 termwidth = win.ws_col;
613 memset(&mbs, 0, sizeof(mbs));
616 clen = mbrtowc(&wc, s, len, &mbs);
619 if (clen == (size_t)-1 || clen == (size_t)-2) {
620 wc = (unsigned char)*s;
622 memset(&mbs, 0, sizeof(mbs));
625 if (col + 1 >= termwidth)
626 fprintf(outfile, "\\\n");
628 fputc('\n', outfile);
630 } else if (iswprint(wc)) {
632 if (col + width >= termwidth) {
633 fprintf(outfile, "\\\n");
636 fwrite(s, 1, clen, outfile);
638 } else if (wc != L'\0' && (c = wctob(wc)) != EOF &&
639 (p = strchr(escapes, c)) != NULL) {
640 if (col + 2 >= termwidth) {
641 fprintf(outfile, "\\\n");
644 fprintf(outfile, "\\%c", "\\abfrtv"[p - escapes]);
647 if (col + 4 * clen >= (unsigned)termwidth) {
648 fprintf(outfile, "\\\n");
651 for (i = 0; i < clen; i++)
652 fprintf(outfile, "\\%03o",
653 (int)(unsigned char)s[i]);
659 if (col + 1 >= termwidth)
660 fprintf(outfile, "\\\n");
661 (void)fputc('$', outfile);
662 (void)fputc('\n', outfile);
664 errx(1, "%s: %s", outfname, strerror(errno ? errno : EIO));
668 regexec_e(regex_t *preg, const char *string, int eflags, int nomatch,
669 size_t start, size_t stop)
675 errx(1, "first RE may not be empty");
680 match[0].rm_so = start;
681 match[0].rm_eo = stop;
683 eval = regexec(defpreg, string,
684 nomatch ? 0 : maxnsub + 1, match, eflags | REG_STARTEND);
691 errx(1, "RE error: %s", strregerror(eval, defpreg));
696 * regsub - perform substitutions after a regexp match
697 * Based on a routine by Henry Spencer
700 regsub(SPACE *sp, char *string, char *src)
705 #define NEEDSP(reqlen) \
706 /* XXX What is the +1 for? */ \
707 if (sp->len + (reqlen) + 1 >= sp->blen) { \
708 sp->blen += (reqlen) + 1024; \
709 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) \
712 dst = sp->space + sp->len; \
715 dst = sp->space + sp->len;
716 while ((c = *src++) != '\0') {
719 else if (c == '\\' && isdigit((unsigned char)*src))
723 if (no < 0) { /* Ordinary character. */
724 if (c == '\\' && (*src == '\\' || *src == '&'))
729 } else if (match[no].rm_so != -1 && match[no].rm_eo != -1) {
730 len = match[no].rm_eo - match[no].rm_so;
732 memmove(dst, string + match[no].rm_so, len);
743 * Concatenate space: append the source space to the destination space,
744 * allocating new space as necessary.
747 cspace(SPACE *sp, const char *p, size_t len, enum e_spflag spflag)
751 /* Make sure SPACE has enough memory and ramp up quickly. */
752 tlen = sp->len + len + 1;
753 if (tlen > sp->blen) {
754 sp->blen = tlen + 1024;
755 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) ==
760 if (spflag == REPLACE)
763 memmove(sp->space + sp->len, p, len);
765 sp->space[sp->len += len] = '\0';
769 * Close all cached opened files and report any errors
772 cfclose(struct s_command *cp, struct s_command *end)
775 for (; cp != end; cp = cp->next)
778 if (cp->u.s->wfd != -1 && close(cp->u.s->wfd))
779 err(1, "%s", cp->u.s->wfile);
783 if (cp->u.fd != -1 && close(cp->u.fd))
788 cfclose(cp->u.c, cp->next);