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