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