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 * 3. 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: head/usr.bin/sed/process.c 277802 2015-01-27 18:58:24Z pfg $
37 #include <sys/types.h>
39 #include <sys/ioctl.h>
58 static SPACE HS
, PS
, SS
, YS
;
62 #define psanl PS.append_newline
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 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
;
86 fwrite(ps, 1, psl, outfile); \
87 if (psanl) fputc('\n', outfile); \
101 for (linenum
= 0; mf_fgets(&PS
, REPLACE
);) {
116 if (appendx
>= appendnum
)
117 if ((appends
= realloc(appends
,
118 sizeof(struct s_appends
) *
119 (appendnum
*= 2))) == NULL
)
121 appends
[appendx
].type
= AP_STRING
;
122 appends
[appendx
].s
= cp
->t
;
123 appends
[appendx
].len
= strlen(cp
->t
);
132 if (cp
->a2
== NULL
|| lastaddr
|| lastline())
133 (void)fprintf(outfile
, "%s", cp
->t
);
142 (p
= memchr(ps
, '\n', psl
)) == NULL
) {
147 memmove(ps
, p
+ 1, psl
);
151 cspace(&PS
, hs
, hsl
, REPLACE
);
154 cspace(&PS
, "\n", 1, APPEND
);
155 cspace(&PS
, hs
, hsl
, APPEND
);
158 cspace(&HS
, ps
, psl
, REPLACE
);
161 cspace(&HS
, "\n", 1, APPEND
);
162 cspace(&HS
, ps
, psl
, APPEND
);
165 (void)fprintf(outfile
, "%s", cp
->t
);
174 if (!mf_fgets(&PS
, REPLACE
))
180 cspace(&PS
, "\n", 1, APPEND
);
181 if (!mf_fgets(&PS
, APPEND
))
192 if ((p
= memchr(ps
, '\n', psl
)) != NULL
) {
210 if (appendx
>= appendnum
)
211 if ((appends
= realloc(appends
,
212 sizeof(struct s_appends
) *
213 (appendnum
*= 2))) == NULL
)
215 appends
[appendx
].type
= AP_FILE
;
216 appends
[appendx
].s
= cp
->t
;
217 appends
[appendx
].len
= strlen(cp
->t
);
221 sdone
|= substitute(cp
);
233 if (cp
->u
.fd
== -1 && (cp
->u
.fd
= open(cp
->t
,
234 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
,
237 if (write(cp
->u
.fd
, ps
, psl
) != (ssize_t
)psl
||
238 write(cp
->u
.fd
, "\n", 1) != 1)
243 * If the hold space is null, make it empty
244 * but not null. Otherwise the pattern space
245 * will become null after the swap, which is
246 * an abnormal condition.
249 cspace(&HS
, "", 0, REPLACE
);
252 psanl
= tspace
.append_newline
;
264 (void)fprintf(outfile
, "%lu\n", linenum
);
269 new: if (!nflag
&& !pd
)
272 } /* for all lines */
276 * TRUE if the address passed matches the current program state
277 * (lastline, linenumber, ps).
280 ((a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, psl) : \
281 (a)->type == AT_LINE ? linenum == (a)->u.l : lastline())
284 * Return TRUE if the command applies to the current line. Sets the start
285 * line for process ranges. Interprets the non-select (``!'') flag.
288 applies(struct s_command
*cp
)
293 if (cp
->a1
== NULL
&& cp
->a2
== NULL
)
296 if (cp
->startline
> 0) {
297 switch (cp
->a2
->type
) {
299 if (linenum
- cp
->startline
<= cp
->a2
->u
.l
)
311 } else if (cp
->a2
->type
== AT_LINE
&&
312 linenum
> cp
->a2
->u
.l
) {
314 * We missed the 2nd address due to a
315 * branch, so just close the range and
323 } else if (cp
->a1
&& MATCH(cp
->a1
)) {
325 * If the second address is a number less than or
326 * equal to the line number first selected, only
327 * one line shall be selected.
329 * Likewise if the relative second line address is zero.
331 if ((cp
->a2
->type
== AT_LINE
&&
332 linenum
>= cp
->a2
->u
.l
) ||
333 (cp
->a2
->type
== AT_RELLINE
&& cp
->a2
->u
.l
== 0))
336 cp
->startline
= linenum
;
343 return (cp
->nonsel
? ! r
: r
);
347 * Reset the sed processor to its initial state.
352 struct s_command
*cp
;
355 * Reset all in-range markers.
357 for (cp
= prog
; cp
; cp
= cp
->code
== '{' ? cp
->u
.c
: cp
->next
)
362 * Clear out the hold space.
364 cspace(&HS
, "", 0, REPLACE
);
369 * Do substitutions in the pattern space. Currently, we build a
370 * copy of the new pattern space in the substitute space structure
371 * and then swap them.
374 substitute(struct s_command
*cp
)
378 regoff_t re_off
, slen
;
385 if (defpreg
!= NULL
&& cp
->u
.s
->maxbref
> defpreg
->re_nsub
) {
386 linenum
= cp
->u
.s
->linenum
;
387 errx(1, "%lu: %s: \\%u not defined in the RE",
388 linenum
, fname
, cp
->u
.s
->maxbref
);
391 if (!regexec_e(re
, s
, 0, 0, psl
))
394 SS
.len
= 0; /* Clean substitute space. */
402 if (lastempty
|| match
[0].rm_so
!= match
[0].rm_eo
) {
403 /* Locate start of replaced string. */
404 re_off
= match
[0].rm_so
;
405 /* Copy leading retained string. */
406 cspace(&SS
, s
, re_off
, APPEND
);
407 /* Add in regular expression. */
408 regsub(&SS
, s
, cp
->u
.s
->new);
411 /* Move past this match. */
412 if (match
[0].rm_so
!= match
[0].rm_eo
) {
414 slen
-= match
[0].rm_eo
;
417 if (match
[0].rm_so
< slen
)
418 cspace(&SS
, s
+ match
[0].rm_so
, 1,
420 s
+= match
[0].rm_so
+ 1;
421 slen
-= match
[0].rm_so
+ 1;
424 } while (slen
>= 0 && regexec_e(re
, s
, REG_NOTBOL
, 0, slen
));
425 /* Copy trailing retained string. */
427 cspace(&SS
, s
, slen
, APPEND
);
429 default: /* Nth occurrence */
431 if (match
[0].rm_eo
== match
[0].rm_so
)
432 match
[0].rm_eo
= match
[0].rm_so
+ 1;
434 slen
-= match
[0].rm_eo
;
437 if (!regexec_e(re
, s
, REG_NOTBOL
, 0, slen
))
441 case 1: /* 1st occurrence */
442 /* Locate start of replaced string. */
443 re_off
= match
[0].rm_so
+ (s
- ps
);
444 /* Copy leading retained string. */
445 cspace(&SS
, ps
, re_off
, APPEND
);
446 /* Add in regular expression. */
447 regsub(&SS
, s
, cp
->u
.s
->new);
448 /* Copy trailing retained string. */
450 slen
-= match
[0].rm_eo
;
451 cspace(&SS
, s
, slen
, APPEND
);
456 * Swap the substitute space and the pattern space, and make sure
457 * that any leftover pointers into stdio memory get lost.
461 psanl
= tspace
.append_newline
;
465 /* Handle the 'p' flag. */
469 /* Handle the 'w' flag. */
470 if (cp
->u
.s
->wfile
&& !pd
) {
471 if (cp
->u
.s
->wfd
== -1 && (cp
->u
.s
->wfd
= open(cp
->u
.s
->wfile
,
472 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
, DEFFILEMODE
)) == -1)
473 err(1, "%s", cp
->u
.s
->wfile
);
474 if (write(cp
->u
.s
->wfd
, ps
, psl
) != (ssize_t
)psl
||
475 write(cp
->u
.s
->wfd
, "\n", 1) != 1)
476 err(1, "%s", cp
->u
.s
->wfile
);
483 * Perform translation ('y' command) in the pattern space.
486 do_tr(struct s_tr
*y
)
493 if (MB_CUR_MAX
== 1) {
495 * Single-byte encoding: perform in-place translation
496 * of the pattern space.
498 for (p
= ps
; p
< &ps
[psl
]; p
++)
499 *p
= y
->bytetab
[(u_char
)*p
];
502 * Multi-byte encoding: perform translation into the
503 * translation space, then swap the translation and
506 /* Clean translation space. */
508 for (p
= ps
, left
= psl
; left
> 0; p
+= clen
, left
-= clen
) {
509 if ((c
= y
->bytetab
[(u_char
)*p
]) != '\0') {
510 cspace(&YS
, &c
, 1, APPEND
);
514 for (i
= 0; i
< y
->nmultis
; i
++)
515 if (left
>= y
->multis
[i
].fromlen
&&
516 memcmp(p
, y
->multis
[i
].from
,
517 y
->multis
[i
].fromlen
) == 0)
519 if (i
< y
->nmultis
) {
520 cspace(&YS
, y
->multis
[i
].to
,
521 y
->multis
[i
].tolen
, APPEND
);
522 clen
= y
->multis
[i
].fromlen
;
524 cspace(&YS
, p
, 1, APPEND
);
528 /* Swap the translation space and the pattern space. */
531 psanl
= tmp
.append_newline
;
538 * Flush append requests. Always called before reading a line,
539 * therefore it also resets the substitution done (sdone) flag.
548 for (i
= 0; i
< appendx
; i
++)
549 switch (appends
[i
].type
) {
551 fwrite(appends
[i
].s
, sizeof(char), appends
[i
].len
,
556 * Read files probably shouldn't be cached. Since
557 * it's not an error to read a non-existent file,
558 * it's possible that another program is interacting
559 * with the sed script through the filesystem. It
560 * would be truly bizarre, but possible. It's probably
561 * not that big a performance win, anyhow.
563 if ((f
= fopen(appends
[i
].s
, "r")) == NULL
)
565 while ((count
= fread(buf
, sizeof(char), sizeof(buf
), f
)))
566 (void)fwrite(buf
, sizeof(char), count
, outfile
);
571 errx(1, "%s: %s", outfname
, strerror(errno
? errno
: EIO
));
576 lputs(char *s
, size_t len
)
578 static const char escapes
[] = "\\\a\b\f\r\t\v";
582 static int termwidth
= -1;
587 if (outfile
!= stdout
)
589 if (termwidth
== -1) {
590 if ((p
= getenv("COLUMNS")) && *p
!= '\0')
592 else if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &win
) == 0 &&
594 termwidth
= win
.ws_col
;
601 memset(&mbs
, 0, sizeof(mbs
));
604 clen
= mbrtowc(&wc
, s
, len
, &mbs
);
607 if (clen
== (size_t)-1 || clen
== (size_t)-2) {
608 wc
= (unsigned char)*s
;
610 memset(&mbs
, 0, sizeof(mbs
));
613 if (col
+ 1 >= termwidth
)
614 fprintf(outfile
, "\\\n");
616 fputc('\n', outfile
);
618 } else if (iswprint(wc
)) {
620 if (col
+ width
>= termwidth
) {
621 fprintf(outfile
, "\\\n");
624 fwrite(s
, 1, clen
, outfile
);
626 } else if (wc
!= L
'\0' && (c
= wctob(wc
)) != EOF
&&
627 (p
= strchr(escapes
, c
)) != NULL
) {
628 if (col
+ 2 >= termwidth
) {
629 fprintf(outfile
, "\\\n");
632 fprintf(outfile
, "\\%c", "\\abfrtv"[p
- escapes
]);
635 if (col
+ 4 * clen
>= (unsigned)termwidth
) {
636 fprintf(outfile
, "\\\n");
639 for (i
= 0; i
< clen
; i
++)
640 fprintf(outfile
, "\\%03o",
641 (int)(unsigned char)s
[i
]);
647 if (col
+ 1 >= termwidth
)
648 fprintf(outfile
, "\\\n");
649 (void)fputc('$', outfile
);
650 (void)fputc('\n', outfile
);
652 errx(1, "%s: %s", outfname
, strerror(errno
? errno
: EIO
));
656 regexec_e(regex_t
*preg
, const char *string
, int eflags
, int nomatch
,
663 errx(1, "first RE may not be empty");
669 match
[0].rm_eo
= slen
;
671 eval
= regexec(defpreg
, string
,
672 nomatch
? 0 : maxnsub
+ 1, match
, eflags
| REG_STARTEND
);
679 errx(1, "RE error: %s", strregerror(eval
, defpreg
));
684 * regsub - perform substitutions after a regexp match
685 * Based on a routine by Henry Spencer
688 regsub(SPACE
*sp
, char *string
, char *src
)
693 #define NEEDSP(reqlen) \
694 /* XXX What is the +1 for? */ \
695 if (sp->len + (reqlen) + 1 >= sp->blen) { \
696 sp->blen += (reqlen) + 1024; \
697 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) \
700 dst = sp->space + sp->len; \
703 dst
= sp
->space
+ sp
->len
;
704 while ((c
= *src
++) != '\0') {
707 else if (c
== '\\' && isdigit((unsigned char)*src
))
711 if (no
< 0) { /* Ordinary character. */
712 if (c
== '\\' && (*src
== '\\' || *src
== '&'))
717 } else if (match
[no
].rm_so
!= -1 && match
[no
].rm_eo
!= -1) {
718 len
= match
[no
].rm_eo
- match
[no
].rm_so
;
720 memmove(dst
, string
+ match
[no
].rm_so
, len
);
731 * Concatenate space: append the source space to the destination space,
732 * allocating new space as necessary.
735 cspace(SPACE
*sp
, const char *p
, size_t len
, enum e_spflag spflag
)
739 /* Make sure SPACE has enough memory and ramp up quickly. */
740 tlen
= sp
->len
+ len
+ 1;
741 if (tlen
> sp
->blen
) {
742 sp
->blen
= tlen
+ 1024;
743 if ((sp
->space
= sp
->back
= realloc(sp
->back
, sp
->blen
)) ==
748 if (spflag
== REPLACE
)
751 memmove(sp
->space
+ sp
->len
, p
, len
);
753 sp
->space
[sp
->len
+= len
] = '\0';
757 * Close all cached opened files and report any errors
760 cfclose(struct s_command
*cp
, struct s_command
*end
)
763 for (; cp
!= end
; cp
= cp
->next
)
766 if (cp
->u
.s
->wfd
!= -1 && close(cp
->u
.s
->wfd
))
767 err(1, "%s", cp
->u
.s
->wfile
);
771 if (cp
->u
.fd
!= -1 && close(cp
->u
.fd
))
776 cfclose(cp
->u
.c
, cp
->next
);