add usefun info on SIGINT handling peculiarities
[oweals/busybox.git] / editors / sed.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * sed.c - very minimalist version of sed
4  *
5  * Copyright (C) 1999,2000,2001 by Lineo, inc. and Mark Whitley
6  * Copyright (C) 1999,2000,2001 by Mark Whitley <markw@codepoet.org>
7  * Copyright (C) 2002  Matt Kraai
8  * Copyright (C) 2003 by Glenn McGrath <bug1@iinet.net.au>
9  * Copyright (C) 2003,2004 by Rob Landley <rob@landley.net>
10  *
11  * MAINTAINER: Rob Landley <rob@landley.net>
12  *
13  * Licensed under GPL version 2, see file LICENSE in this tarball for details.
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   (bbg.sed_cmd_head/bbg.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 "busybox.h"
62 #include "xregex.h"
63
64 /* Each sed command turns into one of these structures. */
65 typedef struct sed_cmd_s {
66         /* Ordered by alignment requirements: currently 36 bytes on x86 */
67
68         /* address storage */
69         regex_t *beg_match;     /* sed -e '/match/cmd' */
70         regex_t *end_match;     /* sed -e '/match/,/end_match/cmd' */
71         regex_t *sub_match;     /* For 's/sub_match/string/' */
72         int beg_line;           /* 'sed 1p'   0 == apply commands to all lines */
73         int end_line;           /* 'sed 1,3p' 0 == one line only. -1 = last line ($) */
74
75         FILE *file;             /* File (sw) command writes to, -1 for none. */
76         char *string;           /* Data string for (saicytb) commands. */
77
78         unsigned short which_match;     /* (s) Which match to replace (0 for all) */
79
80         /* Bitfields (gcc won't group them if we don't) */
81         unsigned int invert:1;          /* the '!' after the address */
82         unsigned int in_match:1;        /* Next line also included in match? */
83         unsigned int no_newline:1;      /* Last line written by (sw) had no '\n' */
84         unsigned int sub_p:1;           /* (s) print option */
85
86         /* GENERAL FIELDS */
87         char cmd;               /* The command char: abcdDgGhHilnNpPqrstwxy:={} */
88         struct sed_cmd_s *next; /* Next command (linked list, NULL terminated) */
89 } sed_cmd_t;
90
91 static const char *const semicolon_whitespace = "; \n\r\t\v";
92
93 struct sed_globals
94 {
95         /* options */
96         int be_quiet, in_place, regex_type;
97         FILE *nonstdout;
98         char *outname, *hold_space;
99
100         /* List of input files */
101         int input_file_count,current_input_file;
102         FILE **input_file_list;
103
104         regmatch_t regmatch[10];
105         regex_t *previous_regex_ptr;
106
107         /* linked list of sed commands */
108         sed_cmd_t sed_cmd_head, *sed_cmd_tail;
109
110         /* Linked list of append lines */
111         llist_t *append_head;
112
113         char *add_cmd_line;
114
115         struct pipeline {
116                 char *buf;      /* Space to hold string */
117                 int idx;        /* Space used */
118                 int len;        /* Space allocated */
119         } pipeline;
120 } bbg;
121
122
123 void sed_free_and_close_stuff(void);
124 #if ENABLE_FEATURE_CLEAN_UP
125 void sed_free_and_close_stuff(void)
126 {
127         sed_cmd_t *sed_cmd = bbg.sed_cmd_head.next;
128
129         llist_free(bbg.append_head, free);
130
131         while (sed_cmd) {
132                 sed_cmd_t *sed_cmd_next = sed_cmd->next;
133
134                 if (sed_cmd->file)
135                         xprint_and_close_file(sed_cmd->file);
136
137                 if (sed_cmd->beg_match) {
138                         regfree(sed_cmd->beg_match);
139                         free(sed_cmd->beg_match);
140                 }
141                 if (sed_cmd->end_match) {
142                         regfree(sed_cmd->end_match);
143                         free(sed_cmd->end_match);
144                 }
145                 if (sed_cmd->sub_match) {
146                         regfree(sed_cmd->sub_match);
147                         free(sed_cmd->sub_match);
148                 }
149                 free(sed_cmd->string);
150                 free(sed_cmd);
151                 sed_cmd = sed_cmd_next;
152         }
153
154         if (bbg.hold_space) free(bbg.hold_space);
155
156         while (bbg.current_input_file < bbg.input_file_count)
157                 fclose(bbg.input_file_list[bbg.current_input_file++]);
158 }
159 #endif
160
161 /* If something bad happens during -i operation, delete temp file */
162
163 static void cleanup_outname(void)
164 {
165         if (bbg.outname) unlink(bbg.outname);
166 }
167
168 /* strdup, replacing "\n" with '\n', and "\delimiter" with 'delimiter' */
169
170 static void parse_escapes(char *dest, char *string, int len, char from, char to)
171 {
172         int i = 0;
173
174         while (i < len) {
175                 if (string[i] == '\\') {
176                         if (!to || string[i+1] == from) {
177                                 *(dest++) = to ? to : string[i+1];
178                                 i += 2;
179                                 continue;
180                         } else *(dest++) = string[i++];
181                 }
182                 *(dest++) = string[i++];
183         }
184         *dest = 0;
185 }
186
187 static char *copy_parsing_escapes(char *string, int len)
188 {
189         char *dest = xmalloc(len+1);
190
191         parse_escapes(dest,string,len,'n','\n');
192         return dest;
193 }
194
195
196 /*
197  * index_of_next_unescaped_regexp_delim - walks left to right through a string
198  * beginning at a specified index and returns the index of the next regular
199  * expression delimiter (typically a forward * slash ('/')) not preceded by
200  * a backslash ('\').  A negative delimiter disables square bracket checking.
201  */
202 static int index_of_next_unescaped_regexp_delim(int delimiter, char *str)
203 {
204         int bracket = -1;
205         int escaped = 0;
206         int idx = 0;
207         char ch;
208
209         if (delimiter < 0) {
210                 bracket--;
211                 delimiter *= -1;
212         }
213
214         for (; (ch = str[idx]); idx++) {
215                 if (bracket >= 0) {
216                         if (ch == ']' && !(bracket == idx - 1 || (bracket == idx - 2
217                                         && str[idx - 1] == '^')))
218                                 bracket = -1;
219                 } else if (escaped)
220                         escaped = 0;
221                 else if (ch == '\\')
222                         escaped = 1;
223                 else if (bracket == -1 && ch == '[')
224                         bracket = idx;
225                 else if (ch == delimiter)
226                         return idx;
227         }
228
229         /* if we make it to here, we've hit the end of the string */
230         bb_error_msg_and_die("unmatched '%c'",delimiter);
231 }
232
233 /*
234  *  Returns the index of the third delimiter
235  */
236 static int parse_regex_delim(char *cmdstr, char **match, char **replace)
237 {
238         char *cmdstr_ptr = cmdstr;
239         char delimiter;
240         int idx = 0;
241
242         /* verify that the 's' or 'y' is followed by something.  That something
243          * (typically a 'slash') is now our regexp delimiter... */
244         if (*cmdstr == '\0')
245                 bb_error_msg_and_die("bad format in substitution expression");
246         delimiter = *cmdstr_ptr++;
247
248         /* save the match string */
249         idx = index_of_next_unescaped_regexp_delim(delimiter, cmdstr_ptr);
250         *match = copy_parsing_escapes(cmdstr_ptr, idx);
251
252         /* save the replacement string */
253         cmdstr_ptr += idx + 1;
254         idx = index_of_next_unescaped_regexp_delim(-delimiter, cmdstr_ptr);
255         *replace = copy_parsing_escapes(cmdstr_ptr, idx);
256
257         return ((cmdstr_ptr - cmdstr) + idx);
258 }
259
260 /*
261  * returns the index in the string just past where the address ends.
262  */
263 static int get_address(char *my_str, int *linenum, regex_t ** regex)
264 {
265         char *pos = my_str;
266
267         if (isdigit(*my_str)) {
268                 *linenum = strtol(my_str, &pos, 10);
269                 /* endstr shouldnt ever equal NULL */
270         } else if (*my_str == '$') {
271                 *linenum = -1;
272                 pos++;
273         } else if (*my_str == '/' || *my_str == '\\') {
274                 int next;
275                 char delimiter;
276                 char *temp;
277
278                 delimiter = '/';
279                 if (*my_str == '\\') delimiter = *++pos;
280                 next = index_of_next_unescaped_regexp_delim(delimiter, ++pos);
281                 temp = copy_parsing_escapes(pos,next);
282                 *regex = xmalloc(sizeof(regex_t));
283                 xregcomp(*regex, temp, bbg.regex_type|REG_NEWLINE);
284                 free(temp);
285                 /* Move position to next character after last delimiter */
286                 pos += (next+1);
287         }
288         return pos - my_str;
289 }
290
291 /* Grab a filename.  Whitespace at start is skipped, then goes to EOL. */
292 static int parse_file_cmd(sed_cmd_t *sed_cmd, char *filecmdstr, char **retval)
293 {
294         int start = 0, idx, hack = 0;
295
296         /* Skip whitespace, then grab filename to end of line */
297         while (isspace(filecmdstr[start])) start++;
298         idx = start;
299         while (filecmdstr[idx] && filecmdstr[idx] != '\n') idx++;
300
301         /* If lines glued together, put backslash back. */
302         if (filecmdstr[idx] == '\n') hack = 1;
303         if (idx == start)
304                 bb_error_msg_and_die("empty filename");
305         *retval = xstrndup(filecmdstr+start, idx-start+hack+1);
306         if (hack) (*retval)[idx] = '\\';
307
308         return idx;
309 }
310
311 static int parse_subst_cmd(sed_cmd_t *sed_cmd, char *substr)
312 {
313         int cflags = bbg.regex_type;
314         char *match;
315         int idx = 0;
316
317         /*
318          * A substitution command should look something like this:
319          *    s/match/replace/ #gIpw
320          *    ||     |        |||
321          *    mandatory       optional
322          */
323         idx = parse_regex_delim(substr, &match, &sed_cmd->string);
324
325         /* determine the number of back references in the match string */
326         /* Note: we compute this here rather than in the do_subst_command()
327          * function to save processor time, at the expense of a little more memory
328          * (4 bits) per sed_cmd */
329
330         /* process the flags */
331
332         sed_cmd->which_match = 1;
333         while (substr[++idx]) {
334                 /* Parse match number */
335                 if (isdigit(substr[idx])) {
336                         if (match[0] != '^') {
337                                 /* Match 0 treated as all, multiple matches we take the last one. */
338                                 char *pos = substr+idx;
339                                 sed_cmd->which_match = (unsigned short)strtol(substr+idx,&pos,10);
340                                 idx = pos-substr;
341                         }
342                         continue;
343                 }
344                 /* Skip spaces */
345                 if (isspace(substr[idx])) continue;
346
347                 switch (substr[idx]) {
348                 /* Replace all occurrences */
349                 case 'g':
350                         if (match[0] != '^') sed_cmd->which_match = 0;
351                         break;
352                 /* Print pattern space */
353                 case 'p':
354                         sed_cmd->sub_p = 1;
355                         break;
356                 /* Write to file */
357                 case 'w':
358                 {
359                         char *temp;
360                         idx += parse_file_cmd(sed_cmd,substr+idx,&temp);
361
362                         break;
363                 }
364                 /* Ignore case (gnu exension) */
365                 case 'I':
366                         cflags |= REG_ICASE;
367                         break;
368                 /* Comment */
369                 case '#':
370                         while (substr[++idx]) /*skip all*/;
371                         /* Fall through */
372                 /* End of command */
373                 case ';':
374                 case '}':
375                         goto out;
376                 default:
377                         bb_error_msg_and_die("bad option in substitution expression");
378                 }
379         }
380 out:
381         /* compile the match string into a regex */
382         if (*match != '\0') {
383                 /* If match is empty, we use last regex used at runtime */
384                 sed_cmd->sub_match = (regex_t *) xmalloc(sizeof(regex_t));
385                 xregcomp(sed_cmd->sub_match, match, cflags);
386         }
387         free(match);
388
389         return idx;
390 }
391
392 /*
393  *  Process the commands arguments
394  */
395 static char *parse_cmd_args(sed_cmd_t *sed_cmd, char *cmdstr)
396 {
397         /* handle (s)ubstitution command */
398         if (sed_cmd->cmd == 's')
399                 cmdstr += parse_subst_cmd(sed_cmd, cmdstr);
400         /* handle edit cmds: (a)ppend, (i)nsert, and (c)hange */
401         else if (strchr("aic", sed_cmd->cmd)) {
402                 if ((sed_cmd->end_line || sed_cmd->end_match) && sed_cmd->cmd != 'c')
403                         bb_error_msg_and_die
404                                 ("only a beginning address can be specified for edit commands");
405                 for (;;) {
406                         if (*cmdstr == '\n' || *cmdstr == '\\') {
407                                 cmdstr++;
408                                 break;
409                         } else if (isspace(*cmdstr))
410                                 cmdstr++;
411                         else
412                                 break;
413                 }
414                 sed_cmd->string = xstrdup(cmdstr);
415                 parse_escapes(sed_cmd->string,sed_cmd->string,strlen(cmdstr),0,0);
416                 cmdstr += strlen(cmdstr);
417         /* handle file cmds: (r)ead */
418         } else if (strchr("rw", sed_cmd->cmd)) {
419                 if (sed_cmd->end_line || sed_cmd->end_match)
420                         bb_error_msg_and_die("command only uses one address");
421                 cmdstr += parse_file_cmd(sed_cmd, cmdstr, &sed_cmd->string);
422                 if (sed_cmd->cmd == 'w')
423                         sed_cmd->file = xfopen(sed_cmd->string,"w");
424         /* handle branch commands */
425         } else if (strchr(":btT", sed_cmd->cmd)) {
426                 int length;
427
428                 cmdstr = skip_whitespace(cmdstr);
429                 length = strcspn(cmdstr, semicolon_whitespace);
430                 if (length) {
431                         sed_cmd->string = xstrndup(cmdstr, length);
432                         cmdstr += length;
433                 }
434         }
435         /* translation command */
436         else if (sed_cmd->cmd == 'y') {
437                 char *match, *replace;
438                 int i = cmdstr[0];
439
440                 cmdstr += parse_regex_delim(cmdstr, &match, &replace)+1;
441                 /* \n already parsed, but \delimiter needs unescaping. */
442                 parse_escapes(match,match,strlen(match),i,i);
443                 parse_escapes(replace,replace,strlen(replace),i,i);
444
445                 sed_cmd->string = xzalloc((strlen(match) + 1) * 2);
446                 for (i = 0; match[i] && replace[i]; i++) {
447                         sed_cmd->string[i*2] = match[i];
448                         sed_cmd->string[i*2+1] = replace[i];
449                 }
450                 free(match);
451                 free(replace);
452         }
453         /* if it wasnt a single-letter command that takes no arguments
454          * then it must be an invalid command.
455          */
456         else if (strchr("dDgGhHlnNpPqx={}", sed_cmd->cmd) == 0) {
457                 bb_error_msg_and_die("unsupported command %c", sed_cmd->cmd);
458         }
459
460         /* give back whatever's left over */
461         return cmdstr;
462 }
463
464
465 /* Parse address+command sets, skipping comment lines. */
466
467 static void add_cmd(char *cmdstr)
468 {
469         sed_cmd_t *sed_cmd;
470         int temp;
471
472         /* Append this line to any unfinished line from last time. */
473         if (bbg.add_cmd_line) {
474                 cmdstr = xasprintf("%s\n%s", bbg.add_cmd_line, cmdstr);
475                 free(bbg.add_cmd_line);
476                 bbg.add_cmd_line = cmdstr;
477         }
478
479         /* If this line ends with backslash, request next line. */
480         temp = strlen(cmdstr);
481         if (temp && cmdstr[temp-1] == '\\') {
482                 if (!bbg.add_cmd_line)
483                         bbg.add_cmd_line = xstrdup(cmdstr);
484                 bbg.add_cmd_line[temp-1] = 0;
485                 return;
486         }
487
488         /* Loop parsing all commands in this line. */
489         while (*cmdstr) {
490                 /* Skip leading whitespace and semicolons */
491                 cmdstr += strspn(cmdstr, semicolon_whitespace);
492
493                 /* If no more commands, exit. */
494                 if (!*cmdstr) break;
495
496                 /* if this is a comment, jump past it and keep going */
497                 if (*cmdstr == '#') {
498                         /* "#n" is the same as using -n on the command line */
499                         if (cmdstr[1] == 'n')
500                                 bbg.be_quiet++;
501                         cmdstr = strpbrk(cmdstr, "\n\r");
502                         if (!cmdstr) break;
503                         continue;
504                 }
505
506                 /* parse the command
507                  * format is: [addr][,addr][!]cmd
508                  *            |----||-----||-|
509                  *            part1 part2  part3
510                  */
511
512                 sed_cmd = xzalloc(sizeof(sed_cmd_t));
513
514                 /* first part (if present) is an address: either a '$', a number or a /regex/ */
515                 cmdstr += get_address(cmdstr, &sed_cmd->beg_line, &sed_cmd->beg_match);
516
517                 /* second part (if present) will begin with a comma */
518                 if (*cmdstr == ',') {
519                         int idx;
520
521                         cmdstr++;
522                         idx = get_address(cmdstr, &sed_cmd->end_line, &sed_cmd->end_match);
523                         if (!idx)
524                                 bb_error_msg_and_die("no address after comma");
525                         cmdstr += idx;
526                 }
527
528                 /* skip whitespace before the command */
529                 cmdstr = skip_whitespace(cmdstr);
530
531                 /* Check for inversion flag */
532                 if (*cmdstr == '!') {
533                         sed_cmd->invert = 1;
534                         cmdstr++;
535
536                         /* skip whitespace before the command */
537                         cmdstr = skip_whitespace(cmdstr);
538                 }
539
540                 /* last part (mandatory) will be a command */
541                 if (!*cmdstr)
542                         bb_error_msg_and_die("missing command");
543                 sed_cmd->cmd = *(cmdstr++);
544                 cmdstr = parse_cmd_args(sed_cmd, cmdstr);
545
546                 /* Add the command to the command array */
547                 bbg.sed_cmd_tail->next = sed_cmd;
548                 bbg.sed_cmd_tail = bbg.sed_cmd_tail->next;
549         }
550
551         /* If we glued multiple lines together, free the memory. */
552         free(bbg.add_cmd_line);
553         bbg.add_cmd_line = NULL;
554 }
555
556 /* Append to a string, reallocating memory as necessary. */
557
558 #define PIPE_GROW 64
559
560 static void pipe_putc(char c)
561 {
562         if (bbg.pipeline.idx == bbg.pipeline.len) {
563                 bbg.pipeline.buf = xrealloc(bbg.pipeline.buf,
564                                 bbg.pipeline.len + PIPE_GROW);
565                 bbg.pipeline.len += PIPE_GROW;
566         }
567         bbg.pipeline.buf[bbg.pipeline.idx++] = c;
568 }
569
570 static void do_subst_w_backrefs(char *line, char *replace)
571 {
572         int i,j;
573
574         /* go through the replacement string */
575         for (i = 0; replace[i]; i++) {
576                 /* if we find a backreference (\1, \2, etc.) print the backref'ed * text */
577                 if (replace[i] == '\\' && replace[i+1] >= '0' && replace[i+1] <= '9') {
578                         int backref = replace[++i]-'0';
579
580                         /* print out the text held in bbg.regmatch[backref] */
581                         if (bbg.regmatch[backref].rm_so != -1) {
582                                 j = bbg.regmatch[backref].rm_so;
583                                 while (j < bbg.regmatch[backref].rm_eo)
584                                         pipe_putc(line[j++]);
585                         }
586                 }
587
588                 /* if we find a backslash escaped character, print the character */
589                 else if (replace[i] == '\\') pipe_putc(replace[++i]);
590
591                 /* if we find an unescaped '&' print out the whole matched text. */
592                 else if (replace[i] == '&') {
593                         j = bbg.regmatch[0].rm_so;
594                         while (j < bbg.regmatch[0].rm_eo)
595                                 pipe_putc(line[j++]);
596                 }
597                 /* Otherwise just output the character. */
598                 else pipe_putc(replace[i]);
599         }
600 }
601
602 static int do_subst_command(sed_cmd_t *sed_cmd, char **line)
603 {
604         char *oldline = *line;
605         int altered = 0;
606         int match_count = 0;
607         regex_t *current_regex;
608
609         /* Handle empty regex. */
610         if (sed_cmd->sub_match == NULL) {
611                 current_regex = bbg.previous_regex_ptr;
612                 if (!current_regex)
613                         bb_error_msg_and_die("no previous regexp");
614         } else
615                 bbg.previous_regex_ptr = current_regex = sed_cmd->sub_match;
616
617         /* Find the first match */
618         if (REG_NOMATCH == regexec(current_regex, oldline, 10, bbg.regmatch, 0))
619                 return 0;
620
621         /* Initialize temporary output buffer. */
622         bbg.pipeline.buf = xmalloc(PIPE_GROW);
623         bbg.pipeline.len = PIPE_GROW;
624         bbg.pipeline.idx = 0;
625
626         /* Now loop through, substituting for matches */
627         do {
628                 int i;
629
630                 /* Work around bug in glibc regexec, demonstrated by:
631                    echo " a.b" | busybox sed 's [^ .]* x g'
632                    The match_count check is so not to break
633                    echo "hi" | busybox sed 's/^/!/g' */
634                 if (!bbg.regmatch[0].rm_so && !bbg.regmatch[0].rm_eo && match_count) {
635                         pipe_putc(*oldline++);
636                         continue;
637                 }
638
639                 match_count++;
640
641                 /* If we aren't interested in this match, output old line to
642                    end of match and continue */
643                 if (sed_cmd->which_match && sed_cmd->which_match!=match_count) {
644                         for (i = 0; i < bbg.regmatch[0].rm_eo; i++)
645                                 pipe_putc(*oldline++);
646                         continue;
647                 }
648
649                 /* print everything before the match */
650                 for (i = 0; i < bbg.regmatch[0].rm_so; i++)
651                         pipe_putc(oldline[i]);
652
653                 /* then print the substitution string */
654                 do_subst_w_backrefs(oldline, sed_cmd->string);
655
656                 /* advance past the match */
657                 oldline += bbg.regmatch[0].rm_eo;
658                 /* flag that something has changed */
659                 altered++;
660
661                 /* if we're not doing this globally, get out now */
662                 if (sed_cmd->which_match) break;
663         } while (*oldline && (regexec(current_regex, oldline, 10, bbg.regmatch, 0) != REG_NOMATCH));
664
665         /* Copy rest of string into output pipeline */
666
667         while (*oldline)
668                 pipe_putc(*oldline++);
669         pipe_putc(0);
670
671         free(*line);
672         *line = bbg.pipeline.buf;
673         return altered;
674 }
675
676 /* Set command pointer to point to this label.  (Does not handle null label.) */
677 static sed_cmd_t *branch_to(char *label)
678 {
679         sed_cmd_t *sed_cmd;
680
681         for (sed_cmd = bbg.sed_cmd_head.next; sed_cmd; sed_cmd = sed_cmd->next) {
682                 if (sed_cmd->cmd == ':' && sed_cmd->string && !strcmp(sed_cmd->string, label)) {
683                         return sed_cmd;
684                 }
685         }
686         bb_error_msg_and_die("can't find label for jump to '%s'", label);
687 }
688
689 static void append(char *s)
690 {
691         llist_add_to_end(&bbg.append_head, xstrdup(s));
692 }
693
694 static void flush_append(void)
695 {
696         char *data;
697
698         /* Output appended lines. */
699         while ((data = (char *)llist_pop(&bbg.append_head))) {
700                 fprintf(bbg.nonstdout,"%s\n",data);
701                 free(data);
702         }
703 }
704
705 static void add_input_file(FILE *file)
706 {
707         bbg.input_file_list = xrealloc(bbg.input_file_list,
708                         (bbg.input_file_count + 1) * sizeof(FILE *));
709         bbg.input_file_list[bbg.input_file_count++] = file;
710 }
711
712 /* Get next line of input from bbg.input_file_list, flushing append buffer and
713  * noting if we ran out of files without a newline on the last line we read.
714  */
715 static char *get_next_line(int *no_newline)
716 {
717         char *temp = NULL;
718         int len;
719
720         flush_append();
721         while (bbg.current_input_file < bbg.input_file_count) {
722                 temp = bb_get_chunk_from_file(bbg.input_file_list[bbg.current_input_file],&len);
723                 if (temp) {
724                         *no_newline = !(len && temp[len-1] == '\n');
725                         if (!*no_newline) temp[len-1] = 0;
726                         break;
727                 // Close this file and advance to next one
728                 } else
729                         fclose(bbg.input_file_list[bbg.current_input_file++]);
730         }
731
732         return temp;
733 }
734
735 /* Output line of text.  missing_newline means the last line output did not
736    end with a newline.  no_newline means this line does not end with a
737    newline. */
738
739 static int puts_maybe_newline(char *s, FILE *file, int missing_newline, int no_newline)
740 {
741         if (missing_newline) fputc('\n',file);
742         fputs(s,file);
743         if (!no_newline) fputc('\n',file);
744
745         if (ferror(file)) {
746                 xfunc_error_retval = 4;  /* It's what gnu sed exits with... */
747                 bb_error_msg_and_die(bb_msg_write_error);
748         }
749
750         return no_newline;
751 }
752
753 #define sed_puts(s,n) missing_newline=puts_maybe_newline(s,bbg.nonstdout,missing_newline,n)
754
755 /* Process all the lines in all the files */
756
757 static void process_files(void)
758 {
759         char *pattern_space, *next_line;
760         int linenum = 0, missing_newline = 0;
761         int no_newline,next_no_newline = 0;
762
763         /* Prime the pump */
764         next_line = get_next_line(&next_no_newline);
765
766         /* go through every line in each file */
767         for (;;) {
768                 sed_cmd_t *sed_cmd;
769                 int substituted = 0;
770
771                 /* Advance to next line.  Stop if out of lines. */
772                 pattern_space = next_line;
773                 if (!pattern_space) break;
774                 no_newline = next_no_newline;
775
776                 /* Read one line in advance so we can act on the last line,
777                  * the '$' address */
778                 next_line = get_next_line(&next_no_newline);
779                 linenum++;
780 restart:
781                 /* for every line, go through all the commands */
782                 for (sed_cmd = bbg.sed_cmd_head.next; sed_cmd; sed_cmd = sed_cmd->next) {
783                         int old_matched, matched;
784
785                         old_matched = sed_cmd->in_match;
786
787                         /* Determine if this command matches this line: */
788
789                         /* Are we continuing a previous multi-line match? */
790                         sed_cmd->in_match = sed_cmd->in_match
791                                 /* Or is no range necessary? */
792                                 || (!sed_cmd->beg_line && !sed_cmd->end_line
793                                         && !sed_cmd->beg_match && !sed_cmd->end_match)
794                                 /* Or did we match the start of a numerical range? */
795                                 || (sed_cmd->beg_line > 0 && (sed_cmd->beg_line == linenum))
796                                 /* Or does this line match our begin address regex? */
797                                 || (sed_cmd->beg_match &&
798                                     !regexec(sed_cmd->beg_match, pattern_space, 0, NULL, 0))
799                                 /* Or did we match last line of input? */
800                                 || (sed_cmd->beg_line == -1 && next_line == NULL);
801
802                         /* Snapshot the value */
803
804                         matched = sed_cmd->in_match;
805
806                         /* Is this line the end of the current match? */
807
808                         if (matched) {
809                                 sed_cmd->in_match = !(
810                                         /* has the ending line come, or is this a single address command? */
811                                         (sed_cmd->end_line ?
812                                                 sed_cmd->end_line==-1 ?
813                                                         !next_line
814                                                         : sed_cmd->end_line<=linenum
815                                                 : !sed_cmd->end_match)
816                                         /* or does this line matches our last address regex */
817                                         || (sed_cmd->end_match && old_matched && (regexec(sed_cmd->end_match, pattern_space, 0, NULL, 0) == 0))
818                                 );
819                         }
820
821                         /* Skip blocks of commands we didn't match. */
822                         if (sed_cmd->cmd == '{') {
823                                 if (sed_cmd->invert ? matched : !matched)
824                                         while (sed_cmd && sed_cmd->cmd != '}')
825                                                 sed_cmd = sed_cmd->next;
826                                 if (!sed_cmd) bb_error_msg_and_die("unterminated {");
827                                 continue;
828                         }
829
830                         /* Okay, so did this line match? */
831                         if (sed_cmd->invert ? !matched : matched) {
832                                 /* Update last used regex in case a blank substitute BRE is found */
833                                 if (sed_cmd->beg_match) {
834                                         bbg.previous_regex_ptr = sed_cmd->beg_match;
835                                 }
836
837                                 /* actual sedding */
838                                 switch (sed_cmd->cmd) {
839
840                                 /* Print line number */
841                                 case '=':
842                                         fprintf(bbg.nonstdout, "%d\n", linenum);
843                                         break;
844
845                                 /* Write the current pattern space up to the first newline */
846                                 case 'P':
847                                 {
848                                         char *tmp = strchr(pattern_space, '\n');
849
850                                         if (tmp) {
851                                                 *tmp = '\0';
852                                                 sed_puts(pattern_space,1);
853                                                 *tmp = '\n';
854                                                 break;
855                                         }
856                                         /* Fall Through */
857                                 }
858
859                                 /* Write the current pattern space to output */
860                                 case 'p':
861                                         sed_puts(pattern_space,no_newline);
862                                         break;
863                                 /* Delete up through first newline */
864                                 case 'D':
865                                 {
866                                         char *tmp = strchr(pattern_space,'\n');
867
868                                         if (tmp) {
869                                                 tmp = xstrdup(tmp+1);
870                                                 free(pattern_space);
871                                                 pattern_space = tmp;
872                                                 goto restart;
873                                         }
874                                 }
875                                 /* discard this line. */
876                                 case 'd':
877                                         goto discard_line;
878
879                                 /* Substitute with regex */
880                                 case 's':
881                                         if (do_subst_command(sed_cmd, &pattern_space)) {
882                                                 substituted |= 1;
883
884                                                 /* handle p option */
885                                                 if (sed_cmd->sub_p)
886                                                         sed_puts(pattern_space,no_newline);
887                                                 /* handle w option */
888                                                 if (sed_cmd->file)
889                                                         sed_cmd->no_newline = puts_maybe_newline(pattern_space, sed_cmd->file, sed_cmd->no_newline, no_newline);
890
891                                         }
892                                         break;
893
894                                 /* Append line to linked list to be printed later */
895                                 case 'a':
896                                 {
897                                         append(sed_cmd->string);
898                                         break;
899                                 }
900
901                                 /* Insert text before this line */
902                                 case 'i':
903                                         sed_puts(sed_cmd->string,1);
904                                         break;
905
906                                 /* Cut and paste text (replace) */
907                                 case 'c':
908                                         /* Only triggers on last line of a matching range. */
909                                         if (!sed_cmd->in_match)
910                                                 sed_puts(sed_cmd->string,0);
911                                         goto discard_line;
912
913                                 /* Read file, append contents to output */
914                                 case 'r':
915                                 {
916                                         FILE *rfile;
917
918                                         rfile = fopen(sed_cmd->string, "r");
919                                         if (rfile) {
920                                                 char *line;
921
922                                                 while ((line = xmalloc_getline(rfile))
923                                                                 != NULL)
924                                                         append(line);
925                                                 xprint_and_close_file(rfile);
926                                         }
927
928                                         break;
929                                 }
930
931                                 /* Write pattern space to file. */
932                                 case 'w':
933                                         sed_cmd->no_newline = puts_maybe_newline(pattern_space,sed_cmd->file, sed_cmd->no_newline,no_newline);
934                                         break;
935
936                                 /* Read next line from input */
937                                 case 'n':
938                                         if (!bbg.be_quiet)
939                                                 sed_puts(pattern_space,no_newline);
940                                         if (next_line) {
941                                                 free(pattern_space);
942                                                 pattern_space = next_line;
943                                                 no_newline = next_no_newline;
944                                                 next_line = get_next_line(&next_no_newline);
945                                                 linenum++;
946                                                 break;
947                                         }
948                                         /* fall through */
949
950                                 /* Quit.  End of script, end of input. */
951                                 case 'q':
952                                         /* Exit the outer while loop */
953                                         free(next_line);
954                                         next_line = NULL;
955                                         goto discard_commands;
956
957                                 /* Append the next line to the current line */
958                                 case 'N':
959                                 {
960                                         /* If no next line, jump to end of script and exit. */
961                                         if (next_line == NULL) {
962                                                 /* Jump to end of script and exit */
963                                                 free(next_line);
964                                                 next_line = NULL;
965                                                 goto discard_line;
966                                         /* append next_line, read new next_line. */
967                                         } else {
968                                                 int len = strlen(pattern_space);
969
970                                                 pattern_space = realloc(pattern_space, len + strlen(next_line) + 2);
971                                                 pattern_space[len] = '\n';
972                                                 strcpy(pattern_space + len+1, next_line);
973                                                 no_newline = next_no_newline;
974                                                 next_line = get_next_line(&next_no_newline);
975                                                 linenum++;
976                                         }
977                                         break;
978                                 }
979
980                                 /* Test/branch if substitution occurred */
981                                 case 't':
982                                         if (!substituted) break;
983                                         substituted = 0;
984                                         /* Fall through */
985                                 /* Test/branch if substitution didn't occur */
986                                 case 'T':
987                                         if (substituted) break;
988                                         /* Fall through */
989                                 /* Branch to label */
990                                 case 'b':
991                                         if (!sed_cmd->string) goto discard_commands;
992                                         else sed_cmd = branch_to(sed_cmd->string);
993                                         break;
994                                 /* Transliterate characters */
995                                 case 'y':
996                                 {
997                                         int i;
998
999                                         for (i = 0; pattern_space[i]; i++) {
1000                                                 int j;
1001
1002                                                 for (j = 0; sed_cmd->string[j]; j += 2) {
1003                                                         if (pattern_space[i] == sed_cmd->string[j]) {
1004                                                                 pattern_space[i] = sed_cmd->string[j + 1];
1005                                                                 break;
1006                                                         }
1007                                                 }
1008                                         }
1009
1010                                         break;
1011                                 }
1012                                 case 'g':       /* Replace pattern space with hold space */
1013                                         free(pattern_space);
1014                                         pattern_space = xstrdup(bbg.hold_space ? bbg.hold_space : "");
1015                                         break;
1016                                 case 'G':       /* Append newline and hold space to pattern space */
1017                                 {
1018                                         int pattern_space_size = 2;
1019                                         int hold_space_size = 0;
1020
1021                                         if (pattern_space)
1022                                                 pattern_space_size += strlen(pattern_space);
1023                                         if (bbg.hold_space)
1024                                                 hold_space_size = strlen(bbg.hold_space);
1025                                         pattern_space = xrealloc(pattern_space,
1026                                                         pattern_space_size + hold_space_size);
1027                                         if (pattern_space_size == 2)
1028                                                 pattern_space[0] = 0;
1029                                         strcat(pattern_space, "\n");
1030                                         if (bbg.hold_space)
1031                                                 strcat(pattern_space, bbg.hold_space);
1032                                         no_newline = 0;
1033
1034                                         break;
1035                                 }
1036                                 case 'h':       /* Replace hold space with pattern space */
1037                                         free(bbg.hold_space);
1038                                         bbg.hold_space = xstrdup(pattern_space);
1039                                         break;
1040                                 case 'H':       /* Append newline and pattern space to hold space */
1041                                 {
1042                                         int hold_space_size = 2;
1043                                         int pattern_space_size = 0;
1044
1045                                         if (bbg.hold_space)
1046                                                 hold_space_size += strlen(bbg.hold_space);
1047                                         if (pattern_space)
1048                                                 pattern_space_size = strlen(pattern_space);
1049                                         bbg.hold_space = xrealloc(bbg.hold_space,
1050                                                         hold_space_size + pattern_space_size);
1051
1052                                         if (hold_space_size == 2)
1053                                                 *bbg.hold_space = 0;
1054                                         strcat(bbg.hold_space, "\n");
1055                                         if (pattern_space)
1056                                                 strcat(bbg.hold_space, pattern_space);
1057
1058                                         break;
1059                                 }
1060                                 case 'x': /* Exchange hold and pattern space */
1061                                 {
1062                                         char *tmp = pattern_space;
1063                                         pattern_space = bbg.hold_space ? : xzalloc(1);
1064                                         no_newline = 0;
1065                                         bbg.hold_space = tmp;
1066                                         break;
1067                                 }
1068                                 }
1069                         }
1070                 }
1071
1072                 /*
1073                  * exit point from sedding...
1074                  */
1075 discard_commands:
1076                 /* we will print the line unless we were told to be quiet ('-n')
1077                    or if the line was suppressed (ala 'd'elete) */
1078                 if (!bbg.be_quiet) sed_puts(pattern_space,no_newline);
1079
1080                 /* Delete and such jump here. */
1081 discard_line:
1082                 flush_append();
1083                 free(pattern_space);
1084         }
1085 }
1086
1087 /* It is possible to have a command line argument with embedded
1088    newlines.  This counts as multiple command lines. */
1089
1090 static void add_cmd_block(char *cmdstr)
1091 {
1092         int go = 1;
1093         char *temp = xstrdup(cmdstr), *temp2 = temp;
1094
1095         while (go) {
1096                 int len = strcspn(temp2,"\n");
1097                 if (!temp2[len]) go = 0;
1098                 else temp2[len] = 0;
1099                 add_cmd(temp2);
1100                 temp2 += len+1;
1101         }
1102         free(temp);
1103 }
1104
1105 static void add_cmds_link(llist_t *opt_e)
1106 {
1107         if (!opt_e) return;
1108         add_cmds_link(opt_e->link);
1109         add_cmd_block(opt_e->data);
1110         free(opt_e);
1111 }
1112
1113 static void add_files_link(llist_t *opt_f)
1114 {
1115         char *line;
1116         FILE *cmdfile;
1117         if (!opt_f) return;
1118         add_files_link(opt_f->link);
1119         cmdfile = xfopen(opt_f->data, "r");
1120         while ((line = xmalloc_getline(cmdfile)) != NULL) {
1121                 add_cmd(line);
1122                 free(line);
1123         }
1124         xprint_and_close_file(cmdfile);
1125         free(opt_f);
1126 }
1127
1128 int sed_main(int argc, char **argv)
1129 {
1130         unsigned opt;
1131         llist_t *opt_e, *opt_f;
1132         int status = EXIT_SUCCESS;
1133
1134         bbg.sed_cmd_tail=&bbg.sed_cmd_head;
1135
1136         /* destroy command strings on exit */
1137         if (ENABLE_FEATURE_CLEAN_UP) atexit(sed_free_and_close_stuff);
1138
1139         /* Lie to autoconf when it starts asking stupid questions. */
1140         if (argc==2 && !strcmp(argv[1],"--version")) {
1141                 printf("This is not GNU sed version 4.0\n");
1142                 exit(0);
1143         }
1144
1145         /* do normal option parsing */
1146         opt_e = opt_f = NULL;
1147         opt_complementary = "e::f::"; /* can occur multiple times */
1148         opt = getopt32(argc, argv, "irne:f:", &opt_e, &opt_f);
1149         if (opt & 0x1) { // -i
1150                 bbg.in_place++;
1151                 atexit(cleanup_outname);
1152         }
1153         if (opt & 0x2) bbg.regex_type|=REG_EXTENDED; // -r
1154         if (opt & 0x4) bbg.be_quiet++; // -n
1155         if (opt & 0x8) { // -e
1156                 /* getopt32 reverses order of arguments, handle it */
1157                 add_cmds_link(opt_e);
1158         }
1159         if (opt & 0x10) { // -f
1160                 /* getopt32 reverses order of arguments, handle it */
1161                 add_files_link(opt_f);
1162         }
1163         /* if we didn't get a pattern from -e or -f, use argv[optind] */
1164         if (!(opt & 0x18)) {
1165                 if (argv[optind] == NULL)
1166                         bb_show_usage();
1167                 else
1168                         add_cmd_block(argv[optind++]);
1169         }
1170         /* Flush any unfinished commands. */
1171         add_cmd("");
1172
1173         /* By default, we write to stdout */
1174         bbg.nonstdout = stdout;
1175
1176         /* argv[(optind)..(argc-1)] should be names of file to process. If no
1177          * files were specified or '-' was specified, take input from stdin.
1178          * Otherwise, we process all the files specified. */
1179         if (argv[optind] == NULL) {
1180                 if (bbg.in_place)
1181                         bb_error_msg_and_die(bb_msg_requires_arg, "-i");
1182                 add_input_file(stdin);
1183                 process_files();
1184         } else {
1185                 int i;
1186                 FILE *file;
1187
1188                 for (i = optind; i < argc; i++) {
1189                         struct stat statbuf;
1190                         int nonstdoutfd;
1191
1192                         if (!strcmp(argv[i], "-") && !bbg.in_place) {
1193                                 add_input_file(stdin);
1194                                 process_files();
1195                                 continue;
1196                         }
1197                         file = fopen_or_warn(argv[i], "r");
1198                         if (!file) {
1199                                 status = EXIT_FAILURE;
1200                                 continue;
1201                         }
1202                         if (!bbg.in_place) {
1203                                 add_input_file(file);
1204                                 continue;
1205                         }
1206
1207                         bbg.outname = xasprintf("%sXXXXXX", argv[i]);
1208                         nonstdoutfd = mkstemp(bbg.outname);
1209                         if (-1 == nonstdoutfd)
1210                                 bb_error_msg_and_die("no temp file");
1211                         bbg.nonstdout = fdopen(nonstdoutfd,"w");
1212
1213                         /* Set permissions of output file */
1214
1215                         fstat(fileno(file),&statbuf);
1216                         fchmod(nonstdoutfd,statbuf.st_mode);
1217                         add_input_file(file);
1218                         process_files();
1219                         fclose(bbg.nonstdout);
1220
1221                         bbg.nonstdout = stdout;
1222                         /* unlink(argv[i]); */
1223                         // FIXME: error check / message?
1224                         rename(bbg.outname,argv[i]);
1225                         free(bbg.outname);
1226                         bbg.outname = 0;
1227                 }
1228                 if (bbg.input_file_count > bbg.current_input_file)
1229                         process_files();
1230         }
1231
1232         return status;
1233 }