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