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$");
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;
99 for (linenum = 0; mf_fgets(&PS, REPLACE);) {
114 if (appendx >= appendnum)
115 if ((appends = realloc(appends,
116 sizeof(struct s_appends) *
117 (appendnum *= 2))) == NULL)
119 appends[appendx].type = AP_STRING;
120 appends[appendx].s = cp->t;
121 appends[appendx].len = strlen(cp->t);
130 if (cp->a2 == NULL || lastaddr)
131 (void)printf("%s", cp->t);
140 (p = memchr(ps, '\n', psl - 1)) == NULL) {
145 memmove(ps, p + 1, psl);
149 cspace(&PS, hs, hsl, REPLACE);
152 cspace(&PS, "\n", 1, 0);
153 cspace(&PS, hs, hsl, 0);
156 cspace(&HS, ps, psl, REPLACE);
159 cspace(&HS, "\n", 1, 0);
160 cspace(&HS, ps, psl, 0);
163 (void)printf("%s", cp->t);
172 if (!mf_fgets(&PS, REPLACE))
178 cspace(&PS, "\n", 1, 0);
179 if (!mf_fgets(&PS, 0)) {
194 (p = memchr(ps, '\n', psl - 1)) != NULL) {
208 if (appendx >= appendnum)
209 if ((appends = realloc(appends,
210 sizeof(struct s_appends) *
211 (appendnum *= 2))) == NULL)
213 appends[appendx].type = AP_FILE;
214 appends[appendx].s = cp->t;
215 appends[appendx].len = strlen(cp->t);
219 sdone |= substitute(cp);
231 if (cp->u.fd == -1 && (cp->u.fd = open(cp->t,
232 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
235 if (write(cp->u.fd, ps, psl) != psl ||
236 write(cp->u.fd, "\n", 1) != 1)
247 for (p = ps, len = psl; len--; ++p)
248 *p = cp->u.y[(unsigned char)*p];
254 (void)printf("%lu\n", linenum);
259 new: if (!nflag && !pd)
262 } /* for all lines */
266 * TRUE if the address passed matches the current program state
267 * (lastline, linenumber, ps).
270 (a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, psl) : \
271 (a)->type == AT_LINE ? linenum == (a)->u.l : lastline
274 * Return TRUE if the command applies to the current line. Sets the inrange
275 * flag to process ranges. Interprets the non-select (``!'') flag.
279 struct s_command *cp;
284 if (cp->a1 == NULL && cp->a2 == NULL)
293 } else if (MATCH(cp->a1)) {
295 * If the second address is a number less than or
296 * equal to the line number first selected, only
297 * one line shall be selected.
300 if (cp->a2->type == AT_LINE &&
301 linenum >= cp->a2->u.l)
310 return (cp->nonsel ? ! r : r);
315 * Do substitutions in the pattern space. Currently, we build a
316 * copy of the new pattern space in the substitute space structure
317 * and then swap them.
321 struct s_command *cp;
332 if (defpreg != NULL && cp->u.s->maxbref > defpreg->re_nsub) {
333 linenum = cp->u.s->linenum;
334 errx(1, "%lu: %s: \\%d not defined in the RE",
335 linenum, fname, cp->u.s->maxbref);
338 if (!regexec_e(re, s, 0, 0, psl))
341 SS.len = 0; /* Clean substitute space. */
349 if (lastempty || match[0].rm_so != match[0].rm_eo) {
350 /* Locate start of replaced string. */
351 re_off = match[0].rm_so;
352 /* Copy leading retained string. */
353 cspace(&SS, s, re_off, APPEND);
354 /* Add in regular expression. */
355 regsub(&SS, s, cp->u.s->new);
358 /* Move past this match. */
359 if (match[0].rm_so != match[0].rm_eo) {
361 slen -= match[0].rm_eo;
363 } else if (match[0].rm_so == slen) {
367 if (match[0].rm_so == 0)
368 cspace(&SS, s, match[0].rm_so + 1,
371 cspace(&SS, s + match[0].rm_so, 1,
373 s += match[0].rm_so + 1;
374 slen -= match[0].rm_so + 1;
377 } while (slen > 0 && regexec_e(re, s, REG_NOTBOL, 0, slen));
378 /* Copy trailing retained string. */
380 cspace(&SS, s, slen, APPEND);
382 default: /* Nth occurrence */
385 slen -= match[0].rm_eo;
386 if (!regexec_e(re, s, REG_NOTBOL, 0, slen))
390 case 1: /* 1st occurrence */
391 /* Locate start of replaced string. */
392 re_off = match[0].rm_so + (s - ps);
393 /* Copy leading retained string. */
394 cspace(&SS, ps, re_off, APPEND);
395 /* Add in regular expression. */
396 regsub(&SS, s, cp->u.s->new);
397 /* Copy trailing retained string. */
399 slen -= match[0].rm_eo;
400 cspace(&SS, s, slen, APPEND);
405 * Swap the substitute space and the pattern space, and make sure
406 * that any leftover pointers into stdio memory get lost.
413 /* Handle the 'p' flag. */
417 /* Handle the 'w' flag. */
418 if (cp->u.s->wfile && !pd) {
419 if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile,
420 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1)
421 err(1, "%s", cp->u.s->wfile);
422 if (write(cp->u.s->wfd, ps, psl) != psl ||
423 write(cp->u.s->wfd, "\n", 1) != 1)
424 err(1, "%s", cp->u.s->wfile);
430 * Flush append requests. Always called before reading a line,
431 * therefore it also resets the substitution done (sdone) flag.
440 for (i = 0; i < appendx; i++)
441 switch (appends[i].type) {
443 fwrite(appends[i].s, sizeof(char), appends[i].len,
448 * Read files probably shouldn't be cached. Since
449 * it's not an error to read a non-existent file,
450 * it's possible that another program is interacting
451 * with the sed script through the filesystem. It
452 * would be truly bizarre, but possible. It's probably
453 * not that big a performance win, anyhow.
455 if ((f = fopen(appends[i].s, "r")) == NULL)
457 while ((count = fread(buf, sizeof(char), sizeof(buf), f)))
458 (void)fwrite(buf, sizeof(char), count, stdout);
463 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);