1 /* $OpenBSD: process.c,v 1.32 2017/02/22 14:09:09 tom Exp $ */
5 * mirabilos <m@mirbsd.org>
6 * Copyright (c) 1992 Diomidis Spinellis.
7 * Copyright (c) 1992, 1993
8 * The Regents of the University of California. All rights reserved.
10 * This code is derived from software contributed to Berkeley by
11 * Diomidis Spinellis of Imperial College, University of London.
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 * 3. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 #include <sys/types.h>
42 __SCCSID("@(#)process.c 8.1 (Berkeley) 6/6/93");
43 __RCSID("$MirOS: src/usr.bin/sed/process.c,v 1.5 2017/11/20 01:23:57 tg Exp $");
58 static SPACE HS
, PS
, SS
;
62 #define psanl PS.append_newline
66 static inline int applies(struct s_command
*);
67 static void flush_appends(void);
68 static void lputs(char *);
69 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 size_t appendx
; /* Index into appends array. */
76 size_t 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);\
98 for (linenum
= 0; mf_fgets(&PS
, REPLACE
);) {
113 if (appendx
>= appendnum
) {
114 appends
= xreallocarray(appends
,
116 2 * sizeof(struct s_appends
));
119 appends
[appendx
].type
= AP_STRING
;
120 appends
[appendx
].s
= cp
->t
;
121 appends
[appendx
].len
= strlen(cp
->t
);
130 if (cp
->a2
== NULL
|| lastaddr
|| lastline())
131 (void)fprintf(outfile
, "%s", cp
->t
);
140 (p
= memchr(ps
, '\n', psl
)) == NULL
) {
145 memmove(ps
, p
+ 1, psl
);
149 cspace(&PS
, hs
, hsl
, REPLACE
);
152 cspace(&PS
, "\n", 1, 0);
153 cspace(&PS
, hs
, hsl
, 0);
156 cspace(&HS
, ps
, psl
, REPLACE
);
159 cspace(&HS
, "\n", 1, 0);
160 cspace(&HS
, ps
, psl
, 0);
163 (void)fprintf(outfile
, "%s", cp
->t
);
172 if (!mf_fgets(&PS
, REPLACE
))
178 cspace(&PS
, "\n", 1, 0);
179 if (!mf_fgets(&PS
, 0))
190 if ((p
= memchr(ps
, '\n', psl
)) != NULL
) {
206 if (appendx
>= appendnum
) {
207 appends
= xreallocarray(appends
,
209 2 * sizeof(struct s_appends
));
212 appends
[appendx
].type
= AP_FILE
;
213 appends
[appendx
].s
= cp
->t
;
214 appends
[appendx
].len
= strlen(cp
->t
);
218 sdone
|= substitute(cp
);
230 if (cp
->u
.fd
== -1 && (cp
->u
.fd
= open(cp
->t
,
231 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
,
233 error(FATAL
, "%s: %s",
234 cp
->t
, strerror(errno
));
235 if ((size_t)write(cp
->u
.fd
, ps
, psl
) != psl
||
236 write(cp
->u
.fd
, "\n", 1) != 1)
237 error(FATAL
, "%s: %s",
238 cp
->t
, strerror(errno
));
242 cspace(&HS
, "", 0, REPLACE
);
245 psanl
= tspace
.append_newline
;
251 for (p
= ps
, len
= psl
; len
--; ++p
)
252 *p
= cp
->u
.y
[(unsigned char)*p
];
258 (void)fprintf(outfile
, "%lu\n", linenum
);
263 new: if (!nflag
&& !pd
)
266 } /* for all lines */
270 * TRUE if the address passed matches the current program state
271 * (lastline, linenumber, ps).
274 (a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, 0, psl) : \
275 (a)->type == AT_LINE ? linenum == (a)->u.l : lastline()
278 * Return TRUE if the command applies to the current line. Sets the inrange
279 * flag to process ranges. Interprets the non-select (``!'') flag.
282 applies(struct s_command
*cp
)
287 if (cp
->a1
== NULL
&& cp
->a2
== NULL
)
296 } else if (MATCH(cp
->a1
)) {
298 * If the second address is a number less than or
299 * equal to the line number first selected, only
300 * one line shall be selected.
303 if (cp
->a2
->type
== AT_LINE
&&
304 linenum
>= cp
->a2
->u
.l
)
313 return (cp
->nonsel
? !r
: r
);
317 * Reset all inrange markers.
322 struct s_command
*cp
;
324 for (cp
= prog
; cp
; cp
= cp
->code
== '{' ? cp
->u
.c
: cp
->next
)
331 * Do substitutions in the pattern space. Currently, we build a
332 * copy of the new pattern space in the substitute space structure
333 * and then swap them.
336 substitute(struct s_command
*cp
)
348 if (defpreg
!= NULL
&& cp
->u
.s
->maxbref
> defpreg
->re_nsub
) {
349 linenum
= cp
->u
.s
->linenum
;
350 error(COMPILE
, "\\%zu not defined in the RE",
354 if (!regexec_e(re
, ps
, 0, 0, 0, psl
))
357 SS
.len
= 0; /* Clean substitute space. */
363 /* Copy the leading retained string. */
364 if (n
<= 1 && (match
[0].rm_so
> le
))
365 cspace(&SS
, s
, match
[0].rm_so
- le
, APPEND
);
367 /* Skip zero-length matches right after other matches. */
368 if (lastempty
|| (match
[0].rm_so
- le
) ||
369 match
[0].rm_so
!= match
[0].rm_eo
) {
371 /* Want this match: append replacement. */
372 regsub(&SS
, ps
, cp
->u
.s
->new);
376 /* Want a later match: append original. */
377 if (match
[0].rm_eo
- le
)
378 cspace(&SS
, s
, match
[0].rm_eo
- le
,
384 /* Move past this match. */
385 s
= ps
+ match
[0].rm_eo
;
386 slen
= psl
- match
[0].rm_eo
;
390 * After a zero-length match, advance one byte,
391 * and at the end of the line, terminate.
393 if (match
[0].rm_so
== match
[0].rm_eo
) {
394 if (*s
== '\0' || *s
== '\n')
399 cspace(&SS
, s
++, 1, APPEND
);
406 } while (n
>= 0 && slen
>= 0 &&
407 regexec_e(re
, ps
, REG_NOTBOL
, 0, le
, psl
));
409 /* Did not find the requested number of matches. */
413 /* Copy the trailing retained string. */
415 cspace(&SS
, s
, slen
, APPEND
);
418 * Swap the substitute space and the pattern space, and make sure
419 * that any leftover pointers into stdio memory get lost.
423 psanl
= tspace
.append_newline
;
427 /* Handle the 'p' flag. */
431 /* Handle the 'w' flag. */
432 if (cp
->u
.s
->wfile
&& !pd
) {
433 if (cp
->u
.s
->wfd
== -1 && (cp
->u
.s
->wfd
= open(cp
->u
.s
->wfile
,
434 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
, DEFFILEMODE
)) == -1)
435 error(FATAL
, "%s: %s", cp
->u
.s
->wfile
, strerror(errno
));
436 if ((size_t)write(cp
->u
.s
->wfd
, ps
, psl
) != psl
||
437 write(cp
->u
.s
->wfd
, "\n", 1) != 1)
438 error(FATAL
, "%s: %s", cp
->u
.s
->wfile
, strerror(errno
));
444 * Flush append requests. Always called before reading a line,
445 * therefore it also resets the substitution done (sdone) flag.
455 for (i
= 0; i
< appendx
; i
++)
456 switch (appends
[i
].type
) {
458 fwrite(appends
[i
].s
, sizeof(char), appends
[i
].len
,
463 * Read files probably shouldn't be cached. Since
464 * it's not an error to read a non-existent file,
465 * it's possible that another program is interacting
466 * with the sed script through the filesystem. It
467 * would be truly bizarre, but possible. It's probably
468 * not that big a performance win, anyhow.
470 if ((f
= fopen(appends
[i
].s
, "r")) == NULL
)
472 while ((count
= fread(buf
, sizeof(char), sizeof(buf
), f
)))
473 (void)fwrite(buf
, sizeof(char), count
, outfile
);
478 error(FATAL
, "%s: %s", outfname
, strerror(errno
? errno
: EIO
));
486 extern int termwidth
;
490 for (count
= 0; *s
; ++s
) {
491 if (count
>= termwidth
) {
492 (void)fprintf(outfile
, "\\\n");
495 if (isascii((unsigned char)*s
) && isprint((unsigned char)*s
)
497 (void)fputc(*s
, outfile
);
500 escapes
= "\\\a\b\f\n\r\t\v";
501 if (*s
== '\n' && s
[1] == '\0') {
502 /* omit trailing newline */
505 (void)fputc('\\', outfile
);
506 if ((p
= strchr(escapes
, *s
))) {
507 (void)fputc("\\abfnrtv"[p
- escapes
], outfile
);
510 (void)fprintf(outfile
, "%03o", *(u_char
*)s
);
515 (void)fputc('$', outfile
);
516 (void)fputc('\n', outfile
);
518 error(FATAL
, "%s: %s", outfname
, strerror(errno
? errno
: EIO
));
522 regexec_e(regex_t
*preg
, const char *string
, int eflags
,
523 int nomatch
, size_t start
, size_t stop
)
529 error(FATAL
, "first RE may not be empty");
534 match
[0].rm_so
= start
;
535 match
[0].rm_eo
= stop
;
537 eval
= regexec(defpreg
, string
,
538 nomatch
? 0 : maxnsub
+ 1, match
, eflags
| REG_STARTEND
);
545 error(FATAL
, "RE error: %s", strregerror(eval
, defpreg
));
549 * regsub - perform substitutions after a regexp match
550 * Based on a routine by Henry Spencer
553 regsub(SPACE
*sp
, char *string
, char *src
)
558 #define NEEDSP(reqlen) \
559 if (sp->len + (reqlen) + 1 >= sp->blen) { \
560 size_t newlen = sp->blen + (reqlen) + 1024; \
561 sp->space = sp->back = xrealloc(sp->back, newlen); \
563 dst = sp->space + sp->len; \
566 dst
= sp
->space
+ sp
->len
;
567 while ((c
= *src
++) != '\0') {
570 else if (c
== '\\' && isdigit((unsigned char)*src
))
574 if (no
< 0) { /* Ordinary character. */
575 if (c
== '\\' && (*src
== '\\' || *src
== '&'))
580 } else if (match
[no
].rm_so
!= -1 && match
[no
].rm_eo
!= -1) {
581 len
= match
[no
].rm_eo
- match
[no
].rm_so
;
583 memmove(dst
, string
+ match
[no
].rm_so
, len
);
594 * Append the source space to the destination space, allocating new
595 * space as necessary.
598 cspace(SPACE
*sp
, const char *p
, size_t len
, enum e_spflag spflag
)
602 /* Make sure SPACE has enough memory and ramp up quickly. */
603 tlen
= sp
->len
+ len
+ 1;
604 if (tlen
> sp
->blen
) {
605 size_t newlen
= tlen
+ 1024;
606 sp
->space
= sp
->back
= xrealloc(sp
->back
, newlen
);
610 if (spflag
== REPLACE
)
613 memmove(sp
->space
+ sp
->len
, p
, len
);
615 sp
->space
[sp
->len
+= len
] = '\0';
619 * Close all cached opened files and report any errors
622 cfclose(struct s_command
*cp
, struct s_command
*end
)
625 for (; cp
!= end
; cp
= cp
->next
)
628 if (cp
->u
.s
->wfd
!= -1 && close(cp
->u
.s
->wfd
))
630 "%s: %s", cp
->u
.s
->wfile
, strerror(errno
));
634 if (cp
->u
.fd
!= -1 && close(cp
->u
.fd
))
635 error(FATAL
, "%s: %s", cp
->t
, strerror(errno
));
639 cfclose(cp
->u
.c
, cp
->next
);