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