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;
66 #define psanl PS.append_newline
70 static inline int applies(struct s_command *);
71 static void do_tr(struct s_tr *);
72 static void flush_appends(void);
73 static void lputs(char *, size_t);
74 static int regexec_e(regex_t *, const char *, int, int, size_t,
76 static void regsub(SPACE *, char *, char *);
77 static int substitute(struct s_command *);
79 struct s_appends *appends; /* Array of pointers to strings to append. */
80 static int appendx; /* Index into appends array. */
81 int appendnum; /* Size of appends array. */
83 static int lastaddr; /* Set by applies if last address of a range. */
84 static int sdone; /* If any substitutes since last line input. */
85 /* Iov structure for 'w' commands. */
86 static regex_t *defpreg;
91 fwrite(ps, 1, psl, outfile); \
92 if (psanl) fputc('\n', outfile); \
105 oldpsanl = oldpsl = 0;
107 for (linenum = 0; mf_fgets(&PS, REPLACE);) {
122 if (appendx >= appendnum)
123 if ((appends = realloc(appends,
124 sizeof(struct s_appends) *
125 (appendnum *= 2))) == NULL)
127 appends[appendx].type = AP_STRING;
128 appends[appendx].s = cp->t;
129 appends[appendx].len = strlen(cp->t);
138 if (cp->a2 == NULL || lastaddr || lastline())
139 (void)fprintf(outfile, "%s", cp->t);
148 (p = memchr(ps, '\n', psl)) == NULL) {
153 memmove(ps, p + 1, psl);
157 cspace(&PS, hs, hsl, REPLACE);
160 cspace(&PS, "\n", 1, APPEND);
161 cspace(&PS, hs, hsl, APPEND);
164 cspace(&HS, ps, psl, REPLACE);
167 cspace(&HS, "\n", 1, APPEND);
168 cspace(&HS, ps, psl, APPEND);
171 (void)fprintf(outfile, "%s", cp->t);
180 if (!mf_fgets(&PS, REPLACE))
186 cspace(&PS, "\n", 1, APPEND);
187 if (!mf_fgets(&PS, APPEND))
198 if ((p = memchr(ps, '\n', psl)) != NULL) {
216 if (appendx >= appendnum)
217 if ((appends = realloc(appends,
218 sizeof(struct s_appends) *
219 (appendnum *= 2))) == NULL)
221 appends[appendx].type = AP_FILE;
222 appends[appendx].s = cp->t;
223 appends[appendx].len = strlen(cp->t);
227 sdone |= substitute(cp);
239 if (cp->u.fd == -1 && (cp->u.fd = open(cp->t,
240 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
243 if (write(cp->u.fd, ps, psl) != (ssize_t)psl ||
244 write(cp->u.fd, "\n", 1) != 1)
249 * If the hold space is null, make it empty
250 * but not null. Otherwise the pattern space
251 * will become null after the swap, which is
252 * an abnormal condition.
255 cspace(&HS, "", 0, REPLACE);
258 psanl = tspace.append_newline;
270 (void)fprintf(outfile, "%lu\n", linenum);
275 new: if (!nflag && !pd)
278 } /* for all lines */
282 * TRUE if the address passed matches the current program state
283 * (lastline, linenumber, ps).
286 ((a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, 0, psl) : \
287 (a)->type == AT_LINE ? linenum == (a)->u.l : lastline())
290 * Return TRUE if the command applies to the current line. Sets the start
291 * line for process ranges. Interprets the non-select (``!'') flag.
294 applies(struct s_command *cp)
299 if (cp->a1 == NULL && cp->a2 == NULL)
302 if (cp->startline > 0) {
303 switch (cp->a2->type) {
305 if (linenum - cp->startline <= cp->a2->u.l)
317 } else if (cp->a2->type == AT_LINE &&
318 linenum > cp->a2->u.l) {
320 * We missed the 2nd address due to a
321 * branch, so just close the range and
329 } else if (cp->a1 && MATCH(cp->a1)) {
331 * If the second address is a number less than or
332 * equal to the line number first selected, only
333 * one line shall be selected.
335 * Likewise if the relative second line address is zero.
337 if ((cp->a2->type == AT_LINE &&
338 linenum >= cp->a2->u.l) ||
339 (cp->a2->type == AT_RELLINE && cp->a2->u.l == 0))
342 cp->startline = linenum;
349 return (cp->nonsel ? ! r : r);
353 * Reset the sed processor to its initial state.
358 struct s_command *cp;
361 * Reset all in-range markers.
363 for (cp = prog; cp; cp = cp->code == '{' ? cp->u.c : cp->next)
368 * Clear out the hold space.
370 cspace(&HS, "", 0, REPLACE);
375 * Do substitutions in the pattern space. Currently, we build a
376 * copy of the new pattern space in the substitute space structure
377 * and then swap them.
380 substitute(struct s_command *cp)
392 if (defpreg != NULL && cp->u.s->maxbref > defpreg->re_nsub) {
393 linenum = cp->u.s->linenum;
394 errx(1, "%lu: %s: \\%u not defined in the RE",
395 linenum, fname, cp->u.s->maxbref);
398 if (!regexec_e(re, ps, 0, 0, 0, psl))
401 SS.len = 0; /* Clean substitute space. */
407 /* Copy the leading retained string. */
408 if (n <= 1 && (match[0].rm_so > le))
409 cspace(&SS, s, match[0].rm_so - le, APPEND);
411 /* Skip zero-length matches right after other matches. */
412 if (lastempty || (match[0].rm_so - le) ||
413 match[0].rm_so != match[0].rm_eo) {
415 /* Want this match: append replacement. */
416 regsub(&SS, ps, cp->u.s->new);
420 /* Want a later match: append original. */
421 if (match[0].rm_eo - le)
422 cspace(&SS, s, match[0].rm_eo - le,
428 /* Move past this match. */
429 s = ps + match[0].rm_eo;
430 slen = psl - match[0].rm_eo;
434 * After a zero-length match, advance one byte,
435 * and at the end of the line, terminate.
437 if (match[0].rm_so == match[0].rm_eo) {
438 if (*s == '\0' || *s == '\n')
443 cspace(&SS, s++, 1, APPEND);
450 } while (n >= 0 && slen >= 0 &&
451 regexec_e(re, ps, REG_NOTBOL, 0, le, psl));
453 /* Did not find the requested number of matches. */
457 /* Copy the trailing retained string. */
459 cspace(&SS, s, slen, APPEND);
462 * Swap the substitute space and the pattern space, and make sure
463 * that any leftover pointers into stdio memory get lost.
467 psanl = tspace.append_newline;
471 /* Handle the 'p' flag. */
475 /* Handle the 'w' flag. */
476 if (cp->u.s->wfile && !pd) {
477 if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile,
478 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1)
479 err(1, "%s", cp->u.s->wfile);
480 if (write(cp->u.s->wfd, ps, psl) != (ssize_t)psl ||
481 write(cp->u.s->wfd, "\n", 1) != 1)
482 err(1, "%s", cp->u.s->wfile);
489 * Perform translation ('y' command) in the pattern space.
492 do_tr(struct s_tr *y)
499 if (MB_CUR_MAX == 1) {
501 * Single-byte encoding: perform in-place translation
502 * of the pattern space.
504 for (p = ps; p < &ps[psl]; p++)
505 *p = y->bytetab[(u_char)*p];
508 * Multi-byte encoding: perform translation into the
509 * translation space, then swap the translation and
512 /* Clean translation space. */
514 for (p = ps, left = psl; left > 0; p += clen, left -= clen) {
515 if ((c = y->bytetab[(u_char)*p]) != '\0') {
516 cspace(&YS, &c, 1, APPEND);
520 for (i = 0; i < y->nmultis; i++)
521 if (left >= y->multis[i].fromlen &&
522 memcmp(p, y->multis[i].from,
523 y->multis[i].fromlen) == 0)
525 if (i < y->nmultis) {
526 cspace(&YS, y->multis[i].to,
527 y->multis[i].tolen, APPEND);
528 clen = y->multis[i].fromlen;
530 cspace(&YS, p, 1, APPEND);
534 /* Swap the translation space and the pattern space. */
537 psanl = tmp.append_newline;
544 * Flush append requests. Always called before reading a line,
545 * therefore it also resets the substitution done (sdone) flag.
554 for (i = 0; i < appendx; i++)
555 switch (appends[i].type) {
557 fwrite(appends[i].s, sizeof(char), appends[i].len,
562 * Read files probably shouldn't be cached. Since
563 * it's not an error to read a non-existent file,
564 * it's possible that another program is interacting
565 * with the sed script through the filesystem. It
566 * would be truly bizarre, but possible. It's probably
567 * not that big a performance win, anyhow.
569 if ((f = fopen(appends[i].s, "r")) == NULL)
571 while ((count = fread(buf, sizeof(char), sizeof(buf), f)))
572 (void)fwrite(buf, sizeof(char), count, outfile);
577 errx(1, "%s: %s", outfname, strerror(errno ? errno : EIO));
582 lputs(char *s, size_t len)
584 static const char escapes[] = "\\\a\b\f\r\t\v";
588 static int termwidth = -1;
593 if (outfile != stdout)
595 if (termwidth == -1) {
596 if ((p = getenv("COLUMNS")) && *p != '\0')
598 else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
600 termwidth = win.ws_col;
607 memset(&mbs, 0, sizeof(mbs));
610 clen = mbrtowc(&wc, s, len, &mbs);
613 if (clen == (size_t)-1 || clen == (size_t)-2) {
614 wc = (unsigned char)*s;
616 memset(&mbs, 0, sizeof(mbs));
619 if (col + 1 >= termwidth)
620 fprintf(outfile, "\\\n");
622 fputc('\n', outfile);
624 } else if (iswprint(wc)) {
626 if (col + width >= termwidth) {
627 fprintf(outfile, "\\\n");
630 fwrite(s, 1, clen, outfile);
632 } else if (wc != L'\0' && (c = wctob(wc)) != EOF &&
633 (p = strchr(escapes, c)) != NULL) {
634 if (col + 2 >= termwidth) {
635 fprintf(outfile, "\\\n");
638 fprintf(outfile, "\\%c", "\\abfrtv"[p - escapes]);
641 if (col + 4 * clen >= (unsigned)termwidth) {
642 fprintf(outfile, "\\\n");
645 for (i = 0; i < clen; i++)
646 fprintf(outfile, "\\%03o",
647 (int)(unsigned char)s[i]);
653 if (col + 1 >= termwidth)
654 fprintf(outfile, "\\\n");
655 (void)fputc('$', outfile);
656 (void)fputc('\n', outfile);
658 errx(1, "%s: %s", outfname, strerror(errno ? errno : EIO));
662 regexec_e(regex_t *preg, const char *string, int eflags, int nomatch,
663 size_t start, size_t stop)
669 errx(1, "first RE may not be empty");
674 match[0].rm_so = start;
675 match[0].rm_eo = stop;
677 eval = regexec(defpreg, string,
678 nomatch ? 0 : maxnsub + 1, match, eflags | REG_STARTEND);
685 errx(1, "RE error: %s", strregerror(eval, defpreg));
690 * regsub - perform substitutions after a regexp match
691 * Based on a routine by Henry Spencer
694 regsub(SPACE *sp, char *string, char *src)
699 #define NEEDSP(reqlen) \
700 /* XXX What is the +1 for? */ \
701 if (sp->len + (reqlen) + 1 >= sp->blen) { \
702 sp->blen += (reqlen) + 1024; \
703 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) \
706 dst = sp->space + sp->len; \
709 dst = sp->space + sp->len;
710 while ((c = *src++) != '\0') {
713 else if (c == '\\' && isdigit((unsigned char)*src))
717 if (no < 0) { /* Ordinary character. */
718 if (c == '\\' && (*src == '\\' || *src == '&'))
723 } else if (match[no].rm_so != -1 && match[no].rm_eo != -1) {
724 len = match[no].rm_eo - match[no].rm_so;
726 memmove(dst, string + match[no].rm_so, len);
737 * Concatenate space: append the source space to the destination space,
738 * allocating new space as necessary.
741 cspace(SPACE *sp, const char *p, size_t len, enum e_spflag spflag)
745 /* Make sure SPACE has enough memory and ramp up quickly. */
746 tlen = sp->len + len + 1;
747 if (tlen > sp->blen) {
748 sp->blen = tlen + 1024;
749 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) ==
754 if (spflag == REPLACE)
757 memmove(sp->space + sp->len, p, len);
759 sp->space[sp->len += len] = '\0';
763 * Close all cached opened files and report any errors
766 cfclose(struct s_command *cp, struct s_command *end)
769 for (; cp != end; cp = cp->next)
772 if (cp->u.s->wfd != -1 && close(cp->u.s->wfd))
773 err(1, "%s", cp->u.s->wfile);
777 if (cp->u.fd != -1 && close(cp->u.fd))
782 cfclose(cp->u.c, cp->next);