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