1 /* $NetBSD: process.c,v 1.52 2015/03/12 12:40:41 christos Exp $ */
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
36 #if HAVE_NBTOOL_CONFIG_H
37 #include "nbtool_config.h"
40 #include <sys/cdefs.h>
41 __RCSID("$NetBSD: process.c,v 1.52 2015/03/12 12:40:41 christos Exp $");
43 __FBSDID("$FreeBSD: head/usr.bin/sed/process.c 192732 2009-05-25 06:45:33Z brian $");
47 static const char sccsid
[] = "@(#)process.c 8.6 (Berkeley) 4/20/94";
50 #include <sys/types.h>
52 #include <sys/ioctl.h>
71 static SPACE HS
, PS
, SS
, YS
;
78 static __inline
int applies(struct s_command
*);
79 static void do_tr(struct s_tr
*);
80 static void flush_appends(void);
81 static void lputs(char *, size_t);
82 static __inline
int regexec_e(regex_t
*, const char *, int, int, size_t);
83 static void regsub(SPACE
*, char *, char *);
84 static int substitute(struct s_command
*);
86 struct s_appends
*appends
; /* Array of pointers to strings to append. */
87 static size_t appendx
; /* Index into appends array. */
88 size_t appendnum
; /* Size of appends array. */
90 static int lastaddr
; /* Set by applies if last address of a range. */
91 static int sdone
; /* If any substitutes since last line input. */
92 /* Iov structure for 'w' commands. */
93 static regex_t
*defpreg
;
97 #define OUT() do {fwrite(ps, 1, psl, outfile); fputc('\n', outfile);} while (0)
102 struct s_command
*cp
;
109 for (linenum
= 0; mf_fgets(&PS
, REPLACE
);) {
124 if (appendx
>= appendnum
)
125 appends
= xrealloc(appends
,
126 sizeof(struct s_appends
) *
128 appends
[appendx
].type
= AP_STRING
;
129 appends
[appendx
].s
= cp
->t
;
130 appends
[appendx
].len
= strlen(cp
->t
);
139 if (cp
->a2
== NULL
|| lastaddr
|| lastline())
140 (void)fprintf(outfile
, "%s", cp
->t
);
149 (p
= memchr(ps
, '\n', psl
- 1)) == NULL
) {
153 psl
-= (size_t)((p
+ 1) - ps
);
154 memmove(ps
, p
+ 1, psl
);
158 cspace(&PS
, hs
, hsl
, REPLACE
);
161 cspace(&PS
, "\n", 1, APPEND
);
162 cspace(&PS
, hs
, hsl
, APPEND
);
165 cspace(&HS
, ps
, psl
, REPLACE
);
168 cspace(&HS
, "\n", 1, APPEND
);
169 cspace(&HS
, ps
, psl
, APPEND
);
172 (void)fprintf(outfile
, "%s", cp
->t
);
181 if (!mf_fgets(&PS
, REPLACE
))
187 cspace(&PS
, "\n", 1, APPEND
);
188 if (!mf_fgets(&PS
, APPEND
))
199 if ((p
= memchr(ps
, '\n', psl
- 1)) != NULL
) {
201 psl
= (size_t)(p
- ps
);
213 if (appendx
>= appendnum
)
214 appends
= xrealloc(appends
,
215 sizeof(struct s_appends
) *
217 appends
[appendx
].type
= AP_FILE
;
218 appends
[appendx
].s
= cp
->t
;
219 appends
[appendx
].len
= strlen(cp
->t
);
223 sdone
|= substitute(cp
);
235 if (cp
->u
.fd
== -1 && (cp
->u
.fd
= open(cp
->t
,
236 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
,
239 if (write(cp
->u
.fd
, ps
, psl
) != (ssize_t
)psl
||
240 write(cp
->u
.fd
, "\n", 1) != 1)
245 * If the hold space is null, make it empty
246 * but not null. Otherwise the pattern space
247 * will become null after the swap, which is
248 * an abnormal condition.
251 cspace(&HS
, "", 0, REPLACE
);
265 (void)fprintf(outfile
, "%lu\n", linenum
);
270 new: if (!nflag
&& !pd
)
273 } /* for all lines */
277 * TRUE if the address passed matches the current program state
278 * (lastline, linenumber, ps).
281 ((a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, psl) : \
282 (a)->type == AT_LINE ? linenum == (a)->u.l : lastline())
285 * Return TRUE if the command applies to the current line. Sets the start
286 * line for process ranges. Interprets the non-select (``!'') flag.
289 applies(struct s_command
*cp
)
294 if (cp
->a1
== NULL
&& cp
->a2
== NULL
)
297 if (cp
->startline
> 0) {
298 switch (cp
->a2
->type
) {
300 if (linenum
- cp
->startline
<= cp
->a2
->u
.l
)
312 } else if (cp
->a2
->type
== AT_LINE
&&
313 linenum
> cp
->a2
->u
.l
) {
315 * We missed the 2nd address due to a
316 * branch, so just close the range and
324 } else if (cp
->a1
&& MATCH(cp
->a1
)) {
326 * If the second address is a number less than or
327 * equal to the line number first selected, only
328 * one line shall be selected.
330 * Likewise if the relative second line address is zero.
332 if ((cp
->a2
->type
== AT_LINE
&&
333 linenum
>= cp
->a2
->u
.l
) ||
334 (cp
->a2
->type
== AT_RELLINE
&& cp
->a2
->u
.l
== 0))
337 cp
->startline
= linenum
;
344 return (cp
->nonsel
? ! r
: r
);
348 * Reset the sed processor to its initial state.
353 struct s_command
*cp
;
356 * Reset all in-range markers.
358 for (cp
= prog
; cp
; cp
= cp
->code
== '{' ? cp
->u
.c
: cp
->next
)
363 * Clear out the hold space.
365 cspace(&HS
, "", 0, REPLACE
);
370 * Do substitutions in the pattern space. Currently, we build a
371 * copy of the new pattern space in the substitute space structure
372 * and then swap them.
375 substitute(struct s_command
*cp
)
379 regoff_t re_off
, slen
;
386 if (defpreg
!= NULL
&& cp
->u
.s
->maxbref
> defpreg
->re_nsub
) {
387 linenum
= cp
->u
.s
->linenum
;
388 errx(1, "%lu: %s: \\%u not defined in the RE",
389 linenum
, fname
, cp
->u
.s
->maxbref
);
392 if (!regexec_e(re
, s
, 0, 0, psl
))
395 SS
.len
= 0; /* Clean substitute space. */
396 slen
= (regoff_t
)psl
;
403 if (lastempty
|| match
[0].rm_so
!= match
[0].rm_eo
) {
404 /* Locate start of replaced string. */
405 re_off
= match
[0].rm_so
;
406 /* Copy leading retained string. */
407 cspace(&SS
, s
, (size_t)re_off
, APPEND
);
408 /* Add in regular expression. */
409 regsub(&SS
, s
, cp
->u
.s
->new);
412 /* Move past this match. */
413 if (match
[0].rm_so
!= match
[0].rm_eo
) {
415 slen
-= match
[0].rm_eo
;
418 if (match
[0].rm_so
< slen
)
419 cspace(&SS
, s
+ match
[0].rm_so
, 1,
421 s
+= match
[0].rm_so
+ 1;
422 slen
-= match
[0].rm_so
+ 1;
425 } while (slen
>= 0 && regexec_e(re
, s
, REG_NOTBOL
, 0, (size_t)slen
));
426 /* Copy trailing retained string. */
428 cspace(&SS
, s
, (size_t)slen
, APPEND
);
430 default: /* Nth occurrence */
432 if (match
[0].rm_eo
== match
[0].rm_so
)
433 match
[0].rm_eo
= match
[0].rm_so
+ 1;
435 slen
-= match
[0].rm_eo
;
438 if (!regexec_e(re
, s
, REG_NOTBOL
, 0, (size_t)slen
))
442 case 1: /* 1st occurrence */
443 /* Locate start of replaced string. */
444 re_off
= match
[0].rm_so
+ (s
- ps
);
445 /* Copy leading retained string. */
446 cspace(&SS
, ps
, (size_t)re_off
, APPEND
);
447 /* Add in regular expression. */
448 regsub(&SS
, s
, cp
->u
.s
->new);
449 /* Copy trailing retained string. */
451 slen
-= match
[0].rm_eo
;
452 cspace(&SS
, s
, (size_t)slen
, APPEND
);
457 * Swap the substitute space and the pattern space, and make sure
458 * that any leftover pointers into stdio memory get lost.
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
= (char)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
= (char)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. */
537 * Flush append requests. Always called before reading a line,
538 * therefore it also resets the substitution done (sdone) flag.
547 for (i
= 0; i
< appendx
; i
++)
548 switch (appends
[i
].type
) {
550 fwrite(appends
[i
].s
, sizeof(char), appends
[i
].len
,
555 * Read files probably shouldn't be cached. Since
556 * it's not an error to read a non-existent file,
557 * it's possible that another program is interacting
558 * with the sed script through the filesystem. It
559 * would be truly bizarre, but possible. It's probably
560 * not that big a performance win, anyhow.
562 if ((f
= fopen(appends
[i
].s
, "r")) == NULL
)
564 while ((count
= fread(buf
, sizeof(char), sizeof(buf
), f
)))
565 (void)fwrite(buf
, sizeof(char), count
, outfile
);
570 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";
585 static size_t termwidth
= (size_t)-1;
590 if (outfile
!= stdout
)
592 if (termwidth
== (size_t)-1) {
593 if ((p
= getenv("COLUMNS")) && *p
!= '\0')
594 termwidth
= (size_t)atoi(p
);
596 else if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &win
) == 0 &&
598 termwidth
= win
.ws_col
;
606 memset(&mbs
, 0, sizeof(mbs
));
609 clen
= mbrtowc(&wc
, s
, len
, &mbs
);
612 if (clen
== (size_t)-1 || clen
== (size_t)-2) {
613 wc
= (unsigned char)*s
;
615 memset(&mbs
, 0, sizeof(mbs
));
618 if (col
+ 1 >= termwidth
)
619 fprintf(outfile
, "\\\n");
621 fputc('\n', outfile
);
623 } else if (iswprint(wc
)) {
624 width
= (size_t)wcwidth(wc
);
625 if (col
+ width
>= termwidth
) {
626 fprintf(outfile
, "\\\n");
629 fwrite(s
, 1, clen
, outfile
);
631 } else if (wc
!= L
'\0' && (c
= wctob(wc
)) != EOF
&&
632 (p
= strchr(escapes
, c
)) != NULL
) {
633 if (col
+ 2 >= termwidth
) {
634 fprintf(outfile
, "\\\n");
637 fprintf(outfile
, "\\%c", "\\abfrtv"[p
- escapes
]);
640 if (col
+ 4 * clen
>= termwidth
) {
641 fprintf(outfile
, "\\\n");
644 for (i
= 0; i
< clen
; i
++)
645 fprintf(outfile
, "\\%03o",
646 (int)(unsigned char)s
[i
]);
652 if (col
+ 1 >= termwidth
)
653 fprintf(outfile
, "\\\n");
654 (void)fputc('$', outfile
);
655 (void)fputc('\n', outfile
);
657 errx(1, "%s: %s", outfname
, strerror(errno
? errno
: EIO
));
661 regexec_e(regex_t
*preg
, const char *string
, int eflags
, int nomatch
,
671 errx(1, "first RE may not be empty");
677 buf
= xmalloc(slen
+ 1);
678 (void)memcpy(buf
, string
, slen
);
680 eval
= regexec(defpreg
, buf
,
681 nomatch
? 0 : maxnsub
+ 1, match
, eflags
);
685 match
[0].rm_eo
= (regoff_t
)slen
;
686 eval
= regexec(defpreg
, string
,
687 nomatch
? 0 : maxnsub
+ 1, match
, eflags
| REG_STARTEND
);
695 errx(1, "RE error: %s", strregerror(eval
, defpreg
));
700 * regsub - perform substitutions after a regexp match
701 * Based on a routine by Henry Spencer
704 regsub(SPACE
*sp
, char *string
, char *src
)
710 #define NEEDSP(reqlen) \
711 /* XXX What is the +1 for? */ \
712 if (sp->len + (reqlen) + 1 >= sp->blen) { \
713 sp->blen += (reqlen) + 1024; \
714 sp->space = sp->back = xrealloc(sp->back, sp->blen); \
715 dst = sp->space + sp->len; \
718 dst
= sp
->space
+ sp
->len
;
719 while ((c
= *src
++) != '\0') {
722 else if (c
== '\\' && isdigit((unsigned char)*src
))
726 if (no
< 0) { /* Ordinary character. */
727 if (c
== '\\' && (*src
== '\\' || *src
== '&'))
732 } else if (match
[no
].rm_so
!= -1 && match
[no
].rm_eo
!= -1) {
733 len
= (size_t)(match
[no
].rm_eo
- match
[no
].rm_so
);
735 memmove(dst
, string
+ match
[no
].rm_so
, len
);
746 * Concatenate space: append the source space to the destination space,
747 * allocating new space as necessary.
750 cspace(SPACE
*sp
, const char *p
, size_t len
, enum e_spflag spflag
)
754 /* Make sure SPACE has enough memory and ramp up quickly. */
755 tlen
= sp
->len
+ len
+ 1;
756 if (tlen
> sp
->blen
) {
757 sp
->blen
= tlen
+ 1024;
758 sp
->space
= sp
->back
= xrealloc(sp
->back
, sp
->blen
);
761 if (spflag
== REPLACE
)
764 memmove(sp
->space
+ sp
->len
, p
, len
);
766 sp
->space
[sp
->len
+= len
] = '\0';
770 * Close all cached opened files and report any errors
773 cfclose(struct s_command
*cp
, struct s_command
*end
)
776 for (; cp
!= end
; cp
= cp
->next
)
779 if (cp
->u
.s
->wfd
!= -1 && close(cp
->u
.s
->wfd
))
780 err(1, "%s", cp
->u
.s
->wfile
);
784 if (cp
->u
.fd
!= -1 && close(cp
->u
.fd
))
789 cfclose(cp
->u
.c
, cp
->next
);