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