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