hush: improve set -x: make "+++" indent level increase in `cmd` and eval.
[oweals/busybox.git] / editors / sed.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * sed.c - very minimalist version of sed
4  *
5  * Copyright (C) 1999,2000,2001 by Lineo, inc. and Mark Whitley
6  * Copyright (C) 1999,2000,2001 by Mark Whitley <markw@codepoet.org>
7  * Copyright (C) 2002  Matt Kraai
8  * Copyright (C) 2003 by Glenn McGrath
9  * Copyright (C) 2003,2004 by Rob Landley <rob@landley.net>
10  *
11  * MAINTAINER: Rob Landley <rob@landley.net>
12  *
13  * Licensed under GPLv2, see file LICENSE in this source tree.
14  */
15 /* Code overview.
16  *
17  * Files are laid out to avoid unnecessary function declarations.  So for
18  * example, every function add_cmd calls occurs before add_cmd in this file.
19  *
20  * add_cmd() is called on each line of sed command text (from a file or from
21  * the command line).  It calls get_address() and parse_cmd_args().  The
22  * resulting sed_cmd_t structures are appended to a linked list
23  * (G.sed_cmd_head/G.sed_cmd_tail).
24  *
25  * process_files() does actual sedding, reading data lines from each input FILE*
26  * (which could be stdin) and applying the sed command list (sed_cmd_head) to
27  * each of the resulting lines.
28  *
29  * sed_main() is where external code calls into this, with a command line.
30  */
31 /* Supported features and commands in this version of sed:
32  *
33  * - comments ('#')
34  * - address matching: num|/matchstr/[,num|/matchstr/|$]command
35  * - commands: (p)rint, (d)elete, (s)ubstitue (with g & I flags)
36  * - edit commands: (a)ppend, (i)nsert, (c)hange
37  * - file commands: (r)ead
38  * - backreferences in substitution expressions (\0, \1, \2...\9)
39  * - grouped commands: {cmd1;cmd2}
40  * - transliteration (y/source-chars/dest-chars/)
41  * - pattern space hold space storing / swapping (g, h, x)
42  * - labels / branching (: label, b, t, T)
43  *
44  * (Note: Specifying an address (range) to match is *optional*; commands
45  * default to the whole pattern space if no specific address match was
46  * requested.)
47  *
48  * Todo:
49  * - Create a wrapper around regex to make libc's regex conform with sed
50  *
51  * Reference
52  * http://www.opengroup.org/onlinepubs/007904975/utilities/sed.html
53  * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html
54  * http://sed.sourceforge.net/sedfaq3.html
55  */
56 //config:config SED
57 //config:       bool "sed (12 kb)"
58 //config:       default y
59 //config:       help
60 //config:       sed is used to perform text transformations on a file
61 //config:       or input from a pipeline.
62
63 //applet:IF_SED(APPLET(sed, BB_DIR_BIN, BB_SUID_DROP))
64
65 //kbuild:lib-$(CONFIG_SED) += sed.o
66
67 //usage:#define sed_trivial_usage
68 //usage:       "[-i[SFX]] [-nrE] [-f FILE]... [-e CMD]... [FILE]...\n"
69 //usage:       "or: sed [-i[SFX]] [-nrE] CMD [FILE]..."
70 //usage:#define sed_full_usage "\n\n"
71 //usage:       "        -e CMD  Add CMD to sed commands to be executed"
72 //usage:     "\n        -f FILE Add FILE contents to sed commands to be executed"
73 //usage:     "\n        -i[SFX] Edit files in-place (otherwise sends to stdout)"
74 //usage:     "\n                Optionally back files up, appending SFX"
75 //usage:     "\n        -n      Suppress automatic printing of pattern space"
76 //usage:     "\n        -r,-E   Use extended regex syntax"
77 //usage:     "\n"
78 //usage:     "\nIf no -e or -f, the first non-option argument is the sed command string."
79 //usage:     "\nRemaining arguments are input files (stdin if none)."
80 //usage:
81 //usage:#define sed_example_usage
82 //usage:       "$ echo \"foo\" | sed -e 's/f[a-zA-Z]o/bar/g'\n"
83 //usage:       "bar\n"
84
85 #include "libbb.h"
86 #include "common_bufsiz.h"
87 #include "xregex.h"
88
89 #if 0
90 # define dbg(...) bb_error_msg(__VA_ARGS__)
91 #else
92 # define dbg(...) ((void)0)
93 #endif
94
95
96 enum {
97         OPT_in_place = 1 << 0,
98 };
99
100 /* Each sed command turns into one of these structures. */
101 typedef struct sed_cmd_s {
102         /* Ordered by alignment requirements: currently 36 bytes on x86 */
103         struct sed_cmd_s *next; /* Next command (linked list, NULL terminated) */
104
105         /* address storage */
106         regex_t *beg_match;     /* sed -e '/match/cmd' */
107         regex_t *end_match;     /* sed -e '/match/,/end_match/cmd' */
108         regex_t *sub_match;     /* For 's/sub_match/string/' */
109         int beg_line;           /* 'sed 1p'   0 == apply commands to all lines */
110         int beg_line_orig;      /* copy of the above, needed for -i */
111         int end_line;           /* 'sed 1,3p' 0 == one line only. -1 = last line ($). -2-N = +N */
112         int end_line_orig;
113
114         FILE *sw_file;          /* File (sw) command writes to, NULL for none. */
115         char *string;           /* Data string for (saicytb) commands. */
116
117         unsigned which_match;   /* (s) Which match to replace (0 for all) */
118
119         /* Bitfields (gcc won't group them if we don't) */
120         unsigned invert:1;      /* the '!' after the address */
121         unsigned in_match:1;    /* Next line also included in match? */
122         unsigned sub_p:1;       /* (s) print option */
123
124         char sw_last_char;      /* Last line written by (sw) had no '\n' */
125
126         /* GENERAL FIELDS */
127         char cmd;               /* The command char: abcdDgGhHilnNpPqrstwxy:={} */
128 } sed_cmd_t;
129
130 static const char semicolon_whitespace[] ALIGN1 = "; \n\r\t\v";
131
132 struct globals {
133         /* options */
134         int be_quiet, regex_type;
135
136         FILE *nonstdout;
137         char *outname, *hold_space;
138         smallint exitcode;
139
140         /* list of input files */
141         int current_input_file, last_input_file;
142         char **input_file_list;
143         FILE *current_fp;
144
145         regmatch_t regmatch[10];
146         regex_t *previous_regex_ptr;
147
148         /* linked list of sed commands */
149         sed_cmd_t *sed_cmd_head, **sed_cmd_tail;
150
151         /* linked list of append lines */
152         llist_t *append_head;
153
154         char *add_cmd_line;
155
156         struct pipeline {
157                 char *buf;  /* Space to hold string */
158                 int idx;    /* Space used */
159                 int len;    /* Space allocated */
160         } pipeline;
161 } FIX_ALIASING;
162 #define G (*(struct globals*)bb_common_bufsiz1)
163 #define INIT_G() do { \
164         setup_common_bufsiz(); \
165         BUILD_BUG_ON(sizeof(G) > COMMON_BUFSIZE); \
166         G.sed_cmd_tail = &G.sed_cmd_head; \
167 } while (0)
168
169
170 #if ENABLE_FEATURE_CLEAN_UP
171 static void sed_free_and_close_stuff(void)
172 {
173         sed_cmd_t *sed_cmd = G.sed_cmd_head;
174
175         llist_free(G.append_head, free);
176
177         while (sed_cmd) {
178                 sed_cmd_t *sed_cmd_next = sed_cmd->next;
179
180                 if (sed_cmd->sw_file)
181                         fclose(sed_cmd->sw_file);
182
183                 if (sed_cmd->beg_match) {
184                         regfree(sed_cmd->beg_match);
185                         free(sed_cmd->beg_match);
186                 }
187                 if (sed_cmd->end_match) {
188                         regfree(sed_cmd->end_match);
189                         free(sed_cmd->end_match);
190                 }
191                 if (sed_cmd->sub_match) {
192                         regfree(sed_cmd->sub_match);
193                         free(sed_cmd->sub_match);
194                 }
195                 free(sed_cmd->string);
196                 free(sed_cmd);
197                 sed_cmd = sed_cmd_next;
198         }
199
200         free(G.hold_space);
201
202         if (G.current_fp)
203                 fclose(G.current_fp);
204 }
205 #else
206 void sed_free_and_close_stuff(void);
207 #endif
208
209 /* If something bad happens during -i operation, delete temp file */
210
211 static void cleanup_outname(void)
212 {
213         if (G.outname) unlink(G.outname);
214 }
215
216 /* strcpy, replacing "\from" with 'to'. If to is NUL, replacing "\any" with 'any' */
217
218 static unsigned parse_escapes(char *dest, const char *string, int len, char from, char to)
219 {
220         char *d = dest;
221         int i = 0;
222
223         if (len == -1)
224                 len = strlen(string);
225
226         while (i < len) {
227                 if (string[i] == '\\') {
228                         if (!to || string[i+1] == from) {
229                                 if ((*d = to ? to : string[i+1]) == '\0')
230                                         return d - dest;
231                                 i += 2;
232                                 d++;
233                                 continue;
234                         }
235                         i++; /* skip backslash in string[] */
236                         *d++ = '\\';
237                         /* fall through: copy next char verbatim */
238                 }
239                 if ((*d = string[i++]) == '\0')
240                         return d - dest;
241                 d++;
242         }
243         *d = '\0';
244         return d - dest;
245 }
246
247 static char *copy_parsing_escapes(const char *string, int len)
248 {
249         const char *s;
250         char *dest = xmalloc(len + 1);
251
252         /* sed recognizes \n */
253         /* GNU sed also recognizes \t and \r */
254         for (s = "\nn\tt\rr"; *s; s += 2) {
255                 len = parse_escapes(dest, string, len, s[1], s[0]);
256                 string = dest;
257         }
258         return dest;
259 }
260
261
262 /*
263  * index_of_next_unescaped_regexp_delim - walks left to right through a string
264  * beginning at a specified index and returns the index of the next regular
265  * expression delimiter (typically a forward slash ('/')) not preceded by
266  * a backslash ('\').  A negative delimiter disables square bracket checking.
267  */
268 static int index_of_next_unescaped_regexp_delim(int delimiter, const char *str)
269 {
270         int bracket = -1;
271         int escaped = 0;
272         int idx = 0;
273         char ch;
274
275         if (delimiter < 0) {
276                 bracket--;
277                 delimiter = -delimiter;
278         }
279
280         for (; (ch = str[idx]) != '\0'; idx++) {
281                 if (bracket >= 0) {
282                         if (ch == ']'
283                          && !(bracket == idx - 1 || (bracket == idx - 2 && str[idx - 1] == '^'))
284                         ) {
285                                 bracket = -1;
286                         }
287                 } else if (escaped)
288                         escaped = 0;
289                 else if (ch == '\\')
290                         escaped = 1;
291                 else if (bracket == -1 && ch == '[')
292                         bracket = idx;
293                 else if (ch == delimiter)
294                         return idx;
295         }
296
297         /* if we make it to here, we've hit the end of the string */
298         bb_error_msg_and_die("unmatched '%c'", delimiter);
299 }
300
301 /*
302  *  Returns the index of the third delimiter
303  */
304 static int parse_regex_delim(const char *cmdstr, char **match, char **replace)
305 {
306         const char *cmdstr_ptr = cmdstr;
307         unsigned char delimiter;
308         int idx = 0;
309
310         /* verify that the 's' or 'y' is followed by something.  That something
311          * (typically a 'slash') is now our regexp delimiter... */
312         if (*cmdstr == '\0')
313                 bb_error_msg_and_die("bad format in substitution expression");
314         delimiter = *cmdstr_ptr++;
315
316         /* save the match string */
317         idx = index_of_next_unescaped_regexp_delim(delimiter, cmdstr_ptr);
318         *match = copy_parsing_escapes(cmdstr_ptr, idx);
319
320         /* save the replacement string */
321         cmdstr_ptr += idx + 1;
322         idx = index_of_next_unescaped_regexp_delim(- (int)delimiter, cmdstr_ptr);
323         *replace = copy_parsing_escapes(cmdstr_ptr, idx);
324
325         return ((cmdstr_ptr - cmdstr) + idx);
326 }
327
328 /*
329  * returns the index in the string just past where the address ends.
330  */
331 static int get_address(const char *my_str, int *linenum, regex_t ** regex)
332 {
333         const char *pos = my_str;
334
335         if (isdigit(*my_str)) {
336                 *linenum = strtol(my_str, (char**)&pos, 10);
337                 /* endstr shouldn't ever equal NULL */
338         } else if (*my_str == '$') {
339                 *linenum = -1;
340                 pos++;
341         } else if (*my_str == '/' || *my_str == '\\') {
342                 int next;
343                 char delimiter;
344                 char *temp;
345
346                 delimiter = '/';
347                 if (*my_str == '\\')
348                         delimiter = *++pos;
349                 next = index_of_next_unescaped_regexp_delim(delimiter, ++pos);
350                 if (next != 0) {
351                         temp = copy_parsing_escapes(pos, next);
352                         G.previous_regex_ptr = *regex = xzalloc(sizeof(regex_t));
353                         xregcomp(*regex, temp, G.regex_type);
354                         free(temp);
355                 } else {
356                         *regex = G.previous_regex_ptr;
357                         if (!G.previous_regex_ptr)
358                                 bb_error_msg_and_die("no previous regexp");
359                 }
360                 /* Move position to next character after last delimiter */
361                 pos += (next+1);
362         }
363         return pos - my_str;
364 }
365
366 /* Grab a filename.  Whitespace at start is skipped, then goes to EOL. */
367 static int parse_file_cmd(/*sed_cmd_t *sed_cmd,*/ const char *filecmdstr, char **retval)
368 {
369         int start = 0, idx, hack = 0;
370
371         /* Skip whitespace, then grab filename to end of line */
372         while (isspace(filecmdstr[start]))
373                 start++;
374         idx = start;
375         while (filecmdstr[idx] && filecmdstr[idx] != '\n')
376                 idx++;
377
378         /* If lines glued together, put backslash back. */
379         if (filecmdstr[idx] == '\n')
380                 hack = 1;
381         if (idx == start)
382                 bb_error_msg_and_die("empty filename");
383         *retval = xstrndup(filecmdstr+start, idx-start+hack+1);
384         if (hack)
385                 (*retval)[idx] = '\\';
386
387         return idx;
388 }
389
390 static int parse_subst_cmd(sed_cmd_t *sed_cmd, const char *substr)
391 {
392         int cflags = G.regex_type;
393         char *match;
394         int idx;
395
396         /*
397          * A substitution command should look something like this:
398          *    s/match/replace/ #giIpw
399          *    ||     |        |||
400          *    mandatory       optional
401          */
402         idx = parse_regex_delim(substr, &match, &sed_cmd->string);
403
404         /* determine the number of back references in the match string */
405         /* Note: we compute this here rather than in the do_subst_command()
406          * function to save processor time, at the expense of a little more memory
407          * (4 bits) per sed_cmd */
408
409         /* process the flags */
410
411         sed_cmd->which_match = 1;
412         dbg("s flags:'%s'", substr + idx + 1);
413         while (substr[++idx]) {
414                 dbg("s flag:'%c'", substr[idx]);
415                 /* Parse match number */
416                 if (isdigit(substr[idx])) {
417                         if (match[0] != '^') {
418                                 /* Match 0 treated as all, multiple matches we take the last one. */
419                                 const char *pos = substr + idx;
420 /* FIXME: error check? */
421                                 sed_cmd->which_match = (unsigned)strtol(substr+idx, (char**) &pos, 10);
422                                 idx = pos - substr - 1;
423                         }
424                         continue;
425                 }
426                 /* Skip spaces */
427                 if (isspace(substr[idx]))
428                         continue;
429
430                 switch (substr[idx]) {
431                 /* Replace all occurrences */
432                 case 'g':
433                         if (match[0] != '^')
434                                 sed_cmd->which_match = 0;
435                         break;
436                 /* Print pattern space */
437                 case 'p':
438                         sed_cmd->sub_p = 1;
439                         break;
440                 /* Write to file */
441                 case 'w':
442                 {
443                         char *fname;
444                         idx += parse_file_cmd(/*sed_cmd,*/ substr+idx+1, &fname);
445                         sed_cmd->sw_file = xfopen_for_write(fname);
446                         sed_cmd->sw_last_char = '\n';
447                         free(fname);
448                         break;
449                 }
450                 /* Ignore case (gnu extension) */
451                 case 'i':
452                 case 'I':
453                         cflags |= REG_ICASE;
454                         break;
455                 /* Comment */
456                 case '#':
457                         // while (substr[++idx]) continue;
458                         idx += strlen(substr + idx); // same
459                         /* Fall through */
460                 /* End of command */
461                 case ';':
462                 case '}':
463                         goto out;
464                 default:
465                         dbg("s bad flags:'%s'", substr + idx);
466                         bb_error_msg_and_die("bad option in substitution expression");
467                 }
468         }
469  out:
470         /* compile the match string into a regex */
471         if (*match != '\0') {
472                 /* If match is empty, we use last regex used at runtime */
473                 sed_cmd->sub_match = xzalloc(sizeof(regex_t));
474                 dbg("xregcomp('%s',%x)", match, cflags);
475                 xregcomp(sed_cmd->sub_match, match, cflags);
476                 dbg("regcomp ok");
477         }
478         free(match);
479
480         return idx;
481 }
482
483 /*
484  *  Process the commands arguments
485  */
486 static const char *parse_cmd_args(sed_cmd_t *sed_cmd, const char *cmdstr)
487 {
488         static const char cmd_letters[] ALIGN1 = "saicrw:btTydDgGhHlnNpPqx={}";
489         enum {
490                 IDX_s = 0,
491                 IDX_a,
492                 IDX_i,
493                 IDX_c,
494                 IDX_r,
495                 IDX_w,
496                 IDX_colon,
497                 IDX_b,
498                 IDX_t,
499                 IDX_T,
500                 IDX_y,
501                 IDX_d,
502                 IDX_D,
503                 IDX_g,
504                 IDX_G,
505                 IDX_h,
506                 IDX_H,
507                 IDX_l,
508                 IDX_n,
509                 IDX_N,
510                 IDX_p,
511                 IDX_P,
512                 IDX_q,
513                 IDX_x,
514                 IDX_equal,
515                 IDX_lbrace,
516                 IDX_rbrace,
517                 IDX_nul
518         };
519         unsigned idx;
520
521         BUILD_BUG_ON(sizeof(cmd_letters)-1 != IDX_nul);
522
523         idx = strchrnul(cmd_letters, sed_cmd->cmd) - cmd_letters;
524
525         /* handle (s)ubstitution command */
526         if (idx == IDX_s) {
527                 cmdstr += parse_subst_cmd(sed_cmd, cmdstr);
528         }
529         /* handle edit cmds: (a)ppend, (i)nsert, and (c)hange */
530         else if (idx <= IDX_c) { /* a,i,c */
531                 unsigned len;
532
533                 if (idx < IDX_c) { /* a,i */
534                         if (sed_cmd->end_line || sed_cmd->end_match)
535                                 bb_error_msg_and_die("command '%c' uses only one address", sed_cmd->cmd);
536                 }
537                 for (;;) {
538                         if (*cmdstr == '\n' || *cmdstr == '\\') {
539                                 cmdstr++;
540                                 break;
541                         }
542                         if (!isspace(*cmdstr))
543                                 break;
544                         cmdstr++;
545                 }
546                 len = strlen(cmdstr);
547                 sed_cmd->string = copy_parsing_escapes(cmdstr, len);
548                 cmdstr += len;
549                 /* "\anychar" -> "anychar" */
550                 parse_escapes(sed_cmd->string, sed_cmd->string, -1, '\0', '\0');
551         }
552         /* handle file cmds: (r)ead */
553         else if (idx <= IDX_w) { /* r,w */
554                 if (idx < IDX_w) { /* r */
555                         if (sed_cmd->end_line || sed_cmd->end_match)
556                                 bb_error_msg_and_die("command '%c' uses only one address", sed_cmd->cmd);
557                 }
558                 cmdstr += parse_file_cmd(/*sed_cmd,*/ cmdstr, &sed_cmd->string);
559                 if (sed_cmd->cmd == 'w') {
560                         sed_cmd->sw_file = xfopen_for_write(sed_cmd->string);
561                         sed_cmd->sw_last_char = '\n';
562                 }
563         }
564         /* handle branch commands */
565         else if (idx <= IDX_T) { /* :,b,t,T */
566                 int length;
567
568                 cmdstr = skip_whitespace(cmdstr);
569                 length = strcspn(cmdstr, semicolon_whitespace);
570                 if (length) {
571                         sed_cmd->string = xstrndup(cmdstr, length);
572                         cmdstr += length;
573                 }
574         }
575         /* translation command */
576         else if (idx == IDX_y) {
577                 char *match, *replace;
578                 int i = cmdstr[0];
579
580                 cmdstr += parse_regex_delim(cmdstr, &match, &replace)+1;
581                 /* \n already parsed, but \delimiter needs unescaping. */
582                 parse_escapes(match,   match,   -1, i, i);
583                 parse_escapes(replace, replace, -1, i, i);
584
585                 sed_cmd->string = xzalloc((strlen(match) + 1) * 2);
586                 for (i = 0; match[i] && replace[i]; i++) {
587                         sed_cmd->string[i*2] = match[i];
588                         sed_cmd->string[i*2+1] = replace[i];
589                 }
590                 free(match);
591                 free(replace);
592         }
593         /* if it wasn't a single-letter command that takes no arguments
594          * then it must be an invalid command.
595          */
596         else if (idx >= IDX_nul) { /* not d,D,g,G,h,H,l,n,N,p,P,q,x,=,{,} */
597                 bb_error_msg_and_die("unsupported command %c", sed_cmd->cmd);
598         }
599
600         /* give back whatever's left over */
601         return cmdstr;
602 }
603
604
605 /* Parse address+command sets, skipping comment lines. */
606
607 static void add_cmd(const char *cmdstr)
608 {
609         sed_cmd_t *sed_cmd;
610         unsigned len, n;
611
612         /* Append this line to any unfinished line from last time. */
613         if (G.add_cmd_line) {
614                 char *tp = xasprintf("%s\n%s", G.add_cmd_line, cmdstr);
615                 free(G.add_cmd_line);
616                 cmdstr = G.add_cmd_line = tp;
617         }
618
619         /* If this line ends with unescaped backslash, request next line. */
620         n = len = strlen(cmdstr);
621         while (n && cmdstr[n-1] == '\\')
622                 n--;
623         if ((len - n) & 1) { /* if odd number of trailing backslashes */
624                 if (!G.add_cmd_line)
625                         G.add_cmd_line = xstrdup(cmdstr);
626                 G.add_cmd_line[len-1] = '\0';
627                 return;
628         }
629
630         /* Loop parsing all commands in this line. */
631         while (*cmdstr) {
632                 /* Skip leading whitespace and semicolons */
633                 cmdstr += strspn(cmdstr, semicolon_whitespace);
634
635                 /* If no more commands, exit. */
636                 if (!*cmdstr) break;
637
638                 /* if this is a comment, jump past it and keep going */
639                 if (*cmdstr == '#') {
640                         /* "#n" is the same as using -n on the command line */
641                         if (cmdstr[1] == 'n')
642                                 G.be_quiet++;
643                         cmdstr = strpbrk(cmdstr, "\n\r");
644                         if (!cmdstr) break;
645                         continue;
646                 }
647
648                 /* parse the command
649                  * format is: [addr][,addr][!]cmd
650                  *            |----||-----||-|
651                  *            part1 part2  part3
652                  */
653
654                 sed_cmd = xzalloc(sizeof(sed_cmd_t));
655
656                 /* first part (if present) is an address: either a '$', a number or a /regex/ */
657                 cmdstr += get_address(cmdstr, &sed_cmd->beg_line, &sed_cmd->beg_match);
658                 sed_cmd->beg_line_orig = sed_cmd->beg_line;
659
660                 /* second part (if present) will begin with a comma */
661                 if (*cmdstr == ',') {
662                         int idx;
663
664                         cmdstr++;
665                         if (*cmdstr == '+' && isdigit(cmdstr[1])) {
666                                 /* http://sed.sourceforge.net/sedfaq3.html#s3.3
667                                  * Under GNU sed 3.02+, ssed, and sed15+, <address2>
668                                  * may also be a notation of the form +num,
669                                  * indicating the next num lines after <address1> is
670                                  * matched.
671                                  * GNU sed 4.2.1 accepts even "+" (meaning "+0").
672                                  * We don't (we check for isdigit, see above), think
673                                  * about the "+-3" case.
674                                  */
675                                 char *end;
676                                 /* code is smaller compared to using &cmdstr here: */
677                                 idx = strtol(cmdstr+1, &end, 10);
678                                 sed_cmd->end_line = -2 - idx;
679                                 cmdstr = end;
680                         } else {
681                                 idx = get_address(cmdstr, &sed_cmd->end_line, &sed_cmd->end_match);
682                                 cmdstr += idx;
683                                 idx--; /* if 0, trigger error check below */
684                         }
685                         if (idx < 0)
686                                 bb_error_msg_and_die("no address after comma");
687                         sed_cmd->end_line_orig = sed_cmd->end_line;
688                 }
689
690                 /* skip whitespace before the command */
691                 cmdstr = skip_whitespace(cmdstr);
692
693                 /* Check for inversion flag */
694                 if (*cmdstr == '!') {
695                         sed_cmd->invert = 1;
696                         cmdstr++;
697
698                         /* skip whitespace before the command */
699                         cmdstr = skip_whitespace(cmdstr);
700                 }
701
702                 /* last part (mandatory) will be a command */
703                 if (!*cmdstr)
704                         bb_error_msg_and_die("missing command");
705                 sed_cmd->cmd = *cmdstr++;
706                 cmdstr = parse_cmd_args(sed_cmd, cmdstr);
707
708                 /* cmdstr now points past args.
709                  * GNU sed requires a separator, if there are more commands,
710                  * else it complains "char N: extra characters after command".
711                  * Example: "sed 'p;d'". We also allow "sed 'pd'".
712                  */
713
714                 /* Add the command to the command array */
715                 *G.sed_cmd_tail = sed_cmd;
716                 G.sed_cmd_tail = &sed_cmd->next;
717         }
718
719         /* If we glued multiple lines together, free the memory. */
720         free(G.add_cmd_line);
721         G.add_cmd_line = NULL;
722 }
723
724 /* Append to a string, reallocating memory as necessary. */
725
726 #define PIPE_GROW 64
727
728 static void pipe_putc(char c)
729 {
730         if (G.pipeline.idx == G.pipeline.len) {
731                 G.pipeline.buf = xrealloc(G.pipeline.buf,
732                                 G.pipeline.len + PIPE_GROW);
733                 G.pipeline.len += PIPE_GROW;
734         }
735         G.pipeline.buf[G.pipeline.idx++] = c;
736 }
737
738 static void do_subst_w_backrefs(char *line, char *replace)
739 {
740         int i, j;
741
742         /* go through the replacement string */
743         for (i = 0; replace[i]; i++) {
744                 /* if we find a backreference (\1, \2, etc.) print the backref'ed text */
745                 if (replace[i] == '\\') {
746                         unsigned backref = replace[++i] - '0';
747                         if (backref <= 9) {
748                                 /* print out the text held in G.regmatch[backref] */
749                                 if (G.regmatch[backref].rm_so != -1) {
750                                         j = G.regmatch[backref].rm_so;
751                                         while (j < G.regmatch[backref].rm_eo)
752                                                 pipe_putc(line[j++]);
753                                 }
754                                 continue;
755                         }
756                         /* I _think_ it is impossible to get '\' to be
757                          * the last char in replace string. Thus we don't check
758                          * for replace[i] == NUL. (counterexample anyone?) */
759                         /* if we find a backslash escaped character, print the character */
760                         pipe_putc(replace[i]);
761                         continue;
762                 }
763                 /* if we find an unescaped '&' print out the whole matched text. */
764                 if (replace[i] == '&') {
765                         j = G.regmatch[0].rm_so;
766                         while (j < G.regmatch[0].rm_eo)
767                                 pipe_putc(line[j++]);
768                         continue;
769                 }
770                 /* Otherwise just output the character. */
771                 pipe_putc(replace[i]);
772         }
773 }
774
775 static int do_subst_command(sed_cmd_t *sed_cmd, char **line_p)
776 {
777         char *line = *line_p;
778         unsigned match_count = 0;
779         bool altered = 0;
780         bool prev_match_empty = 1;
781         bool tried_at_eol = 0;
782         regex_t *current_regex;
783
784         current_regex = sed_cmd->sub_match;
785         /* Handle empty regex. */
786         if (!current_regex) {
787                 current_regex = G.previous_regex_ptr;
788                 if (!current_regex)
789                         bb_error_msg_and_die("no previous regexp");
790         }
791         G.previous_regex_ptr = current_regex;
792
793         /* Find the first match */
794         dbg("matching '%s'", line);
795         if (REG_NOMATCH == regexec(current_regex, line, 10, G.regmatch, 0)) {
796                 dbg("no match");
797                 return 0;
798         }
799         dbg("match");
800
801         /* Initialize temporary output buffer. */
802         G.pipeline.buf = xmalloc(PIPE_GROW);
803         G.pipeline.len = PIPE_GROW;
804         G.pipeline.idx = 0;
805
806         /* Now loop through, substituting for matches */
807         do {
808                 int start = G.regmatch[0].rm_so;
809                 int end = G.regmatch[0].rm_eo;
810                 int i;
811
812                 match_count++;
813
814                 /* If we aren't interested in this match, output old line to
815                  * end of match and continue */
816                 if (sed_cmd->which_match
817                  && (sed_cmd->which_match != match_count)
818                 ) {
819                         for (i = 0; i < end; i++)
820                                 pipe_putc(*line++);
821                         /* Null match? Print one more char */
822                         if (start == end && *line)
823                                 pipe_putc(*line++);
824                         goto next;
825                 }
826
827                 /* Print everything before the match */
828                 for (i = 0; i < start; i++)
829                         pipe_putc(line[i]);
830
831                 /* Then print the substitution string,
832                  * unless we just matched empty string after non-empty one.
833                  * Example: string "cccd", pattern "c*", repl "R":
834                  * result is "RdR", not "RRdR": first match "ccc",
835                  * second is "" before "d", third is "" after "d".
836                  * Second match is NOT replaced!
837                  */
838                 if (prev_match_empty || start != 0 || start != end) {
839                         //dbg("%d %d %d", prev_match_empty, start, end);
840                         dbg("inserting replacement at %d in '%s'", start, line);
841                         do_subst_w_backrefs(line, sed_cmd->string);
842                         /* Flag that something has changed */
843                         altered = 1;
844                 } else {
845                         dbg("NOT inserting replacement at %d in '%s'", start, line);
846                 }
847
848                 /* If matched string is empty (f.e. "c*" pattern),
849                  * copy verbatim one char after it before attempting more matches
850                  */
851                 prev_match_empty = (start == end);
852                 if (prev_match_empty) {
853                         if (!line[end]) {
854                                 tried_at_eol = 1;
855                         } else {
856                                 pipe_putc(line[end]);
857                                 end++;
858                         }
859                 }
860
861                 /* Advance past the match */
862                 dbg("line += %d", end);
863                 line += end;
864
865                 /* if we're not doing this globally, get out now */
866                 if (sed_cmd->which_match != 0)
867                         break;
868  next:
869                 /* Exit if we are at EOL and already tried matching at it */
870                 if (*line == '\0') {
871                         if (tried_at_eol)
872                                 break;
873                         tried_at_eol = 1;
874                 }
875
876 //maybe (end ? REG_NOTBOL : 0) instead of unconditional REG_NOTBOL?
877         } while (regexec(current_regex, line, 10, G.regmatch, REG_NOTBOL) != REG_NOMATCH);
878
879         /* Copy rest of string into output pipeline */
880         while (1) {
881                 char c = *line++;
882                 pipe_putc(c);
883                 if (c == '\0')
884                         break;
885         }
886
887         free(*line_p);
888         *line_p = G.pipeline.buf;
889         return altered;
890 }
891
892 /* Set command pointer to point to this label.  (Does not handle null label.) */
893 static sed_cmd_t *branch_to(char *label)
894 {
895         sed_cmd_t *sed_cmd;
896
897         for (sed_cmd = G.sed_cmd_head; sed_cmd; sed_cmd = sed_cmd->next) {
898                 if (sed_cmd->cmd == ':'
899                  && sed_cmd->string
900                  && strcmp(sed_cmd->string, label) == 0
901                 ) {
902                         return sed_cmd;
903                 }
904         }
905         bb_error_msg_and_die("can't find label for jump to '%s'", label);
906 }
907
908 static void append(char *s)
909 {
910         llist_add_to_end(&G.append_head, s);
911 }
912
913 /* Output line of text. */
914 /* Note:
915  * The tricks with NO_EOL_CHAR and last_puts_char are there to emulate gnu sed.
916  * Without them, we had this:
917  * echo -n thingy >z1
918  * echo -n again >z2
919  * >znull
920  * sed "s/i/z/" z1 z2 znull | hexdump -vC
921  * output:
922  * gnu sed 4.1.5:
923  * 00000000  74 68 7a 6e 67 79 0a 61  67 61 7a 6e              |thzngy.agazn|
924  * bbox:
925  * 00000000  74 68 7a 6e 67 79 61 67  61 7a 6e                 |thzngyagazn|
926  */
927 enum {
928         NO_EOL_CHAR = 1,
929         LAST_IS_NUL = 2,
930 };
931 static void puts_maybe_newline(char *s, FILE *file, char *last_puts_char, char last_gets_char)
932 {
933         char lpc = *last_puts_char;
934
935         /* Need to insert a '\n' between two files because first file's
936          * last line wasn't terminated? */
937         if (lpc != '\n' && lpc != '\0') {
938                 fputc('\n', file);
939                 lpc = '\n';
940         }
941         fputs(s, file);
942
943         /* 'x' - just something which is not '\n', '\0' or NO_EOL_CHAR */
944         if (s[0])
945                 lpc = 'x';
946
947         /* had trailing '\0' and it was last char of file? */
948         if (last_gets_char == LAST_IS_NUL) {
949                 fputc('\0', file);
950                 lpc = 'x'; /* */
951         } else
952         /* had trailing '\n' or '\0'? */
953         if (last_gets_char != NO_EOL_CHAR) {
954                 fputc(last_gets_char, file);
955                 lpc = last_gets_char;
956         }
957
958         if (ferror(file)) {
959                 xfunc_error_retval = 4;  /* It's what gnu sed exits with... */
960                 bb_error_msg_and_die(bb_msg_write_error);
961         }
962         *last_puts_char = lpc;
963 }
964
965 static void flush_append(char *last_puts_char)
966 {
967         char *data;
968
969         /* Output appended lines. */
970         while ((data = (char *)llist_pop(&G.append_head)) != NULL) {
971                 /* Append command does not respect "nonterminated-ness"
972                  * of last line. Try this:
973                  * $ echo -n "woot" | sed -e '/woot/a woo' -
974                  * woot
975                  * woo
976                  * (both lines are terminated with \n)
977                  * Therefore we do not propagate "last_gets_char" here,
978                  * pass '\n' instead:
979                  */
980                 puts_maybe_newline(data, G.nonstdout, last_puts_char, '\n');
981                 free(data);
982         }
983 }
984
985 /* Get next line of input from G.input_file_list, flushing append buffer and
986  * noting if we ran out of files without a newline on the last line we read.
987  */
988 static char *get_next_line(char *gets_char, char *last_puts_char)
989 {
990         char *temp = NULL;
991         size_t len;
992         char gc;
993
994         flush_append(last_puts_char);
995
996         /* will be returned if last line in the file
997          * doesn't end with either '\n' or '\0' */
998         gc = NO_EOL_CHAR;
999         for (; G.current_input_file <= G.last_input_file; G.current_input_file++) {
1000                 FILE *fp = G.current_fp;
1001                 if (!fp) {
1002                         const char *path = G.input_file_list[G.current_input_file];
1003                         fp = stdin;
1004                         if (path != bb_msg_standard_input) {
1005                                 fp = fopen_or_warn(path, "r");
1006                                 if (!fp) {
1007                                         G.exitcode = EXIT_FAILURE;
1008                                         continue;
1009                                 }
1010                         }
1011                         G.current_fp = fp;
1012                 }
1013                 /* Read line up to a newline or NUL byte, inclusive,
1014                  * return malloc'ed char[]. length of the chunk read
1015                  * is stored in len. NULL if EOF/error */
1016                 temp = bb_get_chunk_from_file(fp, &len);
1017                 if (temp) {
1018                         /* len > 0 here, it's ok to do temp[len-1] */
1019                         char c = temp[len-1];
1020                         if (c == '\n' || c == '\0') {
1021                                 temp[len-1] = '\0';
1022                                 gc = c;
1023                                 if (c == '\0') {
1024                                         int ch = fgetc(fp);
1025                                         if (ch != EOF)
1026                                                 ungetc(ch, fp);
1027                                         else
1028                                                 gc = LAST_IS_NUL;
1029                                 }
1030                         }
1031                         /* else we put NO_EOL_CHAR into *gets_char */
1032                         break;
1033
1034                 /* NB: I had the idea of peeking next file(s) and returning
1035                  * NO_EOL_CHAR only if it is the *last* non-empty
1036                  * input file. But there is a case where this won't work:
1037                  * file1: "a woo\nb woo"
1038                  * file2: "c no\nd no"
1039                  * sed -ne 's/woo/bang/p' input1 input2 => "a bang\nb bang"
1040                  * (note: *no* newline after "b bang"!) */
1041                 }
1042                 /* Close this file and advance to next one */
1043                 fclose_if_not_stdin(fp);
1044                 G.current_fp = NULL;
1045         }
1046         *gets_char = gc;
1047         return temp;
1048 }
1049
1050 #define sed_puts(s, n) (puts_maybe_newline(s, G.nonstdout, &last_puts_char, n))
1051
1052 static int beg_match(sed_cmd_t *sed_cmd, const char *pattern_space)
1053 {
1054         int retval = sed_cmd->beg_match && !regexec(sed_cmd->beg_match, pattern_space, 0, NULL, 0);
1055         if (retval)
1056                 G.previous_regex_ptr = sed_cmd->beg_match;
1057         return retval;
1058 }
1059
1060 /* Process all the lines in all the files */
1061
1062 static void process_files(void)
1063 {
1064         char *pattern_space, *next_line;
1065         int linenum = 0;
1066         char last_puts_char = '\n';
1067         char last_gets_char, next_gets_char;
1068         sed_cmd_t *sed_cmd;
1069         int substituted;
1070
1071         /* Prime the pump */
1072         next_line = get_next_line(&next_gets_char, &last_puts_char);
1073
1074         /* Go through every line in each file */
1075  again:
1076         substituted = 0;
1077
1078         /* Advance to next line.  Stop if out of lines. */
1079         pattern_space = next_line;
1080         if (!pattern_space)
1081                 return;
1082         last_gets_char = next_gets_char;
1083
1084         /* Read one line in advance so we can act on the last line,
1085          * the '$' address */
1086         next_line = get_next_line(&next_gets_char, &last_puts_char);
1087         linenum++;
1088
1089         /* For every line, go through all the commands */
1090  restart:
1091         for (sed_cmd = G.sed_cmd_head; sed_cmd; sed_cmd = sed_cmd->next) {
1092                 int old_matched, matched;
1093
1094                 old_matched = sed_cmd->in_match;
1095
1096                 /* Determine if this command matches this line: */
1097
1098                 dbg("match1:%d", sed_cmd->in_match);
1099                 dbg("match2:%d", (!sed_cmd->beg_line && !sed_cmd->end_line
1100                                 && !sed_cmd->beg_match && !sed_cmd->end_match));
1101                 dbg("match3:%d", (sed_cmd->beg_line > 0
1102                         && (sed_cmd->end_line || sed_cmd->end_match
1103                             ? (sed_cmd->beg_line <= linenum)
1104                             : (sed_cmd->beg_line == linenum)
1105                             )
1106                         ));
1107                 dbg("match4:%d", (beg_match(sed_cmd, pattern_space)));
1108                 dbg("match5:%d", (sed_cmd->beg_line == -1 && next_line == NULL));
1109
1110                 /* Are we continuing a previous multi-line match? */
1111                 sed_cmd->in_match = sed_cmd->in_match
1112                         /* Or is no range necessary? */
1113                         || (!sed_cmd->beg_line && !sed_cmd->end_line
1114                                 && !sed_cmd->beg_match && !sed_cmd->end_match)
1115                         /* Or did we match the start of a numerical range? */
1116                         || (sed_cmd->beg_line > 0
1117                             && (sed_cmd->end_line || sed_cmd->end_match
1118                                   /* note: even if end is numeric and is < linenum too,
1119                                    * GNU sed matches! We match too, therefore we don't
1120                                    * check here that linenum <= end.
1121                                    * Example:
1122                                    * printf '1\n2\n3\n4\n' | sed -n '1{N;N;d};1p;2,3p;3p;4p'
1123                                    * first three input lines are deleted;
1124                                    * 4th line is matched and printed
1125                                    * by "2,3" (!) and by "4" ranges
1126                                    */
1127                                 ? (sed_cmd->beg_line <= linenum)    /* N,end */
1128                                 : (sed_cmd->beg_line == linenum)    /* N */
1129                                 )
1130                             )
1131                         /* Or does this line match our begin address regex? */
1132                         || (beg_match(sed_cmd, pattern_space))
1133                         /* Or did we match last line of input? */
1134                         || (sed_cmd->beg_line == -1 && next_line == NULL);
1135
1136                 /* Snapshot the value */
1137                 matched = sed_cmd->in_match;
1138
1139                 dbg("cmd:'%c' matched:%d beg_line:%d end_line:%d linenum:%d",
1140                         sed_cmd->cmd, matched, sed_cmd->beg_line, sed_cmd->end_line, linenum);
1141
1142                 /* Is this line the end of the current match? */
1143
1144                 if (matched) {
1145                         if (sed_cmd->end_line <= -2) {
1146                                 /* address2 is +N, i.e. N lines from beg_line */
1147                                 sed_cmd->end_line = linenum + (-sed_cmd->end_line - 2);
1148                         }
1149                         /* once matched, "n,xxx" range is dead, disabling it */
1150                         if (sed_cmd->beg_line > 0) {
1151                                 sed_cmd->beg_line = -2;
1152                         }
1153                         dbg("end1:%d", sed_cmd->end_line ? sed_cmd->end_line == -1
1154                                                 ? !next_line : (sed_cmd->end_line <= linenum)
1155                                         : !sed_cmd->end_match);
1156                         dbg("end2:%d", sed_cmd->end_match && old_matched
1157                                         && !regexec(sed_cmd->end_match,pattern_space, 0, NULL, 0));
1158                         sed_cmd->in_match = !(
1159                                 /* has the ending line come, or is this a single address command? */
1160                                 (sed_cmd->end_line
1161                                         ? sed_cmd->end_line == -1
1162                                                 ? !next_line
1163                                                 : (sed_cmd->end_line <= linenum)
1164                                         : !sed_cmd->end_match
1165                                 )
1166                                 /* or does this line matches our last address regex */
1167                                 || (sed_cmd->end_match && old_matched
1168                                      && (regexec(sed_cmd->end_match,
1169                                                 pattern_space, 0, NULL, 0) == 0)
1170                                 )
1171                         );
1172                 }
1173
1174                 /* Skip blocks of commands we didn't match */
1175                 if (sed_cmd->cmd == '{') {
1176                         if (sed_cmd->invert ? matched : !matched) {
1177                                 unsigned nest_cnt = 0;
1178                                 while (1) {
1179                                         if (sed_cmd->cmd == '{')
1180                                                 nest_cnt++;
1181                                         if (sed_cmd->cmd == '}') {
1182                                                 nest_cnt--;
1183                                                 if (nest_cnt == 0)
1184                                                         break;
1185                                         }
1186                                         sed_cmd = sed_cmd->next;
1187                                         if (!sed_cmd)
1188                                                 bb_error_msg_and_die("unterminated {");
1189                                 }
1190                         }
1191                         continue;
1192                 }
1193
1194                 /* Okay, so did this line match? */
1195                 if (sed_cmd->invert ? matched : !matched)
1196                         continue; /* no */
1197
1198                 /* Update last used regex in case a blank substitute BRE is found */
1199                 if (sed_cmd->beg_match) {
1200                         G.previous_regex_ptr = sed_cmd->beg_match;
1201                 }
1202
1203                 /* actual sedding */
1204                 dbg("pattern_space:'%s' next_line:'%s' cmd:%c",
1205                                 pattern_space, next_line, sed_cmd->cmd);
1206                 switch (sed_cmd->cmd) {
1207
1208                 /* Print line number */
1209                 case '=':
1210                         fprintf(G.nonstdout, "%d\n", linenum);
1211                         break;
1212
1213                 /* Write the current pattern space up to the first newline */
1214                 case 'P':
1215                 {
1216                         char *tmp = strchr(pattern_space, '\n');
1217                         if (tmp) {
1218                                 *tmp = '\0';
1219                                 /* TODO: explain why '\n' below */
1220                                 sed_puts(pattern_space, '\n');
1221                                 *tmp = '\n';
1222                                 break;
1223                         }
1224                         /* Fall Through */
1225                 }
1226
1227                 /* Write the current pattern space to output */
1228                 case 'p':
1229                         /* NB: we print this _before_ the last line
1230                          * (of current file) is printed. Even if
1231                          * that line is nonterminated, we print
1232                          * '\n' here (gnu sed does the same) */
1233                         sed_puts(pattern_space, '\n');
1234                         break;
1235                 /* Delete up through first newline */
1236                 case 'D':
1237                 {
1238                         char *tmp = strchr(pattern_space, '\n');
1239                         if (tmp) {
1240                                 overlapping_strcpy(pattern_space, tmp + 1);
1241                                 goto restart;
1242                         }
1243                 }
1244                 /* discard this line. */
1245                 case 'd':
1246                         goto discard_line;
1247
1248                 /* Substitute with regex */
1249                 case 's':
1250                         if (!do_subst_command(sed_cmd, &pattern_space))
1251                                 break;
1252                         dbg("do_subst_command succeeded:'%s'", pattern_space);
1253                         substituted |= 1;
1254
1255                         /* handle p option */
1256                         if (sed_cmd->sub_p)
1257                                 sed_puts(pattern_space, last_gets_char);
1258                         /* handle w option */
1259                         if (sed_cmd->sw_file)
1260                                 puts_maybe_newline(
1261                                         pattern_space, sed_cmd->sw_file,
1262                                         &sed_cmd->sw_last_char, last_gets_char);
1263                         break;
1264
1265                 /* Append line to linked list to be printed later */
1266                 case 'a':
1267                         append(xstrdup(sed_cmd->string));
1268                         break;
1269
1270                 /* Insert text before this line */
1271                 case 'i':
1272                         sed_puts(sed_cmd->string, '\n');
1273                         break;
1274
1275                 /* Cut and paste text (replace) */
1276                 case 'c':
1277                         /* Only triggers on last line of a matching range. */
1278                         if (!sed_cmd->in_match)
1279                                 sed_puts(sed_cmd->string, '\n');
1280                         goto discard_line;
1281
1282                 /* Read file, append contents to output */
1283                 case 'r':
1284                 {
1285                         FILE *rfile;
1286                         rfile = fopen_for_read(sed_cmd->string);
1287                         if (rfile) {
1288                                 char *line;
1289                                 while ((line = xmalloc_fgetline(rfile))
1290                                                 != NULL)
1291                                         append(line);
1292                                 fclose(rfile);
1293                         }
1294
1295                         break;
1296                 }
1297
1298                 /* Write pattern space to file. */
1299                 case 'w':
1300                         puts_maybe_newline(
1301                                 pattern_space, sed_cmd->sw_file,
1302                                 &sed_cmd->sw_last_char, last_gets_char);
1303                         break;
1304
1305                 /* Read next line from input */
1306                 case 'n':
1307                         if (!G.be_quiet)
1308                                 sed_puts(pattern_space, last_gets_char);
1309                         if (next_line == NULL) {
1310                                 /* If no next line, jump to end of script and exit. */
1311                                 goto discard_line;
1312                         }
1313                         free(pattern_space);
1314                         pattern_space = next_line;
1315                         last_gets_char = next_gets_char;
1316                         next_line = get_next_line(&next_gets_char, &last_puts_char);
1317                         substituted = 0;
1318                         linenum++;
1319                         break;
1320
1321                 /* Quit.  End of script, end of input. */
1322                 case 'q':
1323                         /* Exit the outer while loop */
1324                         free(next_line);
1325                         next_line = NULL;
1326                         goto discard_commands;
1327
1328                 /* Append the next line to the current line */
1329                 case 'N':
1330                 {
1331                         int len;
1332                         /* If no next line, jump to end of script and exit. */
1333                         /* http://www.gnu.org/software/sed/manual/sed.html:
1334                          * "Most versions of sed exit without printing anything
1335                          * when the N command is issued on the last line of
1336                          * a file. GNU sed prints pattern space before exiting
1337                          * unless of course the -n command switch has been
1338                          * specified. This choice is by design."
1339                          */
1340                         if (next_line == NULL) {
1341                                 //goto discard_line;
1342                                 goto discard_commands; /* GNU behavior */
1343                         }
1344                         /* Append next_line, read new next_line. */
1345                         len = strlen(pattern_space);
1346                         pattern_space = xrealloc(pattern_space, len + strlen(next_line) + 2);
1347                         pattern_space[len] = '\n';
1348                         strcpy(pattern_space + len+1, next_line);
1349                         last_gets_char = next_gets_char;
1350                         next_line = get_next_line(&next_gets_char, &last_puts_char);
1351                         linenum++;
1352                         break;
1353                 }
1354
1355                 /* Test/branch if substitution occurred */
1356                 case 't':
1357                         if (!substituted) break;
1358                         substituted = 0;
1359                         /* Fall through */
1360                 /* Test/branch if substitution didn't occur */
1361                 case 'T':
1362                         if (substituted) break;
1363                         /* Fall through */
1364                 /* Branch to label */
1365                 case 'b':
1366                         if (!sed_cmd->string) goto discard_commands;
1367                         else sed_cmd = branch_to(sed_cmd->string);
1368                         break;
1369                 /* Transliterate characters */
1370                 case 'y':
1371                 {
1372                         int i, j;
1373                         for (i = 0; pattern_space[i]; i++) {
1374                                 for (j = 0; sed_cmd->string[j]; j += 2) {
1375                                         if (pattern_space[i] == sed_cmd->string[j]) {
1376                                                 pattern_space[i] = sed_cmd->string[j + 1];
1377                                                 break;
1378                                         }
1379                                 }
1380                         }
1381
1382                         break;
1383                 }
1384                 case 'g':       /* Replace pattern space with hold space */
1385                         free(pattern_space);
1386                         pattern_space = xstrdup(G.hold_space ? G.hold_space : "");
1387                         break;
1388                 case 'G':       /* Append newline and hold space to pattern space */
1389                 {
1390                         int pattern_space_size = 2;
1391                         int hold_space_size = 0;
1392
1393                         if (pattern_space)
1394                                 pattern_space_size += strlen(pattern_space);
1395                         if (G.hold_space)
1396                                 hold_space_size = strlen(G.hold_space);
1397                         pattern_space = xrealloc(pattern_space,
1398                                         pattern_space_size + hold_space_size);
1399                         if (pattern_space_size == 2)
1400                                 pattern_space[0] = 0;
1401                         strcat(pattern_space, "\n");
1402                         if (G.hold_space)
1403                                 strcat(pattern_space, G.hold_space);
1404                         last_gets_char = '\n';
1405
1406                         break;
1407                 }
1408                 case 'h':       /* Replace hold space with pattern space */
1409                         free(G.hold_space);
1410                         G.hold_space = xstrdup(pattern_space);
1411                         break;
1412                 case 'H':       /* Append newline and pattern space to hold space */
1413                 {
1414                         int hold_space_size = 2;
1415                         int pattern_space_size = 0;
1416
1417                         if (G.hold_space)
1418                                 hold_space_size += strlen(G.hold_space);
1419                         if (pattern_space)
1420                                 pattern_space_size = strlen(pattern_space);
1421                         G.hold_space = xrealloc(G.hold_space,
1422                                         hold_space_size + pattern_space_size);
1423
1424                         if (hold_space_size == 2)
1425                                 *G.hold_space = 0;
1426                         strcat(G.hold_space, "\n");
1427                         if (pattern_space)
1428                                 strcat(G.hold_space, pattern_space);
1429
1430                         break;
1431                 }
1432                 case 'x': /* Exchange hold and pattern space */
1433                 {
1434                         char *tmp = pattern_space;
1435                         pattern_space = G.hold_space ? G.hold_space : xzalloc(1);
1436                         last_gets_char = '\n';
1437                         G.hold_space = tmp;
1438                         break;
1439                 }
1440                 } /* switch */
1441         } /* for each cmd */
1442
1443         /*
1444          * Exit point from sedding...
1445          */
1446  discard_commands:
1447         /* we will print the line unless we were told to be quiet ('-n')
1448            or if the line was suppressed (ala 'd'elete) */
1449         if (!G.be_quiet)
1450                 sed_puts(pattern_space, last_gets_char);
1451
1452         /* Delete and such jump here. */
1453  discard_line:
1454         flush_append(&last_puts_char /*,last_gets_char*/);
1455         free(pattern_space);
1456
1457         goto again;
1458 }
1459
1460 /* It is possible to have a command line argument with embedded
1461  * newlines.  This counts as multiple command lines.
1462  * However, newline can be escaped: 's/e/z\<newline>z/'
1463  * add_cmd() handles this.
1464  */
1465
1466 static void add_cmd_block(char *cmdstr)
1467 {
1468         char *sv, *eol;
1469
1470         cmdstr = sv = xstrdup(cmdstr);
1471         do {
1472                 eol = strchr(cmdstr, '\n');
1473                 if (eol)
1474                         *eol = '\0';
1475                 add_cmd(cmdstr);
1476                 cmdstr = eol + 1;
1477         } while (eol);
1478         free(sv);
1479 }
1480
1481 int sed_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1482 int sed_main(int argc UNUSED_PARAM, char **argv)
1483 {
1484         unsigned opt;
1485         llist_t *opt_e, *opt_f;
1486         char *opt_i;
1487
1488 #if ENABLE_LONG_OPTS
1489         static const char sed_longopts[] ALIGN1 =
1490                 /* name             has_arg             short */
1491                 "in-place\0"        Optional_argument   "i"
1492                 "regexp-extended\0" No_argument         "r"
1493                 "quiet\0"           No_argument         "n"
1494                 "silent\0"          No_argument         "n"
1495                 "expression\0"      Required_argument   "e"
1496                 "file\0"            Required_argument   "f";
1497 #endif
1498
1499         INIT_G();
1500
1501         /* destroy command strings on exit */
1502         if (ENABLE_FEATURE_CLEAN_UP) atexit(sed_free_and_close_stuff);
1503
1504         /* Lie to autoconf when it starts asking stupid questions. */
1505         if (argv[1] && strcmp(argv[1], "--version") == 0) {
1506                 puts("This is not GNU sed version 4.0");
1507                 return 0;
1508         }
1509
1510         /* do normal option parsing */
1511         opt_e = opt_f = NULL;
1512         opt_i = NULL;
1513         /* -i must be first, to match OPT_in_place definition */
1514         /* -E is a synonym of -r:
1515          * GNU sed 4.2.1 mentions it in neither --help
1516          * nor manpage, but does recognize it.
1517          */
1518         opt = getopt32long(argv, "^"
1519                         "i::rEne:*f:*"
1520                         "\0" "nn"/*count -n*/,
1521                         sed_longopts,
1522                         &opt_i, &opt_e, &opt_f,
1523                         &G.be_quiet); /* counter for -n */
1524         //argc -= optind;
1525         argv += optind;
1526         if (opt & OPT_in_place) { // -i
1527                 die_func = cleanup_outname;
1528         }
1529         if (opt & (2|4))
1530                 G.regex_type |= REG_EXTENDED; // -r or -E
1531         //if (opt & 8)
1532         //      G.be_quiet++; // -n (implemented with a counter instead)
1533         while (opt_e) { // -e
1534                 add_cmd_block(llist_pop(&opt_e));
1535         }
1536         while (opt_f) { // -f
1537                 char *line;
1538                 FILE *cmdfile;
1539                 cmdfile = xfopen_stdin(llist_pop(&opt_f));
1540                 while ((line = xmalloc_fgetline(cmdfile)) != NULL) {
1541                         add_cmd(line);
1542                         free(line);
1543                 }
1544                 fclose_if_not_stdin(cmdfile);
1545         }
1546         /* if we didn't get a pattern from -e or -f, use argv[0] */
1547         if (!(opt & 0x30)) {
1548                 if (!*argv)
1549                         bb_show_usage();
1550                 add_cmd_block(*argv++);
1551         }
1552         /* Flush any unfinished commands. */
1553         add_cmd("");
1554
1555         /* By default, we write to stdout */
1556         G.nonstdout = stdout;
1557
1558         /* argv[0..(argc-1)] should be names of file to process. If no
1559          * files were specified or '-' was specified, take input from stdin.
1560          * Otherwise, we process all the files specified. */
1561         G.input_file_list = argv;
1562         if (!argv[0]) {
1563                 if (opt & OPT_in_place)
1564                         bb_error_msg_and_die(bb_msg_requires_arg, "-i");
1565                 argv[0] = (char*)bb_msg_standard_input;
1566                 /* G.last_input_file = 0; - already is */
1567         } else {
1568                 goto start;
1569
1570                 for (; *argv; argv++) {
1571                         struct stat statbuf;
1572                         int nonstdoutfd;
1573                         sed_cmd_t *sed_cmd;
1574
1575                         G.last_input_file++;
1576  start:
1577                         if (!(opt & OPT_in_place)) {
1578                                 if (LONE_DASH(*argv)) {
1579                                         *argv = (char*)bb_msg_standard_input;
1580                                         process_files();
1581                                 }
1582                                 continue;
1583                         }
1584
1585                         /* -i: process each FILE separately: */
1586
1587                         if (stat(*argv, &statbuf) != 0) {
1588                                 bb_simple_perror_msg(*argv);
1589                                 G.exitcode = EXIT_FAILURE;
1590                                 G.current_input_file++;
1591                                 continue;
1592                         }
1593                         G.outname = xasprintf("%sXXXXXX", *argv);
1594                         nonstdoutfd = xmkstemp(G.outname);
1595                         G.nonstdout = xfdopen_for_write(nonstdoutfd);
1596                         /* Set permissions/owner of output file */
1597                         /* chmod'ing AFTER chown would preserve suid/sgid bits,
1598                          * but GNU sed 4.2.1 does not preserve them either */
1599                         fchmod(nonstdoutfd, statbuf.st_mode);
1600                         fchown(nonstdoutfd, statbuf.st_uid, statbuf.st_gid);
1601
1602                         process_files();
1603                         fclose(G.nonstdout);
1604                         G.nonstdout = stdout;
1605
1606                         if (opt_i) {
1607                                 char *backupname = xasprintf("%s%s", *argv, opt_i);
1608                                 xrename(*argv, backupname);
1609                                 free(backupname);
1610                         }
1611                         /* else unlink(*argv); - rename below does this */
1612                         xrename(G.outname, *argv); //TODO: rollback backup on error?
1613                         free(G.outname);
1614                         G.outname = NULL;
1615
1616                         /* Fix disabled range matches and mangled ",+N" ranges */
1617                         for (sed_cmd = G.sed_cmd_head; sed_cmd; sed_cmd = sed_cmd->next) {
1618                                 sed_cmd->beg_line = sed_cmd->beg_line_orig;
1619                                 sed_cmd->end_line = sed_cmd->end_line_orig;
1620                         }
1621                 }
1622                 /* Here, to handle "sed 'cmds' nonexistent_file" case we did:
1623                  * if (G.current_input_file[G.current_input_file] == NULL)
1624                  *      return G.exitcode;
1625                  * but it's not needed since process_files() works correctly
1626                  * in this case too. */
1627         }
1628
1629         process_files();
1630
1631         return G.exitcode;
1632 }