1 /* $NetBSD: process.c,v 1.38 2009/04/13 07:29:55 lukem Exp $ */
4 * Copyright (c) 1992, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Diomidis Spinellis of Imperial College, University of London.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * Copyright (c) 1992 Diomidis Spinellis.
38 * This code is derived from software contributed to Berkeley by
39 * Diomidis Spinellis of Imperial College, University of London.
41 * Redistribution and use in source and binary forms, with or without
42 * modification, are permitted provided that the following conditions
44 * 1. Redistributions of source code must retain the above copyright
45 * notice, this list of conditions and the following disclaimer.
46 * 2. Redistributions in binary form must reproduce the above copyright
47 * notice, this list of conditions and the following disclaimer in the
48 * documentation and/or other materials provided with the distribution.
49 * 3. All advertising materials mentioning features or use of this software
50 * must display the following acknowledgement:
51 * This product includes software developed by the University of
52 * California, Berkeley and its contributors.
53 * 4. Neither the name of the University nor the names of its contributors
54 * may be used to endorse or promote products derived from this software
55 * without specific prior written permission.
57 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
58 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
59 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
60 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
61 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
62 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
63 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
64 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
65 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
66 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
70 #if HAVE_NBTOOL_CONFIG_H
71 #include "nbtool_config.h"
74 #include <sys/cdefs.h>
77 static char sccsid
[] = "@(#)process.c 8.6 (Berkeley) 4/20/94";
79 __RCSID("$NetBSD: process.c,v 1.38 2009/04/13 07:29:55 lukem Exp $");
83 #include <sys/types.h>
85 #include <sys/ioctl.h>
88 #include <minix/termios.h>
103 static SPACE HS
, PS
, SS
;
104 #define pd PS.deleted
110 static inline int applies(struct s_command
*);
111 static void flush_appends(void);
112 static void lputs(char *);
113 static inline int regexec_e(regex_t
*, const char *, int, int, size_t);
114 static void regsub(SPACE
*, char *, char *);
115 static int substitute(struct s_command
*);
117 struct s_appends
*appends
; /* Array of pointers to strings to append. */
118 static int appendx
; /* Index into appends array. */
119 int appendnum
; /* Size of appends array. */
121 static int lastaddr
; /* Set by applies if last address of a range. */
122 static int sdone
; /* If any substitutes since last line input. */
123 /* Iov structure for 'w' commands. */
124 static regex_t
*defpreg
;
128 #define OUT(s) { fwrite(s, sizeof(u_char), psl, stdout); }
133 struct s_command
*cp
;
139 for (linenum
= 0; mf_fgets(&PS
, REPLACE
);) {
154 if (appendx
>= appendnum
) {
155 appends
= xrealloc(appends
,
156 sizeof(struct s_appends
) *
160 appends
[appendx
].type
= AP_STRING
;
161 appends
[appendx
].s
= cp
->t
;
162 appends
[appendx
].len
= strlen(cp
->t
);
171 if (cp
->a2
== NULL
|| lastaddr
)
172 (void)printf("%s", cp
->t
);
182 if ((p
= memchr(ps
, '\n', psl
- 1)) == NULL
) {
187 memmove(ps
, p
+ 1, psl
);
191 cspace(&PS
, hs
, hsl
, REPLACE
);
195 cspace(&HS
, "\n", 1, REPLACE
);
196 cspace(&PS
, hs
, hsl
, 0);
199 cspace(&HS
, ps
, psl
, REPLACE
);
202 cspace(&HS
, ps
, psl
, 0);
205 (void)printf("%s", cp
->t
);
214 if (!mf_fgets(&PS
, REPLACE
))
220 if (!mf_fgets(&PS
, 0)) {
234 if ((p
= memchr(ps
, '\n', psl
- 1)) != NULL
) {
248 if (appendx
>= appendnum
) {
249 appends
= xrealloc(appends
,
250 sizeof(struct s_appends
) *
254 appends
[appendx
].type
= AP_FILE
;
255 appends
[appendx
].s
= cp
->t
;
256 appends
[appendx
].len
= strlen(cp
->t
);
260 sdone
|= substitute(cp
);
272 if (cp
->u
.fd
== -1 && (cp
->u
.fd
= open(cp
->t
,
273 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
,
276 cp
->t
, strerror(errno
));
277 if ((size_t)write(cp
->u
.fd
, ps
, psl
) != psl
)
279 cp
->t
, strerror(errno
));
283 cspace(&HS
, "\n", 1, REPLACE
);
291 for (p
= ps
, len
= psl
; --len
; ++p
)
292 *p
= cp
->u
.y
[(int)*p
];
298 (void)printf("%lu\n", linenum
);
303 new: if (!nflag
&& !pd
)
306 } /* for all lines */
310 * TRUE if the address passed matches the current program state
311 * (lastline, linenumber, ps).
314 (a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, psl) : \
315 (a)->type == AT_LINE ? linenum == (a)->u.l : lastline
318 * Return TRUE if the command applies to the current line. Sets the inrange
319 * flag to process ranges. Interprets the non-select (``!'') flag.
322 applies(struct s_command
*cp
)
327 if (cp
->a1
== NULL
&& cp
->a2
== NULL
)
336 } else if (cp
->a1
&& MATCH(cp
->a1
)) {
338 * If the second address is a number less than or
339 * equal to the line number first selected, only
340 * one line shall be selected.
343 if (cp
->a2
->type
== AT_LINE
&&
344 linenum
>= cp
->a2
->u
.l
)
353 return (cp
->nonsel
? ! r
: r
);
358 * Do substitutions in the pattern space. Currently, we build a
359 * copy of the new pattern space in the substitute space structure
360 * and then swap them.
363 substitute(struct s_command
*cp
)
374 if (defpreg
!= NULL
&& (size_t)cp
->u
.s
->maxbref
> defpreg
->re_nsub
) {
375 linenum
= cp
->u
.s
->linenum
;
376 err(COMPILE
, "\\%d not defined in the RE",
380 if (!regexec_e(re
, s
, 0, 0, psl
))
383 SS
.len
= 0; /* Clean substitute space. */
391 if (lastempty
|| match
[0].rm_so
!= match
[0].rm_eo
) {
392 /* Locate start of replaced string. */
393 re_off
= match
[0].rm_so
;
394 /* Copy leading retained string. */
395 cspace(&SS
, s
, re_off
, APPEND
);
396 /* Add in regular expression. */
397 regsub(&SS
, s
, cp
->u
.s
->new);
400 /* Move past this match. */
401 if (match
[0].rm_so
!= match
[0].rm_eo
) {
403 slen
-= match
[0].rm_eo
;
406 if (match
[0].rm_so
== 0)
408 s
, match
[0].rm_so
+ 1, APPEND
);
411 s
+ match
[0].rm_so
, 1, APPEND
);
412 s
+= match
[0].rm_so
+ 1;
413 slen
-= match
[0].rm_so
+ 1;
416 } while (slen
> 0 && regexec_e(re
, s
, REG_NOTBOL
, 0, slen
));
417 /* Copy trailing retained string. */
419 cspace(&SS
, s
, slen
, APPEND
);
421 default: /* Nth occurrence */
424 slen
-= match
[0].rm_eo
;
425 if (!regexec_e(re
, s
, REG_NOTBOL
, 0, slen
))
429 case 1: /* 1st occurrence */
430 /* Locate start of replaced string. */
431 re_off
= match
[0].rm_so
+ (s
- ps
);
432 /* Copy leading retained string. */
433 cspace(&SS
, ps
, re_off
, APPEND
);
434 /* Add in regular expression. */
435 regsub(&SS
, s
, cp
->u
.s
->new);
436 /* Copy trailing retained string. */
438 slen
-= match
[0].rm_eo
;
439 cspace(&SS
, s
, slen
, APPEND
);
444 * Swap the substitute space and the pattern space, and make sure
445 * that any leftover pointers into stdio memory get lost.
452 /* Handle the 'p' flag. */
456 /* Handle the 'w' flag. */
457 if (cp
->u
.s
->wfile
&& !pd
) {
458 if (cp
->u
.s
->wfd
== -1 && (cp
->u
.s
->wfd
= open(cp
->u
.s
->wfile
,
459 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
, DEFFILEMODE
)) == -1)
460 err(FATAL
, "%s: %s", cp
->u
.s
->wfile
, strerror(errno
));
461 if ((size_t)write(cp
->u
.s
->wfd
, ps
, psl
) != psl
)
462 err(FATAL
, "%s: %s", cp
->u
.s
->wfile
, strerror(errno
));
468 * Flush append requests. Always called before reading a line,
469 * therefore it also resets the substitution done (sdone) flag.
478 for (i
= 0; i
< appendx
; i
++)
479 switch (appends
[i
].type
) {
481 fwrite(appends
[i
].s
, sizeof(char), appends
[i
].len
,
486 * Read files probably shouldn't be cached. Since
487 * it's not an error to read a non-existent file,
488 * it's possible that another program is interacting
489 * with the sed script through the file system. It
490 * would be truly bizarre, but possible. It's probably
491 * not that big a performance win, anyhow.
493 if ((f
= fopen(appends
[i
].s
, "r")) == NULL
)
496 fread(buf
, sizeof(char), sizeof(buf
), f
)) > 0)
497 (void)fwrite(buf
, sizeof(char), count
, stdout
);
502 err(FATAL
, "stdout: %s", strerror(errno
? errno
: EIO
));
510 const char *escapes
, *p
;
511 #ifndef HAVE_NBTOOL_CONFIG_H
514 static int termwidth
= -1;
516 if (termwidth
== -1) {
517 if ((p
= getenv("COLUMNS")) != NULL
)
519 #ifndef HAVE_NBTOOL_CONFIG_H
520 else if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &win
) == 0 &&
522 termwidth
= win
.ws_col
;
527 for (count
= 0; *s
; ++s
) {
528 if (count
>= termwidth
) {
529 (void)printf("\\\n");
532 if (isascii((unsigned char)*s
) && isprint((unsigned char)*s
) &&
537 escapes
= "\\\a\b\f\n\r\t\v";
539 if ((p
= strchr(escapes
, *s
)) != NULL
) {
540 (void)putchar("\\abfnrtv"[p
- escapes
]);
543 (void)printf("%03o", *(u_char
*)s
);
551 err(FATAL
, "stdout: %s", strerror(errno
? errno
: EIO
));
555 regexec_e(regex_t
*preg
, const char *string
, int eflags
, int nomatch
, size_t slen
)
564 err(FATAL
, "first RE may not be empty");
568 /* Set anchors, discounting trailing newline (if any). */
569 if (slen
> 0 && string
[slen
- 1] == '\n')
573 if ((buf
= malloc(slen
+ 1)) == NULL
)
575 (void)memcpy(buf
, string
, slen
);
577 eval
= regexec(defpreg
, buf
,
578 nomatch
? 0 : maxnsub
+ 1, match
, eflags
);
582 match
[0].rm_eo
= slen
;
583 eval
= regexec(defpreg
, string
,
584 nomatch
? 0 : maxnsub
+ 1, match
, eflags
| REG_STARTEND
);
592 err(FATAL
, "RE error: %s", strregerror(eval
, defpreg
));
598 * regsub - perform substitutions after a regexp match
599 * Based on a routine by Henry Spencer
602 regsub(SPACE
*sp
, char *string
, char *src
)
607 #define NEEDSP(reqlen) \
608 if (sp->len + (reqlen) + 1 >= sp->blen) { \
609 size_t newlen = sp->blen + (reqlen) + 1024; \
610 sp->space = sp->back = xrealloc(sp->back, newlen); \
612 dst = sp->space + sp->len; \
615 dst
= sp
->space
+ sp
->len
;
616 while ((c
= *src
++) != '\0') {
619 else if (c
== '\\' && isdigit((unsigned char)*src
))
623 if (no
< 0) { /* Ordinary character. */
624 if (c
== '\\' && (*src
== '\\' || *src
== '&'))
629 } else if (match
[no
].rm_so
!= -1 && match
[no
].rm_eo
!= -1) {
630 len
= match
[no
].rm_eo
- match
[no
].rm_so
;
632 memmove(dst
, string
+ match
[no
].rm_so
, len
);
643 * Append the source space to the destination space, allocating new
644 * space as necessary.
647 cspace(SPACE
*sp
, const char *p
, size_t len
, enum e_spflag spflag
)
651 /* Make sure SPACE has enough memory and ramp up quickly. */
652 tlen
= sp
->len
+ len
+ 1;
653 if (tlen
> sp
->blen
) {
654 size_t newlen
= tlen
+ 1024;
655 sp
->space
= sp
->back
= xrealloc(sp
->back
, newlen
);
659 if (spflag
== REPLACE
)
662 memmove(sp
->space
+ sp
->len
, p
, len
);
664 sp
->space
[sp
->len
+= len
] = '\0';
668 * Close all cached opened files and report any errors
671 cfclose(struct s_command
*cp
, struct s_command
*end
)
674 for (; cp
!= end
; cp
= cp
->next
)
677 if (cp
->u
.s
->wfd
!= -1 && close(cp
->u
.s
->wfd
))
679 "%s: %s", cp
->u
.s
->wfile
, strerror(errno
));
683 if (cp
->u
.fd
!= -1 && close(cp
->u
.fd
))
684 err(FATAL
, "%s: %s", cp
->t
, strerror(errno
));
688 cfclose(cp
->u
.c
, cp
->next
);