2 * Copyright (c) 1992 Diomidis Spinellis.
3 * Copyright (c) 1992, 1993, 1994
4 * The Regents of the University of California. All rights reserved.
6 * This code is derived from software contributed to Berkeley by
7 * Diomidis Spinellis of Imperial College, University of London.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
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.
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
33 * @(#)process.c 8.6 (Berkeley) 4/20/94
34 * $FreeBSD: src/usr.bin/sed/process.c,v 1.50 2009/05/25 06:45:33 brian Exp $
35 * $DragonFly: src/usr.bin/sed/process.c,v 1.6 2008/04/08 13:23:38 swildner Exp $
38 #include <sys/types.h>
40 #include <sys/ioctl.h>
59 static SPACE HS
, PS
, SS
, YS
;
66 static __inline
int applies(struct s_command
*);
67 static void do_tr(struct s_tr
*);
68 static void flush_appends(void);
69 static void lputs(char *, size_t);
70 static __inline
int regexec_e(regex_t
*, const char *, int, int, size_t);
71 static void regsub(SPACE
*, char *, char *);
72 static int substitute(struct s_command
*);
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. */
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
;
85 #define OUT() do {fwrite(ps, 1, psl, outfile); fputc('\n', outfile);} while (0)
97 for (linenum
= 0; mf_fgets(&PS
, REPLACE
);) {
112 if (appendx
>= appendnum
)
113 if ((appends
= realloc(appends
,
114 sizeof(struct s_appends
) *
115 (appendnum
*= 2))) == NULL
)
117 appends
[appendx
].type
= AP_STRING
;
118 appends
[appendx
].s
= cp
->t
;
119 appends
[appendx
].len
= strlen(cp
->t
);
128 if (cp
->a2
== NULL
|| lastaddr
|| lastline())
129 (void)fprintf(outfile
, "%s", cp
->t
);
138 (p
= memchr(ps
, '\n', psl
)) == NULL
) {
143 memmove(ps
, p
+ 1, psl
);
147 cspace(&PS
, hs
, hsl
, REPLACE
);
150 cspace(&PS
, "\n", 1, APPEND
);
151 cspace(&PS
, hs
, hsl
, APPEND
);
154 cspace(&HS
, ps
, psl
, REPLACE
);
157 cspace(&HS
, "\n", 1, APPEND
);
158 cspace(&HS
, ps
, psl
, APPEND
);
161 (void)fprintf(outfile
, "%s", cp
->t
);
170 if (!mf_fgets(&PS
, REPLACE
))
176 cspace(&PS
, "\n", 1, APPEND
);
177 if (!mf_fgets(&PS
, APPEND
))
188 if ((p
= memchr(ps
, '\n', psl
)) != NULL
) {
202 if (appendx
>= appendnum
)
203 if ((appends
= realloc(appends
,
204 sizeof(struct s_appends
) *
205 (appendnum
*= 2))) == NULL
)
207 appends
[appendx
].type
= AP_FILE
;
208 appends
[appendx
].s
= cp
->t
;
209 appends
[appendx
].len
= strlen(cp
->t
);
213 sdone
|= substitute(cp
);
225 if (cp
->u
.fd
== -1 && (cp
->u
.fd
= open(cp
->t
,
226 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
,
229 if (write(cp
->u
.fd
, ps
, psl
) != (ssize_t
)psl
||
230 write(cp
->u
.fd
, "\n", 1) != 1)
235 * If the hold space is null, make it empty
236 * but not null. Otherwise the pattern space
237 * will become null after the swap, which is
238 * an abnormal condition.
241 cspace(&HS
, "", 0, REPLACE
);
255 (void)fprintf(outfile
, "%lu\n", linenum
);
260 new: if (!nflag
&& !pd
)
263 } /* for all lines */
267 * TRUE if the address passed matches the current program state
268 * (lastline, linenumber, ps).
271 ((a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, psl) : \
272 (a)->type == AT_LINE ? linenum == (a)->u.l : lastline())
275 * Return TRUE if the command applies to the current line. Sets the start
276 * line for process ranges. Interprets the non-select (``!'') flag.
279 applies(struct s_command
*cp
)
284 if (cp
->a1
== NULL
&& cp
->a2
== NULL
)
287 if (cp
->startline
> 0) {
292 } else if (linenum
- cp
->startline
<= cp
->a2
->u
.l
)
294 else if ((cp
->a2
->type
== AT_LINE
&&
295 linenum
> cp
->a2
->u
.l
) ||
296 (cp
->a2
->type
== AT_RELLINE
&&
297 linenum
- cp
->startline
> cp
->a2
->u
.l
)) {
299 * We missed the 2nd address due to a branch,
300 * so just close the range and return false.
306 } else if (MATCH(cp
->a1
)) {
308 * If the second address is a number less than or
309 * equal to the line number first selected, only
310 * one line shall be selected.
312 * Likewise if the relative second line address is zero.
314 if ((cp
->a2
->type
== AT_LINE
&&
315 linenum
>= cp
->a2
->u
.l
) ||
316 (cp
->a2
->type
== AT_RELLINE
&& cp
->a2
->u
.l
== 0))
319 cp
->startline
= linenum
;
326 return (cp
->nonsel
? ! r
: r
);
330 * Reset the sed processor to its initial state.
335 struct s_command
*cp
;
338 * Reset all in-range markers.
340 for (cp
= prog
; cp
; cp
= cp
->code
== '{' ? cp
->u
.c
: cp
->next
)
345 * Clear out the hold space.
347 cspace(&HS
, "", 0, REPLACE
);
352 * Do substitutions in the pattern space. Currently, we build a
353 * copy of the new pattern space in the substitute space structure
354 * and then swap them.
357 substitute(struct s_command
*cp
)
361 regoff_t re_off
, slen
;
368 if (defpreg
!= NULL
&& cp
->u
.s
->maxbref
> defpreg
->re_nsub
) {
369 linenum
= cp
->u
.s
->linenum
;
370 errx(1, "%lu: %s: \\%u not defined in the RE",
371 linenum
, fname
, cp
->u
.s
->maxbref
);
374 if (!regexec_e(re
, s
, 0, 0, psl
))
377 SS
.len
= 0; /* Clean substitute space. */
385 if (lastempty
|| match
[0].rm_so
!= match
[0].rm_eo
) {
386 /* Locate start of replaced string. */
387 re_off
= match
[0].rm_so
;
388 /* Copy leading retained string. */
389 cspace(&SS
, s
, re_off
, APPEND
);
390 /* Add in regular expression. */
391 regsub(&SS
, s
, cp
->u
.s
->new);
394 /* Move past this match. */
395 if (match
[0].rm_so
!= match
[0].rm_eo
) {
397 slen
-= match
[0].rm_eo
;
400 if (match
[0].rm_so
< slen
)
401 cspace(&SS
, s
+ match
[0].rm_so
, 1,
403 s
+= match
[0].rm_so
+ 1;
404 slen
-= match
[0].rm_so
+ 1;
407 } while (slen
>= 0 && regexec_e(re
, s
, REG_NOTBOL
, 0, slen
));
408 /* Copy trailing retained string. */
410 cspace(&SS
, s
, slen
, APPEND
);
412 default: /* Nth occurrence */
414 if (match
[0].rm_eo
== match
[0].rm_so
)
415 match
[0].rm_eo
= match
[0].rm_so
+ 1;
417 slen
-= match
[0].rm_eo
;
420 if (!regexec_e(re
, s
, REG_NOTBOL
, 0, slen
))
424 case 1: /* 1st occurrence */
425 /* Locate start of replaced string. */
426 re_off
= match
[0].rm_so
+ (s
- ps
);
427 /* Copy leading retained string. */
428 cspace(&SS
, ps
, re_off
, APPEND
);
429 /* Add in regular expression. */
430 regsub(&SS
, s
, cp
->u
.s
->new);
431 /* Copy trailing retained string. */
433 slen
-= match
[0].rm_eo
;
434 cspace(&SS
, s
, slen
, APPEND
);
439 * Swap the substitute space and the pattern space, and make sure
440 * that any leftover pointers into stdio memory get lost.
447 /* Handle the 'p' flag. */
451 /* Handle the 'w' flag. */
452 if (cp
->u
.s
->wfile
&& !pd
) {
453 if (cp
->u
.s
->wfd
== -1 && (cp
->u
.s
->wfd
= open(cp
->u
.s
->wfile
,
454 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
, DEFFILEMODE
)) == -1)
455 err(1, "%s", cp
->u
.s
->wfile
);
456 if (write(cp
->u
.s
->wfd
, ps
, psl
) != (ssize_t
)psl
||
457 write(cp
->u
.s
->wfd
, "\n", 1) != 1)
458 err(1, "%s", cp
->u
.s
->wfile
);
465 * Perform translation ('y' command) in the pattern space.
468 do_tr(struct s_tr
*y
)
475 if (MB_CUR_MAX
== 1) {
477 * Single-byte encoding: perform in-place translation
478 * of the pattern space.
480 for (p
= ps
; p
< &ps
[psl
]; p
++)
481 *p
= y
->bytetab
[(u_char
)*p
];
484 * Multi-byte encoding: perform translation into the
485 * translation space, then swap the translation and
488 /* Clean translation space. */
490 for (p
= ps
, left
= psl
; left
> 0; p
+= clen
, left
-= clen
) {
491 if ((c
= y
->bytetab
[(u_char
)*p
]) != '\0') {
492 cspace(&YS
, &c
, 1, APPEND
);
496 for (i
= 0; i
< y
->nmultis
; i
++)
497 if (left
>= y
->multis
[i
].fromlen
&&
498 memcmp(p
, y
->multis
[i
].from
,
499 y
->multis
[i
].fromlen
) == 0)
501 if (i
< y
->nmultis
) {
502 cspace(&YS
, y
->multis
[i
].to
,
503 y
->multis
[i
].tolen
, APPEND
);
504 clen
= y
->multis
[i
].fromlen
;
506 cspace(&YS
, p
, 1, APPEND
);
510 /* Swap the translation space and the pattern space. */
519 * Flush append requests. Always called before reading a line,
520 * therefore it also resets the substitution done (sdone) flag.
529 for (i
= 0; i
< appendx
; i
++)
530 switch (appends
[i
].type
) {
532 fwrite(appends
[i
].s
, sizeof(char), appends
[i
].len
,
537 * Read files probably shouldn't be cached. Since
538 * it's not an error to read a non-existent file,
539 * it's possible that another program is interacting
540 * with the sed script through the filesystem. It
541 * would be truly bizarre, but possible. It's probably
542 * not that big a performance win, anyhow.
544 if ((f
= fopen(appends
[i
].s
, "r")) == NULL
)
546 while ((count
= fread(buf
, sizeof(char), sizeof(buf
), f
)))
547 (void)fwrite(buf
, sizeof(char), count
, outfile
);
552 errx(1, "%s: %s", outfname
, strerror(errno
? errno
: EIO
));
557 lputs(char *s
, size_t len
)
559 static const char escapes
[] = "\\\a\b\f\r\t\v";
563 static int termwidth
= -1;
568 if (outfile
!= stdout
)
570 if (termwidth
== -1) {
571 if ((p
= getenv("COLUMNS")) && *p
!= '\0')
573 else if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &win
) == 0 &&
575 termwidth
= win
.ws_col
;
582 memset(&mbs
, 0, sizeof(mbs
));
585 clen
= mbrtowc(&wc
, s
, len
, &mbs
);
588 if (clen
== (size_t)-1 || clen
== (size_t)-2) {
589 wc
= (unsigned char)*s
;
591 memset(&mbs
, 0, sizeof(mbs
));
594 if (col
+ 1 >= termwidth
)
595 fprintf(outfile
, "\\\n");
597 fputc('\n', outfile
);
599 } else if (iswprint(wc
)) {
601 if (col
+ width
>= termwidth
) {
602 fprintf(outfile
, "\\\n");
605 fwrite(s
, 1, clen
, outfile
);
607 } else if (wc
!= L
'\0' && (c
= wctob(wc
)) != EOF
&&
608 (p
= strchr(escapes
, c
)) != NULL
) {
609 if (col
+ 2 >= termwidth
) {
610 fprintf(outfile
, "\\\n");
613 fprintf(outfile
, "\\%c", "\\abfrtv"[p
- escapes
]);
616 if (col
+ 4 * clen
>= (unsigned)termwidth
) {
617 fprintf(outfile
, "\\\n");
620 for (i
= 0; i
< clen
; i
++)
621 fprintf(outfile
, "\\%03o",
622 (int)(unsigned char)s
[i
]);
628 if (col
+ 1 >= termwidth
)
629 fprintf(outfile
, "\\\n");
630 (void)fputc('$', outfile
);
631 (void)fputc('\n', outfile
);
633 errx(1, "%s: %s", outfname
, strerror(errno
? errno
: EIO
));
637 regexec_e(regex_t
*preg
, const char *string
, int eflags
, int nomatch
,
644 errx(1, "first RE may not be empty");
650 match
[0].rm_eo
= slen
;
652 eval
= regexec(defpreg
, string
,
653 nomatch
? 0 : maxnsub
+ 1, match
, eflags
| REG_STARTEND
);
660 errx(1, "RE error: %s", strregerror(eval
, defpreg
));
665 * regsub - perform substitutions after a regexp match
666 * Based on a routine by Henry Spencer
669 regsub(SPACE
*sp
, char *string
, char *src
)
674 #define NEEDSP(reqlen) \
675 /* XXX What is the +1 for? */ \
676 if (sp->len + (reqlen) + 1 >= sp->blen) { \
677 sp->blen += (reqlen) + 1024; \
678 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) \
681 dst = sp->space + sp->len; \
684 dst
= sp
->space
+ sp
->len
;
685 while ((c
= *src
++) != '\0') {
688 else if (c
== '\\' && isdigit((unsigned char)*src
))
692 if (no
< 0) { /* Ordinary character. */
693 if (c
== '\\' && (*src
== '\\' || *src
== '&'))
698 } else if (match
[no
].rm_so
!= -1 && match
[no
].rm_eo
!= -1) {
699 len
= match
[no
].rm_eo
- match
[no
].rm_so
;
701 memmove(dst
, string
+ match
[no
].rm_so
, len
);
712 * Concatenate space: append the source space to the destination space,
713 * allocating new space as necessary.
716 cspace(SPACE
*sp
, const char *p
, size_t len
, enum e_spflag spflag
)
720 /* Make sure SPACE has enough memory and ramp up quickly. */
721 tlen
= sp
->len
+ len
+ 1;
722 if (tlen
> sp
->blen
) {
723 sp
->blen
= tlen
+ 1024;
724 if ((sp
->space
= sp
->back
= realloc(sp
->back
, sp
->blen
)) ==
729 if (spflag
== REPLACE
)
732 memmove(sp
->space
+ sp
->len
, p
, len
);
734 sp
->space
[sp
->len
+= len
] = '\0';
738 * Close all cached opened files and report any errors
741 cfclose(struct s_command
*cp
, struct s_command
*end
)
744 for (; cp
!= end
; cp
= cp
->next
)
747 if (cp
->u
.s
->wfd
!= -1 && close(cp
->u
.s
->wfd
))
748 err(1, "%s", cp
->u
.s
->wfile
);
752 if (cp
->u
.fd
!= -1 && close(cp
->u
.fd
))
757 cfclose(cp
->u
.c
, cp
->next
);