sed.c 35 KB

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