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