Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most
[dragonfly.git] / usr.bin / sed / process.c
1 /*-
2  * Copyright (c) 1992 Diomidis Spinellis.
3  * Copyright (c) 1992, 1993, 1994
4  *      The Regents of the University of California.  All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * Diomidis Spinellis of Imperial College, University of London.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
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.
24  *
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
35  * SUCH DAMAGE.
36  *
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.2 2003/06/17 04:29:31 dillon Exp $
40  */
41
42 #include <sys/types.h>
43 #include <sys/stat.h>
44 #include <sys/ioctl.h>
45 #include <sys/uio.h>
46
47 #include <ctype.h>
48 #include <err.h>
49 #include <errno.h>
50 #include <fcntl.h>
51 #include <limits.h>
52 #include <regex.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <unistd.h>
57
58 #include "defs.h"
59 #include "extern.h"
60
61 static SPACE HS, PS, SS;
62 #define pd              PS.deleted
63 #define ps              PS.space
64 #define psl             PS.len
65 #define hs              HS.space
66 #define hsl             HS.len
67
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 *);
74
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. */
78
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;
83 size_t maxnsub;
84 regmatch_t *match;
85
86 #define OUT(s) { fwrite(s, sizeof(u_char), psl, stdout); putchar('\n'); }
87
88 void
89 process()
90 {
91         struct s_command *cp;
92         SPACE tspace;
93         size_t len, oldpsl = 0;
94         char *p;
95
96         p = NULL;
97
98         for (linenum = 0; mf_fgets(&PS, REPLACE);) {
99                 pd = 0;
100 top:
101                 cp = prog;
102 redirect:
103                 while (cp != NULL) {
104                         if (!applies(cp)) {
105                                 cp = cp->next;
106                                 continue;
107                         }
108                         switch (cp->code) {
109                         case '{':
110                                 cp = cp->u.c;
111                                 goto redirect;
112                         case 'a':
113                                 if (appendx >= appendnum)
114                                         if ((appends = realloc(appends,
115                                             sizeof(struct s_appends) *
116                                             (appendnum *= 2))) == NULL)
117                                                 err(1, "realloc");
118                                 appends[appendx].type = AP_STRING;
119                                 appends[appendx].s = cp->t;
120                                 appends[appendx].len = strlen(cp->t);
121                                 appendx++;
122                                 break;
123                         case 'b':
124                                 cp = cp->u.c;
125                                 goto redirect;
126                         case 'c':
127                                 pd = 1;
128                                 psl = 0;
129                                 if (cp->a2 == NULL || lastaddr)
130                                         (void)printf("%s", cp->t);
131                                 break;
132                         case 'd':
133                                 pd = 1;
134                                 goto new;
135                         case 'D':
136                                 if (pd)
137                                         goto new;
138                                 if (psl == 0 ||
139                                     (p = memchr(ps, '\n', psl)) == NULL) {
140                                         pd = 1;
141                                         goto new;
142                                 } else {
143                                         psl -= (p + 1) - ps;
144                                         memmove(ps, p + 1, psl);
145                                         goto top;
146                                 }
147                         case 'g':
148                                 cspace(&PS, hs, hsl, REPLACE);
149                                 break;
150                         case 'G':
151                                 cspace(&PS, "\n", 1, 0);
152                                 cspace(&PS, hs, hsl, 0);
153                                 break;
154                         case 'h':
155                                 cspace(&HS, ps, psl, REPLACE);
156                                 break;
157                         case 'H':
158                                 cspace(&HS, "\n", 1, 0);
159                                 cspace(&HS, ps, psl, 0);
160                                 break;
161                         case 'i':
162                                 (void)printf("%s", cp->t);
163                                 break;
164                         case 'l':
165                                 lputs(ps);
166                                 break;
167                         case 'n':
168                                 if (!nflag && !pd)
169                                         OUT(ps)
170                                 flush_appends();
171                                 if (!mf_fgets(&PS, REPLACE))
172                                         exit(0);
173                                 pd = 0;
174                                 break;
175                         case 'N':
176                                 flush_appends();
177                                 cspace(&PS, "\n", 1, 0);
178                                 if (!mf_fgets(&PS, 0))
179                                         exit(0);
180                                 break;
181                         case 'p':
182                                 if (pd)
183                                         break;
184                                 OUT(ps)
185                                 break;
186                         case 'P':
187                                 if (pd)
188                                         break;
189                                 if (psl != 0 &&
190                                     (p = memchr(ps, '\n', psl)) != NULL) {
191                                         oldpsl = psl;
192                                         psl = p - ps;
193                                 }
194                                 OUT(ps)
195                                 if (p != NULL)
196                                         psl = oldpsl;
197                                 break;
198                         case 'q':
199                                 if (!nflag && !pd)
200                                         OUT(ps)
201                                 flush_appends();
202                                 exit(0);
203                         case 'r':
204                                 if (appendx >= appendnum)
205                                         if ((appends = realloc(appends,
206                                             sizeof(struct s_appends) *
207                                             (appendnum *= 2))) == NULL)
208                                                 err(1, "realloc");
209                                 appends[appendx].type = AP_FILE;
210                                 appends[appendx].s = cp->t;
211                                 appends[appendx].len = strlen(cp->t);
212                                 appendx++;
213                                 break;
214                         case 's':
215                                 sdone |= substitute(cp);
216                                 break;
217                         case 't':
218                                 if (sdone) {
219                                         sdone = 0;
220                                         cp = cp->u.c;
221                                         goto redirect;
222                                 }
223                                 break;
224                         case 'w':
225                                 if (pd)
226                                         break;
227                                 if (cp->u.fd == -1 && (cp->u.fd = open(cp->t,
228                                     O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
229                                     DEFFILEMODE)) == -1)
230                                         err(1, "%s", cp->t);
231                                 if (write(cp->u.fd, ps, psl) != psl ||
232                                     write(cp->u.fd, "\n", 1) != 1)
233                                         err(1, "%s", cp->t);
234                                 break;
235                         case 'x':
236                                 if (hs == NULL)
237                                         cspace(&HS, "", 0, REPLACE);
238                                 tspace = PS;
239                                 PS = HS;
240                                 HS = tspace;
241                                 break;
242                         case 'y':
243                                 if (pd || psl == 0)
244                                         break;
245                                 for (p = ps, len = psl; len--; ++p)
246                                         *p = cp->u.y[(unsigned char)*p];
247                                 break;
248                         case ':':
249                         case '}':
250                                 break;
251                         case '=':
252                                 (void)printf("%lu\n", linenum);
253                         }
254                         cp = cp->next;
255                 } /* for all cp */
256
257 new:            if (!nflag && !pd)
258                         OUT(ps)
259                 flush_appends();
260         } /* for all lines */
261 }
262
263 /*
264  * TRUE if the address passed matches the current program state
265  * (lastline, linenumber, ps).
266  */
267 #define MATCH(a)                                                \
268         (a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, psl) :       \
269             (a)->type == AT_LINE ? linenum == (a)->u.l : lastline()
270
271 /*
272  * Return TRUE if the command applies to the current line.  Sets the inrange
273  * flag to process ranges.  Interprets the non-select (``!'') flag.
274  */
275 static __inline int
276 applies(cp)
277         struct s_command *cp;
278 {
279         int r;
280
281         lastaddr = 0;
282         if (cp->a1 == NULL && cp->a2 == NULL)
283                 r = 1;
284         else if (cp->a2)
285                 if (cp->inrange) {
286                         if (MATCH(cp->a2)) {
287                                 cp->inrange = 0;
288                                 lastaddr = 1;
289                         }
290                         r = 1;
291                 } else if (MATCH(cp->a1)) {
292                         /*
293                          * If the second address is a number less than or
294                          * equal to the line number first selected, only
295                          * one line shall be selected.
296                          *      -- POSIX 1003.2
297                          */
298                         if (cp->a2->type == AT_LINE &&
299                             linenum >= cp->a2->u.l)
300                                 lastaddr = 1;
301                         else
302                                 cp->inrange = 1;
303                         r = 1;
304                 } else
305                         r = 0;
306         else
307                 r = MATCH(cp->a1);
308         return (cp->nonsel ? ! r : r);
309 }
310
311 /*
312  * substitute --
313  *      Do substitutions in the pattern space.  Currently, we build a
314  *      copy of the new pattern space in the substitute space structure
315  *      and then swap them.
316  */
317 static int
318 substitute(cp)
319         struct s_command *cp;
320 {
321         SPACE tspace;
322         regex_t *re;
323         regoff_t re_off, slen;
324         int lastempty, n;
325         char *s;
326
327         s = ps;
328         re = cp->u.s->re;
329         if (re == NULL) {
330                 if (defpreg != NULL && cp->u.s->maxbref > defpreg->re_nsub) {
331                         linenum = cp->u.s->linenum;
332                         errx(1, "%lu: %s: \\%d not defined in the RE",
333                                         linenum, fname, cp->u.s->maxbref);
334                 }
335         }
336         if (!regexec_e(re, s, 0, 0, psl))
337                 return (0);
338
339         SS.len = 0;                             /* Clean substitute space. */
340         slen = psl;
341         n = cp->u.s->n;
342         lastempty = 1;
343
344         switch (n) {
345         case 0:                                 /* Global */
346                 do {
347                         if (lastempty || match[0].rm_so != match[0].rm_eo) {
348                                 /* Locate start of replaced string. */
349                                 re_off = match[0].rm_so;
350                                 /* Copy leading retained string. */
351                                 cspace(&SS, s, re_off, APPEND);
352                                 /* Add in regular expression. */
353                                 regsub(&SS, s, cp->u.s->new);
354                         }
355
356                         /* Move past this match. */
357                         if (match[0].rm_so != match[0].rm_eo) {
358                                 s += match[0].rm_eo;
359                                 slen -= match[0].rm_eo;
360                                 lastempty = 0;
361                         } else {
362                                 if (match[0].rm_so < slen)
363                                         cspace(&SS, s + match[0].rm_so, 1,
364                                             APPEND);
365                                 s += match[0].rm_so + 1;
366                                 slen -= match[0].rm_so + 1;
367                                 lastempty = 1;
368                         }
369                 } while (slen >= 0 && regexec_e(re, s, REG_NOTBOL, 0, slen));
370                 /* Copy trailing retained string. */
371                 if (slen > 0)
372                         cspace(&SS, s, slen, APPEND);
373                 break;
374         default:                                /* Nth occurrence */
375                 while (--n) {
376                         if (match[0].rm_eo == match[0].rm_so)
377                                 match[0].rm_eo = match[0].rm_so + 1;
378                         s += match[0].rm_eo;
379                         slen -= match[0].rm_eo;
380                         if (slen < 0)
381                                 return (0);
382                         if (!regexec_e(re, s, REG_NOTBOL, 0, slen))
383                                 return (0);
384                 }
385                 /* FALLTHROUGH */
386         case 1:                                 /* 1st occurrence */
387                 /* Locate start of replaced string. */
388                 re_off = match[0].rm_so + (s - ps);
389                 /* Copy leading retained string. */
390                 cspace(&SS, ps, re_off, APPEND);
391                 /* Add in regular expression. */
392                 regsub(&SS, s, cp->u.s->new);
393                 /* Copy trailing retained string. */
394                 s += match[0].rm_eo;
395                 slen -= match[0].rm_eo;
396                 cspace(&SS, s, slen, APPEND);
397                 break;
398         }
399
400         /*
401          * Swap the substitute space and the pattern space, and make sure
402          * that any leftover pointers into stdio memory get lost.
403          */
404         tspace = PS;
405         PS = SS;
406         SS = tspace;
407         SS.space = SS.back;
408
409         /* Handle the 'p' flag. */
410         if (cp->u.s->p)
411                 OUT(ps)
412
413         /* Handle the 'w' flag. */
414         if (cp->u.s->wfile && !pd) {
415                 if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile,
416                     O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1)
417                         err(1, "%s", cp->u.s->wfile);
418                 if (write(cp->u.s->wfd, ps, psl) != psl ||
419                     write(cp->u.s->wfd, "\n", 1) != 1)
420                         err(1, "%s", cp->u.s->wfile);
421         }
422         return (1);
423 }
424
425 /*
426  * Flush append requests.  Always called before reading a line,
427  * therefore it also resets the substitution done (sdone) flag.
428  */
429 static void
430 flush_appends()
431 {
432         FILE *f;
433         int count, i;
434         char buf[8 * 1024];
435
436         for (i = 0; i < appendx; i++)
437                 switch (appends[i].type) {
438                 case AP_STRING:
439                         fwrite(appends[i].s, sizeof(char), appends[i].len,
440                             stdout);
441                         break;
442                 case AP_FILE:
443                         /*
444                          * Read files probably shouldn't be cached.  Since
445                          * it's not an error to read a non-existent file,
446                          * it's possible that another program is interacting
447                          * with the sed script through the filesystem.  It
448                          * would be truly bizarre, but possible.  It's probably
449                          * not that big a performance win, anyhow.
450                          */
451                         if ((f = fopen(appends[i].s, "r")) == NULL)
452                                 break;
453                         while ((count = fread(buf, sizeof(char), sizeof(buf), f)))
454                                 (void)fwrite(buf, sizeof(char), count, stdout);
455                         (void)fclose(f);
456                         break;
457                 }
458         if (ferror(stdout))
459                 errx(1, "stdout: %s", strerror(errno ? errno : EIO));
460         appendx = sdone = 0;
461 }
462
463 static void
464 lputs(s)
465         char *s;
466 {
467         int count;
468         const char *escapes;
469         char *p;
470         struct winsize win;
471         static int termwidth = -1;
472
473         if (termwidth == -1) {
474                 if ((p = getenv("COLUMNS")) && *p != '\0')
475                         termwidth = atoi(p);
476                 else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
477                     win.ws_col > 0)
478                         termwidth = win.ws_col;
479                 else
480                         termwidth = 60;
481         }
482
483         for (count = 0; *s; ++s) {
484                 if (count + 5 >= termwidth) {
485                         (void)printf("\\\n");
486                         count = 0;
487                 }
488                 if (isprint((unsigned char)*s) && *s != '\\') {
489                         (void)putchar(*s);
490                         count++;
491                 } else if (*s == '\n') {
492                         (void)putchar('$');
493                         (void)putchar('\n');
494                         count = 0;
495                 } else {
496                         escapes = "\\\a\b\f\r\t\v";
497                         (void)putchar('\\');
498                         if ((p = strchr(escapes, *s))) {
499                                 (void)putchar("\\abfrtv"[p - escapes]);
500                                 count += 2;
501                         } else {
502                                 (void)printf("%03o", *(u_char *)s);
503                                 count += 4;
504                         }
505                 }
506         }
507         (void)putchar('$');
508         (void)putchar('\n');
509         if (ferror(stdout))
510                 errx(1, "stdout: %s", strerror(errno ? errno : EIO));
511 }
512
513 static __inline int
514 regexec_e(preg, string, eflags, nomatch, slen)
515         regex_t *preg;
516         const char *string;
517         int eflags, nomatch;
518         size_t slen;
519 {
520         int eval;
521
522         if (preg == NULL) {
523                 if (defpreg == NULL)
524                         errx(1, "first RE may not be empty");
525         } else
526                 defpreg = preg;
527
528         /* Set anchors */
529         match[0].rm_so = 0;
530         match[0].rm_eo = slen;
531
532         eval = regexec(defpreg, string,
533             nomatch ? 0 : maxnsub + 1, match, eflags | REG_STARTEND);
534         switch(eval) {
535         case 0:
536                 return (1);
537         case REG_NOMATCH:
538                 return (0);
539         }
540         errx(1, "RE error: %s", strregerror(eval, defpreg));
541         /* NOTREACHED */
542 }
543
544 /*
545  * regsub - perform substitutions after a regexp match
546  * Based on a routine by Henry Spencer
547  */
548 static void
549 regsub(sp, string, src)
550         SPACE *sp;
551         char *string, *src;
552 {
553         int len, no;
554         char c, *dst;
555
556 #define NEEDSP(reqlen)                                                  \
557         if (sp->len >= sp->blen - (reqlen) - 1) {                       \
558                 sp->blen += (reqlen) + 1024;                            \
559                 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) \
560                     == NULL)                                            \
561                         err(1, "realloc");                              \
562                 dst = sp->space + sp->len;                              \
563         }
564
565         dst = sp->space + sp->len;
566         while ((c = *src++) != '\0') {
567                 if (c == '&')
568                         no = 0;
569                 else if (c == '\\' && isdigit((unsigned char)*src))
570                         no = *src++ - '0';
571                 else
572                         no = -1;
573                 if (no < 0) {           /* Ordinary character. */
574                         if (c == '\\' && (*src == '\\' || *src == '&'))
575                                 c = *src++;
576                         NEEDSP(1);
577                         *dst++ = c;
578                         ++sp->len;
579                 } else if (match[no].rm_so != -1 && match[no].rm_eo != -1) {
580                         len = match[no].rm_eo - match[no].rm_so;
581                         NEEDSP(len);
582                         memmove(dst, string + match[no].rm_so, len);
583                         dst += len;
584                         sp->len += len;
585                 }
586         }
587         NEEDSP(1);
588         *dst = '\0';
589 }
590
591 /*
592  * aspace --
593  *      Append the source space to the destination space, allocating new
594  *      space as necessary.
595  */
596 void
597 cspace(sp, p, len, spflag)
598         SPACE *sp;
599         const char *p;
600         size_t len;
601         enum e_spflag spflag;
602 {
603         size_t tlen;
604
605         /* Make sure SPACE has enough memory and ramp up quickly. */
606         tlen = sp->len + len + 1;
607         if (tlen > sp->blen) {
608                 sp->blen = tlen + 1024;
609                 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) ==
610                     NULL)
611                         err(1, "realloc");
612         }
613
614         if (spflag == REPLACE)
615                 sp->len = 0;
616
617         memmove(sp->space + sp->len, p, len);
618
619         sp->space[sp->len += len] = '\0';
620 }
621
622 /*
623  * Close all cached opened files and report any errors
624  */
625 void
626 cfclose(cp, end)
627         struct s_command *cp, *end;
628 {
629
630         for (; cp != end; cp = cp->next)
631                 switch(cp->code) {
632                 case 's':
633                         if (cp->u.s->wfd != -1 && close(cp->u.s->wfd))
634                                 err(1, "%s", cp->u.s->wfile);
635                         cp->u.s->wfd = -1;
636                         break;
637                 case 'w':
638                         if (cp->u.fd != -1 && close(cp->u.fd))
639                                 err(1, "%s", cp->t);
640                         cp->u.fd = -1;
641                         break;
642                 case '{':
643                         cfclose(cp->u.c, cp->next);
644                         break;
645                 }
646 }