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