Annotation of src/usr.bin/sed/process.c, Revision 1.27
1.27 ! mmcc 1: /* $OpenBSD: process.c,v 1.26 2015/07/20 18:24:15 jasper Exp $ */
1.2 deraadt 2:
1.1 deraadt 3: /*-
4: * Copyright (c) 1992 Diomidis Spinellis.
5: * Copyright (c) 1992, 1993
6: * The Regents of the University of California. All rights reserved.
7: *
8: * This code is derived from software contributed to Berkeley by
9: * Diomidis Spinellis of Imperial College, University of London.
10: *
11: * Redistribution and use in source and binary forms, with or without
12: * modification, are permitted provided that the following conditions
13: * are met:
14: * 1. Redistributions of source code must retain the above copyright
15: * notice, this list of conditions and the following disclaimer.
16: * 2. Redistributions in binary form must reproduce the above copyright
17: * notice, this list of conditions and the following disclaimer in the
18: * documentation and/or other materials provided with the distribution.
1.10 millert 19: * 3. Neither the name of the University nor the names of its contributors
1.1 deraadt 20: * may be used to endorse or promote products derived from this software
21: * without specific prior written permission.
22: *
23: * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24: * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25: * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26: * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27: * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28: * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29: * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30: * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31: * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32: * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33: * SUCH DAMAGE.
34: */
35:
36: #include <sys/types.h>
37: #include <sys/stat.h>
38: #include <sys/uio.h>
39:
40: #include <ctype.h>
41: #include <errno.h>
42: #include <fcntl.h>
43: #include <limits.h>
44: #include <regex.h>
45: #include <stdio.h>
46: #include <stdlib.h>
47: #include <string.h>
48: #include <unistd.h>
49:
50: #include "defs.h"
51: #include "extern.h"
52:
53: static SPACE HS, PS, SS;
54: #define pd PS.deleted
55: #define ps PS.space
56: #define psl PS.len
1.24 jasper 57: #define psanl PS.append_newline
1.1 deraadt 58: #define hs HS.space
59: #define hsl HS.len
60:
1.7 millert 61: static inline int applies(struct s_command *);
62: static void flush_appends(void);
63: static void lputs(char *);
64: static inline int regexec_e(regex_t *, const char *, int, int, size_t);
65: static void regsub(SPACE *, char *, char *);
66: static int substitute(struct s_command *);
1.1 deraadt 67:
68: struct s_appends *appends; /* Array of pointers to strings to append. */
69: static int appendx; /* Index into appends array. */
1.22 deraadt 70: size_t appendnum; /* Size of appends array. */
1.1 deraadt 71:
72: static int lastaddr; /* Set by applies if last address of a range. */
73: static int sdone; /* If any substitutes since last line input. */
74: /* Iov structure for 'w' commands. */
75: static regex_t *defpreg;
76: size_t maxnsub;
77: regmatch_t *match;
78:
1.24 jasper 79: #define OUT() do {\
80: fwrite(ps, 1, psl, outfile);\
81: if (psanl) fputc('\n', outfile);\
82: } while (0)
1.1 deraadt 83:
84: void
1.11 deraadt 85: process(void)
1.1 deraadt 86: {
87: struct s_command *cp;
88: SPACE tspace;
89: size_t len, oldpsl;
90: char *p;
1.24 jasper 91: int oldpsanl;
1.1 deraadt 92:
93: for (linenum = 0; mf_fgets(&PS, REPLACE);) {
94: pd = 0;
95: top:
96: cp = prog;
97: redirect:
98: while (cp != NULL) {
99: if (!applies(cp)) {
100: cp = cp->next;
101: continue;
102: }
103: switch (cp->code) {
104: case '{':
105: cp = cp->u.c;
106: goto redirect;
107: case 'a':
1.12 tedu 108: if (appendx >= appendnum) {
1.20 deraadt 109: appends = xreallocarray(appends,
1.22 deraadt 110: appendnum,
111: 2 * sizeof(struct s_appends));
1.12 tedu 112: appendnum *= 2;
113: }
1.1 deraadt 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;
1.24 jasper 125: if (cp->a2 == NULL || lastaddr || lastline())
126: (void)fprintf(outfile, "%s", cp->t);
1.1 deraadt 127: break;
128: case 'd':
129: pd = 1;
130: goto new;
131: case 'D':
132: if (pd)
133: goto new;
1.8 millert 134: if (psl == 0 ||
1.24 jasper 135: (p = memchr(ps, '\n', psl)) == NULL) {
1.1 deraadt 136: pd = 1;
137: goto new;
138: } else {
139: psl -= (p + 1) - ps;
140: memmove(ps, p + 1, psl);
141: goto top;
142: }
143: case 'g':
144: cspace(&PS, hs, hsl, REPLACE);
145: break;
146: case 'G':
1.24 jasper 147: cspace(&PS, "\n", 1, 0);
1.1 deraadt 148: cspace(&PS, hs, hsl, 0);
149: break;
150: case 'h':
151: cspace(&HS, ps, psl, REPLACE);
152: break;
153: case 'H':
1.24 jasper 154: cspace(&HS, "\n", 1, 0);
1.1 deraadt 155: cspace(&HS, ps, psl, 0);
156: break;
157: case 'i':
1.24 jasper 158: (void)fprintf(outfile, "%s", cp->t);
1.1 deraadt 159: break;
160: case 'l':
161: lputs(ps);
162: break;
163: case 'n':
164: if (!nflag && !pd)
1.24 jasper 165: OUT();
1.1 deraadt 166: flush_appends();
167: if (!mf_fgets(&PS, REPLACE))
168: exit(0);
169: pd = 0;
170: break;
171: case 'N':
172: flush_appends();
1.24 jasper 173: cspace(&PS, "\n", 1, 0);
174: if (!mf_fgets(&PS, 0))
1.1 deraadt 175: exit(0);
176: break;
177: case 'p':
178: if (pd)
179: break;
1.24 jasper 180: OUT();
1.1 deraadt 181: break;
182: case 'P':
183: if (pd)
184: break;
1.24 jasper 185: if ((p = memchr(ps, '\n', psl)) != NULL) {
1.1 deraadt 186: oldpsl = psl;
1.24 jasper 187: oldpsanl = psanl;
188: psl = p - ps;
189: psanl = 1;
190: OUT();
1.21 jsg 191: psl = oldpsl;
192: } else {
1.24 jasper 193: OUT();
1.1 deraadt 194: }
195: break;
196: case 'q':
197: if (!nflag && !pd)
1.24 jasper 198: OUT();
1.1 deraadt 199: flush_appends();
200: exit(0);
201: case 'r':
1.22 deraadt 202: if (appendx >= appendnum) {
1.20 deraadt 203: appends = xreallocarray(appends,
1.22 deraadt 204: appendnum,
205: 2 * sizeof(struct s_appends));
206: appendnum *= 2;
207: }
1.1 deraadt 208: appends[appendx].type = AP_FILE;
209: appends[appendx].s = cp->t;
210: appends[appendx].len = strlen(cp->t);
211: appendx++;
212: break;
213: case 's':
214: sdone |= substitute(cp);
215: break;
216: case 't':
217: if (sdone) {
218: sdone = 0;
219: cp = cp->u.c;
220: goto redirect;
221: }
222: break;
223: case 'w':
224: if (pd)
225: break;
226: if (cp->u.fd == -1 && (cp->u.fd = open(cp->t,
227: O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
228: DEFFILEMODE)) == -1)
1.27 ! mmcc 229: error(FATAL, "%s: %s",
1.1 deraadt 230: cp->t, strerror(errno));
1.24 jasper 231: if (write(cp->u.fd, ps, psl) != psl ||
232: write(cp->u.fd, "\n", 1) != 1)
1.27 ! mmcc 233: error(FATAL, "%s: %s",
1.1 deraadt 234: cp->t, strerror(errno));
235: break;
236: case 'x':
237: if (hs == NULL)
1.24 jasper 238: cspace(&HS, "", 0, REPLACE);
1.1 deraadt 239: tspace = PS;
240: PS = HS;
1.24 jasper 241: psanl = tspace.append_newline;
1.1 deraadt 242: HS = tspace;
243: break;
244: case 'y':
1.8 millert 245: if (pd || psl == 0)
1.1 deraadt 246: break;
1.24 jasper 247: for (p = ps, len = psl; len--; ++p)
1.4 deraadt 248: *p = cp->u.y[(unsigned char)*p];
1.1 deraadt 249: break;
250: case ':':
251: case '}':
252: break;
253: case '=':
1.24 jasper 254: (void)fprintf(outfile, "%lu\n", linenum);
1.1 deraadt 255: }
256: cp = cp->next;
257: } /* for all cp */
258:
259: new: if (!nflag && !pd)
1.24 jasper 260: OUT();
1.1 deraadt 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) : \
1.24 jasper 271: (a)->type == AT_LINE ? linenum == (a)->u.l : lastline()
1.1 deraadt 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: */
277: static inline int
1.11 deraadt 278: applies(struct s_command *cp)
1.1 deraadt 279: {
280: int r;
281:
282: lastaddr = 0;
283: if (cp->a1 == NULL && cp->a2 == NULL)
284: r = 1;
285: else if (cp->a2)
286: if (cp->inrange) {
287: if (MATCH(cp->a2)) {
288: cp->inrange = 0;
289: lastaddr = 1;
290: }
291: r = 1;
292: } else if (MATCH(cp->a1)) {
293: /*
294: * If the second address is a number less than or
295: * equal to the line number first selected, only
296: * one line shall be selected.
297: * -- POSIX 1003.2
298: */
299: if (cp->a2->type == AT_LINE &&
300: linenum >= cp->a2->u.l)
301: lastaddr = 1;
302: else
303: cp->inrange = 1;
304: r = 1;
305: } else
306: r = 0;
307: else
308: r = MATCH(cp->a1);
1.13 tedu 309: return (cp->nonsel ? !r : r);
1.1 deraadt 310: }
311:
312: /*
1.24 jasper 313: * Reset all inrange markers.
314: */
315: void
316: resetranges(void)
317: {
318: struct s_command *cp;
319:
320: for (cp = prog; cp; cp = cp->code == '{' ? cp->u.c : cp->next)
321: if (cp->a2)
322: cp->inrange = 0;
323: }
324:
325: /*
1.1 deraadt 326: * substitute --
327: * Do substitutions in the pattern space. Currently, we build a
328: * copy of the new pattern space in the substitute space structure
329: * and then swap them.
330: */
331: static int
1.11 deraadt 332: substitute(struct s_command *cp)
1.1 deraadt 333: {
334: SPACE tspace;
335: regex_t *re;
1.18 schwarze 336: regoff_t slen;
1.1 deraadt 337: int n, lastempty;
338: char *s;
339:
340: s = ps;
341: re = cp->u.s->re;
342: if (re == NULL) {
343: if (defpreg != NULL && cp->u.s->maxbref > defpreg->re_nsub) {
344: linenum = cp->u.s->linenum;
1.27 ! mmcc 345: error(COMPILE, "\\%d not defined in the RE",
1.1 deraadt 346: cp->u.s->maxbref);
347: }
348: }
349: if (!regexec_e(re, s, 0, 0, psl))
350: return (0);
351:
352: SS.len = 0; /* Clean substitute space. */
353: slen = psl;
354: n = cp->u.s->n;
355: lastempty = 1;
356:
1.18 schwarze 357: do {
358: /* Copy the leading retained string. */
359: if (n <= 1 && match[0].rm_so)
360: cspace(&SS, s, match[0].rm_so, APPEND);
361:
362: /* Skip zero-length matches right after other matches. */
363: if (lastempty || match[0].rm_so ||
364: match[0].rm_so != match[0].rm_eo) {
365: if (n <= 1) {
366: /* Want this match: append replacement. */
1.1 deraadt 367: regsub(&SS, s, cp->u.s->new);
1.18 schwarze 368: if (n == 1)
369: n = -1;
1.1 deraadt 370: } else {
1.18 schwarze 371: /* Want a later match: append original. */
372: if (match[0].rm_eo)
373: cspace(&SS, s, match[0].rm_eo, APPEND);
374: n--;
1.1 deraadt 375: }
376: }
1.18 schwarze 377:
378: /* Move past this match. */
1.1 deraadt 379: s += match[0].rm_eo;
380: slen -= match[0].rm_eo;
1.18 schwarze 381:
382: /*
383: * After a zero-length match, advance one byte,
384: * and at the end of the line, terminate.
385: */
386: if (match[0].rm_so == match[0].rm_eo) {
387: if (*s == '\0' || *s == '\n')
388: slen = -1;
389: else
390: slen--;
391: if (*s != '\0')
392: cspace(&SS, s++, 1, APPEND);
393: lastempty = 1;
394: } else
395: lastempty = 0;
396:
397: } while (n >= 0 && slen >= 0 && regexec_e(re, s, REG_NOTBOL, 0, slen));
398:
399: /* Did not find the requested number of matches. */
400: if (n > 1)
401: return (0);
402:
403: /* Copy the trailing retained string. */
404: if (slen > 0)
1.1 deraadt 405: cspace(&SS, s, slen, APPEND);
406:
407: /*
408: * Swap the substitute space and the pattern space, and make sure
409: * that any leftover pointers into stdio memory get lost.
410: */
411: tspace = PS;
412: PS = SS;
1.24 jasper 413: psanl = tspace.append_newline;
1.1 deraadt 414: SS = tspace;
415: SS.space = SS.back;
416:
417: /* Handle the 'p' flag. */
418: if (cp->u.s->p)
1.24 jasper 419: OUT();
1.1 deraadt 420:
421: /* Handle the 'w' flag. */
422: if (cp->u.s->wfile && !pd) {
423: if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile,
424: O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1)
1.27 ! mmcc 425: error(FATAL, "%s: %s", cp->u.s->wfile, strerror(errno));
1.24 jasper 426: if (write(cp->u.s->wfd, ps, psl) != psl ||
427: write(cp->u.s->wfd, "\n", 1) != 1)
1.27 ! mmcc 428: error(FATAL, "%s: %s", cp->u.s->wfile, strerror(errno));
1.1 deraadt 429: }
430: return (1);
431: }
432:
433: /*
434: * Flush append requests. Always called before reading a line,
435: * therefore it also resets the substitution done (sdone) flag.
436: */
437: static void
1.11 deraadt 438: flush_appends(void)
1.1 deraadt 439: {
440: FILE *f;
441: int count, i;
442: char buf[8 * 1024];
443:
1.26 jasper 444: for (i = 0; i < appendx; i++)
1.1 deraadt 445: switch (appends[i].type) {
446: case AP_STRING:
1.26 jasper 447: fwrite(appends[i].s, sizeof(char), appends[i].len,
1.24 jasper 448: outfile);
1.1 deraadt 449: break;
450: case AP_FILE:
451: /*
452: * Read files probably shouldn't be cached. Since
453: * it's not an error to read a non-existent file,
454: * it's possible that another program is interacting
455: * with the sed script through the file system. It
456: * would be truly bizarre, but possible. It's probably
457: * not that big a performance win, anyhow.
458: */
459: if ((f = fopen(appends[i].s, "r")) == NULL)
460: break;
1.3 deraadt 461: while ((count = fread(buf, sizeof(char), sizeof(buf), f)))
1.24 jasper 462: (void)fwrite(buf, sizeof(char), count, outfile);
1.1 deraadt 463: (void)fclose(f);
464: break;
465: }
1.24 jasper 466: if (ferror(outfile))
1.27 ! mmcc 467: error(FATAL, "%s: %s", outfname, strerror(errno ? errno : EIO));
1.1 deraadt 468: appendx = sdone = 0;
469: }
470:
471: static void
1.11 deraadt 472: lputs(char *s)
1.1 deraadt 473: {
1.6 mpech 474: int count;
1.25 deraadt 475: extern int termwidth;
1.24 jasper 476: const char *escapes;
477: char *p;
1.1 deraadt 478:
1.26 jasper 479: for (count = 0; *s; ++s) {
1.1 deraadt 480: if (count >= termwidth) {
1.24 jasper 481: (void)fprintf(outfile, "\\\n");
1.1 deraadt 482: count = 0;
483: }
1.19 deraadt 484: if (isascii((unsigned char)*s) && isprint((unsigned char)*s)
485: && *s != '\\') {
1.24 jasper 486: (void)fputc(*s, outfile);
1.1 deraadt 487: count++;
1.24 jasper 488: } else if (*s == '\n') {
489: (void)fputc('$', outfile);
490: (void)fputc('\n', outfile);
491: count = 0;
492: } else {
1.14 millert 493: escapes = "\\\a\b\f\r\t\v";
1.24 jasper 494: (void)fputc('\\', outfile);
1.3 deraadt 495: if ((p = strchr(escapes, *s))) {
1.24 jasper 496: (void)fputc("\\abfrtv"[p - escapes], outfile);
1.1 deraadt 497: count += 2;
498: } else {
1.24 jasper 499: (void)fprintf(outfile, "%03o", *(u_char *)s);
1.1 deraadt 500: count += 4;
501: }
502: }
503: }
1.24 jasper 504: (void)fputc('$', outfile);
505: (void)fputc('\n', outfile);
506: if (ferror(outfile))
1.27 ! mmcc 507: error(FATAL, "%s: %s", outfname, strerror(errno ? errno : EIO));
1.1 deraadt 508: }
509:
510: static inline int
1.11 deraadt 511: regexec_e(regex_t *preg, const char *string, int eflags,
512: int nomatch, size_t slen)
1.1 deraadt 513: {
514: int eval;
1.26 jasper 515:
1.1 deraadt 516: if (preg == NULL) {
517: if (defpreg == NULL)
1.27 ! mmcc 518: error(FATAL, "first RE may not be empty");
1.1 deraadt 519: } else
520: defpreg = preg;
521:
1.24 jasper 522: /* Set anchors */
1.1 deraadt 523: match[0].rm_so = 0;
524: match[0].rm_eo = slen;
1.26 jasper 525:
1.1 deraadt 526: eval = regexec(defpreg, string,
527: nomatch ? 0 : maxnsub + 1, match, eflags | REG_STARTEND);
1.13 tedu 528: switch (eval) {
1.1 deraadt 529: case 0:
530: return (1);
531: case REG_NOMATCH:
532: return (0);
533: }
1.27 ! mmcc 534: error(FATAL, "RE error: %s", strregerror(eval, defpreg));
1.1 deraadt 535: /* NOTREACHED */
536: }
537:
538: /*
539: * regsub - perform substitutions after a regexp match
540: * Based on a routine by Henry Spencer
541: */
542: static void
1.11 deraadt 543: regsub(SPACE *sp, char *string, char *src)
1.1 deraadt 544: {
1.6 mpech 545: int len, no;
546: char c, *dst;
1.1 deraadt 547:
548: #define NEEDSP(reqlen) \
1.12 tedu 549: if (sp->len + (reqlen) + 1 >= sp->blen) { \
550: size_t newlen = sp->blen + (reqlen) + 1024; \
551: sp->space = sp->back = xrealloc(sp->back, newlen); \
552: sp->blen = newlen; \
1.1 deraadt 553: dst = sp->space + sp->len; \
554: }
555:
556: dst = sp->space + sp->len;
557: while ((c = *src++) != '\0') {
558: if (c == '&')
559: no = 0;
1.19 deraadt 560: else if (c == '\\' && isdigit((unsigned char)*src))
1.1 deraadt 561: no = *src++ - '0';
562: else
563: no = -1;
564: if (no < 0) { /* Ordinary character. */
565: if (c == '\\' && (*src == '\\' || *src == '&'))
566: c = *src++;
567: NEEDSP(1);
568: *dst++ = c;
569: ++sp->len;
570: } else if (match[no].rm_so != -1 && match[no].rm_eo != -1) {
571: len = match[no].rm_eo - match[no].rm_so;
572: NEEDSP(len);
573: memmove(dst, string + match[no].rm_so, len);
574: dst += len;
575: sp->len += len;
576: }
577: }
578: NEEDSP(1);
579: *dst = '\0';
580: }
581:
582: /*
583: * aspace --
584: * Append the source space to the destination space, allocating new
585: * space as necessary.
586: */
587: void
1.24 jasper 588: cspace(SPACE *sp, const char *p, size_t len, enum e_spflag spflag)
1.1 deraadt 589: {
590: size_t tlen;
591:
592: /* Make sure SPACE has enough memory and ramp up quickly. */
593: tlen = sp->len + len + 1;
594: if (tlen > sp->blen) {
1.12 tedu 595: size_t newlen = tlen + 1024;
596: sp->space = sp->back = xrealloc(sp->back, newlen);
597: sp->blen = newlen;
1.1 deraadt 598: }
599:
600: if (spflag == REPLACE)
601: sp->len = 0;
602:
603: memmove(sp->space + sp->len, p, len);
604:
605: sp->space[sp->len += len] = '\0';
606: }
607:
608: /*
609: * Close all cached opened files and report any errors
610: */
611: void
1.11 deraadt 612: cfclose(struct s_command *cp, struct s_command *end)
1.1 deraadt 613: {
614:
615: for (; cp != end; cp = cp->next)
1.13 tedu 616: switch (cp->code) {
1.1 deraadt 617: case 's':
618: if (cp->u.s->wfd != -1 && close(cp->u.s->wfd))
1.27 ! mmcc 619: error(FATAL,
1.1 deraadt 620: "%s: %s", cp->u.s->wfile, strerror(errno));
621: cp->u.s->wfd = -1;
622: break;
623: case 'w':
624: if (cp->u.fd != -1 && close(cp->u.fd))
1.27 ! mmcc 625: error(FATAL, "%s: %s", cp->t, strerror(errno));
1.1 deraadt 626: cp->u.fd = -1;
627: break;
628: case '{':
629: cfclose(cp->u.c, cp->next);
630: break;
631: }
632: }