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;
69 static inline int applies(struct s_command *);
70 static void do_tr(struct s_tr *);
71 static void flush_appends(void);
72 static void lputs(char *, size_t);
73 static int regexec_e(regex_t *, const char *, int, int, size_t);
74 static void regsub(SPACE *, char *, char *);
75 static int substitute(struct s_command *);
77 struct s_appends *appends; /* Array of pointers to strings to append. */
78 static int appendx; /* Index into appends array. */
79 int appendnum; /* Size of appends array. */
81 static int lastaddr; /* Set by applies if last address of a range. */
82 static int sdone; /* If any substitutes since last line input. */
83 /* Iov structure for 'w' commands. */
84 static regex_t *defpreg;
88 #define OUT() do {fwrite(ps, 1, psl, outfile); fputc('\n', outfile);} while (0)
100 for (linenum = 0; mf_fgets(&PS, REPLACE);) {
115 if (appendx >= appendnum)
116 if ((appends = realloc(appends,
117 sizeof(struct s_appends) *
118 (appendnum *= 2))) == NULL)
120 appends[appendx].type = AP_STRING;
121 appends[appendx].s = cp->t;
122 appends[appendx].len = strlen(cp->t);
131 if (cp->a2 == NULL || lastaddr || lastline())
132 (void)fprintf(outfile, "%s", cp->t);
141 (p = memchr(ps, '\n', psl)) == NULL) {
146 memmove(ps, p + 1, psl);
150 cspace(&PS, hs, hsl, REPLACE);
153 cspace(&PS, "\n", 1, APPEND);
154 cspace(&PS, hs, hsl, APPEND);
157 cspace(&HS, ps, psl, REPLACE);
160 cspace(&HS, "\n", 1, APPEND);
161 cspace(&HS, ps, psl, APPEND);
164 (void)fprintf(outfile, "%s", cp->t);
173 if (!mf_fgets(&PS, REPLACE))
179 cspace(&PS, "\n", 1, APPEND);
180 if (!mf_fgets(&PS, APPEND))
191 if ((p = memchr(ps, '\n', psl)) != NULL) {
205 if (appendx >= appendnum)
206 if ((appends = realloc(appends,
207 sizeof(struct s_appends) *
208 (appendnum *= 2))) == NULL)
210 appends[appendx].type = AP_FILE;
211 appends[appendx].s = cp->t;
212 appends[appendx].len = strlen(cp->t);
216 sdone |= substitute(cp);
228 if (cp->u.fd == -1 && (cp->u.fd = open(cp->t,
229 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
232 if (write(cp->u.fd, ps, psl) != (ssize_t)psl ||
233 write(cp->u.fd, "\n", 1) != 1)
238 * If the hold space is null, make it empty
239 * but not null. Otherwise the pattern space
240 * will become null after the swap, which is
241 * an abnormal condition.
244 cspace(&HS, "", 0, REPLACE);
258 (void)fprintf(outfile, "%lu\n", linenum);
263 new: if (!nflag && !pd)
266 } /* for all lines */
270 * TRUE if the address passed matches the current program state
271 * (lastline, linenumber, ps).
274 ((a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, psl) : \
275 (a)->type == AT_LINE ? linenum == (a)->u.l : lastline())
278 * Return TRUE if the command applies to the current line. Sets the start
279 * line for process ranges. Interprets the non-select (``!'') flag.
282 applies(struct s_command *cp)
287 if (cp->a1 == NULL && cp->a2 == NULL)
290 if (cp->startline > 0) {
291 switch (cp->a2->type) {
293 if (linenum - cp->startline <= cp->a2->u.l)
305 } else if (cp->a2->type == AT_LINE &&
306 linenum > cp->a2->u.l) {
308 * We missed the 2nd address due to a
309 * branch, so just close the range and
317 } else if (cp->a1 && MATCH(cp->a1)) {
319 * If the second address is a number less than or
320 * equal to the line number first selected, only
321 * one line shall be selected.
323 * Likewise if the relative second line address is zero.
325 if ((cp->a2->type == AT_LINE &&
326 linenum >= cp->a2->u.l) ||
327 (cp->a2->type == AT_RELLINE && cp->a2->u.l == 0))
330 cp->startline = linenum;
337 return (cp->nonsel ? ! r : r);
341 * Reset the sed processor to its initial state.
346 struct s_command *cp;
349 * Reset all in-range markers.
351 for (cp = prog; cp; cp = cp->code == '{' ? cp->u.c : cp->next)
356 * Clear out the hold space.
358 cspace(&HS, "", 0, REPLACE);
363 * Do substitutions in the pattern space. Currently, we build a
364 * copy of the new pattern space in the substitute space structure
365 * and then swap them.
368 substitute(struct s_command *cp)
379 if (defpreg != NULL && cp->u.s->maxbref > defpreg->re_nsub) {
380 linenum = cp->u.s->linenum;
381 errx(1, "%lu: %s: \\%u not defined in the RE",
382 linenum, fname, cp->u.s->maxbref);
385 if (!regexec_e(re, s, 0, 0, psl))
388 SS.len = 0; /* Clean substitute space. */
394 /* Copy the leading retained string. */
395 if (n <= 1 && match[0].rm_so)
396 cspace(&SS, s, match[0].rm_so, APPEND);
398 /* Skip zero-length matches right after other matches. */
399 if (lastempty || match[0].rm_so ||
400 match[0].rm_so != match[0].rm_eo) {
402 /* Want this match: append replacement. */
403 regsub(&SS, s, cp->u.s->new);
407 /* Want a later match: append original. */
409 cspace(&SS, s, match[0].rm_eo, APPEND);
414 /* Move past this match. */
416 slen -= match[0].rm_eo;
419 * After a zero-length match, advance one byte,
420 * and at the end of the line, terminate.
422 if (match[0].rm_so == match[0].rm_eo) {
423 if (*s == '\0' || *s == '\n')
428 cspace(&SS, s++, 1, APPEND);
433 } while (n >= 0 && slen >= 0 && regexec_e(re, s, REG_NOTBOL, 0, slen));
435 /* Did not find the requested number of matches. */
439 /* Copy the trailing retained string. */
441 cspace(&SS, s, slen, APPEND);
444 * Swap the substitute space and the pattern space, and make sure
445 * that any leftover pointers into stdio memory get lost.
452 /* Handle the 'p' flag. */
456 /* Handle the 'w' flag. */
457 if (cp->u.s->wfile && !pd) {
458 if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile,
459 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1)
460 err(1, "%s", cp->u.s->wfile);
461 if (write(cp->u.s->wfd, ps, psl) != (ssize_t)psl ||
462 write(cp->u.s->wfd, "\n", 1) != 1)
463 err(1, "%s", cp->u.s->wfile);
470 * Perform translation ('y' command) in the pattern space.
473 do_tr(struct s_tr *y)
480 if (MB_CUR_MAX == 1) {
482 * Single-byte encoding: perform in-place translation
483 * of the pattern space.
485 for (p = ps; p < &ps[psl]; p++)
486 *p = y->bytetab[(u_char)*p];
489 * Multi-byte encoding: perform translation into the
490 * translation space, then swap the translation and
493 /* Clean translation space. */
495 for (p = ps, left = psl; left > 0; p += clen, left -= clen) {
496 if ((c = y->bytetab[(u_char)*p]) != '\0') {
497 cspace(&YS, &c, 1, APPEND);
501 for (i = 0; i < y->nmultis; i++)
502 if (left >= y->multis[i].fromlen &&
503 memcmp(p, y->multis[i].from,
504 y->multis[i].fromlen) == 0)
506 if (i < y->nmultis) {
507 cspace(&YS, y->multis[i].to,
508 y->multis[i].tolen, APPEND);
509 clen = y->multis[i].fromlen;
511 cspace(&YS, p, 1, APPEND);
515 /* Swap the translation space and the pattern space. */
524 * Flush append requests. Always called before reading a line,
525 * therefore it also resets the substitution done (sdone) flag.
534 for (i = 0; i < appendx; i++)
535 switch (appends[i].type) {
537 fwrite(appends[i].s, sizeof(char), appends[i].len,
542 * Read files probably shouldn't be cached. Since
543 * it's not an error to read a non-existent file,
544 * it's possible that another program is interacting
545 * with the sed script through the filesystem. It
546 * would be truly bizarre, but possible. It's probably
547 * not that big a performance win, anyhow.
549 if ((f = fopen(appends[i].s, "r")) == NULL)
551 while ((count = fread(buf, sizeof(char), sizeof(buf), f)))
552 (void)fwrite(buf, sizeof(char), count, outfile);
557 errx(1, "%s: %s", outfname, strerror(errno ? errno : EIO));
562 lputs(char *s, size_t len)
564 static const char escapes[] = "\\\a\b\f\r\t\v";
568 static int termwidth = -1;
573 if (outfile != stdout)
575 if (termwidth == -1) {
576 if ((p = getenv("COLUMNS")) && *p != '\0')
578 else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
580 termwidth = win.ws_col;
587 memset(&mbs, 0, sizeof(mbs));
590 clen = mbrtowc(&wc, s, len, &mbs);
593 if (clen == (size_t)-1 || clen == (size_t)-2) {
594 wc = (unsigned char)*s;
596 memset(&mbs, 0, sizeof(mbs));
599 if (col + 1 >= termwidth)
600 fprintf(outfile, "\\\n");
602 fputc('\n', outfile);
604 } else if (iswprint(wc)) {
606 if (col + width >= termwidth) {
607 fprintf(outfile, "\\\n");
610 fwrite(s, 1, clen, outfile);
612 } else if (wc != L'\0' && (c = wctob(wc)) != EOF &&
613 (p = strchr(escapes, c)) != NULL) {
614 if (col + 2 >= termwidth) {
615 fprintf(outfile, "\\\n");
618 fprintf(outfile, "\\%c", "\\abfrtv"[p - escapes]);
621 if (col + 4 * clen >= (unsigned)termwidth) {
622 fprintf(outfile, "\\\n");
625 for (i = 0; i < clen; i++)
626 fprintf(outfile, "\\%03o",
627 (int)(unsigned char)s[i]);
633 if (col + 1 >= termwidth)
634 fprintf(outfile, "\\\n");
635 (void)fputc('$', outfile);
636 (void)fputc('\n', outfile);
638 errx(1, "%s: %s", outfname, strerror(errno ? errno : EIO));
642 regexec_e(regex_t *preg, const char *string, int eflags, int nomatch,
649 errx(1, "first RE may not be empty");
655 match[0].rm_eo = slen;
657 eval = regexec(defpreg, string,
658 nomatch ? 0 : maxnsub + 1, match, eflags | REG_STARTEND);
665 errx(1, "RE error: %s", strregerror(eval, defpreg));
670 * regsub - perform substitutions after a regexp match
671 * Based on a routine by Henry Spencer
674 regsub(SPACE *sp, char *string, char *src)
679 #define NEEDSP(reqlen) \
680 /* XXX What is the +1 for? */ \
681 if (sp->len + (reqlen) + 1 >= sp->blen) { \
682 sp->blen += (reqlen) + 1024; \
683 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) \
686 dst = sp->space + sp->len; \
689 dst = sp->space + sp->len;
690 while ((c = *src++) != '\0') {
693 else if (c == '\\' && isdigit((unsigned char)*src))
697 if (no < 0) { /* Ordinary character. */
698 if (c == '\\' && (*src == '\\' || *src == '&'))
703 } else if (match[no].rm_so != -1 && match[no].rm_eo != -1) {
704 len = match[no].rm_eo - match[no].rm_so;
706 memmove(dst, string + match[no].rm_so, len);
717 * Concatenate space: append the source space to the destination space,
718 * allocating new space as necessary.
721 cspace(SPACE *sp, const char *p, size_t len, enum e_spflag spflag)
725 /* Make sure SPACE has enough memory and ramp up quickly. */
726 tlen = sp->len + len + 1;
727 if (tlen > sp->blen) {
728 sp->blen = tlen + 1024;
729 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) ==
734 if (spflag == REPLACE)
737 memmove(sp->space + sp->len, p, len);
739 sp->space[sp->len += len] = '\0';
743 * Close all cached opened files and report any errors
746 cfclose(struct s_command *cp, struct s_command *end)
749 for (; cp != end; cp = cp->next)
752 if (cp->u.s->wfd != -1 && close(cp->u.s->wfd))
753 err(1, "%s", cp->u.s->wfile);
757 if (cp->u.fd != -1 && close(cp->u.fd))
762 cfclose(cp->u.c, cp->next);