1 /* $NetBSD: process.c,v 1.37 2006/06/18 05:16:41 gdamore 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.37 2006/06/18 05:16:41 gdamore Exp $");
83 #include <sys/types.h>
85 #include <sys/ioctl.h>
101 static SPACE HS
, PS
, SS
;
102 #define pd PS.deleted
108 static inline int applies(struct s_command
*);
109 static void flush_appends(void);
110 static void lputs(char *);
111 static inline int regexec_e(regex_t
*, const char *, int, int, size_t);
112 static void regsub(SPACE
*, char *, char *);
113 static int substitute(struct s_command
*);
115 struct s_appends
*appends
; /* Array of pointers to strings to append. */
116 static int appendx
; /* Index into appends array. */
117 int appendnum
; /* Size of appends array. */
119 static int lastaddr
; /* Set by applies if last address of a range. */
120 static int sdone
; /* If any substitutes since last line input. */
121 /* Iov structure for 'w' commands. */
122 static regex_t
*defpreg
;
126 #define OUT(s) { fwrite(s, sizeof(u_char), psl, stdout); }
131 struct s_command
*cp
;
137 for (linenum
= 0; mf_fgets(&PS
, REPLACE
);) {
152 if (appendx
>= appendnum
) {
153 appends
= xrealloc(appends
,
154 sizeof(struct s_appends
) *
158 appends
[appendx
].type
= AP_STRING
;
159 appends
[appendx
].s
= cp
->t
;
160 appends
[appendx
].len
= strlen(cp
->t
);
169 if (cp
->a2
== NULL
|| lastaddr
)
170 (void)printf("%s", cp
->t
);
180 if ((p
= memchr(ps
, '\n', psl
- 1)) == NULL
) {
185 memmove(ps
, p
+ 1, psl
);
189 cspace(&PS
, hs
, hsl
, REPLACE
);
193 cspace(&HS
, "\n", 1, REPLACE
);
194 cspace(&PS
, hs
, hsl
, 0);
197 cspace(&HS
, ps
, psl
, REPLACE
);
200 cspace(&HS
, ps
, psl
, 0);
203 (void)printf("%s", cp
->t
);
212 if (!mf_fgets(&PS
, REPLACE
))
218 if (!mf_fgets(&PS
, 0)) {
232 if ((p
= memchr(ps
, '\n', psl
- 1)) != NULL
) {
246 if (appendx
>= appendnum
) {
247 appends
= xrealloc(appends
,
248 sizeof(struct s_appends
) *
252 appends
[appendx
].type
= AP_FILE
;
253 appends
[appendx
].s
= cp
->t
;
254 appends
[appendx
].len
= strlen(cp
->t
);
258 sdone
|= substitute(cp
);
270 if (cp
->u
.fd
== -1 && (cp
->u
.fd
= open(cp
->t
,
271 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
,
274 cp
->t
, strerror(errno
));
275 if ((size_t)write(cp
->u
.fd
, ps
, psl
) != psl
)
277 cp
->t
, strerror(errno
));
281 cspace(&HS
, "\n", 1, REPLACE
);
289 for (p
= ps
, len
= psl
; --len
; ++p
)
290 *p
= cp
->u
.y
[(int)*p
];
296 (void)printf("%lu\n", linenum
);
301 new: if (!nflag
&& !pd
)
304 } /* for all lines */
308 * TRUE if the address passed matches the current program state
309 * (lastline, linenumber, ps).
312 (a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, psl) : \
313 (a)->type == AT_LINE ? linenum == (a)->u.l : lastline
316 * Return TRUE if the command applies to the current line. Sets the inrange
317 * flag to process ranges. Interprets the non-select (``!'') flag.
320 applies(struct s_command
*cp
)
325 if (cp
->a1
== NULL
&& cp
->a2
== NULL
)
334 } else if (cp
->a1
&& MATCH(cp
->a1
)) {
336 * If the second address is a number less than or
337 * equal to the line number first selected, only
338 * one line shall be selected.
341 if (cp
->a2
->type
== AT_LINE
&&
342 linenum
>= cp
->a2
->u
.l
)
351 return (cp
->nonsel
? ! r
: r
);
356 * Do substitutions in the pattern space. Currently, we build a
357 * copy of the new pattern space in the substitute space structure
358 * and then swap them.
361 substitute(struct s_command
*cp
)
372 if (defpreg
!= NULL
&& (size_t)cp
->u
.s
->maxbref
> defpreg
->re_nsub
) {
373 linenum
= cp
->u
.s
->linenum
;
374 err(COMPILE
, "\\%d not defined in the RE",
378 if (!regexec_e(re
, s
, 0, 0, psl
))
381 SS
.len
= 0; /* Clean substitute space. */
389 if (lastempty
|| match
[0].rm_so
!= match
[0].rm_eo
) {
390 /* Locate start of replaced string. */
391 re_off
= match
[0].rm_so
;
392 /* Copy leading retained string. */
393 cspace(&SS
, s
, re_off
, APPEND
);
394 /* Add in regular expression. */
395 regsub(&SS
, s
, cp
->u
.s
->new);
398 /* Move past this match. */
399 if (match
[0].rm_so
!= match
[0].rm_eo
) {
401 slen
-= match
[0].rm_eo
;
404 if (match
[0].rm_so
== 0)
406 s
, match
[0].rm_so
+ 1, APPEND
);
409 s
+ match
[0].rm_so
, 1, APPEND
);
410 s
+= match
[0].rm_so
+ 1;
411 slen
-= match
[0].rm_so
+ 1;
414 } while (slen
> 0 && regexec_e(re
, s
, REG_NOTBOL
, 0, slen
));
415 /* Copy trailing retained string. */
417 cspace(&SS
, s
, slen
, APPEND
);
419 default: /* Nth occurrence */
422 slen
-= match
[0].rm_eo
;
423 if (!regexec_e(re
, s
, REG_NOTBOL
, 0, slen
))
427 case 1: /* 1st occurrence */
428 /* Locate start of replaced string. */
429 re_off
= match
[0].rm_so
+ (s
- ps
);
430 /* Copy leading retained string. */
431 cspace(&SS
, ps
, re_off
, APPEND
);
432 /* Add in regular expression. */
433 regsub(&SS
, s
, cp
->u
.s
->new);
434 /* Copy trailing retained string. */
436 slen
-= match
[0].rm_eo
;
437 cspace(&SS
, s
, slen
, APPEND
);
442 * Swap the substitute space and the pattern space, and make sure
443 * that any leftover pointers into stdio memory get lost.
450 /* Handle the 'p' flag. */
454 /* Handle the 'w' flag. */
455 if (cp
->u
.s
->wfile
&& !pd
) {
456 if (cp
->u
.s
->wfd
== -1 && (cp
->u
.s
->wfd
= open(cp
->u
.s
->wfile
,
457 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
, DEFFILEMODE
)) == -1)
458 err(FATAL
, "%s: %s", cp
->u
.s
->wfile
, strerror(errno
));
459 if ((size_t)write(cp
->u
.s
->wfd
, ps
, psl
) != psl
)
460 err(FATAL
, "%s: %s", cp
->u
.s
->wfile
, strerror(errno
));
466 * Flush append requests. Always called before reading a line,
467 * therefore it also resets the substitution done (sdone) flag.
476 for (i
= 0; i
< appendx
; i
++)
477 switch (appends
[i
].type
) {
479 fwrite(appends
[i
].s
, sizeof(char), appends
[i
].len
,
484 * Read files probably shouldn't be cached. Since
485 * it's not an error to read a non-existent file,
486 * it's possible that another program is interacting
487 * with the sed script through the file system. It
488 * would be truly bizarre, but possible. It's probably
489 * not that big a performance win, anyhow.
491 if ((f
= fopen(appends
[i
].s
, "r")) == NULL
)
494 fread(buf
, sizeof(char), sizeof(buf
), f
)) > 0)
495 (void)fwrite(buf
, sizeof(char), count
, stdout
);
500 err(FATAL
, "stdout: %s", strerror(errno
? errno
: EIO
));
508 const char *escapes
, *p
;
509 #ifndef HAVE_NBTOOL_CONFIG_H
512 static int termwidth
= -1;
514 if (termwidth
== -1) {
515 if ((p
= getenv("COLUMNS")) != NULL
)
517 #ifndef HAVE_NBTOOL_CONFIG_H
518 else if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &win
) == 0 &&
520 termwidth
= win
.ws_col
;
525 for (count
= 0; *s
; ++s
) {
526 if (count
>= termwidth
) {
527 (void)printf("\\\n");
530 if (isascii((unsigned char)*s
) && isprint((unsigned char)*s
) &&
535 escapes
= "\\\a\b\f\n\r\t\v";
537 if ((p
= strchr(escapes
, *s
)) != NULL
) {
538 (void)putchar("\\abfnrtv"[p
- escapes
]);
541 (void)printf("%03o", *(u_char
*)s
);
549 err(FATAL
, "stdout: %s", strerror(errno
? errno
: EIO
));
553 regexec_e(regex_t
*preg
, const char *string
, int eflags
, int nomatch
, size_t slen
)
562 err(FATAL
, "first RE may not be empty");
566 /* Set anchors, discounting trailing newline (if any). */
567 if (slen
> 0 && string
[slen
- 1] == '\n')
571 if ((buf
= malloc(slen
+ 1)) == NULL
)
573 (void)memcpy(buf
, string
, slen
);
575 eval
= regexec(defpreg
, buf
,
576 nomatch
? 0 : maxnsub
+ 1, match
, eflags
);
580 match
[0].rm_eo
= slen
;
581 eval
= regexec(defpreg
, string
,
582 nomatch
? 0 : maxnsub
+ 1, match
, eflags
| REG_STARTEND
);
590 err(FATAL
, "RE error: %s", strregerror(eval
, defpreg
));
596 * regsub - perform substitutions after a regexp match
597 * Based on a routine by Henry Spencer
600 regsub(SPACE
*sp
, char *string
, char *src
)
605 #define NEEDSP(reqlen) \
606 if (sp->len + (reqlen) + 1 >= sp->blen) { \
607 size_t newlen = sp->blen + (reqlen) + 1024; \
608 sp->space = sp->back = xrealloc(sp->back, newlen); \
610 dst = sp->space + sp->len; \
613 dst
= sp
->space
+ sp
->len
;
614 while ((c
= *src
++) != '\0') {
617 else if (c
== '\\' && isdigit((unsigned char)*src
))
621 if (no
< 0) { /* Ordinary character. */
622 if (c
== '\\' && (*src
== '\\' || *src
== '&'))
627 } else if (match
[no
].rm_so
!= -1 && match
[no
].rm_eo
!= -1) {
628 len
= match
[no
].rm_eo
- match
[no
].rm_so
;
630 memmove(dst
, string
+ match
[no
].rm_so
, len
);
641 * Append the source space to the destination space, allocating new
642 * space as necessary.
645 cspace(SPACE
*sp
, const char *p
, size_t len
, enum e_spflag spflag
)
649 /* Make sure SPACE has enough memory and ramp up quickly. */
650 tlen
= sp
->len
+ len
+ 1;
651 if (tlen
> sp
->blen
) {
652 size_t newlen
= tlen
+ 1024;
653 sp
->space
= sp
->back
= xrealloc(sp
->back
, newlen
);
657 if (spflag
== REPLACE
)
660 memmove(sp
->space
+ sp
->len
, p
, len
);
662 sp
->space
[sp
->len
+= len
] = '\0';
666 * Close all cached opened files and report any errors
669 cfclose(struct s_command
*cp
, struct s_command
*end
)
672 for (; cp
!= end
; cp
= cp
->next
)
675 if (cp
->u
.s
->wfd
!= -1 && close(cp
->u
.s
->wfd
))
677 "%s: %s", cp
->u
.s
->wfile
, strerror(errno
));
681 if (cp
->u
.fd
!= -1 && close(cp
->u
.fd
))
682 err(FATAL
, "%s: %s", cp
->t
, strerror(errno
));
686 cfclose(cp
->u
.c
, cp
->next
);