xref: /original-bsd/usr.bin/sed/process.c (revision e58c8952)
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  * %sccs.include.redist.c%
10  */
11 
12 #ifndef lint
13 static char sccsid[] = "@(#)process.c	8.3 (Berkeley) 04/16/94";
14 #endif /* not lint */
15 
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #include <sys/ioctl.h>
19 #include <sys/uio.h>
20 
21 #include <ctype.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <limits.h>
25 #include <regex.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <unistd.h>
30 
31 #include "defs.h"
32 #include "extern.h"
33 
34 static SPACE HS, PS, SS;
35 #define	pd		PS.deleted
36 #define	ps		PS.space
37 #define	psl		PS.len
38 #define	hs		HS.space
39 #define	hsl		HS.len
40 
41 static inline int	 applies __P((struct s_command *));
42 static void		 flush_appends __P((void));
43 static void		 lputs __P((char *));
44 static inline int	 regexec_e __P((regex_t *, const char *, int, int, size_t));
45 static void		 regsub __P((SPACE *, char *, char *));
46 static int		 substitute __P((struct s_command *));
47 
48 struct s_appends *appends;	/* Array of pointers to strings to append. */
49 static int appendx;		/* Index into appends array. */
50 int appendnum;			/* Size of appends array. */
51 
52 static int lastaddr;		/* Set by applies if last address of a range. */
53 static int sdone;		/* If any substitutes since last line input. */
54 				/* Iov structure for 'w' commands. */
55 static regex_t *defpreg;
56 size_t maxnsub;
57 regmatch_t *match;
58 
59 #define OUT(s) { fwrite(s, sizeof(u_char), psl, stdout); }
60 
61 void
62 process()
63 {
64 	struct s_command *cp;
65 	SPACE tspace;
66 	size_t len;
67 	int r;
68 	char oldc, *p;
69 
70 	for (linenum = 0; mf_fgets(&PS, REPLACE);) {
71 		pd = 0;
72 		cp = prog;
73 redirect:
74 		while (cp != NULL) {
75 			if (!applies(cp)) {
76 				cp = cp->next;
77 				continue;
78 			}
79 			switch (cp->code) {
80 			case '{':
81 				cp = cp->u.c;
82 				goto redirect;
83 			case 'a':
84 				if (appendx >= appendnum)
85 					appends = xrealloc(appends,
86 					    sizeof(struct s_appends) *
87 					    (appendnum *= 2));
88 				appends[appendx].type = AP_STRING;
89 				appends[appendx].s = cp->t;
90 				appends[appendx].len = strlen(cp->t);
91 				appendx++;
92 				break;
93 			case 'b':
94 				cp = cp->u.c;
95 				goto redirect;
96 			case 'c':
97 				pd = 1;
98 				psl = 0;
99 				if (cp->a2 == NULL || lastaddr)
100 					(void)printf("%s", cp->t);
101 				break;
102 			case 'd':
103 				pd = 1;
104 				goto new;
105 			case 'D':
106 				if (pd)
107 					goto new;
108 				if ((p = memchr(ps, '\n', psl)) == NULL)
109 					pd = 1;
110 				else {
111 					psl -= (p - ps) - 1;
112 					memmove(ps, p + 1, psl);
113 				}
114 				goto new;
115 			case 'g':
116 				cspace(&PS, hs, hsl, REPLACE);
117 				break;
118 			case 'G':
119 				cspace(&PS, hs, hsl, 0);
120 				break;
121 			case 'h':
122 				cspace(&HS, ps, psl, REPLACE);
123 				break;
124 			case 'H':
125 				cspace(&HS, ps, psl, 0);
126 				break;
127 			case 'i':
128 				(void)printf("%s", cp->t);
129 				break;
130 			case 'l':
131 				lputs(ps);
132 				break;
133 			case 'n':
134 				if (!nflag && !pd)
135 					OUT(ps)
136 				flush_appends();
137 				r = mf_fgets(&PS, REPLACE);
138 #ifdef HISTORIC_PRACTICE
139 				if (!r)
140 					exit(0);
141 #endif
142 				pd = 0;
143 				break;
144 			case 'N':
145 				flush_appends();
146 				if (!mf_fgets(&PS, 0)) {
147 					if (!nflag && !pd)
148 						OUT(ps)
149 					exit(0);
150 				}
151 				break;
152 			case 'p':
153 				if (pd)
154 					break;
155 				OUT(ps)
156 				break;
157 			case 'P':
158 				if (pd)
159 					break;
160 				if ((p = memchr(ps, '\n', psl)) != NULL) {
161 					oldc = *p;
162 					*p = '\0';
163 				}
164 				OUT(ps)
165 				if (p != NULL)
166 					*p = oldc;
167 				break;
168 			case 'q':
169 				if (!nflag && !pd)
170 					OUT(ps)
171 				flush_appends();
172 				exit(0);
173 			case 'r':
174 				if (appendx >= appendnum)
175 					appends = xrealloc(appends,
176 					    sizeof(struct s_appends) *
177 					    (appendnum *= 2));
178 				appends[appendx].type = AP_FILE;
179 				appends[appendx].s = cp->t;
180 				appends[appendx].len = strlen(cp->t);
181 				appendx++;
182 				break;
183 			case 's':
184 				sdone |= substitute(cp);
185 				break;
186 			case 't':
187 				if (sdone) {
188 					sdone = 0;
189 					cp = cp->u.c;
190 					goto redirect;
191 				}
192 				break;
193 			case 'w':
194 				if (pd)
195 					break;
196 				if (cp->u.fd == -1 && (cp->u.fd = open(cp->t,
197 				    O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
198 				    DEFFILEMODE)) == -1)
199 					err(FATAL, "%s: %s\n",
200 					    cp->t, strerror(errno));
201 				if (write(cp->u.fd, ps, psl) != psl)
202 					err(FATAL, "%s: %s\n",
203 					    cp->t, strerror(errno));
204 				break;
205 			case 'x':
206 				if (hs == NULL)
207 					cspace(&HS, "", 0, REPLACE);
208 				tspace = PS;
209 				PS = HS;
210 				HS = tspace;
211 				break;
212 			case 'y':
213 				if (pd)
214 					break;
215 				for (p = ps, len = psl; --len; ++p)
216 					*p = cp->u.y[*p];
217 				break;
218 			case ':':
219 			case '}':
220 				break;
221 			case '=':
222 				(void)printf("%lu\n", linenum);
223 			}
224 			cp = cp->next;
225 		} /* for all cp */
226 
227 new:		if (!nflag && !pd)
228 			OUT(ps)
229 		flush_appends();
230 	} /* for all lines */
231 }
232 
233 /*
234  * TRUE if the address passed matches the current program state
235  * (lastline, linenumber, ps).
236  */
237 #define	MATCH(a)						\
238 	(a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, psl) :	\
239 	    (a)->type == AT_LINE ? linenum == (a)->u.l : lastline
240 
241 /*
242  * Return TRUE if the command applies to the current line.  Sets the inrange
243  * flag to process ranges.  Interprets the non-select (``!'') flag.
244  */
245 static inline int
246 applies(cp)
247 	struct s_command *cp;
248 {
249 	int r;
250 
251 	lastaddr = 0;
252 	if (cp->a1 == NULL && cp->a2 == NULL)
253 		r = 1;
254 	else if (cp->a2)
255 		if (cp->inrange) {
256 			if (MATCH(cp->a2)) {
257 				cp->inrange = 0;
258 				lastaddr = 1;
259 			}
260 			r = 1;
261 		} else if (MATCH(cp->a1)) {
262 			/*
263 			 * If the second address is a number less than or
264 			 * equal to the line number first selected, only
265 			 * one line shall be selected.
266 			 *	-- POSIX 1003.2
267 			 */
268 			if (cp->a2->type == AT_LINE &&
269 			    linenum >= cp->a2->u.l)
270 				lastaddr = 1;
271 			else
272 				cp->inrange = 1;
273 			r = 1;
274 		} else
275 			r = 0;
276 	else
277 		r = MATCH(cp->a1);
278 	return (cp->nonsel ? ! r : r);
279 }
280 
281 /*
282  * substitute --
283  *	Do substitutions in the pattern space.  Currently, we build a
284  *	copy of the new pattern space in the substitute space structure
285  *	and then swap them.
286  */
287 static int
288 substitute(cp)
289 	struct s_command *cp;
290 {
291 	SPACE tspace;
292 	regex_t *re;
293 	size_t re_off, slen;
294 	int n;
295 	char *s;
296 
297 	s = ps;
298 	re = cp->u.s->re;
299 	if (re == NULL) {
300 		if (defpreg != NULL && cp->u.s->maxbref > defpreg->re_nsub) {
301 			linenum = cp->u.s->linenum;
302 			err(COMPILE, "\\%d not defined in the RE",
303 			    cp->u.s->maxbref);
304 		}
305 	}
306 	if (!regexec_e(re, s, 0, 0, psl))
307 		return (0);
308 
309 	SS.len = 0;				/* Clean substitute space. */
310 	slen = psl;
311 	n = cp->u.s->n;
312 	switch (n) {
313 	case 0:					/* Global */
314 		do {
315 			/* Locate start of replaced string. */
316 			re_off = match[0].rm_so;
317 			/* Copy leading retained string. */
318 			cspace(&SS, s, re_off, APPEND);
319 			/* Add in regular expression. */
320 			regsub(&SS, s, cp->u.s->new);
321 			/* Move past this match. */
322 			s += match[0].rm_eo;
323 			slen -= match[0].rm_eo;
324 		} while(match[0].rm_so != match[0].rm_eo &&
325 		    regexec_e(re, s, REG_NOTBOL, 0, slen));
326 
327 		/* Copy trailing retained string. */
328 		cspace(&SS, s, slen, APPEND);
329 		break;
330 	default:				/* Nth occurrence */
331 		while (--n) {
332 			s += match[0].rm_eo;
333 			slen -= match[0].rm_eo;
334 			if (!regexec_e(re, s, REG_NOTBOL, 0, slen))
335 				return (0);
336 		}
337 		/* FALLTHROUGH */
338 	case 1:					/* 1st occurrence */
339 		/* Locate start of replaced string. */
340 		re_off = match[0].rm_so + (s - ps);
341 		/* Copy leading retained string. */
342 		cspace(&SS, ps, re_off, APPEND);
343 		/* Add in regular expression. */
344 		regsub(&SS, s, cp->u.s->new);
345 		/* Copy trailing retained string. */
346 		s += match[0].rm_eo;
347 		slen -= match[0].rm_eo;
348 		cspace(&SS, s, slen, APPEND);
349 		break;
350 	}
351 
352 	/*
353 	 * Swap the substitute space and the pattern space, and make sure
354 	 * that any leftover pointers into stdio memory get lost.
355 	 */
356 	tspace = PS;
357 	PS = SS;
358 	SS = tspace;
359 	SS.space = SS.back;
360 
361 	/* Handle the 'p' flag. */
362 	if (cp->u.s->p)
363 		OUT(ps)
364 
365 	/* Handle the 'w' flag. */
366 	if (cp->u.s->wfile && !pd) {
367 		if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile,
368 		    O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1)
369 			err(FATAL, "%s: %s\n", cp->u.s->wfile, strerror(errno));
370 		if (write(cp->u.s->wfd, ps, psl) != psl)
371 			err(FATAL, "%s: %s\n", cp->u.s->wfile, strerror(errno));
372 	}
373 	return (1);
374 }
375 
376 /*
377  * Flush append requests.  Always called before reading a line,
378  * therefore it also resets the substitution done (sdone) flag.
379  */
380 static void
381 flush_appends()
382 {
383 	FILE *f;
384 	int count, i;
385 	char buf[8 * 1024];
386 
387 	for (i = 0; i < appendx; i++)
388 		switch (appends[i].type) {
389 		case AP_STRING:
390 			fwrite(appends[i].s, sizeof(char), appends[i].len,
391 			    stdout);
392 			break;
393 		case AP_FILE:
394 			/*
395 			 * Read files probably shouldn't be cached.  Since
396 			 * it's not an error to read a non-existent file,
397 			 * it's possible that another program is interacting
398 			 * with the sed script through the file system.  It
399 			 * would be truly bizarre, but possible.  It's probably
400 			 * not that big a performance win, anyhow.
401 			 */
402 			if ((f = fopen(appends[i].s, "r")) == NULL)
403 				break;
404 			while (count = fread(buf, sizeof(char), sizeof(buf), f))
405 				(void)fwrite(buf, sizeof(char), count, stdout);
406 			(void)fclose(f);
407 			break;
408 		}
409 	if (ferror(stdout))
410 		err(FATAL, "stdout: %s", strerror(errno ? errno : EIO));
411 	appendx = sdone = 0;
412 }
413 
414 static void
415 lputs(s)
416 	register char *s;
417 {
418 	register int count;
419 	register char *escapes, *p;
420 	struct winsize win;
421 	static int termwidth = -1;
422 
423 	if (termwidth == -1)
424 		if (p = getenv("COLUMNS"))
425 			termwidth = atoi(p);
426 		else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
427 		    win.ws_col > 0)
428 			termwidth = win.ws_col;
429 		else
430 			termwidth = 60;
431 
432 	for (count = 0; *s; ++s) {
433 		if (count >= termwidth) {
434 			(void)printf("\\\n");
435 			count = 0;
436 		}
437 		if (isascii(*s) && isprint(*s) && *s != '\\') {
438 			(void)putchar(*s);
439 			count++;
440 		} else {
441 			escapes = "\\\a\b\f\n\r\t\v";
442 			(void)putchar('\\');
443 			if (p = strchr(escapes, *s)) {
444 				(void)putchar("\\abfnrtv"[p - escapes]);
445 				count += 2;
446 			} else {
447 				(void)printf("%03o", *(u_char *)s);
448 				count += 4;
449 			}
450 		}
451 	}
452 	(void)putchar('$');
453 	(void)putchar('\n');
454 	if (ferror(stdout))
455 		err(FATAL, "stdout: %s", strerror(errno ? errno : EIO));
456 }
457 
458 static inline int
459 regexec_e(preg, string, eflags, nomatch, slen)
460 	regex_t *preg;
461 	const char *string;
462 	int eflags, nomatch;
463 	size_t slen;
464 {
465 	int eval;
466 
467 	if (preg == NULL) {
468 		if (defpreg == NULL)
469 			err(FATAL, "first RE may not be empty");
470 	} else
471 		defpreg = preg;
472 
473 	/* Set anchors, discounting trailing newline (if any). */
474 	if (slen > 0 && string[slen - 1] == '\n')
475 		slen--;
476 	match[0].rm_so = 0;
477 	match[0].rm_eo = slen;
478 
479 	eval = regexec(defpreg, string,
480 	    nomatch ? 0 : maxnsub + 1, match, eflags | REG_STARTEND);
481 	switch(eval) {
482 	case 0:
483 		return (1);
484 	case REG_NOMATCH:
485 		return (0);
486 	}
487 	err(FATAL, "RE error: %s", strregerror(eval, defpreg));
488 	/* NOTREACHED */
489 }
490 
491 /*
492  * regsub - perform substitutions after a regexp match
493  * Based on a routine by Henry Spencer
494  */
495 static void
496 regsub(sp, string, src)
497 	SPACE *sp;
498 	char *string, *src;
499 {
500 	register int len, no;
501 	register char c, *dst;
502 
503 #define	NEEDSP(reqlen)							\
504 	if (sp->len >= sp->blen - (reqlen) - 1) {			\
505 		sp->blen += (reqlen) + 1024;				\
506 		sp->space = sp->back = xrealloc(sp->back, sp->blen);	\
507 		dst = sp->space + sp->len;				\
508 	}
509 
510 	dst = sp->space + sp->len;
511 	while ((c = *src++) != '\0') {
512 		if (c == '&')
513 			no = 0;
514 		else if (c == '\\' && isdigit(*src))
515 			no = *src++ - '0';
516 		else
517 			no = -1;
518 		if (no < 0) {		/* Ordinary character. */
519  			if (c == '\\' && (*src == '\\' || *src == '&'))
520  				c = *src++;
521 			NEEDSP(1);
522  			*dst++ = c;
523 			++sp->len;
524  		} else if (match[no].rm_so != -1 && match[no].rm_eo != -1) {
525 			len = match[no].rm_eo - match[no].rm_so;
526 			NEEDSP(len);
527 			memmove(dst, string + match[no].rm_so, len);
528 			dst += len;
529 			sp->len += len;
530 		}
531 	}
532 	NEEDSP(1);
533 	*dst = '\0';
534 }
535 
536 /*
537  * aspace --
538  *	Append the source space to the destination space, allocating new
539  *	space as necessary.
540  */
541 void
542 cspace(sp, p, len, spflag)
543 	SPACE *sp;
544 	char *p;
545 	size_t len;
546 	enum e_spflag spflag;
547 {
548 	size_t tlen;
549 
550 	/* Make sure SPACE has enough memory and ramp up quickly. */
551 	tlen = sp->len + len + 1;
552 	if (tlen > sp->blen) {
553 		sp->blen = tlen + 1024;
554 		sp->space = sp->back = xrealloc(sp->back, sp->blen);
555 	}
556 
557 	if (spflag == REPLACE)
558 		sp->len = 0;
559 
560 	memmove(sp->space + sp->len, p, len);
561 
562 	sp->space[sp->len += len] = '\0';
563 }
564 
565 /*
566  * Close all cached opened files and report any errors
567  */
568 void
569 cfclose(cp, end)
570 	register struct s_command *cp, *end;
571 {
572 
573 	for (; cp != end; cp = cp->next)
574 		switch(cp->code) {
575 		case 's':
576 			if (cp->u.s->wfd != -1 && close(cp->u.s->wfd))
577 				err(FATAL,
578 				    "%s: %s", cp->u.s->wfile, strerror(errno));
579 			cp->u.s->wfd = -1;
580 			break;
581 		case 'w':
582 			if (cp->u.fd != -1 && close(cp->u.fd))
583 				err(FATAL, "%s: %s", cp->t, strerror(errno));
584 			cp->u.fd = -1;
585 			break;
586 		case '{':
587 			cfclose(cp->u.c, cp->next);
588 			break;
589 		}
590 }
591