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