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. All advertising materials mentioning features or use of this software
18 * must display the following acknowledgement:
19 * This product includes software developed by the University of
20 * California, Berkeley and its contributors.
21 * 4. 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
37 * @(#)process.c 8.6 (Berkeley) 4/20/94
38 * $FreeBSD: src/usr.bin/sed/process.c,v 1.10.2.10 2003/06/13 07:32:08 fanf Exp $
39 * $DragonFly: src/usr.bin/sed/process.c,v 1.5 2003/11/04 15:48:16 drhodus Exp $
42 #include <sys/types.h>
44 #include <sys/ioctl.h>
61 static SPACE HS
, PS
, SS
;
68 static __inline
int applies(struct s_command
*);
69 static void flush_appends(void);
70 static void lputs(char *);
71 static __inline
int regexec_e(regex_t
*, const char *, int, int, size_t);
72 static void regsub(SPACE
*, char *, char *);
73 static int substitute(struct s_command
*);
75 struct s_appends
*appends
; /* Array of pointers to strings to append. */
76 static int appendx
; /* Index into appends array. */
77 int appendnum
; /* Size of appends array. */
79 static int lastaddr
; /* Set by applies if last address of a range. */
80 static int sdone
; /* If any substitutes since last line input. */
81 /* Iov structure for 'w' commands. */
82 static regex_t
*defpreg
;
86 #define OUT(s) { fwrite(s, sizeof(u_char), psl, stdout); putchar('\n'); }
93 size_t len
, oldpsl
= 0;
98 for (linenum
= 0; mf_fgets(&PS
, REPLACE
);) {
113 if (appendx
>= appendnum
)
114 if ((appends
= realloc(appends
,
115 sizeof(struct s_appends
) *
116 (appendnum
*= 2))) == NULL
)
118 appends
[appendx
].type
= AP_STRING
;
119 appends
[appendx
].s
= cp
->t
;
120 appends
[appendx
].len
= strlen(cp
->t
);
129 if (cp
->a2
== NULL
|| lastaddr
)
130 (void)printf("%s", cp
->t
);
139 (p
= memchr(ps
, '\n', psl
)) == NULL
) {
144 memmove(ps
, p
+ 1, psl
);
148 cspace(&PS
, hs
, hsl
, REPLACE
);
151 cspace(&PS
, "\n", 1, 0);
152 cspace(&PS
, hs
, hsl
, 0);
155 cspace(&HS
, ps
, psl
, REPLACE
);
158 cspace(&HS
, "\n", 1, 0);
159 cspace(&HS
, ps
, psl
, 0);
162 (void)printf("%s", cp
->t
);
171 if (!mf_fgets(&PS
, REPLACE
))
177 cspace(&PS
, "\n", 1, 0);
178 if (!mf_fgets(&PS
, 0))
190 (p
= memchr(ps
, '\n', psl
)) != NULL
) {
204 if (appendx
>= appendnum
)
205 if ((appends
= realloc(appends
,
206 sizeof(struct s_appends
) *
207 (appendnum
*= 2))) == NULL
)
209 appends
[appendx
].type
= AP_FILE
;
210 appends
[appendx
].s
= cp
->t
;
211 appends
[appendx
].len
= strlen(cp
->t
);
215 sdone
|= substitute(cp
);
227 if (cp
->u
.fd
== -1 && (cp
->u
.fd
= open(cp
->t
,
228 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
,
231 if (write(cp
->u
.fd
, ps
, psl
) != psl
||
232 write(cp
->u
.fd
, "\n", 1) != 1)
237 cspace(&HS
, "", 0, REPLACE
);
245 for (p
= ps
, len
= psl
; len
--; ++p
)
246 *p
= cp
->u
.y
[(unsigned char)*p
];
252 (void)printf("%lu\n", linenum
);
257 new: if (!nflag
&& !pd
)
260 } /* for all lines */
264 * TRUE if the address passed matches the current program state
265 * (lastline, linenumber, ps).
268 (a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, psl) : \
269 (a)->type == AT_LINE ? linenum == (a)->u.l : lastline()
272 * Return TRUE if the command applies to the current line. Sets the inrange
273 * flag to process ranges. Interprets the non-select (``!'') flag.
276 applies(struct s_command
*cp
)
281 if (cp
->a1
== NULL
&& cp
->a2
== NULL
)
290 } else if (MATCH(cp
->a1
)) {
292 * If the second address is a number less than or
293 * equal to the line number first selected, only
294 * one line shall be selected.
297 if (cp
->a2
->type
== AT_LINE
&&
298 linenum
>= cp
->a2
->u
.l
)
307 return (cp
->nonsel
? ! r
: r
);
312 * Do substitutions in the pattern space. Currently, we build a
313 * copy of the new pattern space in the substitute space structure
314 * and then swap them.
317 substitute(struct s_command
*cp
)
321 regoff_t re_off
, slen
;
328 if (defpreg
!= NULL
&& cp
->u
.s
->maxbref
> defpreg
->re_nsub
) {
329 linenum
= cp
->u
.s
->linenum
;
330 errx(1, "%lu: %s: \\%d not defined in the RE",
331 linenum
, fname
, cp
->u
.s
->maxbref
);
334 if (!regexec_e(re
, s
, 0, 0, psl
))
337 SS
.len
= 0; /* Clean substitute space. */
345 if (lastempty
|| match
[0].rm_so
!= match
[0].rm_eo
) {
346 /* Locate start of replaced string. */
347 re_off
= match
[0].rm_so
;
348 /* Copy leading retained string. */
349 cspace(&SS
, s
, re_off
, APPEND
);
350 /* Add in regular expression. */
351 regsub(&SS
, s
, cp
->u
.s
->new);
354 /* Move past this match. */
355 if (match
[0].rm_so
!= match
[0].rm_eo
) {
357 slen
-= match
[0].rm_eo
;
360 if (match
[0].rm_so
< slen
)
361 cspace(&SS
, s
+ match
[0].rm_so
, 1,
363 s
+= match
[0].rm_so
+ 1;
364 slen
-= match
[0].rm_so
+ 1;
367 } while (slen
>= 0 && regexec_e(re
, s
, REG_NOTBOL
, 0, slen
));
368 /* Copy trailing retained string. */
370 cspace(&SS
, s
, slen
, APPEND
);
372 default: /* Nth occurrence */
374 if (match
[0].rm_eo
== match
[0].rm_so
)
375 match
[0].rm_eo
= match
[0].rm_so
+ 1;
377 slen
-= match
[0].rm_eo
;
380 if (!regexec_e(re
, s
, REG_NOTBOL
, 0, slen
))
384 case 1: /* 1st occurrence */
385 /* Locate start of replaced string. */
386 re_off
= match
[0].rm_so
+ (s
- ps
);
387 /* Copy leading retained string. */
388 cspace(&SS
, ps
, re_off
, APPEND
);
389 /* Add in regular expression. */
390 regsub(&SS
, s
, cp
->u
.s
->new);
391 /* Copy trailing retained string. */
393 slen
-= match
[0].rm_eo
;
394 cspace(&SS
, s
, slen
, APPEND
);
399 * Swap the substitute space and the pattern space, and make sure
400 * that any leftover pointers into stdio memory get lost.
407 /* Handle the 'p' flag. */
411 /* Handle the 'w' flag. */
412 if (cp
->u
.s
->wfile
&& !pd
) {
413 if (cp
->u
.s
->wfd
== -1 && (cp
->u
.s
->wfd
= open(cp
->u
.s
->wfile
,
414 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
, DEFFILEMODE
)) == -1)
415 err(1, "%s", cp
->u
.s
->wfile
);
416 if (write(cp
->u
.s
->wfd
, ps
, psl
) != psl
||
417 write(cp
->u
.s
->wfd
, "\n", 1) != 1)
418 err(1, "%s", cp
->u
.s
->wfile
);
424 * Flush append requests. Always called before reading a line,
425 * therefore it also resets the substitution done (sdone) flag.
434 for (i
= 0; i
< appendx
; i
++)
435 switch (appends
[i
].type
) {
437 fwrite(appends
[i
].s
, sizeof(char), appends
[i
].len
,
442 * Read files probably shouldn't be cached. Since
443 * it's not an error to read a non-existent file,
444 * it's possible that another program is interacting
445 * with the sed script through the filesystem. It
446 * would be truly bizarre, but possible. It's probably
447 * not that big a performance win, anyhow.
449 if ((f
= fopen(appends
[i
].s
, "r")) == NULL
)
451 while ((count
= fread(buf
, sizeof(char), sizeof(buf
), f
)))
452 (void)fwrite(buf
, sizeof(char), count
, stdout
);
457 errx(1, "stdout: %s", strerror(errno
? errno
: EIO
));
468 static int termwidth
= -1;
470 if (termwidth
== -1) {
471 if ((p
= getenv("COLUMNS")) && *p
!= '\0')
473 else if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &win
) == 0 &&
475 termwidth
= win
.ws_col
;
480 for (count
= 0; *s
; ++s
) {
481 if (count
+ 5 >= termwidth
) {
482 (void)printf("\\\n");
485 if (isprint((unsigned char)*s
) && *s
!= '\\') {
488 } else if (*s
== '\n') {
493 escapes
= "\\\a\b\f\r\t\v";
495 if ((p
= strchr(escapes
, *s
))) {
496 (void)putchar("\\abfrtv"[p
- escapes
]);
499 (void)printf("%03o", *(u_char
*)s
);
507 errx(1, "stdout: %s", strerror(errno
? errno
: EIO
));
511 regexec_e(regex_t
*preg
, const char *string
, int eflags
, int nomatch
,
518 errx(1, "first RE may not be empty");
524 match
[0].rm_eo
= slen
;
526 eval
= regexec(defpreg
, string
,
527 nomatch
? 0 : maxnsub
+ 1, match
, eflags
| REG_STARTEND
);
534 errx(1, "RE error: %s", strregerror(eval
, defpreg
));
539 * regsub - perform substitutions after a regexp match
540 * Based on a routine by Henry Spencer
543 regsub(SPACE
*sp
, char *string
, char *src
)
548 #define NEEDSP(reqlen) \
549 /* XXX What is the +1 for? */ \
550 if (sp->len + (reqlen) + 1 >= sp->blen) { \
551 sp->blen += (reqlen) + 1024; \
552 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) \
555 dst = sp->space + sp->len; \
558 dst
= sp
->space
+ sp
->len
;
559 while ((c
= *src
++) != '\0') {
562 else if (c
== '\\' && isdigit((unsigned char)*src
))
566 if (no
< 0) { /* Ordinary character. */
567 if (c
== '\\' && (*src
== '\\' || *src
== '&'))
572 } else if (match
[no
].rm_so
!= -1 && match
[no
].rm_eo
!= -1) {
573 len
= match
[no
].rm_eo
- match
[no
].rm_so
;
575 memmove(dst
, string
+ match
[no
].rm_so
, len
);
586 * Append the source space to the destination space, allocating new
587 * space as necessary.
590 cspace(SPACE
*sp
, const char *p
, size_t len
, enum e_spflag spflag
)
594 /* Make sure SPACE has enough memory and ramp up quickly. */
595 tlen
= sp
->len
+ len
+ 1;
596 if (tlen
> sp
->blen
) {
597 sp
->blen
= tlen
+ 1024;
598 if ((sp
->space
= sp
->back
= realloc(sp
->back
, sp
->blen
)) ==
603 if (spflag
== REPLACE
)
606 memmove(sp
->space
+ sp
->len
, p
, len
);
608 sp
->space
[sp
->len
+= len
] = '\0';
612 * Close all cached opened files and report any errors
615 cfclose(struct s_command
*cp
, struct s_command
*end
)
618 for (; cp
!= end
; cp
= cp
->next
)
621 if (cp
->u
.s
->wfd
!= -1 && close(cp
->u
.s
->wfd
))
622 err(1, "%s", cp
->u
.s
->wfile
);
626 if (cp
->u
.fd
!= -1 && close(cp
->u
.fd
))
631 cfclose(cp
->u
.c
, cp
->next
);