2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1992 Diomidis Spinellis.
5 * Copyright (c) 1992, 1993, 1994
6 * The Regents of the University of California. All rights reserved.
8 * This code is derived from software contributed to Berkeley by
9 * Diomidis Spinellis of Imperial College, University of London.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * @(#)process.c 8.6 (Berkeley) 4/20/94
36 * $FreeBSD: head/usr.bin/sed/process.c 338375 2018-08-29 17:09:03Z markj $
39 #include <sys/cdefs.h>
41 #include <sys/types.h>
43 #include <sys/ioctl.h>
62 static SPACE HS
, PS
, SS
, YS
;
66 #define psanl PS.append_newline
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,
76 static void regsub(SPACE
*, char *, char *);
77 static int substitute(struct s_command
*);
79 struct s_appends
*appends
; /* Array of pointers to strings to append. */
80 static unsigned int appendx
; /* Index into appends array. */
81 unsigned int appendnum
; /* Size of appends array. */
83 static int lastaddr
; /* Set by applies if last address of a range. */
84 static int sdone
; /* If any substitutes since last line input. */
85 /* Iov structure for 'w' commands. */
86 static regex_t
*defpreg
;
91 fwrite(ps, 1, psl, outfile); \
92 if (psanl) fputc('\n', outfile); \
105 oldpsanl
= oldpsl
= 0;
107 for (linenum
= 0; mf_fgets(&PS
, REPLACE
);) {
122 if (appendx
>= appendnum
)
123 if ((appends
= realloc(appends
,
124 sizeof(struct s_appends
) *
125 (appendnum
*= 2))) == NULL
)
127 appends
[appendx
].type
= AP_STRING
;
128 appends
[appendx
].s
= cp
->t
;
129 appends
[appendx
].len
= strlen(cp
->t
);
138 if (cp
->a2
== NULL
|| lastaddr
|| lastline())
139 (void)fprintf(outfile
, "%s", cp
->t
);
148 (p
= memchr(ps
, '\n', psl
)) == NULL
) {
153 memmove(ps
, p
+ 1, psl
);
157 cspace(&PS
, hs
, hsl
, REPLACE
);
160 cspace(&PS
, "\n", 1, APPEND
);
161 cspace(&PS
, hs
, hsl
, APPEND
);
164 cspace(&HS
, ps
, psl
, REPLACE
);
167 cspace(&HS
, "\n", 1, APPEND
);
168 cspace(&HS
, ps
, psl
, APPEND
);
171 (void)fprintf(outfile
, "%s", cp
->t
);
180 if (!mf_fgets(&PS
, REPLACE
))
186 cspace(&PS
, "\n", 1, APPEND
);
187 if (!mf_fgets(&PS
, APPEND
))
198 if ((p
= memchr(ps
, '\n', psl
)) != NULL
) {
211 if (inplace
== NULL
) {
220 if (appendx
>= appendnum
)
221 if ((appends
= realloc(appends
,
222 sizeof(struct s_appends
) *
223 (appendnum
*= 2))) == NULL
)
225 appends
[appendx
].type
= AP_FILE
;
226 appends
[appendx
].s
= cp
->t
;
227 appends
[appendx
].len
= strlen(cp
->t
);
231 sdone
|= substitute(cp
);
243 if (cp
->u
.fd
== -1 && (cp
->u
.fd
= open(cp
->t
,
244 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
,
247 if (write(cp
->u
.fd
, ps
, psl
) != (ssize_t
)psl
||
248 write(cp
->u
.fd
, "\n", 1) != 1)
253 * If the hold space is null, make it empty
254 * but not null. Otherwise the pattern space
255 * will become null after the swap, which is
256 * an abnormal condition.
259 cspace(&HS
, "", 0, REPLACE
);
262 psanl
= tspace
.append_newline
;
274 (void)fprintf(outfile
, "%lu\n", linenum
);
279 new: if (!nflag
&& !pd
)
282 } /* for all lines */
286 * TRUE if the address passed matches the current program state
287 * (lastline, linenumber, ps).
290 ((a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, 0, psl) : \
291 (a)->type == AT_LINE ? linenum == (a)->u.l : lastline())
294 * Return TRUE if the command applies to the current line. Sets the start
295 * line for process ranges. Interprets the non-select (``!'') flag.
298 applies(struct s_command
*cp
)
303 if (cp
->a1
== NULL
&& cp
->a2
== NULL
)
306 if (cp
->startline
> 0) {
307 switch (cp
->a2
->type
) {
309 if (linenum
- cp
->startline
<= cp
->a2
->u
.l
)
321 } else if (cp
->a2
->type
== AT_LINE
&&
322 linenum
> cp
->a2
->u
.l
) {
324 * We missed the 2nd address due to a
325 * branch, so just close the range and
333 } else if (cp
->a1
&& MATCH(cp
->a1
)) {
335 * If the second address is a number less than or
336 * equal to the line number first selected, only
337 * one line shall be selected.
339 * Likewise if the relative second line address is zero.
341 if ((cp
->a2
->type
== AT_LINE
&&
342 linenum
>= cp
->a2
->u
.l
) ||
343 (cp
->a2
->type
== AT_RELLINE
&& cp
->a2
->u
.l
== 0))
346 cp
->startline
= linenum
;
353 return (cp
->nonsel
? ! r
: r
);
357 * Reset the sed processor to its initial state.
362 struct s_command
*cp
;
365 * Reset all in-range markers.
367 for (cp
= prog
; cp
; cp
= cp
->code
== '{' ? cp
->u
.c
: cp
->next
)
372 * Clear out the hold space.
374 cspace(&HS
, "", 0, REPLACE
);
379 * Do substitutions in the pattern space. Currently, we build a
380 * copy of the new pattern space in the substitute space structure
381 * and then swap them.
384 substitute(struct s_command
*cp
)
396 if (defpreg
!= NULL
&& cp
->u
.s
->maxbref
> defpreg
->re_nsub
) {
397 linenum
= cp
->u
.s
->linenum
;
398 errx(1, "%lu: %s: \\%u not defined in the RE",
399 linenum
, fname
, cp
->u
.s
->maxbref
);
402 if (!regexec_e(re
, ps
, 0, 0, 0, psl
))
405 SS
.len
= 0; /* Clean substitute space. */
411 /* Copy the leading retained string. */
412 if (n
<= 1 && (match
[0].rm_so
> le
))
413 cspace(&SS
, s
, match
[0].rm_so
- le
, APPEND
);
415 /* Skip zero-length matches right after other matches. */
416 if (lastempty
|| (match
[0].rm_so
- le
) ||
417 match
[0].rm_so
!= match
[0].rm_eo
) {
419 /* Want this match: append replacement. */
420 regsub(&SS
, ps
, cp
->u
.s
->new);
424 /* Want a later match: append original. */
425 if (match
[0].rm_eo
- le
)
426 cspace(&SS
, s
, match
[0].rm_eo
- le
,
432 /* Move past this match. */
433 s
= ps
+ match
[0].rm_eo
;
434 slen
= psl
- match
[0].rm_eo
;
438 * After a zero-length match, advance one byte,
439 * and at the end of the line, terminate.
441 if (match
[0].rm_so
== match
[0].rm_eo
) {
442 if (*s
== '\0' || *s
== '\n')
447 cspace(&SS
, s
++, 1, APPEND
);
454 } while (n
>= 0 && slen
>= 0 &&
455 regexec_e(re
, ps
, REG_NOTBOL
, 0, le
, psl
));
457 /* Did not find the requested number of matches. */
461 /* Copy the trailing retained string. */
463 cspace(&SS
, s
, slen
, APPEND
);
466 * Swap the substitute space and the pattern space, and make sure
467 * that any leftover pointers into stdio memory get lost.
471 psanl
= tspace
.append_newline
;
475 /* Handle the 'p' flag. */
479 /* Handle the 'w' flag. */
480 if (cp
->u
.s
->wfile
&& !pd
) {
481 if (cp
->u
.s
->wfd
== -1 && (cp
->u
.s
->wfd
= open(cp
->u
.s
->wfile
,
482 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
, DEFFILEMODE
)) == -1)
483 err(1, "%s", cp
->u
.s
->wfile
);
484 if (write(cp
->u
.s
->wfd
, ps
, psl
) != (ssize_t
)psl
||
485 write(cp
->u
.s
->wfd
, "\n", 1) != 1)
486 err(1, "%s", cp
->u
.s
->wfile
);
493 * Perform translation ('y' command) in the pattern space.
496 do_tr(struct s_tr
*y
)
503 if (MB_CUR_MAX
== 1) {
505 * Single-byte encoding: perform in-place translation
506 * of the pattern space.
508 for (p
= ps
; p
< &ps
[psl
]; p
++)
509 *p
= y
->bytetab
[(u_char
)*p
];
512 * Multi-byte encoding: perform translation into the
513 * translation space, then swap the translation and
516 /* Clean translation space. */
518 for (p
= ps
, left
= psl
; left
> 0; p
+= clen
, left
-= clen
) {
519 if ((c
= y
->bytetab
[(u_char
)*p
]) != '\0') {
520 cspace(&YS
, &c
, 1, APPEND
);
524 for (i
= 0; i
< y
->nmultis
; i
++)
525 if (left
>= y
->multis
[i
].fromlen
&&
526 memcmp(p
, y
->multis
[i
].from
,
527 y
->multis
[i
].fromlen
) == 0)
529 if (i
< y
->nmultis
) {
530 cspace(&YS
, y
->multis
[i
].to
,
531 y
->multis
[i
].tolen
, APPEND
);
532 clen
= y
->multis
[i
].fromlen
;
534 cspace(&YS
, p
, 1, APPEND
);
538 /* Swap the translation space and the pattern space. */
541 psanl
= tmp
.append_newline
;
548 * Flush append requests. Always called before reading a line,
549 * therefore it also resets the substitution done (sdone) flag.
555 unsigned int count
, idx
;
558 for (idx
= 0; idx
< appendx
; idx
++)
559 switch (appends
[idx
].type
) {
561 fwrite(appends
[idx
].s
, sizeof(char), appends
[idx
].len
,
566 * Read files probably shouldn't be cached. Since
567 * it's not an error to read a non-existent file,
568 * it's possible that another program is interacting
569 * with the sed script through the filesystem. It
570 * would be truly bizarre, but possible. It's probably
571 * not that big a performance win, anyhow.
573 if ((f
= fopen(appends
[idx
].s
, "r")) == NULL
)
575 while ((count
= fread(buf
, sizeof(char), sizeof(buf
), f
)))
576 (void)fwrite(buf
, sizeof(char), count
, outfile
);
581 errx(1, "%s: %s", outfname
, strerror(errno
? errno
: EIO
));
586 lputs(char *s
, size_t len
)
588 static const char escapes
[] = "\\\a\b\f\r\t\v";
592 static int termwidth
= -1;
597 if (outfile
!= stdout
)
599 if (termwidth
== -1) {
600 if ((p
= getenv("COLUMNS")) && *p
!= '\0')
602 else if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &win
) == 0 &&
604 termwidth
= win
.ws_col
;
611 memset(&mbs
, 0, sizeof(mbs
));
614 clen
= mbrtowc(&wc
, s
, len
, &mbs
);
617 if (clen
== (size_t)-1 || clen
== (size_t)-2) {
618 wc
= (unsigned char)*s
;
620 memset(&mbs
, 0, sizeof(mbs
));
623 if (col
+ 1 >= termwidth
)
624 fprintf(outfile
, "\\\n");
626 fputc('\n', outfile
);
628 } else if (iswprint(wc
)) {
630 if (col
+ width
>= termwidth
) {
631 fprintf(outfile
, "\\\n");
634 fwrite(s
, 1, clen
, outfile
);
636 } else if (wc
!= L
'\0' && (c
= wctob(wc
)) != EOF
&&
637 (p
= strchr(escapes
, c
)) != NULL
) {
638 if (col
+ 2 >= termwidth
) {
639 fprintf(outfile
, "\\\n");
642 fprintf(outfile
, "\\%c", "\\abfrtv"[p
- escapes
]);
645 if (col
+ 4 * clen
>= (unsigned)termwidth
) {
646 fprintf(outfile
, "\\\n");
649 for (i
= 0; i
< clen
; i
++)
650 fprintf(outfile
, "\\%03o",
651 (int)(unsigned char)s
[i
]);
657 if (col
+ 1 >= termwidth
)
658 fprintf(outfile
, "\\\n");
659 (void)fputc('$', outfile
);
660 (void)fputc('\n', outfile
);
662 errx(1, "%s: %s", outfname
, strerror(errno
? errno
: EIO
));
666 regexec_e(regex_t
*preg
, const char *string
, int eflags
, int nomatch
,
667 size_t start
, size_t stop
)
673 errx(1, "first RE may not be empty");
678 match
[0].rm_so
= start
;
679 match
[0].rm_eo
= stop
;
681 eval
= regexec(defpreg
, string
,
682 nomatch
? 0 : maxnsub
+ 1, match
, eflags
| REG_STARTEND
);
689 errx(1, "RE error: %s", strregerror(eval
, defpreg
));
694 * regsub - perform substitutions after a regexp match
695 * Based on a routine by Henry Spencer
698 regsub(SPACE
*sp
, char *string
, char *src
)
703 #define NEEDSP(reqlen) \
704 /* XXX What is the +1 for? */ \
705 if (sp->len + (reqlen) + 1 >= sp->blen) { \
706 sp->blen += (reqlen) + 1024; \
707 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) \
710 dst = sp->space + sp->len; \
713 dst
= sp
->space
+ sp
->len
;
714 while ((c
= *src
++) != '\0') {
717 else if (c
== '\\' && isdigit((unsigned char)*src
))
721 if (no
< 0) { /* Ordinary character. */
722 if (c
== '\\' && (*src
== '\\' || *src
== '&'))
727 } else if (match
[no
].rm_so
!= -1 && match
[no
].rm_eo
!= -1) {
728 len
= match
[no
].rm_eo
- match
[no
].rm_so
;
730 memmove(dst
, string
+ match
[no
].rm_so
, len
);
741 * Concatenate space: append the source space to the destination space,
742 * allocating new space as necessary.
745 cspace(SPACE
*sp
, const char *p
, size_t len
, enum e_spflag spflag
)
749 /* Make sure SPACE has enough memory and ramp up quickly. */
750 tlen
= sp
->len
+ len
+ 1;
751 if (tlen
> sp
->blen
) {
752 sp
->blen
= tlen
+ 1024;
753 if ((sp
->space
= sp
->back
= realloc(sp
->back
, sp
->blen
)) ==
758 if (spflag
== REPLACE
)
761 memmove(sp
->space
+ sp
->len
, p
, len
);
763 sp
->space
[sp
->len
+= len
] = '\0';
767 * Close all cached opened files and report any errors
770 cfclose(struct s_command
*cp
, struct s_command
*end
)
773 for (; cp
!= end
; cp
= cp
->next
)
776 if (cp
->u
.s
->wfd
!= -1 && close(cp
->u
.s
->wfd
))
777 err(1, "%s", cp
->u
.s
->wfile
);
781 if (cp
->u
.fd
!= -1 && close(cp
->u
.fd
))
786 cfclose(cp
->u
.c
, cp
->next
);