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,
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;
89 #define OUT() do {fwrite(ps, 1, psl, outfile); fputc('\n', outfile);} while (0)
101 for (linenum = 0; mf_fgets(&PS, REPLACE);) {
116 if (appendx >= appendnum)
117 if ((appends = realloc(appends,
118 sizeof(struct s_appends) *
119 (appendnum *= 2))) == NULL)
121 appends[appendx].type = AP_STRING;
122 appends[appendx].s = cp->t;
123 appends[appendx].len = strlen(cp->t);
132 if (cp->a2 == NULL || lastaddr || lastline())
133 (void)fprintf(outfile, "%s", cp->t);
142 (p = memchr(ps, '\n', psl)) == NULL) {
147 memmove(ps, p + 1, psl);
151 cspace(&PS, hs, hsl, REPLACE);
154 cspace(&PS, "\n", 1, APPEND);
155 cspace(&PS, hs, hsl, APPEND);
158 cspace(&HS, ps, psl, REPLACE);
161 cspace(&HS, "\n", 1, APPEND);
162 cspace(&HS, ps, psl, APPEND);
165 (void)fprintf(outfile, "%s", cp->t);
174 if (!mf_fgets(&PS, REPLACE))
180 cspace(&PS, "\n", 1, APPEND);
181 if (!mf_fgets(&PS, APPEND))
192 if ((p = memchr(ps, '\n', psl)) != NULL) {
206 if (appendx >= appendnum)
207 if ((appends = realloc(appends,
208 sizeof(struct s_appends) *
209 (appendnum *= 2))) == NULL)
211 appends[appendx].type = AP_FILE;
212 appends[appendx].s = cp->t;
213 appends[appendx].len = strlen(cp->t);
217 sdone |= substitute(cp);
229 if (cp->u.fd == -1 && (cp->u.fd = open(cp->t,
230 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
233 if (write(cp->u.fd, ps, psl) != (ssize_t)psl ||
234 write(cp->u.fd, "\n", 1) != 1)
239 * If the hold space is null, make it empty
240 * but not null. Otherwise the pattern space
241 * will become null after the swap, which is
242 * an abnormal condition.
245 cspace(&HS, "", 0, REPLACE);
259 (void)fprintf(outfile, "%lu\n", linenum);
264 new: if (!nflag && !pd)
267 } /* for all lines */
271 * TRUE if the address passed matches the current program state
272 * (lastline, linenumber, ps).
275 ((a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, 0, psl) : \
276 (a)->type == AT_LINE ? linenum == (a)->u.l : lastline())
279 * Return TRUE if the command applies to the current line. Sets the start
280 * line for process ranges. Interprets the non-select (``!'') flag.
283 applies(struct s_command *cp)
288 if (cp->a1 == NULL && cp->a2 == NULL)
291 if (cp->startline > 0) {
292 switch (cp->a2->type) {
294 if (linenum - cp->startline <= cp->a2->u.l)
306 } else if (cp->a2->type == AT_LINE &&
307 linenum > cp->a2->u.l) {
309 * We missed the 2nd address due to a
310 * branch, so just close the range and
318 } else if (cp->a1 && MATCH(cp->a1)) {
320 * If the second address is a number less than or
321 * equal to the line number first selected, only
322 * one line shall be selected.
324 * Likewise if the relative second line address is zero.
326 if ((cp->a2->type == AT_LINE &&
327 linenum >= cp->a2->u.l) ||
328 (cp->a2->type == AT_RELLINE && cp->a2->u.l == 0))
331 cp->startline = linenum;
338 return (cp->nonsel ? ! r : r);
342 * Reset the sed processor to its initial state.
347 struct s_command *cp;
350 * Reset all in-range markers.
352 for (cp = prog; cp; cp = cp->code == '{' ? cp->u.c : cp->next)
357 * Clear out the hold space.
359 cspace(&HS, "", 0, REPLACE);
364 * Do substitutions in the pattern space. Currently, we build a
365 * copy of the new pattern space in the substitute space structure
366 * and then swap them.
369 substitute(struct s_command *cp)
381 if (defpreg != NULL && cp->u.s->maxbref > defpreg->re_nsub) {
382 linenum = cp->u.s->linenum;
383 errx(1, "%lu: %s: \\%u not defined in the RE",
384 linenum, fname, cp->u.s->maxbref);
387 if (!regexec_e(re, ps, 0, 0, 0, psl))
390 SS.len = 0; /* Clean substitute space. */
396 /* Copy the leading retained string. */
397 if (n <= 1 && (match[0].rm_so > le))
398 cspace(&SS, s, match[0].rm_so - le, APPEND);
400 /* Skip zero-length matches right after other matches. */
401 if (lastempty || (match[0].rm_so - le) ||
402 match[0].rm_so != match[0].rm_eo) {
404 /* Want this match: append replacement. */
405 regsub(&SS, ps, cp->u.s->new);
409 /* Want a later match: append original. */
410 if (match[0].rm_eo - le)
411 cspace(&SS, s, match[0].rm_eo - le,
417 /* Move past this match. */
418 s = ps + match[0].rm_eo;
419 slen = psl - match[0].rm_eo;
423 * After a zero-length match, advance one byte,
424 * and at the end of the line, terminate.
426 if (match[0].rm_so == match[0].rm_eo) {
427 if (*s == '\0' || *s == '\n')
432 cspace(&SS, s++, 1, APPEND);
439 } while (n >= 0 && slen >= 0 &&
440 regexec_e(re, ps, REG_NOTBOL, 0, le, psl));
442 /* Did not find the requested number of matches. */
446 /* Copy the trailing retained string. */
448 cspace(&SS, s, slen, APPEND);
451 * Swap the substitute space and the pattern space, and make sure
452 * that any leftover pointers into stdio memory get lost.
459 /* Handle the 'p' flag. */
463 /* Handle the 'w' flag. */
464 if (cp->u.s->wfile && !pd) {
465 if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile,
466 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1)
467 err(1, "%s", cp->u.s->wfile);
468 if (write(cp->u.s->wfd, ps, psl) != (ssize_t)psl ||
469 write(cp->u.s->wfd, "\n", 1) != 1)
470 err(1, "%s", cp->u.s->wfile);
477 * Perform translation ('y' command) in the pattern space.
480 do_tr(struct s_tr *y)
487 if (MB_CUR_MAX == 1) {
489 * Single-byte encoding: perform in-place translation
490 * of the pattern space.
492 for (p = ps; p < &ps[psl]; p++)
493 *p = y->bytetab[(u_char)*p];
496 * Multi-byte encoding: perform translation into the
497 * translation space, then swap the translation and
500 /* Clean translation space. */
502 for (p = ps, left = psl; left > 0; p += clen, left -= clen) {
503 if ((c = y->bytetab[(u_char)*p]) != '\0') {
504 cspace(&YS, &c, 1, APPEND);
508 for (i = 0; i < y->nmultis; i++)
509 if (left >= y->multis[i].fromlen &&
510 memcmp(p, y->multis[i].from,
511 y->multis[i].fromlen) == 0)
513 if (i < y->nmultis) {
514 cspace(&YS, y->multis[i].to,
515 y->multis[i].tolen, APPEND);
516 clen = y->multis[i].fromlen;
518 cspace(&YS, p, 1, APPEND);
522 /* Swap the translation space and the pattern space. */
531 * Flush append requests. Always called before reading a line,
532 * therefore it also resets the substitution done (sdone) flag.
541 for (i = 0; i < appendx; i++)
542 switch (appends[i].type) {
544 fwrite(appends[i].s, sizeof(char), appends[i].len,
549 * Read files probably shouldn't be cached. Since
550 * it's not an error to read a non-existent file,
551 * it's possible that another program is interacting
552 * with the sed script through the filesystem. It
553 * would be truly bizarre, but possible. It's probably
554 * not that big a performance win, anyhow.
556 if ((f = fopen(appends[i].s, "r")) == NULL)
558 while ((count = fread(buf, sizeof(char), sizeof(buf), f)))
559 (void)fwrite(buf, sizeof(char), count, outfile);
564 errx(1, "%s: %s", outfname, strerror(errno ? errno : EIO));
569 lputs(char *s, size_t len)
571 static const char escapes[] = "\\\a\b\f\r\t\v";
575 static int termwidth = -1;
580 if (outfile != stdout)
582 if (termwidth == -1) {
583 if ((p = getenv("COLUMNS")) && *p != '\0')
585 else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
587 termwidth = win.ws_col;
594 memset(&mbs, 0, sizeof(mbs));
597 clen = mbrtowc(&wc, s, len, &mbs);
600 if (clen == (size_t)-1 || clen == (size_t)-2) {
601 wc = (unsigned char)*s;
603 memset(&mbs, 0, sizeof(mbs));
606 if (col + 1 >= termwidth)
607 fprintf(outfile, "\\\n");
609 fputc('\n', outfile);
611 } else if (iswprint(wc)) {
613 if (col + width >= termwidth) {
614 fprintf(outfile, "\\\n");
617 fwrite(s, 1, clen, outfile);
619 } else if (wc != L'\0' && (c = wctob(wc)) != EOF &&
620 (p = strchr(escapes, c)) != NULL) {
621 if (col + 2 >= termwidth) {
622 fprintf(outfile, "\\\n");
625 fprintf(outfile, "\\%c", "\\abfrtv"[p - escapes]);
628 if (col + 4 * clen >= (unsigned)termwidth) {
629 fprintf(outfile, "\\\n");
632 for (i = 0; i < clen; i++)
633 fprintf(outfile, "\\%03o",
634 (int)(unsigned char)s[i]);
640 if (col + 1 >= termwidth)
641 fprintf(outfile, "\\\n");
642 (void)fputc('$', outfile);
643 (void)fputc('\n', outfile);
645 errx(1, "%s: %s", outfname, strerror(errno ? errno : EIO));
649 regexec_e(regex_t *preg, const char *string, int eflags, int nomatch,
650 size_t start, size_t stop)
656 errx(1, "first RE may not be empty");
661 match[0].rm_so = start;
662 match[0].rm_eo = stop;
664 eval = regexec(defpreg, string,
665 nomatch ? 0 : maxnsub + 1, match, eflags | REG_STARTEND);
672 errx(1, "RE error: %s", strregerror(eval, defpreg));
677 * regsub - perform substitutions after a regexp match
678 * Based on a routine by Henry Spencer
681 regsub(SPACE *sp, char *string, char *src)
686 #define NEEDSP(reqlen) \
687 /* XXX What is the +1 for? */ \
688 if (sp->len + (reqlen) + 1 >= sp->blen) { \
689 sp->blen += (reqlen) + 1024; \
690 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) \
693 dst = sp->space + sp->len; \
696 dst = sp->space + sp->len;
697 while ((c = *src++) != '\0') {
700 else if (c == '\\' && isdigit((unsigned char)*src))
704 if (no < 0) { /* Ordinary character. */
705 if (c == '\\' && (*src == '\\' || *src == '&'))
710 } else if (match[no].rm_so != -1 && match[no].rm_eo != -1) {
711 len = match[no].rm_eo - match[no].rm_so;
713 memmove(dst, string + match[no].rm_so, len);
724 * Concatenate space: append the source space to the destination space,
725 * allocating new space as necessary.
728 cspace(SPACE *sp, const char *p, size_t len, enum e_spflag spflag)
732 /* Make sure SPACE has enough memory and ramp up quickly. */
733 tlen = sp->len + len + 1;
734 if (tlen > sp->blen) {
735 sp->blen = tlen + 1024;
736 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) ==
741 if (spflag == REPLACE)
744 memmove(sp->space + sp->len, p, len);
746 sp->space[sp->len += len] = '\0';
750 * Close all cached opened files and report any errors
753 cfclose(struct s_command *cp, struct s_command *end)
756 for (; cp != end; cp = cp->next)
759 if (cp->u.s->wfd != -1 && close(cp->u.s->wfd))
760 err(1, "%s", cp->u.s->wfile);
764 if (cp->u.fd != -1 && close(cp->u.fd))
769 cfclose(cp->u.c, cp->next);