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>
38 #include <sys/types.h>
40 #include <sys/ioctl.h>
59 static SPACE HS, PS, SS, YS;
63 #define psanl PS.append_newline
67 static inline int applies(struct s_command *);
68 static void do_tr(struct s_tr *);
69 static void flush_appends(void);
70 static void lputs(char *, size_t);
71 static int regexec_e(regex_t *, const char *, int, int, size_t,
73 static void regsub(SPACE *, char *, char *);
74 static int substitute(struct s_command *);
76 struct s_appends *appends; /* Array of pointers to strings to append. */
77 static unsigned int appendx; /* Index into appends array. */
78 unsigned int appendnum; /* Size of appends array. */
80 static int lastaddr; /* Set by applies if last address of a range. */
81 static int sdone; /* If any substitutes since last line input. */
82 /* Iov structure for 'w' commands. */
83 static regex_t *defpreg;
88 fwrite(ps, 1, psl, outfile); \
89 if (psanl) fputc('\n', outfile); \
102 oldpsanl = oldpsl = 0;
104 for (linenum = 0; mf_fgets(&PS, REPLACE);) {
119 if (appendx >= appendnum)
120 if ((appends = realloc(appends,
121 sizeof(struct s_appends) *
122 (appendnum *= 2))) == NULL)
124 appends[appendx].type = AP_STRING;
125 appends[appendx].s = cp->t;
126 appends[appendx].len = strlen(cp->t);
135 if (cp->a2 == NULL || lastaddr || lastline())
136 (void)fprintf(outfile, "%s", cp->t);
145 (p = memchr(ps, '\n', psl)) == NULL) {
150 memmove(ps, p + 1, psl);
154 cspace(&PS, hs, hsl, REPLACE);
157 cspace(&PS, "\n", 1, APPEND);
158 cspace(&PS, hs, hsl, APPEND);
161 cspace(&HS, ps, psl, REPLACE);
164 cspace(&HS, "\n", 1, APPEND);
165 cspace(&HS, ps, psl, APPEND);
168 (void)fprintf(outfile, "%s", cp->t);
177 if (!mf_fgets(&PS, REPLACE))
183 cspace(&PS, "\n", 1, APPEND);
184 if (!mf_fgets(&PS, APPEND))
195 if ((p = memchr(ps, '\n', psl)) != NULL) {
208 if (inplace == NULL) {
217 if (appendx >= appendnum)
218 if ((appends = realloc(appends,
219 sizeof(struct s_appends) *
220 (appendnum *= 2))) == NULL)
222 appends[appendx].type = AP_FILE;
223 appends[appendx].s = cp->t;
224 appends[appendx].len = strlen(cp->t);
228 sdone |= substitute(cp);
240 if (cp->u.fd == -1 && (cp->u.fd = open(cp->t,
241 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
244 if (write(cp->u.fd, ps, psl) != (ssize_t)psl ||
245 write(cp->u.fd, "\n", 1) != 1)
250 * If the hold space is null, make it empty
251 * but not null. Otherwise the pattern space
252 * will become null after the swap, which is
253 * an abnormal condition.
256 cspace(&HS, "", 0, REPLACE);
259 psanl = tspace.append_newline;
271 (void)fprintf(outfile, "%lu\n", linenum);
276 new: if (!nflag && !pd)
279 } /* for all lines */
283 * TRUE if the address passed matches the current program state
284 * (lastline, linenumber, ps).
287 ((a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, 0, psl) : \
288 (a)->type == AT_LINE ? linenum == (a)->u.l : lastline())
291 * Return TRUE if the command applies to the current line. Sets the start
292 * line for process ranges. Interprets the non-select (``!'') flag.
295 applies(struct s_command *cp)
300 if (cp->a1 == NULL && cp->a2 == NULL)
303 if (cp->startline > 0) {
304 switch (cp->a2->type) {
306 if (linenum - cp->startline <= cp->a2->u.l)
318 } else if (cp->a2->type == AT_LINE &&
319 linenum > cp->a2->u.l) {
321 * We missed the 2nd address due to a
322 * branch, so just close the range and
330 } else if (cp->a1 && MATCH(cp->a1)) {
332 * If the second address is a number less than or
333 * equal to the line number first selected, only
334 * one line shall be selected.
336 * Likewise if the relative second line address is zero.
338 if ((cp->a2->type == AT_LINE &&
339 linenum >= cp->a2->u.l) ||
340 (cp->a2->type == AT_RELLINE && cp->a2->u.l == 0))
343 cp->startline = linenum;
350 return (cp->nonsel ? ! r : r);
354 * Reset the sed processor to its initial state.
359 struct s_command *cp;
362 * Reset all in-range markers.
364 for (cp = prog; cp; cp = cp->code == '{' ? cp->u.c : cp->next)
369 * Clear out the hold space.
371 cspace(&HS, "", 0, REPLACE);
376 * Do substitutions in the pattern space. Currently, we build a
377 * copy of the new pattern space in the substitute space structure
378 * and then swap them.
381 substitute(struct s_command *cp)
393 if (defpreg != NULL && cp->u.s->maxbref > defpreg->re_nsub) {
394 linenum = cp->u.s->linenum;
395 errx(1, "%lu: %s: \\%u not defined in the RE",
396 linenum, fname, cp->u.s->maxbref);
399 if (!regexec_e(re, ps, 0, 0, 0, psl))
402 SS.len = 0; /* Clean substitute space. */
408 /* Copy the leading retained string. */
409 if (n <= 1 && (match[0].rm_so > le))
410 cspace(&SS, s, match[0].rm_so - le, APPEND);
412 /* Skip zero-length matches right after other matches. */
413 if (lastempty || (match[0].rm_so - le) ||
414 match[0].rm_so != match[0].rm_eo) {
416 /* Want this match: append replacement. */
417 regsub(&SS, ps, cp->u.s->new);
421 /* Want a later match: append original. */
422 if (match[0].rm_eo - le)
423 cspace(&SS, s, match[0].rm_eo - le,
429 /* Move past this match. */
430 s = ps + match[0].rm_eo;
431 slen = psl - match[0].rm_eo;
435 * After a zero-length match, advance one byte,
436 * and at the end of the line, terminate.
438 if (match[0].rm_so == match[0].rm_eo) {
439 if (*s == '\0' || *s == '\n')
444 cspace(&SS, s++, 1, APPEND);
451 } while (n >= 0 && slen >= 0 &&
452 regexec_e(re, ps, REG_NOTBOL, 0, le, psl));
454 /* Did not find the requested number of matches. */
458 /* Copy the trailing retained string. */
460 cspace(&SS, s, slen, APPEND);
463 * Swap the substitute space and the pattern space, and make sure
464 * that any leftover pointers into stdio memory get lost.
468 psanl = tspace.append_newline;
472 /* Handle the 'p' flag. */
476 /* Handle the 'w' flag. */
477 if (cp->u.s->wfile && !pd) {
478 if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile,
479 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1)
480 err(1, "%s", cp->u.s->wfile);
481 if (write(cp->u.s->wfd, ps, psl) != (ssize_t)psl ||
482 write(cp->u.s->wfd, "\n", 1) != 1)
483 err(1, "%s", cp->u.s->wfile);
490 * Perform translation ('y' command) in the pattern space.
493 do_tr(struct s_tr *y)
500 if (MB_CUR_MAX == 1) {
502 * Single-byte encoding: perform in-place translation
503 * of the pattern space.
505 for (p = ps; p < &ps[psl]; p++)
506 *p = y->bytetab[(u_char)*p];
509 * Multi-byte encoding: perform translation into the
510 * translation space, then swap the translation and
513 /* Clean translation space. */
515 for (p = ps, left = psl; left > 0; p += clen, left -= clen) {
516 if ((c = y->bytetab[(u_char)*p]) != '\0') {
517 cspace(&YS, &c, 1, APPEND);
521 for (i = 0; i < y->nmultis; i++)
522 if (left >= y->multis[i].fromlen &&
523 memcmp(p, y->multis[i].from,
524 y->multis[i].fromlen) == 0)
526 if (i < y->nmultis) {
527 cspace(&YS, y->multis[i].to,
528 y->multis[i].tolen, APPEND);
529 clen = y->multis[i].fromlen;
531 cspace(&YS, p, 1, APPEND);
535 /* Swap the translation space and the pattern space. */
538 psanl = tmp.append_newline;
545 * Flush append requests. Always called before reading a line,
546 * therefore it also resets the substitution done (sdone) flag.
552 unsigned int count, idx;
555 for (idx = 0; idx < appendx; idx++)
556 switch (appends[idx].type) {
558 fwrite(appends[idx].s, sizeof(char), appends[idx].len,
563 * Read files probably shouldn't be cached. Since
564 * it's not an error to read a non-existent file,
565 * it's possible that another program is interacting
566 * with the sed script through the filesystem. It
567 * would be truly bizarre, but possible. It's probably
568 * not that big a performance win, anyhow.
570 if ((f = fopen(appends[idx].s, "r")) == NULL)
572 while ((count = fread(buf, sizeof(char), sizeof(buf), f)))
573 (void)fwrite(buf, sizeof(char), count, outfile);
578 errx(1, "%s: %s", outfname, strerror(errno ? errno : EIO));
583 lputs(char *s, size_t len)
585 static const char escapes[] = "\\\a\b\f\r\t\v";
589 static int termwidth = -1;
594 if (outfile != stdout)
596 if (termwidth == -1) {
597 if ((p = getenv("COLUMNS")) && *p != '\0')
599 else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
601 termwidth = win.ws_col;
608 memset(&mbs, 0, sizeof(mbs));
611 clen = mbrtowc(&wc, s, len, &mbs);
614 if (clen == (size_t)-1 || clen == (size_t)-2) {
615 wc = (unsigned char)*s;
617 memset(&mbs, 0, sizeof(mbs));
620 if (col + 1 >= termwidth)
621 fprintf(outfile, "\\\n");
623 fputc('\n', outfile);
625 } else if (iswprint(wc)) {
627 if (col + width >= termwidth) {
628 fprintf(outfile, "\\\n");
631 fwrite(s, 1, clen, outfile);
633 } else if (wc != L'\0' && (c = wctob(wc)) != EOF &&
634 (p = strchr(escapes, c)) != NULL) {
635 if (col + 2 >= termwidth) {
636 fprintf(outfile, "\\\n");
639 fprintf(outfile, "\\%c", "\\abfrtv"[p - escapes]);
642 if (col + 4 * clen >= (unsigned)termwidth) {
643 fprintf(outfile, "\\\n");
646 for (i = 0; i < clen; i++)
647 fprintf(outfile, "\\%03o",
648 (int)(unsigned char)s[i]);
654 if (col + 1 >= termwidth)
655 fprintf(outfile, "\\\n");
656 (void)fputc('$', outfile);
657 (void)fputc('\n', outfile);
659 errx(1, "%s: %s", outfname, strerror(errno ? errno : EIO));
663 regexec_e(regex_t *preg, const char *string, int eflags, int nomatch,
664 size_t start, size_t stop)
670 errx(1, "first RE may not be empty");
675 match[0].rm_so = start;
676 match[0].rm_eo = stop;
678 eval = regexec(defpreg, string,
679 nomatch ? 0 : maxnsub + 1, match, eflags | REG_STARTEND);
686 errx(1, "RE error: %s", strregerror(eval, defpreg));
691 * regsub - perform substitutions after a regexp match
692 * Based on a routine by Henry Spencer
695 regsub(SPACE *sp, char *string, char *src)
700 #define NEEDSP(reqlen) \
701 /* XXX What is the +1 for? */ \
702 if (sp->len + (reqlen) + 1 >= sp->blen) { \
703 sp->blen += (reqlen) + 1024; \
704 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) \
707 dst = sp->space + sp->len; \
710 dst = sp->space + sp->len;
711 while ((c = *src++) != '\0') {
714 else if (c == '\\' && isdigit((unsigned char)*src))
718 if (no < 0) { /* Ordinary character. */
719 if (c == '\\' && (*src == '\\' || *src == '&'))
724 } else if (match[no].rm_so != -1 && match[no].rm_eo != -1) {
725 len = match[no].rm_eo - match[no].rm_so;
727 memmove(dst, string + match[no].rm_so, len);
738 * Concatenate space: append the source space to the destination space,
739 * allocating new space as necessary.
742 cspace(SPACE *sp, const char *p, size_t len, enum e_spflag spflag)
746 /* Make sure SPACE has enough memory and ramp up quickly. */
747 tlen = sp->len + len + 1;
748 if (tlen > sp->blen) {
749 sp->blen = tlen + 1024;
750 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) ==
755 if (spflag == REPLACE)
758 memmove(sp->space + sp->len, p, len);
760 sp->space[sp->len += len] = '\0';
764 * Close all cached opened files and report any errors
767 cfclose(struct s_command *cp, struct s_command *end)
770 for (; cp != end; cp = cp->next)
773 if (cp->u.s->wfd != -1 && close(cp->u.s->wfd))
774 err(1, "%s", cp->u.s->wfile);
778 if (cp->u.fd != -1 && close(cp->u.fd))
783 cfclose(cp->u.c, cp->next);