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