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