source: MondoRescue/branches/2.2.9/mindi-busybox/editors/sed.c@ 2725

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