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 * 4. Neither the name of the University nor the names of its contributors 18 * may be used to endorse or promote products derived from this software 19 * without specific prior written permission. 20 * 21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * SUCH DAMAGE. 32 */ 33 34 #include <sys/cdefs.h> 35 __FBSDID("$FreeBSD$"); 36 37 #ifndef lint 38 static const char sccsid[] = "@(#)process.c 8.6 (Berkeley) 4/20/94"; 39 #endif 40 41 #include <sys/types.h> 42 #include <sys/stat.h> 43 #include <sys/ioctl.h> 44 #include <sys/uio.h> 45 46 #include <ctype.h> 47 #include <err.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 #include <wchar.h> 57 #include <wctype.h> 58 59 #include "defs.h" 60 #include "extern.h" 61 62 static SPACE HS, PS, SS, YS; 63 #define pd PS.deleted 64 #define ps PS.space 65 #define psl PS.len 66 #define psanl PS.append_newline 67 #define hs HS.space 68 #define hsl HS.len 69 70 static inline int applies(struct s_command *); 71 static void do_tr(struct s_tr *); 72 static void flush_appends(void); 73 static void lputs(char *, size_t); 74 static int regexec_e(regex_t *, const char *, int, int, size_t); 75 static void regsub(SPACE *, char *, char *); 76 static int substitute(struct s_command *); 77 78 struct s_appends *appends; /* Array of pointers to strings to append. */ 79 static int appendx; /* Index into appends array. */ 80 int appendnum; /* Size of appends array. */ 81 82 static int lastaddr; /* Set by applies if last address of a range. */ 83 static int sdone; /* If any substitutes since last line input. */ 84 /* Iov structure for 'w' commands. */ 85 static regex_t *defpreg; 86 size_t maxnsub; 87 regmatch_t *match; 88 89 #define OUT() do { \ 90 fwrite(ps, 1, psl, outfile); \ 91 if (psanl) fputc('\n', outfile); \ 92 } while (0) 93 94 void 95 process(void) 96 { 97 struct s_command *cp; 98 SPACE tspace; 99 size_t oldpsl = 0; 100 char *p; 101 int oldpsanl; 102 103 p = NULL; 104 105 for (linenum = 0; mf_fgets(&PS, REPLACE);) { 106 pd = 0; 107 top: 108 cp = prog; 109 redirect: 110 while (cp != NULL) { 111 if (!applies(cp)) { 112 cp = cp->next; 113 continue; 114 } 115 switch (cp->code) { 116 case '{': 117 cp = cp->u.c; 118 goto redirect; 119 case 'a': 120 if (appendx >= appendnum) 121 if ((appends = realloc(appends, 122 sizeof(struct s_appends) * 123 (appendnum *= 2))) == NULL) 124 err(1, "realloc"); 125 appends[appendx].type = AP_STRING; 126 appends[appendx].s = cp->t; 127 appends[appendx].len = strlen(cp->t); 128 appendx++; 129 break; 130 case 'b': 131 cp = cp->u.c; 132 goto redirect; 133 case 'c': 134 pd = 1; 135 psl = 0; 136 if (cp->a2 == NULL || lastaddr || lastline()) 137 (void)fprintf(outfile, "%s", cp->t); 138 break; 139 case 'd': 140 pd = 1; 141 goto new; 142 case 'D': 143 if (pd) 144 goto new; 145 if (psl == 0 || 146 (p = memchr(ps, '\n', psl)) == NULL) { 147 pd = 1; 148 goto new; 149 } else { 150 psl -= (p + 1) - ps; 151 memmove(ps, p + 1, psl); 152 goto top; 153 } 154 case 'g': 155 cspace(&PS, hs, hsl, REPLACE); 156 break; 157 case 'G': 158 cspace(&PS, "\n", 1, APPEND); 159 cspace(&PS, hs, hsl, APPEND); 160 break; 161 case 'h': 162 cspace(&HS, ps, psl, REPLACE); 163 break; 164 case 'H': 165 cspace(&HS, "\n", 1, APPEND); 166 cspace(&HS, ps, psl, APPEND); 167 break; 168 case 'i': 169 (void)fprintf(outfile, "%s", cp->t); 170 break; 171 case 'l': 172 lputs(ps, psl); 173 break; 174 case 'n': 175 if (!nflag && !pd) 176 OUT(); 177 flush_appends(); 178 if (!mf_fgets(&PS, REPLACE)) 179 exit(0); 180 pd = 0; 181 break; 182 case 'N': 183 flush_appends(); 184 cspace(&PS, "\n", 1, APPEND); 185 if (!mf_fgets(&PS, APPEND)) 186 exit(0); 187 break; 188 case 'p': 189 if (pd) 190 break; 191 OUT(); 192 break; 193 case 'P': 194 if (pd) 195 break; 196 if ((p = memchr(ps, '\n', psl)) != NULL) { 197 oldpsl = psl; 198 oldpsanl = psanl; 199 psl = p - ps; 200 psanl = 1; 201 } 202 OUT(); 203 if (p != NULL) { 204 psl = oldpsl; 205 psanl = oldpsanl; 206 } 207 break; 208 case 'q': 209 if (!nflag && !pd) 210 OUT(); 211 flush_appends(); 212 exit(0); 213 case 'r': 214 if (appendx >= appendnum) 215 if ((appends = realloc(appends, 216 sizeof(struct s_appends) * 217 (appendnum *= 2))) == NULL) 218 err(1, "realloc"); 219 appends[appendx].type = AP_FILE; 220 appends[appendx].s = cp->t; 221 appends[appendx].len = strlen(cp->t); 222 appendx++; 223 break; 224 case 's': 225 sdone |= substitute(cp); 226 break; 227 case 't': 228 if (sdone) { 229 sdone = 0; 230 cp = cp->u.c; 231 goto redirect; 232 } 233 break; 234 case 'w': 235 if (pd) 236 break; 237 if (cp->u.fd == -1 && (cp->u.fd = open(cp->t, 238 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, 239 DEFFILEMODE)) == -1) 240 err(1, "%s", cp->t); 241 if (write(cp->u.fd, ps, psl) != (ssize_t)psl || 242 write(cp->u.fd, "\n", 1) != 1) 243 err(1, "%s", cp->t); 244 break; 245 case 'x': 246 /* 247 * If the hold space is null, make it empty 248 * but not null. Otherwise the pattern space 249 * will become null after the swap, which is 250 * an abnormal condition. 251 */ 252 if (hs == NULL) 253 cspace(&HS, "", 0, REPLACE); 254 tspace = PS; 255 PS = HS; 256 psanl = tspace.append_newline; 257 HS = tspace; 258 break; 259 case 'y': 260 if (pd || psl == 0) 261 break; 262 do_tr(cp->u.y); 263 break; 264 case ':': 265 case '}': 266 break; 267 case '=': 268 (void)fprintf(outfile, "%lu\n", linenum); 269 } 270 cp = cp->next; 271 } /* for all cp */ 272 273 new: if (!nflag && !pd) 274 OUT(); 275 flush_appends(); 276 } /* for all lines */ 277 } 278 279 /* 280 * TRUE if the address passed matches the current program state 281 * (lastline, linenumber, ps). 282 */ 283 #define MATCH(a) \ 284 ((a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, psl) : \ 285 (a)->type == AT_LINE ? linenum == (a)->u.l : lastline()) 286 287 /* 288 * Return TRUE if the command applies to the current line. Sets the start 289 * line for process ranges. Interprets the non-select (``!'') flag. 290 */ 291 static inline int 292 applies(struct s_command *cp) 293 { 294 int r; 295 296 lastaddr = 0; 297 if (cp->a1 == NULL && cp->a2 == NULL) 298 r = 1; 299 else if (cp->a2) 300 if (cp->startline > 0) { 301 switch (cp->a2->type) { 302 case AT_RELLINE: 303 if (linenum - cp->startline <= cp->a2->u.l) 304 r = 1; 305 else { 306 cp->startline = 0; 307 r = 0; 308 } 309 break; 310 default: 311 if (MATCH(cp->a2)) { 312 cp->startline = 0; 313 lastaddr = 1; 314 r = 1; 315 } else if (cp->a2->type == AT_LINE && 316 linenum > cp->a2->u.l) { 317 /* 318 * We missed the 2nd address due to a 319 * branch, so just close the range and 320 * return false. 321 */ 322 cp->startline = 0; 323 r = 0; 324 } else 325 r = 1; 326 } 327 } else if (cp->a1 && MATCH(cp->a1)) { 328 /* 329 * If the second address is a number less than or 330 * equal to the line number first selected, only 331 * one line shall be selected. 332 * -- POSIX 1003.2 333 * Likewise if the relative second line address is zero. 334 */ 335 if ((cp->a2->type == AT_LINE && 336 linenum >= cp->a2->u.l) || 337 (cp->a2->type == AT_RELLINE && cp->a2->u.l == 0)) 338 lastaddr = 1; 339 else { 340 cp->startline = linenum; 341 } 342 r = 1; 343 } else 344 r = 0; 345 else 346 r = MATCH(cp->a1); 347 return (cp->nonsel ? ! r : r); 348 } 349 350 /* 351 * Reset the sed processor to its initial state. 352 */ 353 void 354 resetstate(void) 355 { 356 struct s_command *cp; 357 358 /* 359 * Reset all in-range markers. 360 */ 361 for (cp = prog; cp; cp = cp->code == '{' ? cp->u.c : cp->next) 362 if (cp->a2) 363 cp->startline = 0; 364 365 /* 366 * Clear out the hold space. 367 */ 368 cspace(&HS, "", 0, REPLACE); 369 } 370 371 /* 372 * substitute -- 373 * Do substitutions in the pattern space. Currently, we build a 374 * copy of the new pattern space in the substitute space structure 375 * and then swap them. 376 */ 377 static int 378 substitute(struct s_command *cp) 379 { 380 SPACE tspace; 381 regex_t *re; 382 regoff_t slen; 383 int lastempty, n; 384 char *s; 385 386 s = ps; 387 re = cp->u.s->re; 388 if (re == NULL) { 389 if (defpreg != NULL && cp->u.s->maxbref > defpreg->re_nsub) { 390 linenum = cp->u.s->linenum; 391 errx(1, "%lu: %s: \\%u not defined in the RE", 392 linenum, fname, cp->u.s->maxbref); 393 } 394 } 395 if (!regexec_e(re, s, 0, 0, psl)) 396 return (0); 397 398 SS.len = 0; /* Clean substitute space. */ 399 slen = psl; 400 n = cp->u.s->n; 401 lastempty = 1; 402 403 do { 404 /* Copy the leading retained string. */ 405 if (n <= 1 && match[0].rm_so) 406 cspace(&SS, s, match[0].rm_so, APPEND); 407 408 /* Skip zero-length matches right after other matches. */ 409 if (lastempty || match[0].rm_so || 410 match[0].rm_so != match[0].rm_eo) { 411 if (n <= 1) { 412 /* Want this match: append replacement. */ 413 regsub(&SS, s, cp->u.s->new); 414 if (n == 1) 415 n = -1; 416 } else { 417 /* Want a later match: append original. */ 418 if (match[0].rm_eo) 419 cspace(&SS, s, match[0].rm_eo, APPEND); 420 n--; 421 } 422 } 423 424 /* Move past this match. */ 425 s += match[0].rm_eo; 426 slen -= match[0].rm_eo; 427 428 /* 429 * After a zero-length match, advance one byte, 430 * and at the end of the line, terminate. 431 */ 432 if (match[0].rm_so == match[0].rm_eo) { 433 if (*s == '\0' || *s == '\n') 434 slen = -1; 435 else 436 slen--; 437 if (*s != '\0') 438 cspace(&SS, s++, 1, APPEND); 439 lastempty = 1; 440 } else 441 lastempty = 0; 442 443 } while (n >= 0 && slen >= 0 && regexec_e(re, s, REG_NOTBOL, 0, slen)); 444 445 /* Did not find the requested number of matches. */ 446 if (n > 1) 447 return (0); 448 449 /* Copy the trailing retained string. */ 450 if (slen > 0) 451 cspace(&SS, s, slen, APPEND); 452 453 /* 454 * Swap the substitute space and the pattern space, and make sure 455 * that any leftover pointers into stdio memory get lost. 456 */ 457 tspace = PS; 458 PS = SS; 459 psanl = tspace.append_newline; 460 SS = tspace; 461 SS.space = SS.back; 462 463 /* Handle the 'p' flag. */ 464 if (cp->u.s->p) 465 OUT(); 466 467 /* Handle the 'w' flag. */ 468 if (cp->u.s->wfile && !pd) { 469 if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile, 470 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1) 471 err(1, "%s", cp->u.s->wfile); 472 if (write(cp->u.s->wfd, ps, psl) != (ssize_t)psl || 473 write(cp->u.s->wfd, "\n", 1) != 1) 474 err(1, "%s", cp->u.s->wfile); 475 } 476 return (1); 477 } 478 479 /* 480 * do_tr -- 481 * Perform translation ('y' command) in the pattern space. 482 */ 483 static void 484 do_tr(struct s_tr *y) 485 { 486 SPACE tmp; 487 char c, *p; 488 size_t clen, left; 489 int i; 490 491 if (MB_CUR_MAX == 1) { 492 /* 493 * Single-byte encoding: perform in-place translation 494 * of the pattern space. 495 */ 496 for (p = ps; p < &ps[psl]; p++) 497 *p = y->bytetab[(u_char)*p]; 498 } else { 499 /* 500 * Multi-byte encoding: perform translation into the 501 * translation space, then swap the translation and 502 * pattern spaces. 503 */ 504 /* Clean translation space. */ 505 YS.len = 0; 506 for (p = ps, left = psl; left > 0; p += clen, left -= clen) { 507 if ((c = y->bytetab[(u_char)*p]) != '\0') { 508 cspace(&YS, &c, 1, APPEND); 509 clen = 1; 510 continue; 511 } 512 for (i = 0; i < y->nmultis; i++) 513 if (left >= y->multis[i].fromlen && 514 memcmp(p, y->multis[i].from, 515 y->multis[i].fromlen) == 0) 516 break; 517 if (i < y->nmultis) { 518 cspace(&YS, y->multis[i].to, 519 y->multis[i].tolen, APPEND); 520 clen = y->multis[i].fromlen; 521 } else { 522 cspace(&YS, p, 1, APPEND); 523 clen = 1; 524 } 525 } 526 /* Swap the translation space and the pattern space. */ 527 tmp = PS; 528 PS = YS; 529 psanl = tmp.append_newline; 530 YS = tmp; 531 YS.space = YS.back; 532 } 533 } 534 535 /* 536 * Flush append requests. Always called before reading a line, 537 * therefore it also resets the substitution done (sdone) flag. 538 */ 539 static void 540 flush_appends(void) 541 { 542 FILE *f; 543 int count, i; 544 char buf[8 * 1024]; 545 546 for (i = 0; i < appendx; i++) 547 switch (appends[i].type) { 548 case AP_STRING: 549 fwrite(appends[i].s, sizeof(char), appends[i].len, 550 outfile); 551 break; 552 case AP_FILE: 553 /* 554 * Read files probably shouldn't be cached. Since 555 * it's not an error to read a non-existent file, 556 * it's possible that another program is interacting 557 * with the sed script through the filesystem. It 558 * would be truly bizarre, but possible. It's probably 559 * not that big a performance win, anyhow. 560 */ 561 if ((f = fopen(appends[i].s, "r")) == NULL) 562 break; 563 while ((count = fread(buf, sizeof(char), sizeof(buf), f))) 564 (void)fwrite(buf, sizeof(char), count, outfile); 565 (void)fclose(f); 566 break; 567 } 568 if (ferror(outfile)) 569 errx(1, "%s: %s", outfname, strerror(errno ? errno : EIO)); 570 appendx = sdone = 0; 571 } 572 573 static void 574 lputs(char *s, size_t len) 575 { 576 static const char escapes[] = "\\\a\b\f\r\t\v"; 577 int c, col, width; 578 const char *p; 579 struct winsize win; 580 static int termwidth = -1; 581 size_t clen, i; 582 wchar_t wc; 583 mbstate_t mbs; 584 585 if (outfile != stdout) 586 termwidth = 60; 587 if (termwidth == -1) { 588 if ((p = getenv("COLUMNS")) && *p != '\0') 589 termwidth = atoi(p); 590 else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 && 591 win.ws_col > 0) 592 termwidth = win.ws_col; 593 else 594 termwidth = 60; 595 } 596 if (termwidth <= 0) 597 termwidth = 1; 598 599 memset(&mbs, 0, sizeof(mbs)); 600 col = 0; 601 while (len != 0) { 602 clen = mbrtowc(&wc, s, len, &mbs); 603 if (clen == 0) 604 clen = 1; 605 if (clen == (size_t)-1 || clen == (size_t)-2) { 606 wc = (unsigned char)*s; 607 clen = 1; 608 memset(&mbs, 0, sizeof(mbs)); 609 } 610 if (wc == '\n') { 611 if (col + 1 >= termwidth) 612 fprintf(outfile, "\\\n"); 613 fputc('$', outfile); 614 fputc('\n', outfile); 615 col = 0; 616 } else if (iswprint(wc)) { 617 width = wcwidth(wc); 618 if (col + width >= termwidth) { 619 fprintf(outfile, "\\\n"); 620 col = 0; 621 } 622 fwrite(s, 1, clen, outfile); 623 col += width; 624 } else if (wc != L'\0' && (c = wctob(wc)) != EOF && 625 (p = strchr(escapes, c)) != NULL) { 626 if (col + 2 >= termwidth) { 627 fprintf(outfile, "\\\n"); 628 col = 0; 629 } 630 fprintf(outfile, "\\%c", "\\abfrtv"[p - escapes]); 631 col += 2; 632 } else { 633 if (col + 4 * clen >= (unsigned)termwidth) { 634 fprintf(outfile, "\\\n"); 635 col = 0; 636 } 637 for (i = 0; i < clen; i++) 638 fprintf(outfile, "\\%03o", 639 (int)(unsigned char)s[i]); 640 col += 4 * clen; 641 } 642 s += clen; 643 len -= clen; 644 } 645 if (col + 1 >= termwidth) 646 fprintf(outfile, "\\\n"); 647 (void)fputc('$', outfile); 648 (void)fputc('\n', outfile); 649 if (ferror(outfile)) 650 errx(1, "%s: %s", outfname, strerror(errno ? errno : EIO)); 651 } 652 653 static int 654 regexec_e(regex_t *preg, const char *string, int eflags, int nomatch, 655 size_t slen) 656 { 657 int eval; 658 659 if (preg == NULL) { 660 if (defpreg == NULL) 661 errx(1, "first RE may not be empty"); 662 } else 663 defpreg = preg; 664 665 /* Set anchors */ 666 match[0].rm_so = 0; 667 match[0].rm_eo = slen; 668 669 eval = regexec(defpreg, string, 670 nomatch ? 0 : maxnsub + 1, match, eflags | REG_STARTEND); 671 switch(eval) { 672 case 0: 673 return (1); 674 case REG_NOMATCH: 675 return (0); 676 } 677 errx(1, "RE error: %s", strregerror(eval, defpreg)); 678 /* NOTREACHED */ 679 } 680 681 /* 682 * regsub - perform substitutions after a regexp match 683 * Based on a routine by Henry Spencer 684 */ 685 static void 686 regsub(SPACE *sp, char *string, char *src) 687 { 688 int len, no; 689 char c, *dst; 690 691 #define NEEDSP(reqlen) \ 692 /* XXX What is the +1 for? */ \ 693 if (sp->len + (reqlen) + 1 >= sp->blen) { \ 694 sp->blen += (reqlen) + 1024; \ 695 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) \ 696 == NULL) \ 697 err(1, "realloc"); \ 698 dst = sp->space + sp->len; \ 699 } 700 701 dst = sp->space + sp->len; 702 while ((c = *src++) != '\0') { 703 if (c == '&') 704 no = 0; 705 else if (c == '\\' && isdigit((unsigned char)*src)) 706 no = *src++ - '0'; 707 else 708 no = -1; 709 if (no < 0) { /* Ordinary character. */ 710 if (c == '\\' && (*src == '\\' || *src == '&')) 711 c = *src++; 712 NEEDSP(1); 713 *dst++ = c; 714 ++sp->len; 715 } else if (match[no].rm_so != -1 && match[no].rm_eo != -1) { 716 len = match[no].rm_eo - match[no].rm_so; 717 NEEDSP(len); 718 memmove(dst, string + match[no].rm_so, len); 719 dst += len; 720 sp->len += len; 721 } 722 } 723 NEEDSP(1); 724 *dst = '\0'; 725 } 726 727 /* 728 * cspace -- 729 * Concatenate space: append the source space to the destination space, 730 * allocating new space as necessary. 731 */ 732 void 733 cspace(SPACE *sp, const char *p, size_t len, enum e_spflag spflag) 734 { 735 size_t tlen; 736 737 /* Make sure SPACE has enough memory and ramp up quickly. */ 738 tlen = sp->len + len + 1; 739 if (tlen > sp->blen) { 740 sp->blen = tlen + 1024; 741 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) == 742 NULL) 743 err(1, "realloc"); 744 } 745 746 if (spflag == REPLACE) 747 sp->len = 0; 748 749 memmove(sp->space + sp->len, p, len); 750 751 sp->space[sp->len += len] = '\0'; 752 } 753 754 /* 755 * Close all cached opened files and report any errors 756 */ 757 void 758 cfclose(struct s_command *cp, struct s_command *end) 759 { 760 761 for (; cp != end; cp = cp->next) 762 switch(cp->code) { 763 case 's': 764 if (cp->u.s->wfd != -1 && close(cp->u.s->wfd)) 765 err(1, "%s", cp->u.s->wfile); 766 cp->u.s->wfd = -1; 767 break; 768 case 'w': 769 if (cp->u.fd != -1 && close(cp->u.fd)) 770 err(1, "%s", cp->t); 771 cp->u.fd = -1; 772 break; 773 case '{': 774 cfclose(cp->u.c, cp->next); 775 break; 776 } 777 } 778