Home | History | Annotate | Line # | Download | only in sed
process.c revision 1.37
      1  1.37   gdamore /*	$NetBSD: process.c,v 1.37 2006/06/18 05:16:41 gdamore Exp $	*/
      2  1.18       tls 
      3   1.1       alm /*-
      4  1.19       mrg  * Copyright (c) 1992, 1993, 1994
      5   1.8       cgd  *	The Regents of the University of California.  All rights reserved.
      6   1.1       alm  *
      7   1.1       alm  * This code is derived from software contributed to Berkeley by
      8   1.1       alm  * Diomidis Spinellis of Imperial College, University of London.
      9   1.1       alm  *
     10   1.1       alm  * Redistribution and use in source and binary forms, with or without
     11   1.1       alm  * modification, are permitted provided that the following conditions
     12   1.1       alm  * are met:
     13   1.1       alm  * 1. Redistributions of source code must retain the above copyright
     14   1.1       alm  *    notice, this list of conditions and the following disclaimer.
     15   1.1       alm  * 2. Redistributions in binary form must reproduce the above copyright
     16   1.1       alm  *    notice, this list of conditions and the following disclaimer in the
     17   1.1       alm  *    documentation and/or other materials provided with the distribution.
     18  1.33       agc  * 3. Neither the name of the University nor the names of its contributors
     19  1.33       agc  *    may be used to endorse or promote products derived from this software
     20  1.33       agc  *    without specific prior written permission.
     21  1.33       agc  *
     22  1.33       agc  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  1.33       agc  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  1.33       agc  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  1.33       agc  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  1.33       agc  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  1.33       agc  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  1.33       agc  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  1.33       agc  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  1.33       agc  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  1.33       agc  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  1.33       agc  * SUCH DAMAGE.
     33  1.33       agc  */
     34  1.33       agc 
     35  1.33       agc /*-
     36  1.33       agc  * Copyright (c) 1992 Diomidis Spinellis.
     37  1.33       agc  *
     38  1.33       agc  * This code is derived from software contributed to Berkeley by
     39  1.33       agc  * Diomidis Spinellis of Imperial College, University of London.
     40  1.33       agc  *
     41  1.33       agc  * Redistribution and use in source and binary forms, with or without
     42  1.33       agc  * modification, are permitted provided that the following conditions
     43  1.33       agc  * are met:
     44  1.33       agc  * 1. Redistributions of source code must retain the above copyright
     45  1.33       agc  *    notice, this list of conditions and the following disclaimer.
     46  1.33       agc  * 2. Redistributions in binary form must reproduce the above copyright
     47  1.33       agc  *    notice, this list of conditions and the following disclaimer in the
     48  1.33       agc  *    documentation and/or other materials provided with the distribution.
     49   1.1       alm  * 3. All advertising materials mentioning features or use of this software
     50   1.1       alm  *    must display the following acknowledgement:
     51   1.1       alm  *	This product includes software developed by the University of
     52   1.1       alm  *	California, Berkeley and its contributors.
     53   1.1       alm  * 4. Neither the name of the University nor the names of its contributors
     54   1.1       alm  *    may be used to endorse or promote products derived from this software
     55   1.1       alm  *    without specific prior written permission.
     56   1.1       alm  *
     57   1.1       alm  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     58   1.1       alm  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     59   1.1       alm  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     60   1.1       alm  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     61   1.1       alm  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     62   1.1       alm  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     63   1.1       alm  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     64   1.1       alm  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     65   1.1       alm  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     66   1.1       alm  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     67   1.1       alm  * SUCH DAMAGE.
     68   1.1       alm  */
     69   1.1       alm 
     70  1.37   gdamore #if HAVE_NBTOOL_CONFIG_H
     71  1.37   gdamore #include "nbtool_config.h"
     72  1.37   gdamore #endif
     73  1.37   gdamore 
     74  1.20     lukem #include <sys/cdefs.h>
     75   1.1       alm #ifndef lint
     76  1.19       mrg #if 0
     77  1.19       mrg static char sccsid[] = "@(#)process.c	8.6 (Berkeley) 4/20/94";
     78  1.19       mrg #else
     79  1.37   gdamore __RCSID("$NetBSD: process.c,v 1.37 2006/06/18 05:16:41 gdamore Exp $");
     80  1.19       mrg #endif
     81   1.1       alm #endif /* not lint */
     82   1.1       alm 
     83   1.1       alm #include <sys/types.h>
     84   1.1       alm #include <sys/stat.h>
     85   1.1       alm #include <sys/ioctl.h>
     86   1.1       alm #include <sys/uio.h>
     87   1.1       alm 
     88   1.1       alm #include <ctype.h>
     89   1.1       alm #include <errno.h>
     90   1.1       alm #include <fcntl.h>
     91   1.1       alm #include <limits.h>
     92   1.1       alm #include <regex.h>
     93   1.1       alm #include <stdio.h>
     94   1.1       alm #include <stdlib.h>
     95   1.1       alm #include <string.h>
     96   1.1       alm #include <unistd.h>
     97   1.1       alm 
     98   1.1       alm #include "defs.h"
     99   1.1       alm #include "extern.h"
    100   1.1       alm 
    101   1.8       cgd static SPACE HS, PS, SS;
    102   1.1       alm #define	pd		PS.deleted
    103   1.1       alm #define	ps		PS.space
    104   1.1       alm #define	psl		PS.len
    105   1.1       alm #define	hs		HS.space
    106   1.1       alm #define	hsl		HS.len
    107   1.1       alm 
    108  1.32       wiz static inline int	 applies(struct s_command *);
    109  1.32       wiz static void		 flush_appends(void);
    110  1.32       wiz static void		 lputs(char *);
    111  1.32       wiz static inline int	 regexec_e(regex_t *, const char *, int, int, size_t);
    112  1.32       wiz static void		 regsub(SPACE *, char *, char *);
    113  1.32       wiz static int		 substitute(struct s_command *);
    114   1.1       alm 
    115   1.1       alm struct s_appends *appends;	/* Array of pointers to strings to append. */
    116   1.1       alm static int appendx;		/* Index into appends array. */
    117   1.1       alm int appendnum;			/* Size of appends array. */
    118   1.1       alm 
    119   1.1       alm static int lastaddr;		/* Set by applies if last address of a range. */
    120   1.1       alm static int sdone;		/* If any substitutes since last line input. */
    121   1.1       alm 				/* Iov structure for 'w' commands. */
    122   1.1       alm static regex_t *defpreg;
    123   1.1       alm size_t maxnsub;
    124   1.1       alm regmatch_t *match;
    125   1.1       alm 
    126   1.8       cgd #define OUT(s) { fwrite(s, sizeof(u_char), psl, stdout); }
    127   1.8       cgd 
    128   1.1       alm void
    129  1.32       wiz process(void)
    130   1.1       alm {
    131   1.1       alm 	struct s_command *cp;
    132   1.1       alm 	SPACE tspace;
    133  1.15   mycroft 	size_t len, oldpsl;
    134  1.15   mycroft 	char *p;
    135   1.1       alm 
    136  1.20     lukem 	oldpsl = 0;
    137   1.1       alm 	for (linenum = 0; mf_fgets(&PS, REPLACE);) {
    138   1.1       alm 		pd = 0;
    139  1.16   mycroft top:
    140   1.1       alm 		cp = prog;
    141   1.1       alm redirect:
    142   1.1       alm 		while (cp != NULL) {
    143   1.1       alm 			if (!applies(cp)) {
    144   1.1       alm 				cp = cp->next;
    145   1.1       alm 				continue;
    146   1.1       alm 			}
    147   1.1       alm 			switch (cp->code) {
    148   1.1       alm 			case '{':
    149   1.1       alm 				cp = cp->u.c;
    150   1.1       alm 				goto redirect;
    151   1.1       alm 			case 'a':
    152  1.35    itojun 				if (appendx >= appendnum) {
    153   1.1       alm 					appends = xrealloc(appends,
    154   1.1       alm 					    sizeof(struct s_appends) *
    155  1.35    itojun 					    (appendnum * 2));
    156  1.35    itojun 					appendnum *= 2;
    157  1.35    itojun 				}
    158   1.1       alm 				appends[appendx].type = AP_STRING;
    159   1.1       alm 				appends[appendx].s = cp->t;
    160   1.8       cgd 				appends[appendx].len = strlen(cp->t);
    161   1.1       alm 				appendx++;
    162   1.1       alm 				break;
    163   1.1       alm 			case 'b':
    164   1.1       alm 				cp = cp->u.c;
    165   1.1       alm 				goto redirect;
    166   1.1       alm 			case 'c':
    167   1.1       alm 				pd = 1;
    168   1.1       alm 				psl = 0;
    169   1.1       alm 				if (cp->a2 == NULL || lastaddr)
    170   1.1       alm 					(void)printf("%s", cp->t);
    171   1.1       alm 				break;
    172   1.1       alm 			case 'd':
    173   1.1       alm 				pd = 1;
    174   1.1       alm 				goto new;
    175   1.1       alm 			case 'D':
    176  1.30    atatat 				if (psl == 0)
    177  1.30    atatat 					pd = 1;
    178   1.1       alm 				if (pd)
    179   1.1       alm 					goto new;
    180  1.16   mycroft 				if ((p = memchr(ps, '\n', psl - 1)) == NULL) {
    181   1.1       alm 					pd = 1;
    182  1.16   mycroft 					goto new;
    183  1.28    atatat 				} else {
    184  1.13   mycroft 					psl -= (p + 1) - ps;
    185   1.1       alm 					memmove(ps, p + 1, psl);
    186  1.28    atatat 					goto top;
    187   1.1       alm 				}
    188   1.1       alm 			case 'g':
    189   1.1       alm 				cspace(&PS, hs, hsl, REPLACE);
    190   1.1       alm 				break;
    191   1.1       alm 			case 'G':
    192  1.25       kim 				if (hs == NULL)
    193  1.25       kim 					cspace(&HS, "\n", 1, REPLACE);
    194   1.8       cgd 				cspace(&PS, hs, hsl, 0);
    195   1.1       alm 				break;
    196   1.1       alm 			case 'h':
    197   1.1       alm 				cspace(&HS, ps, psl, REPLACE);
    198   1.1       alm 				break;
    199   1.1       alm 			case 'H':
    200   1.8       cgd 				cspace(&HS, ps, psl, 0);
    201   1.1       alm 				break;
    202   1.1       alm 			case 'i':
    203   1.1       alm 				(void)printf("%s", cp->t);
    204   1.1       alm 				break;
    205   1.1       alm 			case 'l':
    206   1.1       alm 				lputs(ps);
    207   1.1       alm 				break;
    208   1.1       alm 			case 'n':
    209   1.1       alm 				if (!nflag && !pd)
    210   1.8       cgd 					OUT(ps)
    211   1.1       alm 				flush_appends();
    212  1.14   mycroft 				if (!mf_fgets(&PS, REPLACE))
    213   1.1       alm 					exit(0);
    214   1.1       alm 				pd = 0;
    215   1.1       alm 				break;
    216   1.1       alm 			case 'N':
    217   1.1       alm 				flush_appends();
    218   1.8       cgd 				if (!mf_fgets(&PS, 0)) {
    219   1.1       alm 					if (!nflag && !pd)
    220   1.8       cgd 						OUT(ps)
    221   1.1       alm 					exit(0);
    222   1.1       alm 				}
    223   1.1       alm 				break;
    224   1.1       alm 			case 'p':
    225   1.1       alm 				if (pd)
    226   1.1       alm 					break;
    227   1.8       cgd 				OUT(ps)
    228   1.1       alm 				break;
    229   1.1       alm 			case 'P':
    230   1.1       alm 				if (pd)
    231   1.1       alm 					break;
    232  1.15   mycroft 				if ((p = memchr(ps, '\n', psl - 1)) != NULL) {
    233  1.15   mycroft 					oldpsl = psl;
    234  1.15   mycroft 					psl = (p + 1) - ps;
    235   1.1       alm 				}
    236   1.8       cgd 				OUT(ps)
    237   1.1       alm 				if (p != NULL)
    238  1.15   mycroft 					psl = oldpsl;
    239   1.1       alm 				break;
    240   1.1       alm 			case 'q':
    241   1.1       alm 				if (!nflag && !pd)
    242   1.8       cgd 					OUT(ps)
    243   1.1       alm 				flush_appends();
    244   1.1       alm 				exit(0);
    245   1.1       alm 			case 'r':
    246  1.35    itojun 				if (appendx >= appendnum) {
    247   1.1       alm 					appends = xrealloc(appends,
    248   1.1       alm 					    sizeof(struct s_appends) *
    249  1.35    itojun 					    (appendnum * 2));
    250  1.35    itojun 					appendnum *= 2;
    251  1.35    itojun 				}
    252   1.1       alm 				appends[appendx].type = AP_FILE;
    253   1.1       alm 				appends[appendx].s = cp->t;
    254   1.8       cgd 				appends[appendx].len = strlen(cp->t);
    255   1.1       alm 				appendx++;
    256   1.1       alm 				break;
    257   1.1       alm 			case 's':
    258   1.1       alm 				sdone |= substitute(cp);
    259   1.1       alm 				break;
    260   1.1       alm 			case 't':
    261   1.1       alm 				if (sdone) {
    262   1.1       alm 					sdone = 0;
    263   1.1       alm 					cp = cp->u.c;
    264   1.1       alm 					goto redirect;
    265   1.1       alm 				}
    266   1.1       alm 				break;
    267   1.1       alm 			case 'w':
    268   1.1       alm 				if (pd)
    269   1.1       alm 					break;
    270   1.1       alm 				if (cp->u.fd == -1 && (cp->u.fd = open(cp->t,
    271   1.1       alm 				    O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
    272   1.1       alm 				    DEFFILEMODE)) == -1)
    273  1.31    itojun 					err(FATAL, "%s: %s",
    274   1.1       alm 					    cp->t, strerror(errno));
    275   1.8       cgd 				if (write(cp->u.fd, ps, psl) != psl)
    276  1.31    itojun 					err(FATAL, "%s: %s",
    277   1.1       alm 					    cp->t, strerror(errno));
    278   1.1       alm 				break;
    279   1.1       alm 			case 'x':
    280   1.8       cgd 				if (hs == NULL)
    281  1.17       cgd 					cspace(&HS, "\n", 1, REPLACE);
    282   1.1       alm 				tspace = PS;
    283   1.1       alm 				PS = HS;
    284   1.1       alm 				HS = tspace;
    285   1.1       alm 				break;
    286   1.1       alm 			case 'y':
    287   1.1       alm 				if (pd)
    288   1.1       alm 					break;
    289   1.8       cgd 				for (p = ps, len = psl; --len; ++p)
    290  1.22       mrg 					*p = cp->u.y[(int)*p];
    291   1.1       alm 				break;
    292   1.1       alm 			case ':':
    293   1.1       alm 			case '}':
    294   1.1       alm 				break;
    295   1.1       alm 			case '=':
    296   1.1       alm 				(void)printf("%lu\n", linenum);
    297   1.1       alm 			}
    298   1.1       alm 			cp = cp->next;
    299   1.1       alm 		} /* for all cp */
    300   1.1       alm 
    301   1.1       alm new:		if (!nflag && !pd)
    302   1.8       cgd 			OUT(ps)
    303   1.1       alm 		flush_appends();
    304   1.1       alm 	} /* for all lines */
    305   1.1       alm }
    306   1.1       alm 
    307   1.1       alm /*
    308   1.1       alm  * TRUE if the address passed matches the current program state
    309   1.1       alm  * (lastline, linenumber, ps).
    310   1.1       alm  */
    311   1.8       cgd #define	MATCH(a)						\
    312   1.8       cgd 	(a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, psl) :	\
    313   1.1       alm 	    (a)->type == AT_LINE ? linenum == (a)->u.l : lastline
    314   1.1       alm 
    315   1.1       alm /*
    316   1.1       alm  * Return TRUE if the command applies to the current line.  Sets the inrange
    317   1.1       alm  * flag to process ranges.  Interprets the non-select (``!'') flag.
    318   1.1       alm  */
    319   1.1       alm static inline int
    320  1.32       wiz applies(struct s_command *cp)
    321   1.1       alm {
    322   1.1       alm 	int r;
    323   1.1       alm 
    324   1.1       alm 	lastaddr = 0;
    325   1.1       alm 	if (cp->a1 == NULL && cp->a2 == NULL)
    326   1.1       alm 		r = 1;
    327  1.24  christos 	else if (cp->a2) {
    328   1.1       alm 		if (cp->inrange) {
    329   1.1       alm 			if (MATCH(cp->a2)) {
    330   1.1       alm 				cp->inrange = 0;
    331   1.1       alm 				lastaddr = 1;
    332   1.1       alm 			}
    333   1.1       alm 			r = 1;
    334  1.36  christos 		} else if (cp->a1 && MATCH(cp->a1)) {
    335   1.1       alm 			/*
    336   1.1       alm 			 * If the second address is a number less than or
    337   1.1       alm 			 * equal to the line number first selected, only
    338   1.1       alm 			 * one line shall be selected.
    339   1.1       alm 			 *	-- POSIX 1003.2
    340   1.1       alm 			 */
    341   1.1       alm 			if (cp->a2->type == AT_LINE &&
    342   1.1       alm 			    linenum >= cp->a2->u.l)
    343   1.1       alm 				lastaddr = 1;
    344   1.1       alm 			else
    345   1.1       alm 				cp->inrange = 1;
    346   1.1       alm 			r = 1;
    347   1.1       alm 		} else
    348   1.1       alm 			r = 0;
    349  1.24  christos 	} else
    350   1.1       alm 		r = MATCH(cp->a1);
    351   1.1       alm 	return (cp->nonsel ? ! r : r);
    352   1.1       alm }
    353   1.1       alm 
    354   1.1       alm /*
    355   1.1       alm  * substitute --
    356   1.1       alm  *	Do substitutions in the pattern space.  Currently, we build a
    357   1.1       alm  *	copy of the new pattern space in the substitute space structure
    358   1.1       alm  *	and then swap them.
    359   1.1       alm  */
    360   1.1       alm static int
    361  1.32       wiz substitute(struct s_command *cp)
    362   1.1       alm {
    363   1.1       alm 	SPACE tspace;
    364   1.1       alm 	regex_t *re;
    365   1.8       cgd 	size_t re_off, slen;
    366  1.19       mrg 	int lastempty, n;
    367   1.1       alm 	char *s;
    368   1.1       alm 
    369   1.1       alm 	s = ps;
    370   1.1       alm 	re = cp->u.s->re;
    371   1.1       alm 	if (re == NULL) {
    372   1.1       alm 		if (defpreg != NULL && cp->u.s->maxbref > defpreg->re_nsub) {
    373   1.1       alm 			linenum = cp->u.s->linenum;
    374   1.1       alm 			err(COMPILE, "\\%d not defined in the RE",
    375   1.1       alm 			    cp->u.s->maxbref);
    376   1.1       alm 		}
    377   1.1       alm 	}
    378   1.8       cgd 	if (!regexec_e(re, s, 0, 0, psl))
    379   1.1       alm 		return (0);
    380   1.1       alm 
    381   1.1       alm 	SS.len = 0;				/* Clean substitute space. */
    382   1.8       cgd 	slen = psl;
    383   1.1       alm 	n = cp->u.s->n;
    384  1.12       cgd 	lastempty = 1;
    385  1.12       cgd 
    386   1.1       alm 	switch (n) {
    387   1.1       alm 	case 0:					/* Global */
    388   1.1       alm 		do {
    389  1.12       cgd 			if (lastempty || match[0].rm_so != match[0].rm_eo) {
    390  1.12       cgd 				/* Locate start of replaced string. */
    391  1.12       cgd 				re_off = match[0].rm_so;
    392  1.12       cgd 				/* Copy leading retained string. */
    393  1.12       cgd 				cspace(&SS, s, re_off, APPEND);
    394  1.12       cgd 				/* Add in regular expression. */
    395  1.12       cgd 				regsub(&SS, s, cp->u.s->new);
    396  1.12       cgd 			}
    397  1.12       cgd 
    398   1.1       alm 			/* Move past this match. */
    399  1.12       cgd 			if (match[0].rm_so != match[0].rm_eo) {
    400  1.12       cgd 				s += match[0].rm_eo;
    401  1.12       cgd 				slen -= match[0].rm_eo;
    402  1.12       cgd 				lastempty = 0;
    403  1.12       cgd 			} else {
    404  1.12       cgd 				if (match[0].rm_so == 0)
    405  1.19       mrg 					cspace(&SS,
    406  1.19       mrg 					    s, match[0].rm_so + 1, APPEND);
    407  1.12       cgd 				else
    408  1.19       mrg 					cspace(&SS,
    409  1.19       mrg 					    s + match[0].rm_so, 1, APPEND);
    410  1.12       cgd 				s += match[0].rm_so + 1;
    411  1.12       cgd 				slen -= match[0].rm_so + 1;
    412  1.12       cgd 				lastempty = 1;
    413  1.12       cgd 			}
    414  1.12       cgd 		} while (slen > 0 && regexec_e(re, s, REG_NOTBOL, 0, slen));
    415   1.1       alm 		/* Copy trailing retained string. */
    416  1.12       cgd 		if (slen > 0)
    417  1.12       cgd 			cspace(&SS, s, slen, APPEND);
    418   1.1       alm 		break;
    419   1.1       alm 	default:				/* Nth occurrence */
    420   1.1       alm 		while (--n) {
    421   1.1       alm 			s += match[0].rm_eo;
    422   1.8       cgd 			slen -= match[0].rm_eo;
    423   1.8       cgd 			if (!regexec_e(re, s, REG_NOTBOL, 0, slen))
    424   1.1       alm 				return (0);
    425   1.1       alm 		}
    426   1.1       alm 		/* FALLTHROUGH */
    427   1.1       alm 	case 1:					/* 1st occurrence */
    428   1.1       alm 		/* Locate start of replaced string. */
    429   1.1       alm 		re_off = match[0].rm_so + (s - ps);
    430   1.1       alm 		/* Copy leading retained string. */
    431   1.1       alm 		cspace(&SS, ps, re_off, APPEND);
    432   1.1       alm 		/* Add in regular expression. */
    433   1.1       alm 		regsub(&SS, s, cp->u.s->new);
    434   1.1       alm 		/* Copy trailing retained string. */
    435   1.1       alm 		s += match[0].rm_eo;
    436   1.8       cgd 		slen -= match[0].rm_eo;
    437   1.8       cgd 		cspace(&SS, s, slen, APPEND);
    438   1.1       alm 		break;
    439   1.1       alm 	}
    440   1.1       alm 
    441   1.1       alm 	/*
    442   1.1       alm 	 * Swap the substitute space and the pattern space, and make sure
    443   1.1       alm 	 * that any leftover pointers into stdio memory get lost.
    444   1.1       alm 	 */
    445   1.1       alm 	tspace = PS;
    446   1.1       alm 	PS = SS;
    447   1.1       alm 	SS = tspace;
    448   1.1       alm 	SS.space = SS.back;
    449   1.1       alm 
    450   1.1       alm 	/* Handle the 'p' flag. */
    451   1.1       alm 	if (cp->u.s->p)
    452   1.8       cgd 		OUT(ps)
    453   1.1       alm 
    454   1.1       alm 	/* Handle the 'w' flag. */
    455   1.1       alm 	if (cp->u.s->wfile && !pd) {
    456   1.1       alm 		if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile,
    457   1.1       alm 		    O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1)
    458  1.31    itojun 			err(FATAL, "%s: %s", cp->u.s->wfile, strerror(errno));
    459   1.8       cgd 		if (write(cp->u.s->wfd, ps, psl) != psl)
    460  1.31    itojun 			err(FATAL, "%s: %s", cp->u.s->wfile, strerror(errno));
    461   1.1       alm 	}
    462   1.1       alm 	return (1);
    463   1.1       alm }
    464   1.1       alm 
    465   1.1       alm /*
    466   1.1       alm  * Flush append requests.  Always called before reading a line,
    467   1.1       alm  * therefore it also resets the substitution done (sdone) flag.
    468   1.1       alm  */
    469   1.1       alm static void
    470  1.32       wiz flush_appends(void)
    471   1.1       alm {
    472   1.1       alm 	FILE *f;
    473   1.1       alm 	int count, i;
    474   1.1       alm 	char buf[8 * 1024];
    475   1.1       alm 
    476   1.1       alm 	for (i = 0; i < appendx; i++)
    477   1.1       alm 		switch (appends[i].type) {
    478   1.1       alm 		case AP_STRING:
    479   1.8       cgd 			fwrite(appends[i].s, sizeof(char), appends[i].len,
    480   1.8       cgd 			    stdout);
    481   1.1       alm 			break;
    482   1.1       alm 		case AP_FILE:
    483   1.1       alm 			/*
    484   1.1       alm 			 * Read files probably shouldn't be cached.  Since
    485   1.1       alm 			 * it's not an error to read a non-existent file,
    486   1.1       alm 			 * it's possible that another program is interacting
    487   1.1       alm 			 * with the sed script through the file system.  It
    488   1.1       alm 			 * would be truly bizarre, but possible.  It's probably
    489   1.1       alm 			 * not that big a performance win, anyhow.
    490   1.1       alm 			 */
    491   1.1       alm 			if ((f = fopen(appends[i].s, "r")) == NULL)
    492   1.1       alm 				break;
    493  1.20     lukem 			while ((count =
    494  1.21   thorpej 			    fread(buf, sizeof(char), sizeof(buf), f)) > 0)
    495   1.8       cgd 				(void)fwrite(buf, sizeof(char), count, stdout);
    496   1.1       alm 			(void)fclose(f);
    497   1.1       alm 			break;
    498   1.1       alm 		}
    499   1.1       alm 	if (ferror(stdout))
    500   1.1       alm 		err(FATAL, "stdout: %s", strerror(errno ? errno : EIO));
    501   1.1       alm 	appendx = sdone = 0;
    502   1.1       alm }
    503   1.1       alm 
    504   1.1       alm static void
    505  1.32       wiz lputs(char *s)
    506   1.1       alm {
    507  1.20     lukem 	int count;
    508  1.20     lukem 	char *escapes, *p;
    509  1.37   gdamore #ifndef HAVE_NBTOOL_CONFIG_H
    510   1.1       alm 	struct winsize win;
    511  1.37   gdamore #endif
    512   1.1       alm 	static int termwidth = -1;
    513   1.1       alm 
    514  1.23      ross 	if (termwidth == -1) {
    515  1.20     lukem 		if ((p = getenv("COLUMNS")) != NULL)
    516   1.1       alm 			termwidth = atoi(p);
    517  1.37   gdamore #ifndef HAVE_NBTOOL_CONFIG_H
    518   1.1       alm 		else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
    519   1.1       alm 		    win.ws_col > 0)
    520   1.1       alm 			termwidth = win.ws_col;
    521  1.37   gdamore #endif
    522   1.1       alm 		else
    523   1.1       alm 			termwidth = 60;
    524  1.23      ross 	}
    525   1.1       alm 	for (count = 0; *s; ++s) {
    526   1.1       alm 		if (count >= termwidth) {
    527   1.1       alm 			(void)printf("\\\n");
    528   1.1       alm 			count = 0;
    529   1.1       alm 		}
    530  1.24  christos 		if (isascii((unsigned char)*s) && isprint((unsigned char)*s) &&
    531  1.24  christos 		    *s != '\\') {
    532   1.1       alm 			(void)putchar(*s);
    533   1.1       alm 			count++;
    534   1.1       alm 		} else {
    535   1.1       alm 			escapes = "\\\a\b\f\n\r\t\v";
    536   1.1       alm 			(void)putchar('\\');
    537  1.20     lukem 			if ((p = strchr(escapes, *s)) != NULL) {
    538   1.1       alm 				(void)putchar("\\abfnrtv"[p - escapes]);
    539   1.1       alm 				count += 2;
    540   1.1       alm 			} else {
    541   1.8       cgd 				(void)printf("%03o", *(u_char *)s);
    542   1.1       alm 				count += 4;
    543   1.1       alm 			}
    544   1.1       alm 		}
    545   1.1       alm 	}
    546   1.1       alm 	(void)putchar('$');
    547   1.1       alm 	(void)putchar('\n');
    548   1.1       alm 	if (ferror(stdout))
    549   1.1       alm 		err(FATAL, "stdout: %s", strerror(errno ? errno : EIO));
    550   1.1       alm }
    551   1.1       alm 
    552   1.1       alm static inline int
    553  1.32       wiz regexec_e(regex_t *preg, const char *string, int eflags, int nomatch, size_t slen)
    554   1.1       alm {
    555   1.1       alm 	int eval;
    556  1.24  christos #ifndef REG_STARTEND
    557  1.24  christos 	char *buf;
    558  1.24  christos #endif
    559   1.8       cgd 
    560   1.1       alm 	if (preg == NULL) {
    561   1.1       alm 		if (defpreg == NULL)
    562   1.1       alm 			err(FATAL, "first RE may not be empty");
    563   1.1       alm 	} else
    564   1.1       alm 		defpreg = preg;
    565   1.1       alm 
    566   1.8       cgd 	/* Set anchors, discounting trailing newline (if any). */
    567   1.8       cgd 	if (slen > 0 && string[slen - 1] == '\n')
    568   1.8       cgd 		slen--;
    569  1.24  christos 
    570  1.24  christos #ifndef REG_STARTEND
    571  1.24  christos 	if ((buf = malloc(slen + 1)) == NULL)
    572  1.26  drochner 		err(1, NULL);
    573  1.24  christos 	(void)memcpy(buf, string, slen);
    574  1.24  christos 	buf[slen] = '\0';
    575  1.24  christos 	eval = regexec(defpreg, buf,
    576  1.24  christos 	    nomatch ? 0 : maxnsub + 1, match, eflags);
    577  1.24  christos 	free(buf);
    578  1.24  christos #else
    579   1.8       cgd 	match[0].rm_so = 0;
    580   1.8       cgd 	match[0].rm_eo = slen;
    581   1.1       alm 	eval = regexec(defpreg, string,
    582   1.8       cgd 	    nomatch ? 0 : maxnsub + 1, match, eflags | REG_STARTEND);
    583  1.24  christos #endif
    584   1.1       alm 	switch(eval) {
    585   1.1       alm 	case 0:
    586   1.1       alm 		return (1);
    587   1.1       alm 	case REG_NOMATCH:
    588   1.1       alm 		return (0);
    589   1.1       alm 	}
    590   1.1       alm 	err(FATAL, "RE error: %s", strregerror(eval, defpreg));
    591   1.1       alm 	/* NOTREACHED */
    592  1.20     lukem 	return (0);
    593   1.1       alm }
    594   1.1       alm 
    595   1.1       alm /*
    596   1.1       alm  * regsub - perform substitutions after a regexp match
    597   1.1       alm  * Based on a routine by Henry Spencer
    598   1.1       alm  */
    599   1.1       alm static void
    600  1.32       wiz regsub(SPACE *sp, char *string, char *src)
    601   1.1       alm {
    602  1.20     lukem 	int len, no;
    603  1.20     lukem 	char c, *dst;
    604   1.1       alm 
    605   1.1       alm #define	NEEDSP(reqlen)							\
    606  1.34    itojun 	if (sp->len + (reqlen) + 1 >= sp->blen) {			\
    607  1.35    itojun 		size_t newlen = sp->blen + (reqlen) + 1024;		\
    608  1.35    itojun 		sp->space = sp->back = xrealloc(sp->back, newlen);	\
    609  1.35    itojun 		sp->blen = newlen;					\
    610   1.1       alm 		dst = sp->space + sp->len;				\
    611   1.1       alm 	}
    612   1.1       alm 
    613   1.1       alm 	dst = sp->space + sp->len;
    614   1.1       alm 	while ((c = *src++) != '\0') {
    615   1.1       alm 		if (c == '&')
    616   1.1       alm 			no = 0;
    617  1.24  christos 		else if (c == '\\' && isdigit((unsigned char)*src))
    618   1.1       alm 			no = *src++ - '0';
    619   1.1       alm 		else
    620   1.1       alm 			no = -1;
    621   1.1       alm 		if (no < 0) {		/* Ordinary character. */
    622   1.1       alm  			if (c == '\\' && (*src == '\\' || *src == '&'))
    623   1.1       alm  				c = *src++;
    624   1.1       alm 			NEEDSP(1);
    625   1.1       alm  			*dst++ = c;
    626   1.1       alm 			++sp->len;
    627   1.1       alm  		} else if (match[no].rm_so != -1 && match[no].rm_eo != -1) {
    628   1.1       alm 			len = match[no].rm_eo - match[no].rm_so;
    629   1.1       alm 			NEEDSP(len);
    630   1.1       alm 			memmove(dst, string + match[no].rm_so, len);
    631   1.1       alm 			dst += len;
    632   1.1       alm 			sp->len += len;
    633   1.1       alm 		}
    634   1.1       alm 	}
    635   1.1       alm 	NEEDSP(1);
    636   1.1       alm 	*dst = '\0';
    637   1.1       alm }
    638   1.1       alm 
    639   1.1       alm /*
    640   1.1       alm  * aspace --
    641   1.1       alm  *	Append the source space to the destination space, allocating new
    642   1.1       alm  *	space as necessary.
    643   1.1       alm  */
    644   1.1       alm void
    645  1.32       wiz cspace(SPACE *sp, char *p, size_t len, enum e_spflag spflag)
    646   1.1       alm {
    647   1.1       alm 	size_t tlen;
    648   1.1       alm 
    649   1.8       cgd 	/* Make sure SPACE has enough memory and ramp up quickly. */
    650   1.8       cgd 	tlen = sp->len + len + 1;
    651   1.1       alm 	if (tlen > sp->blen) {
    652  1.35    itojun 		size_t newlen = tlen + 1024;
    653  1.35    itojun 		sp->space = sp->back = xrealloc(sp->back, newlen);
    654  1.35    itojun 		sp->blen = newlen;
    655   1.1       alm 	}
    656   1.1       alm 
    657   1.8       cgd 	if (spflag == REPLACE)
    658   1.1       alm 		sp->len = 0;
    659   1.1       alm 
    660   1.1       alm 	memmove(sp->space + sp->len, p, len);
    661   1.8       cgd 
    662   1.1       alm 	sp->space[sp->len += len] = '\0';
    663   1.1       alm }
    664   1.1       alm 
    665   1.1       alm /*
    666   1.1       alm  * Close all cached opened files and report any errors
    667   1.1       alm  */
    668   1.1       alm void
    669  1.32       wiz cfclose(struct s_command *cp, struct s_command *end)
    670   1.1       alm {
    671   1.1       alm 
    672   1.1       alm 	for (; cp != end; cp = cp->next)
    673   1.1       alm 		switch(cp->code) {
    674   1.1       alm 		case 's':
    675   1.1       alm 			if (cp->u.s->wfd != -1 && close(cp->u.s->wfd))
    676   1.1       alm 				err(FATAL,
    677   1.1       alm 				    "%s: %s", cp->u.s->wfile, strerror(errno));
    678   1.1       alm 			cp->u.s->wfd = -1;
    679   1.1       alm 			break;
    680   1.1       alm 		case 'w':
    681   1.1       alm 			if (cp->u.fd != -1 && close(cp->u.fd))
    682   1.1       alm 				err(FATAL, "%s: %s", cp->t, strerror(errno));
    683   1.1       alm 			cp->u.fd = -1;
    684   1.1       alm 			break;
    685   1.1       alm 		case '{':
    686   1.1       alm 			cfclose(cp->u.c, cp->next);
    687   1.1       alm 			break;
    688   1.1       alm 		}
    689   1.1       alm }
    690