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
37 * @(#)process.c 8.6 (Berkeley) 4/20/94
38 * $FreeBSD: src/usr.bin/sed/process.c,v 1.10.2.10 2003/06/13 07:32:08 fanf Exp $
39 * $DragonFly: src/usr.bin/sed/process.c,v 1.2 2003/06/17 04:29:31 dillon Exp $
42 #include <sys/types.h>
44 #include <sys/ioctl.h>
61 static SPACE HS, PS, SS;
68 static __inline int applies(struct s_command *);
69 static void flush_appends(void);
70 static void lputs(char *);
71 static __inline int regexec_e(regex_t *, const char *, int, int, size_t);
72 static void regsub(SPACE *, char *, char *);
73 static int substitute(struct s_command *);
75 struct s_appends *appends; /* Array of pointers to strings to append. */
76 static int appendx; /* Index into appends array. */
77 int appendnum; /* Size of appends array. */
79 static int lastaddr; /* Set by applies if last address of a range. */
80 static int sdone; /* If any substitutes since last line input. */
81 /* Iov structure for 'w' commands. */
82 static regex_t *defpreg;
86 #define OUT(s) { fwrite(s, sizeof(u_char), psl, stdout); putchar('\n'); }
93 size_t len, oldpsl = 0;
98 for (linenum = 0; mf_fgets(&PS, REPLACE);) {
113 if (appendx >= appendnum)
114 if ((appends = realloc(appends,
115 sizeof(struct s_appends) *
116 (appendnum *= 2))) == NULL)
118 appends[appendx].type = AP_STRING;
119 appends[appendx].s = cp->t;
120 appends[appendx].len = strlen(cp->t);
129 if (cp->a2 == NULL || lastaddr)
130 (void)printf("%s", cp->t);
139 (p = memchr(ps, '\n', psl)) == NULL) {
144 memmove(ps, p + 1, psl);
148 cspace(&PS, hs, hsl, REPLACE);
151 cspace(&PS, "\n", 1, 0);
152 cspace(&PS, hs, hsl, 0);
155 cspace(&HS, ps, psl, REPLACE);
158 cspace(&HS, "\n", 1, 0);
159 cspace(&HS, ps, psl, 0);
162 (void)printf("%s", cp->t);
171 if (!mf_fgets(&PS, REPLACE))
177 cspace(&PS, "\n", 1, 0);
178 if (!mf_fgets(&PS, 0))
190 (p = memchr(ps, '\n', psl)) != NULL) {
204 if (appendx >= appendnum)
205 if ((appends = realloc(appends,
206 sizeof(struct s_appends) *
207 (appendnum *= 2))) == NULL)
209 appends[appendx].type = AP_FILE;
210 appends[appendx].s = cp->t;
211 appends[appendx].len = strlen(cp->t);
215 sdone |= substitute(cp);
227 if (cp->u.fd == -1 && (cp->u.fd = open(cp->t,
228 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
231 if (write(cp->u.fd, ps, psl) != psl ||
232 write(cp->u.fd, "\n", 1) != 1)
237 cspace(&HS, "", 0, REPLACE);
245 for (p = ps, len = psl; len--; ++p)
246 *p = cp->u.y[(unsigned char)*p];
252 (void)printf("%lu\n", linenum);
257 new: if (!nflag && !pd)
260 } /* for all lines */
264 * TRUE if the address passed matches the current program state
265 * (lastline, linenumber, ps).
268 (a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, psl) : \
269 (a)->type == AT_LINE ? linenum == (a)->u.l : lastline()
272 * Return TRUE if the command applies to the current line. Sets the inrange
273 * flag to process ranges. Interprets the non-select (``!'') flag.
277 struct s_command *cp;
282 if (cp->a1 == NULL && cp->a2 == NULL)
291 } else if (MATCH(cp->a1)) {
293 * If the second address is a number less than or
294 * equal to the line number first selected, only
295 * one line shall be selected.
298 if (cp->a2->type == AT_LINE &&
299 linenum >= cp->a2->u.l)
308 return (cp->nonsel ? ! r : r);
313 * Do substitutions in the pattern space. Currently, we build a
314 * copy of the new pattern space in the substitute space structure
315 * and then swap them.
319 struct s_command *cp;
323 regoff_t re_off, slen;
330 if (defpreg != NULL && cp->u.s->maxbref > defpreg->re_nsub) {
331 linenum = cp->u.s->linenum;
332 errx(1, "%lu: %s: \\%d not defined in the RE",
333 linenum, fname, cp->u.s->maxbref);
336 if (!regexec_e(re, s, 0, 0, psl))
339 SS.len = 0; /* Clean substitute space. */
347 if (lastempty || match[0].rm_so != match[0].rm_eo) {
348 /* Locate start of replaced string. */
349 re_off = match[0].rm_so;
350 /* Copy leading retained string. */
351 cspace(&SS, s, re_off, APPEND);
352 /* Add in regular expression. */
353 regsub(&SS, s, cp->u.s->new);
356 /* Move past this match. */
357 if (match[0].rm_so != match[0].rm_eo) {
359 slen -= match[0].rm_eo;
362 if (match[0].rm_so < slen)
363 cspace(&SS, s + match[0].rm_so, 1,
365 s += match[0].rm_so + 1;
366 slen -= match[0].rm_so + 1;
369 } while (slen >= 0 && regexec_e(re, s, REG_NOTBOL, 0, slen));
370 /* Copy trailing retained string. */
372 cspace(&SS, s, slen, APPEND);
374 default: /* Nth occurrence */
376 if (match[0].rm_eo == match[0].rm_so)
377 match[0].rm_eo = match[0].rm_so + 1;
379 slen -= match[0].rm_eo;
382 if (!regexec_e(re, s, REG_NOTBOL, 0, slen))
386 case 1: /* 1st occurrence */
387 /* Locate start of replaced string. */
388 re_off = match[0].rm_so + (s - ps);
389 /* Copy leading retained string. */
390 cspace(&SS, ps, re_off, APPEND);
391 /* Add in regular expression. */
392 regsub(&SS, s, cp->u.s->new);
393 /* Copy trailing retained string. */
395 slen -= match[0].rm_eo;
396 cspace(&SS, s, slen, APPEND);
401 * Swap the substitute space and the pattern space, and make sure
402 * that any leftover pointers into stdio memory get lost.
409 /* Handle the 'p' flag. */
413 /* Handle the 'w' flag. */
414 if (cp->u.s->wfile && !pd) {
415 if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile,
416 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1)
417 err(1, "%s", cp->u.s->wfile);
418 if (write(cp->u.s->wfd, ps, psl) != psl ||
419 write(cp->u.s->wfd, "\n", 1) != 1)
420 err(1, "%s", cp->u.s->wfile);
426 * Flush append requests. Always called before reading a line,
427 * therefore it also resets the substitution done (sdone) flag.
436 for (i = 0; i < appendx; i++)
437 switch (appends[i].type) {
439 fwrite(appends[i].s, sizeof(char), appends[i].len,
444 * Read files probably shouldn't be cached. Since
445 * it's not an error to read a non-existent file,
446 * it's possible that another program is interacting
447 * with the sed script through the filesystem. It
448 * would be truly bizarre, but possible. It's probably
449 * not that big a performance win, anyhow.
451 if ((f = fopen(appends[i].s, "r")) == NULL)
453 while ((count = fread(buf, sizeof(char), sizeof(buf), f)))
454 (void)fwrite(buf, sizeof(char), count, stdout);
459 errx(1, "stdout: %s", strerror(errno ? errno : EIO));
471 static int termwidth = -1;
473 if (termwidth == -1) {
474 if ((p = getenv("COLUMNS")) && *p != '\0')
476 else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
478 termwidth = win.ws_col;
483 for (count = 0; *s; ++s) {
484 if (count + 5 >= termwidth) {
485 (void)printf("\\\n");
488 if (isprint((unsigned char)*s) && *s != '\\') {
491 } else if (*s == '\n') {
496 escapes = "\\\a\b\f\r\t\v";
498 if ((p = strchr(escapes, *s))) {
499 (void)putchar("\\abfrtv"[p - escapes]);
502 (void)printf("%03o", *(u_char *)s);
510 errx(1, "stdout: %s", strerror(errno ? errno : EIO));
514 regexec_e(preg, string, eflags, nomatch, slen)
524 errx(1, "first RE may not be empty");
530 match[0].rm_eo = slen;
532 eval = regexec(defpreg, string,
533 nomatch ? 0 : maxnsub + 1, match, eflags | REG_STARTEND);
540 errx(1, "RE error: %s", strregerror(eval, defpreg));
545 * regsub - perform substitutions after a regexp match
546 * Based on a routine by Henry Spencer
549 regsub(sp, string, src)
556 #define NEEDSP(reqlen) \
557 if (sp->len >= sp->blen - (reqlen) - 1) { \
558 sp->blen += (reqlen) + 1024; \
559 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) \
562 dst = sp->space + sp->len; \
565 dst = sp->space + sp->len;
566 while ((c = *src++) != '\0') {
569 else if (c == '\\' && isdigit((unsigned char)*src))
573 if (no < 0) { /* Ordinary character. */
574 if (c == '\\' && (*src == '\\' || *src == '&'))
579 } else if (match[no].rm_so != -1 && match[no].rm_eo != -1) {
580 len = match[no].rm_eo - match[no].rm_so;
582 memmove(dst, string + match[no].rm_so, len);
593 * Append the source space to the destination space, allocating new
594 * space as necessary.
597 cspace(sp, p, len, spflag)
601 enum e_spflag spflag;
605 /* Make sure SPACE has enough memory and ramp up quickly. */
606 tlen = sp->len + len + 1;
607 if (tlen > sp->blen) {
608 sp->blen = tlen + 1024;
609 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) ==
614 if (spflag == REPLACE)
617 memmove(sp->space + sp->len, p, len);
619 sp->space[sp->len += len] = '\0';
623 * Close all cached opened files and report any errors
627 struct s_command *cp, *end;
630 for (; cp != end; cp = cp->next)
633 if (cp->u.s->wfd != -1 && close(cp->u.s->wfd))
634 err(1, "%s", cp->u.s->wfile);
638 if (cp->u.fd != -1 && close(cp->u.fd))
643 cfclose(cp->u.c, cp->next);