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