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