aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

sed.c (47481B)


      1 
      2 
      3 /* FIXME: summary
      4  * decide whether we enforce valid UTF-8, right now its enforced in certain
      5  * parts of the script, but not the input...
      6  * nul bytes cause explosions due to use of libc string functions. thoughts?
      7  * lack of newline at end of file, currently we add one. what should we do?
      8  * allow "\\t" for "\t" etc. in regex? in replacement text?
      9  * POSIX says dont flush on n when out of input, but GNU and busybox do
     10  */
     11 
     12 #if FEATURE_SED_ASCII
     13 #ifndef _DEFAULT_SOURCE
     14 #define _DEFAULT_SOURCE
     15 #endif
     16 #endif
     17 #include "config.h"
     18 #include "utf.h"
     19 #include "util.h"
     20 
     21 #include <ctype.h>
     22 #include <errno.h>
     23 #include <libgen.h>
     24 #include <regex.h>
     25 #include <stdlib.h>
     26 #include <string.h>
     27 #include <sys/stat.h>
     28 #include <unistd.h>
     29 
     30 /* types */
     31 
     32 /* used as queue for writes and stack for {,:,b,t */
     33 typedef struct {
     34   void **data;
     35   size_t size;
     36   size_t cap;
     37 } Vec;
     38 
     39 /* used for arbitrary growth, str is a c string
     40  * FIXME: does it make sense to keep track of length? or just rely on libc
     41  * string functions? if we want to support nul bytes everything changes
     42  */
     43 typedef struct {
     44   char  *str;
     45   size_t cap;
     46 } String;
     47 
     48 typedef struct Cmd Cmd;
     49 typedef struct {
     50   void (*fn)(Cmd *);
     51   char *(*getarg)(Cmd *, char *);
     52   void (*freearg)(Cmd *);
     53   unsigned char naddr;
     54 } Fninfo;
     55 
     56 typedef struct {
     57   union {
     58     size_t   lineno;
     59     regex_t *re;
     60   } u;
     61   enum {
     62     IGNORE, /* empty address, ignore */
     63     EVERY,  /* every line */
     64     LINE,   /* line number */
     65     LAST,   /* last line ($) */
     66     REGEX,  /* use included regex */
     67     LASTRE, /* use most recently used regex */
     68   } type;
     69 } Addr;
     70 
     71 /* DISCUSS: naddr is not strictly necessary, but very helpful
     72  * naddr == 0 iff beg.type == EVERY && end.type == IGNORE
     73  * naddr == 1 iff beg.type != IGNORE && end.type == IGNORE
     74  * naddr == 2 iff beg.type != IGNORE && end.type != IGNORE
     75  */
     76 typedef struct {
     77   Addr          beg;
     78   Addr          end;
     79   unsigned char naddr;
     80 } Range;
     81 
     82 typedef struct {
     83   regex_t     *re; /* if NULL use last regex */
     84   String       repl;
     85   FILE        *file;
     86   size_t       occurrence; /* 0 for all (g flag) */
     87   Rune         delim;
     88   unsigned int p : 1;
     89 } Sarg;
     90 
     91 typedef struct {
     92   Rune *set1;
     93   Rune *set2;
     94 } Yarg;
     95 
     96 typedef struct {
     97   String str;                    /* a,c,i text. r file path */
     98   void (*print)(char *, FILE *); /* check_puts for a, write_file for r,
     99                                   * unused for c,i */
    100 } ACIRarg;
    101 
    102 struct Cmd {
    103   Range   range;
    104   Fninfo *fninfo;
    105   union {
    106     Cmd      *jump;   /* used for b,t when running */
    107     char     *label;  /* used for :,b,t when building */
    108     ptrdiff_t offset; /* used for { (pointers break during realloc) */
    109     FILE     *file;   /* used for w */
    110 
    111     /* FIXME: should the following be in the union? or pointers and
    112      * malloc? */
    113     Sarg    s;
    114     Yarg    y;
    115     ACIRarg acir;
    116   } u; /* i find your lack of anonymous unions disturbing */
    117   unsigned int in_match : 1;
    118   unsigned int negate : 1;
    119 };
    120 
    121 /* files for w command (and s' w flag) */
    122 typedef struct {
    123   char *path;
    124   FILE *file;
    125 } Wfile;
    126 
    127 /*
    128  * function declarations
    129  */
    130 
    131 /* dynamically allocated arrays and strings */
    132 static void  resize(void **ptr, size_t *nmemb, size_t size, size_t new_nmemb, void **next);
    133 static void *pop(Vec *v);
    134 static void  push(Vec *v, void *p);
    135 static void  stracat(String *dst, char *src);
    136 static void  strnacat(String *dst, char *src, size_t n);
    137 static void  stracpy(String *dst, char *src);
    138 
    139 /* cleanup and errors */
    140 static void usage(void);
    141 
    142 /* parsing functions and related utilities */
    143 static void   compile(char *s, int isfile);
    144 static int    read_line(FILE *f, String *s);
    145 static char  *make_range(Range *range, char *s);
    146 static char  *make_addr(Addr *addr, char *s);
    147 static char  *find_delim(char *s, Rune delim, int do_brackets);
    148 static char  *chompr(char *s, Rune rune);
    149 static char  *chomp(char *s);
    150 static Rune  *strtorunes(char *s, size_t nrunes);
    151 static long   stol(char *s, char **endp);
    152 static size_t escapes(char *beg, char *end, Rune delim, int n_newline);
    153 static size_t echarntorune(Rune *r, char *s, size_t n);
    154 static void   insert_labels(void);
    155 
    156 /* get and free arg and related utilities */
    157 static char *get_aci_arg(Cmd *c, char *s);
    158 static void  aci_append(Cmd *c, char *s);
    159 static void  free_acir_arg(Cmd *c);
    160 static char *get_bt_arg(Cmd *c, char *s);
    161 static char *get_r_arg(Cmd *c, char *s);
    162 static char *get_s_arg(Cmd *c, char *s);
    163 static void  free_s_arg(Cmd *c);
    164 static char *get_w_arg(Cmd *c, char *s);
    165 static char *get_y_arg(Cmd *c, char *s);
    166 static void  free_y_arg(Cmd *c);
    167 static char *get_colon_arg(Cmd *c, char *s);
    168 static char *get_lbrace_arg(Cmd *c, char *s);
    169 static char *get_rbrace_arg(Cmd *c, char *s);
    170 static char *semicolon_arg(char *s);
    171 
    172 /* running */
    173 static void run(void);
    174 static int  in_range(Cmd *c);
    175 static int  match_addr(Addr *a);
    176 static int  next_file(void);
    177 static int  is_eof(FILE *f);
    178 static void do_writes(void);
    179 static void write_file(char *path, FILE *out);
    180 static void check_puts(char *s, FILE *f);
    181 static void write_patt(char *s, FILE *f);
    182 static void update_ranges(Cmd *beg, Cmd *end);
    183 
    184 /* sed functions */
    185 static void cmd_y(Cmd *c);
    186 static void cmd_x(Cmd *c);
    187 static void cmd_w(Cmd *c);
    188 static void cmd_t(Cmd *c);
    189 static void cmd_s(Cmd *c);
    190 static void cmd_r(Cmd *c);
    191 static void cmd_q(Cmd *c);
    192 static void cmd_P(Cmd *c);
    193 static void cmd_p(Cmd *c);
    194 static void cmd_N(Cmd *c);
    195 static void cmd_n(Cmd *c);
    196 static void cmd_l(Cmd *c);
    197 static void cmd_i(Cmd *c);
    198 static void cmd_H(Cmd *c);
    199 static void cmd_h(Cmd *c);
    200 static void cmd_G(Cmd *c);
    201 static void cmd_g(Cmd *c);
    202 static void cmd_D(Cmd *c);
    203 static void cmd_d(Cmd *c);
    204 static void cmd_c(Cmd *c);
    205 static void cmd_b(Cmd *c);
    206 static void cmd_a(Cmd *c);
    207 static void cmd_colon(Cmd *c);
    208 static void cmd_equal(Cmd *c);
    209 static void cmd_lbrace(Cmd *c);
    210 static void cmd_rbrace(Cmd *c);
    211 static void cmd_last(Cmd *c);
    212 
    213 /* actions */
    214 static void new_line(void);
    215 static void app_line(void);
    216 static void new_next(void);
    217 static void old_next(void);
    218 
    219 /*
    220  * globals
    221  */
    222 static Vec braces, labels, branches; /* holds ptrdiff_t. addrs of {, :, bt */
    223 static Vec writes;                   /* holds cmd*. writes scheduled by a and r commands */
    224 static Vec wfiles;                   /* holds Wfile*. files for w and s// /w commands */
    225 
    226 static Cmd   *prog, *pc; /* program, program counter */
    227 static size_t pcap;
    228 static size_t lineno;
    229 #if FEATURE_SED_PRESERVE_NEWLINE
    230 static int hadnl = 1;
    231 #endif
    232 
    233 static regex_t *lastre; /* last used regex for empty regex search */
    234 static char   **files;  /* list of file names from argv */
    235 static FILE    *file;   /* current file we are reading */
    236 static int      ret;    /* exit status */
    237 
    238 static String patt, hold, genbuf;
    239 
    240 static struct {
    241   unsigned int n : 1;        /* -n (no print) */
    242   unsigned int E : 1;        /* -E (extended re) */
    243   unsigned int s : 1;        /* s// / replacement happened */
    244   unsigned int aci_cont : 1; /* a,c,i text continuation */
    245   unsigned int s_cont : 1;   /* s// / replacement text continuation */
    246   unsigned int halt : 1;     /* halt execution */
    247 } gflags;
    248 
    249 /* FIXME: move character inside fninfo and only use 26*sizeof(fninfo) instead of
    250  * 127*sizeof(fninfo) bytes */
    251 static Fninfo fns[] = {
    252     ['a'] = {cmd_a, get_aci_arg, free_acir_arg, 1}, /* schedule write of text for later */
    253     ['b'] = {cmd_b, get_bt_arg, NULL, 2}, /* branch to label char *label when building, cmd *jump
    254                                            * when running */
    255     ['c'] = {cmd_c, get_aci_arg, free_acir_arg, 2}, /* delete pattern space. at 0 or 1 addr or end
    256                                                      * of 2 addr, write text */
    257     ['d'] = {cmd_d, NULL, NULL, 2},                 /* delete pattern space */
    258     ['D'] = {cmd_D, NULL, NULL, 2}, /* delete to first newline and start new cycle without
    259                                      * reading (if no newline, d) */
    260     ['g'] = {cmd_g, NULL, NULL, 2}, /* replace pattern space with hold space */
    261     ['G'] = {cmd_G, NULL, NULL, 2}, /* append newline and hold space to pattern space */
    262     ['h'] = {cmd_h, NULL, NULL, 2}, /* replace hold space with pattern space */
    263     ['H'] = {cmd_H, NULL, NULL, 2}, /* append newline and pattern space to hold space */
    264     ['i'] = {cmd_i, get_aci_arg, free_acir_arg, 1}, /* write text */
    265     ['l'] = {cmd_l, NULL, NULL, 2}, /* write pattern space in 'visually unambiguous form' */
    266     ['n'] = {cmd_n, NULL, NULL, 2}, /* write pattern space (unless -n) read to replace pattern
    267                                      * space (if no input, quit) */
    268     ['N'] = {cmd_N, NULL, NULL, 2}, /* append to pattern space separated by newline, line
    269                                      * number changes (if no input, quit) */
    270     ['p'] = {cmd_p, NULL, NULL, 2}, /* write pattern space */
    271     ['P'] = {cmd_P, NULL, NULL, 2}, /* write pattern space up to first newline */
    272     ['q'] = {cmd_q, NULL, NULL, 1}, /* quit */
    273     ['r'] = {cmd_r, get_r_arg, free_acir_arg, 1}, /* write contents of file (unable to open/read
    274                                                    * treated as empty file) */
    275     ['s'] = {cmd_s, get_s_arg, free_s_arg, 2},    /* find/replace/all that crazy s stuff */
    276     ['t'] = {cmd_t, get_bt_arg, NULL, 2}, /* if s// / succeeded (since input or last t) branch to
    277                                        label (branch to end if no label) */
    278     ['w'] = {cmd_w, get_w_arg, NULL, 2},  /* append pattern space to file */
    279     ['x'] = {cmd_x, NULL, NULL, 2},       /* exchange pattern and hold spaces */
    280     ['y'] = {cmd_y, get_y_arg, free_y_arg, 2},     /* replace runes in set1 with runes in set2 */
    281     [':'] = {cmd_colon, get_colon_arg, NULL, 0},   /* defines label for later b and t commands */
    282     ['='] = {cmd_equal, NULL, NULL, 1},            /* printf("%d\n", line_number); */
    283     ['{'] = {cmd_lbrace, get_lbrace_arg, NULL, 2}, /* if we match, run commands, otherwise jump to
    284                                                     * close */
    285     ['}'] = {cmd_rbrace, get_rbrace_arg, NULL, 0}, /* noop, hold onto open for ease of building
    286                                                     * scripts */
    287 
    288     [0x7f] = {NULL, NULL, NULL, 0}, /* index is checked with isascii(3p)
    289                                      * fill out rest of array */
    290 };
    291 
    292 /*
    293  * function definitions
    294  */
    295 
    296 /* given memory pointed to by *ptr that currently holds *nmemb members of size
    297  * size, realloc to hold new_nmemb members, return new_nmemb in *memb and one
    298  * past old end in *next. if realloc fails...explode
    299  */
    300 static void
    301 resize(void **ptr, size_t *nmemb, size_t size, size_t new_nmemb, void **next)
    302 {
    303   void *n, *tmp;
    304 
    305   if (new_nmemb) {
    306     tmp = ereallocarray(*ptr, new_nmemb, size);
    307   } else { /* turns out realloc(*ptr, 0) != free(*ptr) */
    308     free(*ptr);
    309     tmp = NULL;
    310   }
    311   n      = (char *)tmp + *nmemb * size;
    312   *nmemb = new_nmemb;
    313   *ptr   = tmp;
    314   if (next)
    315     *next = n;
    316 }
    317 
    318 static void *
    319 pop(Vec *v)
    320 {
    321   if (!v->size)
    322     return NULL;
    323   return v->data[--v->size];
    324 }
    325 
    326 static void
    327 push(Vec *v, void *p)
    328 {
    329   if (v->size == v->cap)
    330     resize((void **)&v->data, &v->cap, sizeof(*v->data), v->cap * 2 + 1, NULL);
    331   v->data[v->size++] = p;
    332 }
    333 
    334 static void
    335 stracat(String *dst, char *src)
    336 {
    337   int new = !dst->cap;
    338   size_t len;
    339 
    340   len = (new ? 0 : strlen(dst->str)) + strlen(src) + 1;
    341   if (dst->cap < len)
    342     resize((void **)&dst->str, &dst->cap, 1, len * 2, NULL);
    343   if (new)
    344     *dst->str = '\0';
    345   strcat(dst->str, src);
    346 }
    347 
    348 static void
    349 strnacat(String *dst, char *src, size_t n)
    350 {
    351   int new = !dst->cap;
    352   size_t len;
    353 
    354   len = strlen(src);
    355   len = (new ? 0 : strlen(dst->str)) + MIN(n, len) + 1;
    356   if (dst->cap < len)
    357     resize((void **)&dst->str, &dst->cap, 1, len * 2, NULL);
    358   if (new)
    359     *dst->str = '\0';
    360   strlcat(dst->str, src, len);
    361 }
    362 
    363 static void
    364 stracpy(String *dst, char *src)
    365 {
    366   size_t len;
    367 
    368   len = strlen(src) + 1;
    369   if (dst->cap < len)
    370     resize((void **)&dst->str, &dst->cap, 1, len * 2, NULL);
    371   strcpy(dst->str, src);
    372 }
    373 
    374 static void
    375 leprintf(char *s)
    376 {
    377   if (errno)
    378     eprintf("%zu: %s: %s\n", lineno, s, strerror(errno));
    379   else
    380     eprintf("%zu: %s\n", lineno, s);
    381 }
    382 
    383 /* FIXME: write usage message */
    384 #if FEATURE_SED_INPLACE
    385 static int   iflag         = 0;
    386 static char *backup_suffix = NULL;
    387 
    388 static int
    389 create_temp_file(const char *orig_path, char **temp_path)
    390 {
    391   char *dir, *dircopy, *tmpl;
    392   int   fd;
    393 
    394   dircopy = estrdup(orig_path);
    395   dir     = dirname(dircopy);
    396   tmpl    = emalloc(strlen(dir) + 16);
    397   sprintf(tmpl, "%s/sedtmpXXXXXX", dir);
    398   free(dircopy);
    399 
    400   fd = mkstemp(tmpl);
    401   if (fd < 0) {
    402     free(tmpl);
    403     return -1;
    404   }
    405   *temp_path = tmpl;
    406   return fd;
    407 }
    408 #endif
    409 
    410 static void
    411 usage(void)
    412 {
    413   eprintf(
    414       "usage: sed [-nrE] script [file ...]\n"
    415       "       sed [-nrE] -e script [-e script] ... [-f scriptfile] "
    416       "... [file ...]\n"
    417       "       sed [-nrE] [-e script] ... -f scriptfile [-f "
    418       "scriptfile] ... [file ...]\n"
    419   );
    420 }
    421 
    422 /* differences from POSIX
    423  * we allows semicolons and trailing blanks inside {}
    424  * we allow spaces after ! (and in between !s)
    425  * we allow extended regular expressions (-E)
    426  */
    427 static void
    428 compile(char *s, int isfile)
    429 {
    430   FILE *f;
    431 
    432   if (isfile) {
    433     f = fopen(s, "r");
    434     if (!f)
    435       eprintf("fopen %s:", s);
    436   } else {
    437     if (!*s) /* empty string script */
    438       return;
    439     f = fmemopen(s, strlen(s), "r");
    440     if (!f)
    441       eprintf("fmemopen:");
    442   }
    443 
    444   /* NOTE: get arg functions cant use genbuf */
    445   while (read_line(f, &genbuf) != EOF) {
    446     s = genbuf.str;
    447 
    448     /* if the first two characters of the script are "#n" default
    449      * output shall be suppressed */
    450     if (++lineno == 1 && *s == '#' && s[1] == 'n') {
    451       gflags.n = 1;
    452       continue;
    453     }
    454 
    455     if (gflags.aci_cont) {
    456       aci_append(pc - 1, s);
    457       continue;
    458     }
    459     if (gflags.s_cont)
    460       s = (pc - 1)->fninfo->getarg(pc - 1, s);
    461 
    462     while (*s) {
    463       s = chompr(s, ';');
    464       if (!*s || *s == '#')
    465         break;
    466 
    467       if ((size_t)(pc - prog) == pcap)
    468         resize((void **)&prog, &pcap, sizeof(*prog), pcap * 2 + 1, (void **)&pc);
    469 
    470       pc->range.beg.type = pc->range.end.type = IGNORE;
    471       pc->fninfo                              = NULL;
    472       pc->in_match                            = 0;
    473 
    474       s          = make_range(&pc->range, s);
    475       s          = chomp(s);
    476       pc->negate = *s == '!';
    477       s          = chompr(s, '!');
    478 
    479       if (!isascii(*s) || !(pc->fninfo = &fns[(unsigned)*s])->fn)
    480         leprintf("bad sed function");
    481       if (pc->range.naddr > pc->fninfo->naddr)
    482         leprintf("wrong number of addresses");
    483       s++;
    484 
    485       if (pc->fninfo->getarg)
    486         s = pc->fninfo->getarg(pc, s);
    487 
    488       pc++;
    489     }
    490   }
    491 
    492   fshut(f, s);
    493 }
    494 
    495 /* FIXME: if we decide to honor lack of trailing newline, set/clear a global
    496  * flag when reading a line
    497  */
    498 static int
    499 read_line(FILE *f, String *s)
    500 {
    501   ssize_t len;
    502 
    503   if (!f)
    504     return EOF;
    505 
    506   if ((len = getline(&s->str, &s->cap, f)) < 0) {
    507     if (ferror(f))
    508       eprintf("getline:");
    509     return EOF;
    510   }
    511 #if FEATURE_SED_PRESERVE_NEWLINE
    512   if (len > 0)
    513     hadnl = (s->str[len - 1] == '\n');
    514 #endif
    515   if (s->str[--len] == '\n')
    516     s->str[len] = '\0';
    517   return 0;
    518 }
    519 
    520 /* read first range from s, return pointer to one past end of range */
    521 static char *
    522 make_range(Range *range, char *s)
    523 {
    524   s = make_addr(&range->beg, s);
    525 
    526   if (*s == ',')
    527     s = make_addr(&range->end, s + 1);
    528   else
    529     range->end.type = IGNORE;
    530 
    531   if (range->beg.type == EVERY && range->end.type == IGNORE)
    532     range->naddr = 0;
    533   else if (range->beg.type != IGNORE && range->end.type == IGNORE)
    534     range->naddr = 1;
    535   else if (range->beg.type != IGNORE && range->end.type != IGNORE)
    536     range->naddr = 2;
    537   else
    538     leprintf("this is impossible...");
    539 
    540   return s;
    541 }
    542 
    543 /* read first addr from s, return pointer to one past end of addr */
    544 static char *
    545 make_addr(Addr *addr, char *s)
    546 {
    547   Rune   r;
    548   char  *p    = s + strlen(s);
    549   size_t rlen = echarntorune(&r, s, p - s);
    550 
    551   if (r == '$') {
    552     addr->type = LAST;
    553     s += rlen;
    554   } else if (isdigitrune(r)) {
    555     addr->type     = LINE;
    556     addr->u.lineno = stol(s, &s);
    557   } else if (r == '/' || r == '\\') {
    558     Rune delim;
    559     if (r == '\\') {
    560       s += rlen;
    561       rlen = echarntorune(&r, s, p - s);
    562     }
    563     if (r == '\\')
    564       leprintf("bad delimiter '\\'");
    565     delim = r;
    566     s += rlen;
    567     rlen = echarntorune(&r, s, p - s);
    568     if (r == delim) {
    569       addr->type = LASTRE;
    570       s += rlen;
    571     } else {
    572       addr->type = REGEX;
    573       p          = find_delim(s, delim, 1);
    574       if (!*p)
    575         leprintf("unclosed regex");
    576       p -= escapes(s, p, delim, 0);
    577       *p++       = '\0';
    578       addr->u.re = emalloc(sizeof(*addr->u.re));
    579       eregcomp(addr->u.re, s, gflags.E ? REG_EXTENDED : 0);
    580       s = p;
    581     }
    582   } else {
    583     addr->type = EVERY;
    584   }
    585 
    586   return s;
    587 }
    588 
    589 /* return pointer to first delim in s that is not escaped
    590  * and if do_brackets is set, not in [] (note possible [::], [..], [==], inside
    591  * []) return pointer to trailing nul byte if no delim found
    592  *
    593  * any escaped character that is not special is just itself (POSIX undefined)
    594  * FIXME: pull out into some util thing, will be useful for ed as well
    595  */
    596 static char *
    597 find_delim(char *s, Rune delim, int do_brackets)
    598 {
    599   enum {
    600     OUTSIDE,          /* not in brackets */
    601     BRACKETS_OPENING, /* last char was first [ or last two were
    602                        * first [^ */
    603     BRACKETS_INSIDE,  /* inside [] */
    604     INSIDE_OPENING,   /* inside [] and last char was [ */
    605     CLASS_INSIDE,     /* inside class [::], or colating element [..] or
    606                        * [==], inside [] */
    607     CLASS_CLOSING,    /* inside class [::], or colating element [..] or
    608                        * [==], and last character was the respective :
    609                        * . or = */
    610   } state = OUTSIDE;
    611 
    612   Rune   r, c = 0; /* no c wont be used uninitialized, shutup -wall */
    613   size_t rlen;
    614   int    escape = 0;
    615   char  *end    = s + strlen(s);
    616 
    617   for (; *s; s += rlen) {
    618     rlen = echarntorune(&r, s, end - s);
    619 
    620     if (state == BRACKETS_OPENING && r == '^') {
    621       continue;
    622     } else if (state == BRACKETS_OPENING && r == ']') {
    623       state = BRACKETS_INSIDE;
    624       continue;
    625     } else if (state == BRACKETS_OPENING) {
    626       state = BRACKETS_INSIDE;
    627     }
    628 
    629     if (state == CLASS_CLOSING && r == ']') {
    630       state = BRACKETS_INSIDE;
    631     } else if (state == CLASS_CLOSING) {
    632       state = CLASS_INSIDE;
    633     } else if (state == CLASS_INSIDE && r == c) {
    634       state = CLASS_CLOSING;
    635     } else if (state == INSIDE_OPENING && (r == ':' || r == '.' || r == '=')) {
    636       state = CLASS_INSIDE;
    637       c     = r;
    638     } else if (state == INSIDE_OPENING && r == ']') {
    639       state = OUTSIDE;
    640     } else if (state == INSIDE_OPENING) {
    641       state = BRACKETS_INSIDE;
    642     } else if (state == BRACKETS_INSIDE && r == '[') {
    643       state = INSIDE_OPENING;
    644     } else if (state == BRACKETS_INSIDE && r == ']') {
    645       state = OUTSIDE;
    646     } else if (state == OUTSIDE && escape) {
    647       escape = 0;
    648     } else if (state == OUTSIDE && r == '\\') {
    649       escape = 1;
    650     } else if (state == OUTSIDE && r == delim)
    651       return s;
    652     else if (state == OUTSIDE && do_brackets && r == '[') {
    653       state = BRACKETS_OPENING;
    654     }
    655   }
    656   return s;
    657 }
    658 
    659 static char *
    660 chomp(char *s)
    661 {
    662   return chompr(s, 0);
    663 }
    664 
    665 /* eat all leading whitespace and occurrences of rune */
    666 static char *
    667 chompr(char *s, Rune rune)
    668 {
    669   Rune   r;
    670   size_t rlen;
    671   char  *end = s + strlen(s);
    672 
    673   while (*s && (rlen = echarntorune(&r, s, end - s)) && (isspacerune(r) || r == rune))
    674     s += rlen;
    675   return s;
    676 }
    677 
    678 /* convert first nrunes runes from UTF-8 string s in allocated rune*
    679  * NOTE: sequence must be valid UTF-8, check first */
    680 static Rune *
    681 strtorunes(char *s, size_t nrunes)
    682 {
    683   Rune *rs, *rp;
    684 
    685   rp = rs = ereallocarray(NULL, nrunes + 1, sizeof(*rs));
    686 
    687   while (nrunes--)
    688     s += chartorune(rp++, s);
    689 
    690   *rp = '\0';
    691   return rs;
    692 }
    693 
    694 static long
    695 stol(char *s, char **endp)
    696 {
    697   long n;
    698   errno = 0;
    699   n     = strtol(s, endp, 10);
    700 
    701   if (errno)
    702     leprintf("strtol:");
    703   if (*endp == s)
    704     leprintf("strtol: invalid number");
    705 
    706   return n;
    707 }
    708 
    709 /* from beg to end replace "\\d" with "d" and "\\n" with "\n" (where d is delim)
    710  * if delim is 'n' and n_newline is 0 then "\\n" is replaced with "n" (normal)
    711  * if delim is 'n' and n_newline is 1 then "\\n" is replaced with "\n" (y
    712  * command) if delim is 0 all escaped characters represent themselves (aci text)
    713  * memmove rest of string (beyond end) into place
    714  * return the number of converted escapes (backslashes removed)
    715  * FIXME: this has had too many corner cases slapped on and is ugly. rewrite
    716  * better
    717  */
    718 static size_t
    719 escapes(char *beg, char *end, Rune delim, int n_newline)
    720 {
    721   size_t num = 0;
    722   char  *src = beg, *dst = beg;
    723 
    724   while (src < end) {
    725     /* handle escaped backslash specially so we dont think the
    726      * second backslash is escaping something */
    727     if (*src == '\\' && src[1] == '\\') {
    728       *dst++ = *src++;
    729       if (delim)
    730         *dst++ = *src++;
    731       else
    732         src++;
    733     } else if (*src == '\\' && !delim) {
    734       src++;
    735     } else if (*src == '\\' && src[1]) {
    736       Rune   r;
    737       size_t rlen;
    738       num++;
    739       src++;
    740       rlen = echarntorune(&r, src, end - src);
    741 
    742       if (r == 'n' && delim == 'n') {
    743         *src = n_newline ? '\n' : 'n'; /* src so we can still
    744                                         * memmove() */
    745       } else if (r == 'n') {
    746         *src = '\n';
    747       } else if (r != delim) {
    748         *dst++ = '\\';
    749         num--;
    750       }
    751 
    752       memmove(dst, src, rlen);
    753       dst += rlen;
    754       src += rlen;
    755     } else {
    756       *dst++ = *src++;
    757     }
    758   }
    759   memmove(dst, src, strlen(src) + 1);
    760   return num;
    761 }
    762 
    763 static size_t
    764 echarntorune(Rune *r, char *s, size_t n)
    765 {
    766   size_t rlen = charntorune(r, s, n);
    767   if (!rlen || *r == Runeerror)
    768     leprintf("invalid UTF-8");
    769   return rlen;
    770 }
    771 
    772 static void
    773 insert_labels(void)
    774 {
    775   size_t i;
    776   Cmd   *from, *to;
    777 
    778   while (branches.size) {
    779     from = prog + (ptrdiff_t)pop(&branches);
    780 
    781     if (!from->u.label) { /* no label branch to end of script */
    782       from->u.jump = pc - 1;
    783     } else {
    784       for (i = 0; i < labels.size; i++) {
    785         to = prog + (ptrdiff_t)labels.data[i];
    786         if (!strcmp(from->u.label, to->u.label)) {
    787           from->u.jump = to;
    788           break;
    789         }
    790       }
    791       if (i == labels.size)
    792         leprintf("bad label");
    793     }
    794   }
    795 }
    796 
    797 /*
    798  * getargs / freeargs
    799  * read argument from s, return pointer to one past last character of argument
    800  */
    801 
    802 /* POSIX compliant
    803  * i\
    804  * foobar
    805  *
    806  * also allow the following non POSIX compliant
    807  * i # empty line
    808  * ifoobar
    809  * ifoobar\
    810  * baz
    811  *
    812  * FIXME: GNU and busybox discard leading spaces
    813  * i foobar
    814  * i foobar
    815  * ifoobar
    816  * are equivalent in GNU and busybox. we dont. should we?
    817  */
    818 static char *
    819 get_aci_arg(Cmd *c, char *s)
    820 {
    821   c->u.acir.print = check_puts;
    822   c->u.acir.str   = (String){NULL, 0};
    823 
    824   gflags.aci_cont = !!*s; /* no continue flag if empty string */
    825 
    826   /* neither empty string nor POSIX compliant */
    827   if (*s && !(*s == '\\' && !s[1]))
    828     aci_append(c, s);
    829 
    830   return s + strlen(s);
    831 }
    832 
    833 static void
    834 aci_append(Cmd *c, char *s)
    835 {
    836   char *end = s + strlen(s), *p = end;
    837 
    838   gflags.aci_cont = 0;
    839   while (--p >= s && *p == '\\')
    840     gflags.aci_cont = !gflags.aci_cont;
    841 
    842   if (gflags.aci_cont)
    843     *--end = '\n';
    844 
    845   escapes(s, end, 0, 0);
    846   stracat(&c->u.acir.str, s);
    847 }
    848 
    849 static void
    850 free_acir_arg(Cmd *c)
    851 {
    852   free(c->u.acir.str.str);
    853 }
    854 
    855 /* POSIX dictates that label is rest of line, including semicolons, trailing
    856  * whitespace, closing braces, etc. and can be limited to 8 bytes
    857  *
    858  * i allow a semicolon or closing brace to terminate a label name, its not
    859  * POSIX compliant, but its useful and every sed version i have tried to date
    860  * does the same
    861  *
    862  * FIXME: POSIX dictates that leading whitespace is ignored but trailing
    863  * whitespace is not. this is annoying and we should probably get rid of it
    864  */
    865 static char *
    866 get_bt_arg(Cmd *c, char *s)
    867 {
    868   char *p = semicolon_arg(s = chomp(s));
    869 
    870   if (p != s) {
    871     c->u.label = estrndup(s, p - s);
    872   } else {
    873     c->u.label = NULL;
    874   }
    875 
    876   push(&branches, (void *)(c - prog));
    877 
    878   return p;
    879 }
    880 
    881 /* POSIX dictates file name is rest of line including semicolons, trailing
    882  * whitespace, closing braces, etc. and file name must be preceded by a space
    883  *
    884  * i allow a semicolon or closing brace to terminate a file name and dont
    885  * enforce leading space
    886  *
    887  * FIXME: decide whether trailing whitespace should be included and fix
    888  * accordingly
    889  */
    890 static char *
    891 get_r_arg(Cmd *c, char *s)
    892 {
    893   char *p = semicolon_arg(s = chomp(s));
    894 
    895   if (p == s)
    896     leprintf("no file name");
    897 
    898   c->u.acir.str.str = estrndup(s, p - s);
    899   c->u.acir.print   = write_file;
    900 
    901   return p;
    902 }
    903 
    904 /* we allow "\\n" in replacement text to mean "\n" (undefined in POSIX)
    905  *
    906  * FIXME: allow other escapes in regex and replacement? if so change escapes()
    907  */
    908 static char *
    909 get_s_arg(Cmd *c, char *s)
    910 {
    911   Rune  delim, r;
    912   Cmd   buf;
    913   char *p;
    914   int   esc, lastre;
    915 
    916   /* s/find/replace/flags */
    917 
    918   /* find */
    919   if (!gflags.s_cont) { /* NOT continuing from literal newline in
    920                          * replacement text */
    921     lastre            = 0;
    922     c->u.s.repl       = (String){NULL, 0};
    923     c->u.s.occurrence = 1;
    924     c->u.s.file       = NULL;
    925     c->u.s.p          = 0;
    926 
    927     if (!*s || *s == '\\')
    928       leprintf("bad delimiter");
    929 
    930     p = s + strlen(s);
    931     s += echarntorune(&delim, s, p - s);
    932     c->u.s.delim = delim;
    933 
    934     echarntorune(&r, s, p - s);
    935     if (r == delim) /* empty regex */
    936       lastre = 1;
    937 
    938     p = find_delim(s, delim, 1);
    939     if (!*p)
    940       leprintf("missing second delimiter");
    941     p -= escapes(s, p, delim, 0);
    942     *p = '\0';
    943 
    944     if (lastre) {
    945       c->u.s.re = NULL;
    946     } else {
    947       c->u.s.re = emalloc(sizeof(*c->u.s.re));
    948       /* FIXME: different eregcomp that calls fatal */
    949       eregcomp(c->u.s.re, s, gflags.E ? REG_EXTENDED : 0);
    950     }
    951     s = p + runelen(delim);
    952   }
    953 
    954   /* replace */
    955   delim = c->u.s.delim;
    956 
    957   p = find_delim(s, delim, 0);
    958   p -= escapes(s, p, delim, 0);
    959   if (!*p) { /* no third delimiter */
    960     /* FIXME: same backslash counting as aci_append() */
    961     if (p[-1] != '\\')
    962       leprintf(
    963           "missing third delimiter or "
    964           "<backslash><newline>"
    965       );
    966     p[-1]         = '\n';
    967     gflags.s_cont = 1;
    968   } else {
    969     gflags.s_cont = 0;
    970   }
    971 
    972   /* check for bad references in replacement text */
    973   *p = '\0';
    974   for (esc = 0, p = s; *p; p++) {
    975     if (esc) {
    976       esc = 0;
    977       if (isdigit(*p) && c->u.s.re && (size_t)(*p - '0') > c->u.s.re->re_nsub)
    978         leprintf(
    979             "back reference number greater than "
    980             "number of groups"
    981         );
    982     } else if (*p == '\\') {
    983       esc = 1;
    984     }
    985   }
    986   stracat(&c->u.s.repl, s);
    987 
    988   if (gflags.s_cont)
    989     return p;
    990 
    991   s = p + runelen(delim);
    992 
    993   /* flags */
    994   p = semicolon_arg(s = chomp(s));
    995 
    996   /* FIXME: currently for simplicity take last of g or occurrence flags
    997    * and ignore multiple p flags. need to fix that */
    998   for (; s < p; s++) {
    999     if (isdigit(*s)) {
   1000       c->u.s.occurrence = stol(s, &s);
   1001       s--; /* for loop will advance pointer */
   1002     } else {
   1003       switch (*s) {
   1004         case 'g':
   1005           c->u.s.occurrence = 0;
   1006           break;
   1007         case 'p':
   1008           c->u.s.p = 1;
   1009           break;
   1010         case 'w':
   1011           /* must be last flag, take everything up to
   1012            * newline/semicolon s == p after this */
   1013           s           = get_w_arg(&buf, chomp(s + 1));
   1014           c->u.s.file = buf.u.file;
   1015           break;
   1016       }
   1017     }
   1018   }
   1019   return p;
   1020 }
   1021 
   1022 static void
   1023 free_s_arg(Cmd *c)
   1024 {
   1025   if (c->u.s.re)
   1026     regfree(c->u.s.re);
   1027   free(c->u.s.re);
   1028   free(c->u.s.repl.str);
   1029 }
   1030 
   1031 /* see get_r_arg notes */
   1032 static char *
   1033 get_w_arg(Cmd *c, char *s)
   1034 {
   1035   char  *p = semicolon_arg(s = chomp(s));
   1036   Wfile *w, **wp;
   1037 
   1038   if (p == s)
   1039     leprintf("no file name");
   1040 
   1041   for (wp = (Wfile **)wfiles.data; (size_t)(wp - (Wfile **)wfiles.data) < wfiles.size; wp++) {
   1042     if (strlen((*wp)->path) == (size_t)(p - s) && !strncmp(s, (*wp)->path, p - s)) {
   1043       c->u.file = (*wp)->file;
   1044       return p;
   1045     }
   1046   }
   1047 
   1048   w       = emalloc(sizeof(*w));
   1049   w->path = estrndup(s, p - s);
   1050 
   1051   if (!(w->file = fopen(w->path, "w")))
   1052     leprintf("fopen failed");
   1053 
   1054   c->u.file = w->file;
   1055 
   1056   push(&wfiles, w);
   1057   return p;
   1058 }
   1059 
   1060 static char *
   1061 get_y_arg(Cmd *c, char *s)
   1062 {
   1063   Rune   delim;
   1064   char  *p    = s + strlen(s);
   1065   size_t rlen = echarntorune(&delim, s, p - s);
   1066   size_t nrunes1, nrunes2;
   1067 
   1068   c->u.y.set1 = c->u.y.set2 = NULL;
   1069 
   1070   s += rlen;
   1071   p = find_delim(s, delim, 0);
   1072   p -= escapes(s, p, delim, 1);
   1073   nrunes1     = utfnlen(s, p - s);
   1074   c->u.y.set1 = strtorunes(s, nrunes1);
   1075 
   1076   s = p + rlen;
   1077   p = find_delim(s, delim, 0);
   1078   p -= escapes(s, p, delim, 1);
   1079   nrunes2 = utfnlen(s, p - s);
   1080 
   1081   if (nrunes1 != nrunes2)
   1082     leprintf("different set lengths");
   1083 
   1084   c->u.y.set2 = strtorunes(s, utfnlen(s, p - s));
   1085 
   1086   return p + rlen;
   1087 }
   1088 
   1089 static void
   1090 free_y_arg(Cmd *c)
   1091 {
   1092   free(c->u.y.set1);
   1093   free(c->u.y.set2);
   1094 }
   1095 
   1096 /* see get_bt_arg notes */
   1097 static char *
   1098 get_colon_arg(Cmd *c, char *s)
   1099 {
   1100   char *p = semicolon_arg(s = chomp(s));
   1101 
   1102   if (p == s)
   1103     leprintf("no label name");
   1104 
   1105   c->u.label = estrndup(s, p - s);
   1106   push(&labels, (void *)(c - prog));
   1107   return p;
   1108 }
   1109 
   1110 static char *
   1111 get_lbrace_arg(Cmd *c, char *s)
   1112 {
   1113   push(&braces, (void *)(c - prog));
   1114   return s;
   1115 }
   1116 
   1117 static char *
   1118 get_rbrace_arg(Cmd *c, char *s)
   1119 {
   1120   Cmd *lbrace;
   1121 
   1122   if (!braces.size)
   1123     leprintf("extra }");
   1124 
   1125   lbrace           = prog + (ptrdiff_t)pop(&braces);
   1126   lbrace->u.offset = c - prog;
   1127   return s;
   1128 }
   1129 
   1130 /* s points to beginning of an argument that may be semicolon terminated
   1131  * return pointer to semicolon or nul byte after string
   1132  * or closing brace as to not force ; before }
   1133  * FIXME: decide whether or not to eat trailing whitespace for arguments that
   1134  * we allow semicolon/brace termination that POSIX doesnt
   1135  * b, r, t, w, :
   1136  * POSIX says trailing whitespace is part of label name, file name, etc
   1137  * we should probably eat it
   1138  */
   1139 static char *
   1140 semicolon_arg(char *s)
   1141 {
   1142   char *p = strpbrk(s, ";}");
   1143   if (!p)
   1144     p = s + strlen(s);
   1145   return p;
   1146 }
   1147 
   1148 static void
   1149 run(void)
   1150 {
   1151   lineno = 0;
   1152   if (braces.size)
   1153     leprintf("extra {");
   1154 
   1155   /* genbuf has already been initialized, patt will be in new_line
   1156    * (or we will halt) */
   1157   stracpy(&hold, "");
   1158 
   1159   insert_labels();
   1160   next_file();
   1161   new_line();
   1162 
   1163   for (pc = prog; !gflags.halt; pc++)
   1164     pc->fninfo->fn(pc);
   1165 }
   1166 
   1167 /* return true if we are in range for c, set c->in_match appropriately */
   1168 static int
   1169 in_range(Cmd *c)
   1170 {
   1171   if (match_addr(&c->range.beg)) {
   1172     if (c->range.naddr == 2) {
   1173       if (c->range.end.type == LINE && c->range.end.u.lineno <= lineno)
   1174         c->in_match = 0;
   1175       else
   1176         c->in_match = 1;
   1177     }
   1178     return !c->negate;
   1179   }
   1180   if (c->in_match && match_addr(&c->range.end)) {
   1181     c->in_match = 0;
   1182     return !c->negate;
   1183   }
   1184   return c->in_match ^ c->negate;
   1185 }
   1186 
   1187 /* return true if addr matches current line */
   1188 static int
   1189 match_addr(Addr *a)
   1190 {
   1191   switch (a->type) {
   1192     default:
   1193     case IGNORE:
   1194       return 0;
   1195     case EVERY:
   1196       return 1;
   1197     case LINE:
   1198       return lineno == a->u.lineno;
   1199     case LAST:
   1200       while (is_eof(file) && !next_file())
   1201         ;
   1202       return !file;
   1203     case REGEX:
   1204       lastre = a->u.re;
   1205       return !regexec(a->u.re, patt.str, 0, NULL, 0);
   1206     case LASTRE:
   1207       if (!lastre)
   1208         leprintf("no previous regex");
   1209       return !regexec(lastre, patt.str, 0, NULL, 0);
   1210   }
   1211 }
   1212 
   1213 /* move to next input file
   1214  * stdin if first call and no files
   1215  * return 0 for success and 1 for no more files
   1216  */
   1217 static int
   1218 next_file(void)
   1219 {
   1220   static unsigned char first = 1;
   1221 
   1222   if (file == stdin)
   1223     clearerr(file);
   1224   else if (file)
   1225     fshut(file, "<file>");
   1226   /* given no files, default to stdin */
   1227   file  = first && !*files ? stdin : NULL;
   1228   first = 0;
   1229 
   1230   while (!file && *files) {
   1231     if (!strcmp(*files, "-")) {
   1232       file = stdin;
   1233     } else if (!(file = fopen(*files, "r"))) {
   1234       /* warn this file didnt open, but move on to next */
   1235       weprintf("fopen %s:", *files);
   1236       ret = 1;
   1237     }
   1238     files++;
   1239   }
   1240 
   1241   return !file;
   1242 }
   1243 
   1244 /* test if stream is at EOF */
   1245 static int
   1246 is_eof(FILE *f)
   1247 {
   1248   int c;
   1249 
   1250   if (!f || feof(f))
   1251     return 1;
   1252 
   1253   c = fgetc(f);
   1254   if (c == EOF && ferror(f))
   1255     eprintf("fgetc:");
   1256   if (c != EOF && ungetc(c, f) == EOF)
   1257     eprintf("ungetc EOF\n");
   1258 
   1259   return c == EOF;
   1260 }
   1261 
   1262 /* perform writes that were scheduled
   1263  * for aci this is check_puts(string, stdout)
   1264  * for r this is write_file(path, stdout)
   1265  */
   1266 static void
   1267 do_writes(void)
   1268 {
   1269   Cmd   *c;
   1270   size_t i;
   1271 
   1272   for (i = 0; i < writes.size; i++) {
   1273     c = writes.data[i];
   1274     c->u.acir.print(c->u.acir.str.str, stdout);
   1275   }
   1276   writes.size = 0;
   1277 }
   1278 
   1279 /* used for r's u.acir.print()
   1280  * FIXME: something like util's concat() would be better
   1281  */
   1282 static void
   1283 write_file(char *path, FILE *out)
   1284 {
   1285   FILE *in = fopen(path, "r");
   1286   if (!in) /* no file is treated as empty file */
   1287     return;
   1288 
   1289   while (read_line(in, &genbuf) != EOF)
   1290     check_puts(genbuf.str, out);
   1291 
   1292   fshut(in, path);
   1293 }
   1294 
   1295 static void
   1296 check_puts(char *s, FILE *f)
   1297 {
   1298   if (s && fputs(s, f) == EOF)
   1299     eprintf("fputs:");
   1300   if (fputs("\n", f) == EOF)
   1301     eprintf("fputs:");
   1302 }
   1303 
   1304 static void
   1305 write_patt(char *s, FILE *f)
   1306 {
   1307 #if FEATURE_SED_PRESERVE_NEWLINE
   1308   if (s && fputs(s, f) == EOF)
   1309     eprintf("fputs:");
   1310   if (hadnl) {
   1311     if (fputs("\n", f) == EOF)
   1312       eprintf("fputs:");
   1313   }
   1314 #else
   1315   check_puts(s, f);
   1316 #endif
   1317 }
   1318 
   1319 /* iterate from beg to end updating ranges so we dont miss any commands
   1320  * e.g. sed -n '1d;1,3p' should still print lines 2 and 3
   1321  */
   1322 static void
   1323 update_ranges(Cmd *beg, Cmd *end)
   1324 {
   1325   while (beg < end)
   1326     in_range(beg++);
   1327 }
   1328 
   1329 /*
   1330  * sed functions
   1331  */
   1332 static void
   1333 cmd_a(Cmd *c)
   1334 {
   1335   if (in_range(c))
   1336     push(&writes, c);
   1337 }
   1338 
   1339 static void
   1340 cmd_b(Cmd *c)
   1341 {
   1342   if (!in_range(c))
   1343     return;
   1344 
   1345   /* if we jump backwards update to end, otherwise update to destination
   1346    */
   1347   update_ranges(c + 1, c->u.jump > c ? c->u.jump : prog + pcap);
   1348   pc = c->u.jump;
   1349 }
   1350 
   1351 static void
   1352 cmd_c(Cmd *c)
   1353 {
   1354   if (!in_range(c))
   1355     return;
   1356 
   1357   /* write the text on the last line of the match */
   1358   if (!c->in_match)
   1359     check_puts(c->u.acir.str.str, stdout);
   1360   /* otherwise start the next cycle without printing pattern space
   1361    * effectively deleting the text */
   1362   new_next();
   1363 }
   1364 
   1365 static void
   1366 cmd_d(Cmd *c)
   1367 {
   1368   if (!in_range(c))
   1369     return;
   1370 
   1371   new_next();
   1372 }
   1373 
   1374 static void
   1375 cmd_D(Cmd *c)
   1376 {
   1377   char *p;
   1378 
   1379   if (!in_range(c))
   1380     return;
   1381 
   1382   if ((p = strchr(patt.str, '\n'))) {
   1383     p++;
   1384     memmove(patt.str, p, strlen(p) + 1);
   1385     old_next();
   1386   } else {
   1387     new_next();
   1388   }
   1389 }
   1390 
   1391 static void
   1392 cmd_g(Cmd *c)
   1393 {
   1394   if (in_range(c))
   1395     stracpy(&patt, hold.str);
   1396 }
   1397 
   1398 static void
   1399 cmd_G(Cmd *c)
   1400 {
   1401   if (!in_range(c))
   1402     return;
   1403 
   1404   stracat(&patt, "\n");
   1405   stracat(&patt, hold.str);
   1406 }
   1407 
   1408 static void
   1409 cmd_h(Cmd *c)
   1410 {
   1411   if (in_range(c))
   1412     stracpy(&hold, patt.str);
   1413 }
   1414 
   1415 static void
   1416 cmd_H(Cmd *c)
   1417 {
   1418   if (!in_range(c))
   1419     return;
   1420 
   1421   stracat(&hold, "\n");
   1422   stracat(&hold, patt.str);
   1423 }
   1424 
   1425 static void
   1426 cmd_i(Cmd *c)
   1427 {
   1428   if (in_range(c))
   1429     check_puts(c->u.acir.str.str, stdout);
   1430 }
   1431 
   1432 /* i think it makes sense to print invalid UTF-8 sequences in octal to satisfy
   1433  * the "visually unambiguous form" sed(1p)
   1434  */
   1435 static void
   1436 cmd_l(Cmd *c)
   1437 {
   1438   Rune   r;
   1439   char  *p, *end;
   1440   size_t rlen;
   1441 
   1442   char *escapes[] = {
   1443       /* FIXME: 7 entries and search instead of 127 */
   1444       ['\\'] = "\\\\",
   1445       ['\a'] = "\\a",
   1446       ['\b'] = "\\b",
   1447       ['\f'] = "\\f",
   1448       ['\r'] = "\\r",
   1449       ['\t'] = "\\t",
   1450       ['\v'] = "\\v",
   1451       [0x7f] = NULL, /* fill out the table */
   1452   };
   1453 
   1454   if (!in_range(c))
   1455     return;
   1456 
   1457   /* FIXME: line wrapping. sed(1p) says "length at which folding occurs is
   1458    * unspecified, but should be appropraite for the output device"
   1459    * just wrap at 80 runes?
   1460    */
   1461   for (p = patt.str, end = p + strlen(p); p < end; p += rlen) {
   1462     if (isascii(*p) && escapes[(unsigned int)*p]) {
   1463       fputs(escapes[(unsigned int)*p], stdout);
   1464       rlen = 1;
   1465     } else if (!(rlen = charntorune(&r, p, end - p))) {
   1466       /* ran out of chars, print the bytes of the short
   1467        * sequence */
   1468       for (; p < end; p++)
   1469         printf("\\%03hho", (unsigned char)*p);
   1470       break;
   1471     } else if (r == Runeerror) {
   1472       for (; rlen; rlen--, p++)
   1473         printf("\\%03hho", (unsigned char)*p);
   1474     } else {
   1475       while (fwrite(p, rlen, 1, stdout) < 1 && errno == EINTR)
   1476         ;
   1477       if (ferror(stdout))
   1478         eprintf("fwrite:");
   1479     }
   1480   }
   1481   check_puts("$", stdout);
   1482 }
   1483 
   1484 static void
   1485 cmd_n(Cmd *c)
   1486 {
   1487   if (!in_range(c))
   1488     return;
   1489 
   1490   if (!gflags.n)
   1491     write_patt(patt.str, stdout);
   1492   do_writes();
   1493   new_line();
   1494 }
   1495 
   1496 static void
   1497 cmd_N(Cmd *c)
   1498 {
   1499   if (!in_range(c))
   1500     return;
   1501   do_writes();
   1502   app_line();
   1503 }
   1504 
   1505 static void
   1506 cmd_p(Cmd *c)
   1507 {
   1508   if (in_range(c))
   1509     write_patt(patt.str, stdout);
   1510 }
   1511 
   1512 static void
   1513 cmd_P(Cmd *c)
   1514 {
   1515   char *p;
   1516 
   1517   if (!in_range(c))
   1518     return;
   1519 
   1520   if ((p = strchr(patt.str, '\n')))
   1521     *p = '\0';
   1522 
   1523   write_patt(patt.str, stdout);
   1524 
   1525   if (p)
   1526     *p = '\n';
   1527 }
   1528 
   1529 static void
   1530 cmd_q(Cmd *c)
   1531 {
   1532   if (!in_range(c))
   1533     return;
   1534 
   1535   if (!gflags.n)
   1536     check_puts(patt.str, stdout);
   1537   do_writes();
   1538   gflags.halt = 1;
   1539 }
   1540 
   1541 static void
   1542 cmd_r(Cmd *c)
   1543 {
   1544   if (in_range(c))
   1545     push(&writes, c);
   1546 }
   1547 
   1548 static void
   1549 cmd_s(Cmd *c)
   1550 {
   1551   String       tmp;
   1552   Rune         r;
   1553   size_t       plen, rlen, len;
   1554   char        *p, *s, *end;
   1555   unsigned int matches = 0, last_empty = 1, qflag = 0, cflags = 0;
   1556   regex_t     *re;
   1557   regmatch_t  *rm, *pmatch = NULL;
   1558 
   1559   if (!in_range(c))
   1560     return;
   1561 
   1562   if (!c->u.s.re && !lastre)
   1563     leprintf("no previous regex");
   1564 
   1565   re     = c->u.s.re ? c->u.s.re : lastre;
   1566   lastre = re;
   1567 
   1568   plen   = re->re_nsub + 1;
   1569   pmatch = ereallocarray(NULL, plen, sizeof(regmatch_t));
   1570 
   1571   *genbuf.str = '\0';
   1572   s           = patt.str;
   1573 
   1574   while (!qflag && !regexec(re, s, plen, pmatch, cflags)) {
   1575     cflags = REG_NOTBOL; /* match against beginning of line first
   1576                           * time, but not again */
   1577     if (!*s)             /* match against empty string first time, but not again
   1578                           */
   1579       qflag = 1;
   1580 
   1581     /* dont substitute if last match was not empty but this one is
   1582      * s_a*_._g
   1583      * foobar -> .f.o.o.b.r
   1584      */
   1585     if ((last_empty || pmatch[0].rm_eo) && (++matches == c->u.s.occurrence || !c->u.s.occurrence)) {
   1586       /* copy over everything before the match */
   1587       strnacat(&genbuf, s, pmatch[0].rm_so);
   1588 
   1589       /* copy over replacement text, taking into account &,
   1590        * backreferences, and \ escapes */
   1591       for (p = c->u.s.repl.str, len = strcspn(p, "\\&"); *p; len = strcspn(++p, "\\&")) {
   1592         strnacat(&genbuf, p, len);
   1593         p += len;
   1594         switch (*p) {
   1595           default:
   1596             leprintf("this shouldn't be possible");
   1597             break;
   1598           case '\0':
   1599             /* we are at the end, back up one so the
   1600              * ++p will put us on the null byte to
   1601              * break out of the loop */
   1602             --p;
   1603             break;
   1604           case '&':
   1605             strnacat(&genbuf, s + pmatch[0].rm_so, pmatch[0].rm_eo - pmatch[0].rm_so);
   1606             break;
   1607           case '\\':
   1608             if (isdigit(*++p)) { /* backreference */
   1609               /* only need to check here if
   1610                * using lastre, otherwise we
   1611                * checked when building */
   1612               if (!c->u.s.re && (size_t)(*p - '0') > re->re_nsub)
   1613                 leprintf(
   1614                     "back "
   1615                     "reference "
   1616                     "number "
   1617                     "greater than "
   1618                     "number of "
   1619                     "groups"
   1620                 );
   1621               rm = &pmatch[*p - '0'];
   1622               strnacat(&genbuf, s + rm->rm_so, rm->rm_eo - rm->rm_so);
   1623             } else { /* character after backslash
   1624                       * taken literally (well one
   1625                       * byte, but it works) */
   1626               strnacat(&genbuf, p, 1);
   1627             }
   1628             break;
   1629         }
   1630       }
   1631     } else {
   1632       /* not replacing, copy over everything up to and
   1633        * including the match */
   1634       strnacat(&genbuf, s, pmatch[0].rm_eo);
   1635     }
   1636 
   1637     if (!pmatch[0].rm_eo) { /* empty match, advance one rune and add
   1638                              * it to output */
   1639       end  = s + strlen(s);
   1640       rlen = charntorune(&r, s, end - s);
   1641 
   1642       if (!rlen) { /* ran out of bytes, copy short sequence */
   1643         stracat(&genbuf, s);
   1644         s = end;
   1645       } else { /* copy whether or not its a good rune */
   1646         strnacat(&genbuf, s, rlen);
   1647         s += rlen;
   1648       }
   1649     }
   1650     last_empty = !pmatch[0].rm_eo;
   1651     s += pmatch[0].rm_eo;
   1652   }
   1653   free(pmatch);
   1654 
   1655   if (!(matches && matches >= c->u.s.occurrence)) /* no replacement */
   1656     return;
   1657 
   1658   gflags.s = 1;
   1659 
   1660   stracat(&genbuf, s);
   1661 
   1662   tmp    = patt;
   1663   patt   = genbuf;
   1664   genbuf = tmp;
   1665 
   1666   if (c->u.s.p)
   1667     write_patt(patt.str, stdout);
   1668   if (c->u.s.file)
   1669     write_patt(patt.str, c->u.s.file);
   1670 }
   1671 
   1672 static void
   1673 cmd_t(Cmd *c)
   1674 {
   1675   if (!in_range(c) || !gflags.s)
   1676     return;
   1677 
   1678   /* if we jump backwards update to end, otherwise update to destination
   1679    */
   1680   update_ranges(c + 1, c->u.jump > c ? c->u.jump : prog + pcap);
   1681   pc       = c->u.jump;
   1682   gflags.s = 0;
   1683 }
   1684 
   1685 static void
   1686 cmd_w(Cmd *c)
   1687 {
   1688   if (in_range(c))
   1689     write_patt(patt.str, c->u.file);
   1690 }
   1691 
   1692 static void
   1693 cmd_x(Cmd *c)
   1694 {
   1695   String tmp;
   1696 
   1697   if (!in_range(c))
   1698     return;
   1699 
   1700   tmp  = patt;
   1701   patt = hold;
   1702   hold = tmp;
   1703 }
   1704 
   1705 static void
   1706 cmd_y(Cmd *c)
   1707 {
   1708   String tmp;
   1709   Rune   r, *rp;
   1710   size_t n, rlen;
   1711   char  *s, *end, buf[UTFmax];
   1712 
   1713   if (!in_range(c))
   1714     return;
   1715 
   1716   *genbuf.str = '\0';
   1717   for (s = patt.str, end = s + strlen(s); *s; s += rlen) {
   1718     if (!(rlen = charntorune(&r, s, end - s))) { /* ran out of chars, copy rest */
   1719       stracat(&genbuf, s);
   1720       break;
   1721     } else if (r == Runeerror) { /* bad UTF-8 sequence, copy bytes */
   1722       strnacat(&genbuf, s, rlen);
   1723     } else {
   1724       for (rp = c->u.y.set1; *rp; rp++)
   1725         if (*rp == r)
   1726           break;
   1727       if (*rp) { /* found r in set1, replace with rune from
   1728                   * set2 */
   1729         n = runetochar(buf, c->u.y.set2 + (rp - c->u.y.set1));
   1730         strnacat(&genbuf, buf, n);
   1731       } else {
   1732         strnacat(&genbuf, s, rlen);
   1733       }
   1734     }
   1735   }
   1736   tmp    = patt;
   1737   patt   = genbuf;
   1738   genbuf = tmp;
   1739 }
   1740 
   1741 static void
   1742 cmd_colon(Cmd *c)
   1743 {
   1744   (void)c;
   1745 }
   1746 
   1747 static void
   1748 cmd_equal(Cmd *c)
   1749 {
   1750   if (in_range(c))
   1751     printf("%zu\n", lineno);
   1752 }
   1753 
   1754 static void
   1755 cmd_lbrace(Cmd *c)
   1756 {
   1757   Cmd *jump;
   1758 
   1759   if (in_range(c))
   1760     return;
   1761 
   1762   /* update ranges on all commands we skip */
   1763   jump = prog + c->u.offset;
   1764   update_ranges(c + 1, jump);
   1765   pc = jump;
   1766 }
   1767 
   1768 static void
   1769 cmd_rbrace(Cmd *c)
   1770 {
   1771   (void)c;
   1772 }
   1773 
   1774 /* not actually a sed function, but acts like one, put in last spot of script */
   1775 static void
   1776 cmd_last(Cmd *c)
   1777 {
   1778   (void)c;
   1779   if (!gflags.n)
   1780     write_patt(patt.str, stdout);
   1781   do_writes();
   1782   new_next();
   1783 }
   1784 
   1785 /*
   1786  * actions
   1787  */
   1788 
   1789 /* read new line, continue current cycle */
   1790 static void
   1791 new_line(void)
   1792 {
   1793   while (read_line(file, &patt) == EOF) {
   1794     if (next_file()) {
   1795       gflags.halt = 1;
   1796       return;
   1797     }
   1798   }
   1799   gflags.s = 0;
   1800   lineno++;
   1801 }
   1802 
   1803 /* append new line, continue current cycle
   1804  * FIXME: used for n, POSIX specifies do not print pattern space when out of
   1805  * input, but GNU does so busybox does as well. currently we dont
   1806  * should we?
   1807  */
   1808 static void
   1809 app_line(void)
   1810 {
   1811   while (read_line(file, &genbuf) == EOF) {
   1812     if (next_file()) {
   1813       gflags.halt = 1;
   1814       return;
   1815     }
   1816   }
   1817 
   1818   stracat(&patt, "\n");
   1819   stracat(&patt, genbuf.str);
   1820   gflags.s = 0;
   1821   lineno++;
   1822 }
   1823 
   1824 /* read new line, start new cycle */
   1825 static void
   1826 new_next(void)
   1827 {
   1828   *patt.str = '\0';
   1829   update_ranges(pc + 1, prog + pcap);
   1830   new_line();
   1831   pc = prog - 1;
   1832 }
   1833 
   1834 /* keep old pattern space, start new cycle */
   1835 static void
   1836 old_next(void)
   1837 {
   1838   update_ranges(pc + 1, prog + pcap);
   1839   pc = prog - 1;
   1840 }
   1841 
   1842 // ?man sed: stream editor
   1843 // ?man arguments: script [file ...]
   1844 // ?man stream editor for filtering and transforming text
   1845 int
   1846 main(int argc, char *argv[])
   1847 {
   1848   char *arg;
   1849   int   script = 0;
   1850 
   1851   ARGBEGIN
   1852   {
   1853     // ?man -n: print line numbers or counts
   1854     case 'n':
   1855       gflags.n = 1;
   1856       break;
   1857     // ?man -r: operate recursively
   1858     case 'r':
   1859     // ?man -E: specify option flag
   1860     case 'E':
   1861       gflags.E = 1;
   1862       break;
   1863     // ?man -e:str: specify expression or pattern
   1864     case 'e':
   1865       arg = EARGF(usage());
   1866       compile(arg, 0);
   1867       script = 1;
   1868       break;
   1869     // ?man -f:str: force the operation
   1870     case 'f':
   1871       arg = EARGF(usage());
   1872       compile(arg, 1);
   1873       script = 1;
   1874       break;
   1875 #if FEATURE_SED_INPLACE
   1876     // ?man -i: interactive mode or prompt for confirmation
   1877     case 'i':
   1878       iflag = 1;
   1879       if (argv[0][1] != '\0') {
   1880         backup_suffix = &argv[0][1];
   1881         brk_          = 1;
   1882       } else {
   1883         backup_suffix = "";
   1884       }
   1885       break;
   1886 #endif
   1887     default:
   1888       usage();
   1889   }
   1890   ARGEND
   1891 
   1892   /* no script to run */
   1893   if (!script && !argc)
   1894     usage();
   1895 
   1896   /* no script yet, next argument is script */
   1897   if (!script)
   1898     compile(*argv++, 0);
   1899 
   1900   /* shrink/grow memory to fit and add our last instruction */
   1901   resize((void **)&prog, &pcap, sizeof(*prog), pc - prog + 1, NULL);
   1902   pc         = prog + pcap - 1;
   1903   pc->fninfo = &(Fninfo){cmd_last, NULL, NULL, 0};
   1904 
   1905 #if FEATURE_SED_INPLACE
   1906   if (iflag) {
   1907     char  *single_file[2] = {NULL, NULL};
   1908     char **orig_files     = argv;
   1909     int    i;
   1910 
   1911     if (!*orig_files)
   1912       eprintf("no input files\n");
   1913 
   1914     for (i = 0; orig_files[i]; i++) {
   1915       char       *temp_path = NULL;
   1916       int         temp_fd;
   1917       int         real_stdout;
   1918       struct stat st;
   1919       Cmd        *c;
   1920 
   1921       if (strcmp(orig_files[i], "-") == 0) {
   1922         weprintf("cannot edit stdin in-place\n");
   1923         ret = 1;
   1924         continue;
   1925       }
   1926 
   1927       if (stat(orig_files[i], &st) < 0) {
   1928         weprintf("stat %s:", orig_files[i]);
   1929         ret = 1;
   1930         continue;
   1931       }
   1932 
   1933       temp_fd = create_temp_file(orig_files[i], &temp_path);
   1934       if (temp_fd < 0) {
   1935         weprintf("create_temp_file:");
   1936         ret = 1;
   1937         continue;
   1938       }
   1939 
   1940       real_stdout = dup(1);
   1941       if (real_stdout < 0) {
   1942         weprintf("dup stdout:");
   1943         close(temp_fd);
   1944         free(temp_path);
   1945         ret = 1;
   1946         continue;
   1947       }
   1948       if (dup2(temp_fd, 1) < 0) {
   1949         weprintf("dup2 stdout:");
   1950         close(temp_fd);
   1951         close(real_stdout);
   1952         free(temp_path);
   1953         ret = 1;
   1954         continue;
   1955       }
   1956       close(temp_fd);
   1957 
   1958       single_file[0] = orig_files[i];
   1959       files          = single_file;
   1960 
   1961       /* reset state for next file */
   1962       lineno      = 0;
   1963       gflags.halt = 0;
   1964       stracpy(&hold, "");
   1965       stracpy(&patt, "");
   1966       writes.size = 0;
   1967       for (c = prog; c->fninfo->fn != cmd_last; c++) {
   1968         c->in_match = 0;
   1969       }
   1970 
   1971       run();
   1972 
   1973       fflush(stdout);
   1974       dup2(real_stdout, 1);
   1975       close(real_stdout);
   1976 
   1977       if (backup_suffix && *backup_suffix) {
   1978         char *backup_path = emalloc(strlen(orig_files[i]) + strlen(backup_suffix) + 1);
   1979         sprintf(backup_path, "%s%s", orig_files[i], backup_suffix);
   1980         if (rename(orig_files[i], backup_path) < 0) {
   1981           weprintf("rename %s to %s:", orig_files[i], backup_path);
   1982           unlink(temp_path);
   1983           free(backup_path);
   1984           free(temp_path);
   1985           ret = 1;
   1986           continue;
   1987         }
   1988         free(backup_path);
   1989       } else {
   1990         unlink(orig_files[i]);
   1991       }
   1992 
   1993       if (rename(temp_path, orig_files[i]) < 0) {
   1994         weprintf("rename %s to %s:", temp_path, orig_files[i]);
   1995         unlink(temp_path);
   1996         free(temp_path);
   1997         ret = 1;
   1998         continue;
   1999       }
   2000 
   2001       chmod(orig_files[i], st.st_mode);
   2002       chown(orig_files[i], st.st_uid, st.st_gid);
   2003 
   2004       free(temp_path);
   2005     }
   2006   } else
   2007 #endif
   2008   {
   2009     files = argv;
   2010     run();
   2011   }
   2012 
   2013   ret |= fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>");
   2014 
   2015   return ret;
   2016 }