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 * 3. All advertising materials mentioning features or use of this software
18 * must display the following acknowledgement:
19 * This product includes software developed by the University of
20 * California, Berkeley and its contributors.
21 * 4. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD: src/usr.bin/sed/process.c,v 1.10.2.10 2003/06/13 07:32:08 fanf Exp $");
42 static const char sccsid[] = "@(#)process.c 8.6 (Berkeley) 4/20/94";
45 #include <sys/types.h>
47 #include <sys/ioctl.h>
64 static SPACE HS, PS, SS;
71 static __inline int applies(struct s_command *);
72 static void flush_appends(void);
73 static void lputs(char *);
74 static __inline 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(s) { fwrite(s, sizeof(u_char), psl, stdout); putchar('\n'); }
96 size_t len, oldpsl = 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)
133 (void)printf("%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, 0);
155 cspace(&PS, hs, hsl, 0);
158 cspace(&HS, ps, psl, REPLACE);
161 cspace(&HS, "\n", 1, 0);
162 cspace(&HS, ps, psl, 0);
165 (void)printf("%s", cp->t);
174 if (!mf_fgets(&PS, REPLACE))
180 cspace(&PS, "\n", 1, 0);
181 if (!mf_fgets(&PS, 0))
193 (p = memchr(ps, '\n', psl)) != NULL) {
207 if (appendx >= appendnum)
208 if ((appends = realloc(appends,
209 sizeof(struct s_appends) *
210 (appendnum *= 2))) == NULL)
212 appends[appendx].type = AP_FILE;
213 appends[appendx].s = cp->t;
214 appends[appendx].len = strlen(cp->t);
218 sdone |= substitute(cp);
230 if (cp->u.fd == -1 && (cp->u.fd = open(cp->t,
231 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
234 if (write(cp->u.fd, ps, psl) != psl ||
235 write(cp->u.fd, "\n", 1) != 1)
240 cspace(&HS, "", 0, REPLACE);
248 for (p = ps, len = psl; len--; ++p)
249 *p = cp->u.y[(unsigned char)*p];
255 (void)printf("%lu\n", linenum);
260 new: if (!nflag && !pd)
263 } /* for all lines */
267 * TRUE if the address passed matches the current program state
268 * (lastline, linenumber, ps).
271 (a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, psl) : \
272 (a)->type == AT_LINE ? linenum == (a)->u.l : lastline()
275 * Return TRUE if the command applies to the current line. Sets the inrange
276 * flag to process ranges. Interprets the non-select (``!'') flag.
280 struct s_command *cp;
285 if (cp->a1 == NULL && cp->a2 == NULL)
294 } else if (MATCH(cp->a1)) {
296 * If the second address is a number less than or
297 * equal to the line number first selected, only
298 * one line shall be selected.
301 if (cp->a2->type == AT_LINE &&
302 linenum >= cp->a2->u.l)
311 return (cp->nonsel ? ! r : r);
316 * Do substitutions in the pattern space. Currently, we build a
317 * copy of the new pattern space in the substitute space structure
318 * and then swap them.
322 struct s_command *cp;
326 regoff_t re_off, slen;
333 if (defpreg != NULL && cp->u.s->maxbref > defpreg->re_nsub) {
334 linenum = cp->u.s->linenum;
335 errx(1, "%lu: %s: \\%d not defined in the RE",
336 linenum, fname, cp->u.s->maxbref);
339 if (!regexec_e(re, s, 0, 0, psl))
342 SS.len = 0; /* Clean substitute space. */
350 if (lastempty || match[0].rm_so != match[0].rm_eo) {
351 /* Locate start of replaced string. */
352 re_off = match[0].rm_so;
353 /* Copy leading retained string. */
354 cspace(&SS, s, re_off, APPEND);
355 /* Add in regular expression. */
356 regsub(&SS, s, cp->u.s->new);
359 /* Move past this match. */
360 if (match[0].rm_so != match[0].rm_eo) {
362 slen -= match[0].rm_eo;
365 if (match[0].rm_so < slen)
366 cspace(&SS, s + match[0].rm_so, 1,
368 s += match[0].rm_so + 1;
369 slen -= match[0].rm_so + 1;
372 } while (slen >= 0 && regexec_e(re, s, REG_NOTBOL, 0, slen));
373 /* Copy trailing retained string. */
375 cspace(&SS, s, slen, APPEND);
377 default: /* Nth occurrence */
379 if (match[0].rm_eo == match[0].rm_so)
380 match[0].rm_eo = match[0].rm_so + 1;
382 slen -= match[0].rm_eo;
385 if (!regexec_e(re, s, REG_NOTBOL, 0, slen))
389 case 1: /* 1st occurrence */
390 /* Locate start of replaced string. */
391 re_off = match[0].rm_so + (s - ps);
392 /* Copy leading retained string. */
393 cspace(&SS, ps, re_off, APPEND);
394 /* Add in regular expression. */
395 regsub(&SS, s, cp->u.s->new);
396 /* Copy trailing retained string. */
398 slen -= match[0].rm_eo;
399 cspace(&SS, s, slen, APPEND);
404 * Swap the substitute space and the pattern space, and make sure
405 * that any leftover pointers into stdio memory get lost.
412 /* Handle the 'p' flag. */
416 /* Handle the 'w' flag. */
417 if (cp->u.s->wfile && !pd) {
418 if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile,
419 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1)
420 err(1, "%s", cp->u.s->wfile);
421 if (write(cp->u.s->wfd, ps, psl) != psl ||
422 write(cp->u.s->wfd, "\n", 1) != 1)
423 err(1, "%s", cp->u.s->wfile);
429 * Flush append requests. Always called before reading a line,
430 * therefore it also resets the substitution done (sdone) flag.
439 for (i = 0; i < appendx; i++)
440 switch (appends[i].type) {
442 fwrite(appends[i].s, sizeof(char), appends[i].len,
447 * Read files probably shouldn't be cached. Since
448 * it's not an error to read a non-existent file,
449 * it's possible that another program is interacting
450 * with the sed script through the filesystem. It
451 * would be truly bizarre, but possible. It's probably
452 * not that big a performance win, anyhow.
454 if ((f = fopen(appends[i].s, "r")) == NULL)
456 while ((count = fread(buf, sizeof(char), sizeof(buf), f)))
457 (void)fwrite(buf, sizeof(char), count, stdout);
462 errx(1, "stdout: %s", strerror(errno ? errno : EIO));
474 static int termwidth = -1;
476 if (termwidth == -1) {
477 if ((p = getenv("COLUMNS")) && *p != '\0')
479 else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
481 termwidth = win.ws_col;
486 for (count = 0; *s; ++s) {
487 if (count + 5 >= termwidth) {
488 (void)printf("\\\n");
491 if (isprint((unsigned char)*s) && *s != '\\') {
494 } else if (*s == '\n') {
499 escapes = "\\\a\b\f\r\t\v";
501 if ((p = strchr(escapes, *s))) {
502 (void)putchar("\\abfrtv"[p - escapes]);
505 (void)printf("%03o", *(u_char *)s);
513 errx(1, "stdout: %s", strerror(errno ? errno : EIO));
517 regexec_e(preg, string, eflags, nomatch, slen)
527 errx(1, "first RE may not be empty");
533 match[0].rm_eo = slen;
535 eval = regexec(defpreg, string,
536 nomatch ? 0 : maxnsub + 1, match, eflags | REG_STARTEND);
543 errx(1, "RE error: %s", strregerror(eval, defpreg));
548 * regsub - perform substitutions after a regexp match
549 * Based on a routine by Henry Spencer
552 regsub(sp, string, src)
559 #define NEEDSP(reqlen) \
560 if (sp->len >= sp->blen - (reqlen) - 1) { \
561 sp->blen += (reqlen) + 1024; \
562 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) \
565 dst = sp->space + sp->len; \
568 dst = sp->space + sp->len;
569 while ((c = *src++) != '\0') {
572 else if (c == '\\' && isdigit((unsigned char)*src))
576 if (no < 0) { /* Ordinary character. */
577 if (c == '\\' && (*src == '\\' || *src == '&'))
582 } else if (match[no].rm_so != -1 && match[no].rm_eo != -1) {
583 len = match[no].rm_eo - match[no].rm_so;
585 memmove(dst, string + match[no].rm_so, len);
596 * Append the source space to the destination space, allocating new
597 * space as necessary.
600 cspace(sp, p, len, spflag)
604 enum e_spflag spflag;
608 /* Make sure SPACE has enough memory and ramp up quickly. */
609 tlen = sp->len + len + 1;
610 if (tlen > sp->blen) {
611 sp->blen = tlen + 1024;
612 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) ==
617 if (spflag == REPLACE)
620 memmove(sp->space + sp->len, p, len);
622 sp->space[sp->len += len] = '\0';
626 * Close all cached opened files and report any errors
630 struct s_command *cp, *end;
633 for (; cp != end; cp = cp->next)
636 if (cp->u.s->wfd != -1 && close(cp->u.s->wfd))
637 err(1, "%s", cp->u.s->wfile);
641 if (cp->u.fd != -1 && close(cp->u.fd))
646 cfclose(cp->u.c, cp->next);