sed.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350
  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(sed_cmd->string, "w");
  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)
  531. {
  532. char *oldline = *line;
  533. int altered = 0;
  534. unsigned match_count = 0;
  535. regex_t *current_regex;
  536. /* Handle empty regex. */
  537. if (sed_cmd->sub_match == NULL) {
  538. current_regex = G.previous_regex_ptr;
  539. if (!current_regex)
  540. bb_error_msg_and_die("no previous regexp");
  541. } else
  542. G.previous_regex_ptr = current_regex = sed_cmd->sub_match;
  543. /* Find the first match */
  544. if (REG_NOMATCH == regexec(current_regex, oldline, 10, G.regmatch, 0))
  545. return 0;
  546. /* Initialize temporary output buffer. */
  547. G.pipeline.buf = xmalloc(PIPE_GROW);
  548. G.pipeline.len = PIPE_GROW;
  549. G.pipeline.idx = 0;
  550. /* Now loop through, substituting for matches */
  551. do {
  552. int i;
  553. /* Work around bug in glibc regexec, demonstrated by:
  554. echo " a.b" | busybox sed 's [^ .]* x g'
  555. The match_count check is so not to break
  556. echo "hi" | busybox sed 's/^/!/g' */
  557. if (!G.regmatch[0].rm_so && !G.regmatch[0].rm_eo && match_count) {
  558. pipe_putc(*oldline++);
  559. continue;
  560. }
  561. match_count++;
  562. /* If we aren't interested in this match, output old line to
  563. end of match and continue */
  564. if (sed_cmd->which_match
  565. && (sed_cmd->which_match != match_count)
  566. ) {
  567. for (i = 0; i < G.regmatch[0].rm_eo; i++)
  568. pipe_putc(*oldline++);
  569. continue;
  570. }
  571. /* print everything before the match */
  572. for (i = 0; i < G.regmatch[0].rm_so; i++)
  573. pipe_putc(oldline[i]);
  574. /* then print the substitution string */
  575. do_subst_w_backrefs(oldline, sed_cmd->string);
  576. /* advance past the match */
  577. oldline += G.regmatch[0].rm_eo;
  578. /* flag that something has changed */
  579. altered++;
  580. /* if we're not doing this globally, get out now */
  581. if (sed_cmd->which_match)
  582. break;
  583. } while (*oldline && (regexec(current_regex, oldline, 10, G.regmatch, 0) != REG_NOMATCH));
  584. /* Copy rest of string into output pipeline */
  585. while (*oldline)
  586. pipe_putc(*oldline++);
  587. pipe_putc(0);
  588. free(*line);
  589. *line = G.pipeline.buf;
  590. return altered;
  591. }
  592. /* Set command pointer to point to this label. (Does not handle null label.) */
  593. static sed_cmd_t *branch_to(char *label)
  594. {
  595. sed_cmd_t *sed_cmd;
  596. for (sed_cmd = G.sed_cmd_head.next; sed_cmd; sed_cmd = sed_cmd->next) {
  597. if (sed_cmd->cmd == ':' && sed_cmd->string && !strcmp(sed_cmd->string, label)) {
  598. return sed_cmd;
  599. }
  600. }
  601. bb_error_msg_and_die("can't find label for jump to '%s'", label);
  602. }
  603. static void append(char *s)
  604. {
  605. llist_add_to_end(&G.append_head, xstrdup(s));
  606. }
  607. static void flush_append(void)
  608. {
  609. char *data;
  610. /* Output appended lines. */
  611. while ((data = (char *)llist_pop(&G.append_head))) {
  612. fprintf(G.nonstdout, "%s\n", data);
  613. free(data);
  614. }
  615. }
  616. static void add_input_file(FILE *file)
  617. {
  618. G.input_file_list = xrealloc(G.input_file_list,
  619. (G.input_file_count + 1) * sizeof(FILE *));
  620. G.input_file_list[G.input_file_count++] = file;
  621. }
  622. /* Get next line of input from G.input_file_list, flushing append buffer and
  623. * noting if we ran out of files without a newline on the last line we read.
  624. */
  625. enum {
  626. NO_EOL_CHAR = 1,
  627. LAST_IS_NUL = 2,
  628. };
  629. static char *get_next_line(char *gets_char)
  630. {
  631. char *temp = NULL;
  632. int len;
  633. char gc;
  634. flush_append();
  635. /* will be returned if last line in the file
  636. * doesn't end with either '\n' or '\0' */
  637. gc = NO_EOL_CHAR;
  638. while (G.current_input_file < G.input_file_count) {
  639. FILE *fp = G.input_file_list[G.current_input_file];
  640. /* Read line up to a newline or NUL byte, inclusive,
  641. * return malloc'ed char[]. length of the chunk read
  642. * is stored in len. NULL if EOF/error */
  643. temp = bb_get_chunk_from_file(fp, &len);
  644. if (temp) {
  645. /* len > 0 here, it's ok to do temp[len-1] */
  646. char c = temp[len-1];
  647. if (c == '\n' || c == '\0') {
  648. temp[len-1] = '\0';
  649. gc = c;
  650. if (c == '\0') {
  651. int ch = fgetc(fp);
  652. if (ch != EOF)
  653. ungetc(ch, fp);
  654. else
  655. gc = LAST_IS_NUL;
  656. }
  657. }
  658. /* else we put NO_EOL_CHAR into *gets_char */
  659. break;
  660. /* NB: I had the idea of peeking next file(s) and returning
  661. * NO_EOL_CHAR only if it is the *last* non-empty
  662. * input file. But there is a case where this won't work:
  663. * file1: "a woo\nb woo"
  664. * file2: "c no\nd no"
  665. * sed -ne 's/woo/bang/p' input1 input2 => "a bang\nb bang"
  666. * (note: *no* newline after "b bang"!) */
  667. }
  668. /* Close this file and advance to next one */
  669. fclose(fp);
  670. G.current_input_file++;
  671. }
  672. *gets_char = gc;
  673. return temp;
  674. }
  675. /* Output line of text. */
  676. /* Note:
  677. * The tricks with NO_EOL_CHAR and last_puts_char are there to emulate gnu sed.
  678. * Without them, we had this:
  679. * echo -n thingy >z1
  680. * echo -n again >z2
  681. * >znull
  682. * sed "s/i/z/" z1 z2 znull | hexdump -vC
  683. * output:
  684. * gnu sed 4.1.5:
  685. * 00000000 74 68 7a 6e 67 79 0a 61 67 61 7a 6e |thzngy.agazn|
  686. * bbox:
  687. * 00000000 74 68 7a 6e 67 79 61 67 61 7a 6e |thzngyagazn|
  688. */
  689. static void puts_maybe_newline(char *s, FILE *file, char *last_puts_char, char last_gets_char)
  690. {
  691. char lpc = *last_puts_char;
  692. /* Need to insert a '\n' between two files because first file's
  693. * last line wasn't terminated? */
  694. if (lpc != '\n' && lpc != '\0') {
  695. fputc('\n', file);
  696. lpc = '\n';
  697. }
  698. fputs(s, file);
  699. /* 'x' - just something which is not '\n', '\0' or NO_EOL_CHAR */
  700. if (s[0])
  701. lpc = 'x';
  702. /* had trailing '\0' and it was last char of file? */
  703. if (last_gets_char == LAST_IS_NUL) {
  704. fputc('\0', file);
  705. lpc = 'x'; /* */
  706. } else
  707. /* had trailing '\n' or '\0'? */
  708. if (last_gets_char != NO_EOL_CHAR) {
  709. fputc(last_gets_char, file);
  710. lpc = last_gets_char;
  711. }
  712. if (ferror(file)) {
  713. xfunc_error_retval = 4; /* It's what gnu sed exits with... */
  714. bb_error_msg_and_die(bb_msg_write_error);
  715. }
  716. *last_puts_char = lpc;
  717. }
  718. #define sed_puts(s, n) (puts_maybe_newline(s, G.nonstdout, &last_puts_char, n))
  719. static int beg_match(sed_cmd_t *sed_cmd, const char *pattern_space)
  720. {
  721. int retval = sed_cmd->beg_match && !regexec(sed_cmd->beg_match, pattern_space, 0, NULL, 0);
  722. if (retval)
  723. G.previous_regex_ptr = sed_cmd->beg_match;
  724. return retval;
  725. }
  726. /* Process all the lines in all the files */
  727. static void process_files(void)
  728. {
  729. char *pattern_space, *next_line;
  730. int linenum = 0;
  731. char last_puts_char = '\n';
  732. char last_gets_char, next_gets_char;
  733. sed_cmd_t *sed_cmd;
  734. int substituted;
  735. /* Prime the pump */
  736. next_line = get_next_line(&next_gets_char);
  737. /* go through every line in each file */
  738. again:
  739. substituted = 0;
  740. /* Advance to next line. Stop if out of lines. */
  741. pattern_space = next_line;
  742. if (!pattern_space) return;
  743. last_gets_char = next_gets_char;
  744. /* Read one line in advance so we can act on the last line,
  745. * the '$' address */
  746. next_line = get_next_line(&next_gets_char);
  747. linenum++;
  748. restart:
  749. /* for every line, go through all the commands */
  750. for (sed_cmd = G.sed_cmd_head.next; sed_cmd; sed_cmd = sed_cmd->next) {
  751. int old_matched, matched;
  752. old_matched = sed_cmd->in_match;
  753. /* Determine if this command matches this line: */
  754. /* Are we continuing a previous multi-line match? */
  755. sed_cmd->in_match = sed_cmd->in_match
  756. /* Or is no range necessary? */
  757. || (!sed_cmd->beg_line && !sed_cmd->end_line
  758. && !sed_cmd->beg_match && !sed_cmd->end_match)
  759. /* Or did we match the start of a numerical range? */
  760. || (sed_cmd->beg_line > 0 && (sed_cmd->beg_line == linenum))
  761. /* Or does this line match our begin address regex? */
  762. || (beg_match(sed_cmd, pattern_space))
  763. /* Or did we match last line of input? */
  764. || (sed_cmd->beg_line == -1 && next_line == NULL);
  765. /* Snapshot the value */
  766. matched = sed_cmd->in_match;
  767. /* Is this line the end of the current match? */
  768. if (matched) {
  769. sed_cmd->in_match = !(
  770. /* has the ending line come, or is this a single address command? */
  771. (sed_cmd->end_line ?
  772. sed_cmd->end_line == -1 ?
  773. !next_line
  774. : (sed_cmd->end_line <= linenum)
  775. : !sed_cmd->end_match
  776. )
  777. /* or does this line matches our last address regex */
  778. || (sed_cmd->end_match && old_matched
  779. && (regexec(sed_cmd->end_match,
  780. pattern_space, 0, NULL, 0) == 0))
  781. );
  782. }
  783. /* Skip blocks of commands we didn't match. */
  784. if (sed_cmd->cmd == '{') {
  785. if (sed_cmd->invert ? matched : !matched) {
  786. while (sed_cmd->cmd != '}') {
  787. sed_cmd = sed_cmd->next;
  788. if (!sed_cmd)
  789. bb_error_msg_and_die("unterminated {");
  790. }
  791. }
  792. continue;
  793. }
  794. /* Okay, so did this line match? */
  795. if (sed_cmd->invert ? !matched : matched) {
  796. /* Update last used regex in case a blank substitute BRE is found */
  797. if (sed_cmd->beg_match) {
  798. G.previous_regex_ptr = sed_cmd->beg_match;
  799. }
  800. /* actual sedding */
  801. switch (sed_cmd->cmd) {
  802. /* Print line number */
  803. case '=':
  804. fprintf(G.nonstdout, "%d\n", linenum);
  805. break;
  806. /* Write the current pattern space up to the first newline */
  807. case 'P':
  808. {
  809. char *tmp = strchr(pattern_space, '\n');
  810. if (tmp) {
  811. *tmp = '\0';
  812. /* TODO: explain why '\n' below */
  813. sed_puts(pattern_space, '\n');
  814. *tmp = '\n';
  815. break;
  816. }
  817. /* Fall Through */
  818. }
  819. /* Write the current pattern space to output */
  820. case 'p':
  821. /* NB: we print this _before_ the last line
  822. * (of current file) is printed. Even if
  823. * that line is nonterminated, we print
  824. * '\n' here (gnu sed does the same) */
  825. sed_puts(pattern_space, '\n');
  826. break;
  827. /* Delete up through first newline */
  828. case 'D':
  829. {
  830. char *tmp = strchr(pattern_space, '\n');
  831. if (tmp) {
  832. tmp = xstrdup(tmp+1);
  833. free(pattern_space);
  834. pattern_space = tmp;
  835. goto restart;
  836. }
  837. }
  838. /* discard this line. */
  839. case 'd':
  840. goto discard_line;
  841. /* Substitute with regex */
  842. case 's':
  843. if (!do_subst_command(sed_cmd, &pattern_space))
  844. break;
  845. substituted |= 1;
  846. /* handle p option */
  847. if (sed_cmd->sub_p)
  848. sed_puts(pattern_space, last_gets_char);
  849. /* handle w option */
  850. if (sed_cmd->sw_file)
  851. puts_maybe_newline(
  852. pattern_space, sed_cmd->sw_file,
  853. &sed_cmd->sw_last_char, last_gets_char);
  854. break;
  855. /* Append line to linked list to be printed later */
  856. case 'a':
  857. append(sed_cmd->string);
  858. break;
  859. /* Insert text before this line */
  860. case 'i':
  861. sed_puts(sed_cmd->string, '\n');
  862. break;
  863. /* Cut and paste text (replace) */
  864. case 'c':
  865. /* Only triggers on last line of a matching range. */
  866. if (!sed_cmd->in_match)
  867. sed_puts(sed_cmd->string, NO_EOL_CHAR);
  868. goto discard_line;
  869. /* Read file, append contents to output */
  870. case 'r':
  871. {
  872. FILE *rfile;
  873. rfile = fopen(sed_cmd->string, "r");
  874. if (rfile) {
  875. char *line;
  876. while ((line = xmalloc_fgetline(rfile))
  877. != NULL)
  878. append(line);
  879. xprint_and_close_file(rfile);
  880. }
  881. break;
  882. }
  883. /* Write pattern space to file. */
  884. case 'w':
  885. puts_maybe_newline(
  886. pattern_space, sed_cmd->sw_file,
  887. &sed_cmd->sw_last_char, last_gets_char);
  888. break;
  889. /* Read next line from input */
  890. case 'n':
  891. if (!G.be_quiet)
  892. sed_puts(pattern_space, last_gets_char);
  893. if (next_line) {
  894. free(pattern_space);
  895. pattern_space = next_line;
  896. last_gets_char = next_gets_char;
  897. next_line = get_next_line(&next_gets_char);
  898. substituted = 0;
  899. linenum++;
  900. break;
  901. }
  902. /* fall through */
  903. /* Quit. End of script, end of input. */
  904. case 'q':
  905. /* Exit the outer while loop */
  906. free(next_line);
  907. next_line = NULL;
  908. goto discard_commands;
  909. /* Append the next line to the current line */
  910. case 'N':
  911. {
  912. int len;
  913. /* If no next line, jump to end of script and exit. */
  914. if (next_line == NULL) {
  915. /* Jump to end of script and exit */
  916. free(next_line);
  917. next_line = NULL;
  918. goto discard_line;
  919. /* append next_line, read new next_line. */
  920. }
  921. len = strlen(pattern_space);
  922. pattern_space = realloc(pattern_space, len + strlen(next_line) + 2);
  923. pattern_space[len] = '\n';
  924. strcpy(pattern_space + len+1, next_line);
  925. last_gets_char = next_gets_char;
  926. next_line = get_next_line(&next_gets_char);
  927. linenum++;
  928. break;
  929. }
  930. /* Test/branch if substitution occurred */
  931. case 't':
  932. if (!substituted) break;
  933. substituted = 0;
  934. /* Fall through */
  935. /* Test/branch if substitution didn't occur */
  936. case 'T':
  937. if (substituted) break;
  938. /* Fall through */
  939. /* Branch to label */
  940. case 'b':
  941. if (!sed_cmd->string) goto discard_commands;
  942. else sed_cmd = branch_to(sed_cmd->string);
  943. break;
  944. /* Transliterate characters */
  945. case 'y':
  946. {
  947. int i, j;
  948. for (i = 0; pattern_space[i]; i++) {
  949. for (j = 0; sed_cmd->string[j]; j += 2) {
  950. if (pattern_space[i] == sed_cmd->string[j]) {
  951. pattern_space[i] = sed_cmd->string[j + 1];
  952. break;
  953. }
  954. }
  955. }
  956. break;
  957. }
  958. case 'g': /* Replace pattern space with hold space */
  959. free(pattern_space);
  960. pattern_space = xstrdup(G.hold_space ? G.hold_space : "");
  961. break;
  962. case 'G': /* Append newline and hold space to pattern space */
  963. {
  964. int pattern_space_size = 2;
  965. int hold_space_size = 0;
  966. if (pattern_space)
  967. pattern_space_size += strlen(pattern_space);
  968. if (G.hold_space)
  969. hold_space_size = strlen(G.hold_space);
  970. pattern_space = xrealloc(pattern_space,
  971. pattern_space_size + hold_space_size);
  972. if (pattern_space_size == 2)
  973. pattern_space[0] = 0;
  974. strcat(pattern_space, "\n");
  975. if (G.hold_space)
  976. strcat(pattern_space, G.hold_space);
  977. last_gets_char = '\n';
  978. break;
  979. }
  980. case 'h': /* Replace hold space with pattern space */
  981. free(G.hold_space);
  982. G.hold_space = xstrdup(pattern_space);
  983. break;
  984. case 'H': /* Append newline and pattern space to hold space */
  985. {
  986. int hold_space_size = 2;
  987. int pattern_space_size = 0;
  988. if (G.hold_space)
  989. hold_space_size += strlen(G.hold_space);
  990. if (pattern_space)
  991. pattern_space_size = strlen(pattern_space);
  992. G.hold_space = xrealloc(G.hold_space,
  993. hold_space_size + pattern_space_size);
  994. if (hold_space_size == 2)
  995. *G.hold_space = 0;
  996. strcat(G.hold_space, "\n");
  997. if (pattern_space)
  998. strcat(G.hold_space, pattern_space);
  999. break;
  1000. }
  1001. case 'x': /* Exchange hold and pattern space */
  1002. {
  1003. char *tmp = pattern_space;
  1004. pattern_space = G.hold_space ? : xzalloc(1);
  1005. last_gets_char = '\n';
  1006. G.hold_space = tmp;
  1007. break;
  1008. }
  1009. }
  1010. }
  1011. }
  1012. /*
  1013. * exit point from sedding...
  1014. */
  1015. discard_commands:
  1016. /* we will print the line unless we were told to be quiet ('-n')
  1017. or if the line was suppressed (ala 'd'elete) */
  1018. if (!G.be_quiet)
  1019. sed_puts(pattern_space, last_gets_char);
  1020. /* Delete and such jump here. */
  1021. discard_line:
  1022. flush_append();
  1023. free(pattern_space);
  1024. goto again;
  1025. }
  1026. /* It is possible to have a command line argument with embedded
  1027. * newlines. This counts as multiple command lines.
  1028. * However, newline can be escaped: 's/e/z\<newline>z/'
  1029. * We check for this.
  1030. */
  1031. static void add_cmd_block(char *cmdstr)
  1032. {
  1033. char *sv, *eol;
  1034. cmdstr = sv = xstrdup(cmdstr);
  1035. do {
  1036. eol = strchr(cmdstr, '\n');
  1037. next:
  1038. if (eol) {
  1039. /* Count preceding slashes */
  1040. int slashes = 0;
  1041. char *sl = eol;
  1042. while (sl != cmdstr && *--sl == '\\')
  1043. slashes++;
  1044. /* Odd number of preceding slashes - newline is escaped */
  1045. if (slashes & 1) {
  1046. strcpy(eol-1, eol);
  1047. eol = strchr(eol, '\n');
  1048. goto next;
  1049. }
  1050. *eol = '\0';
  1051. }
  1052. add_cmd(cmdstr);
  1053. cmdstr = eol + 1;
  1054. } while (eol);
  1055. free(sv);
  1056. }
  1057. int sed_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1058. int sed_main(int argc ATTRIBUTE_UNUSED, char **argv)
  1059. {
  1060. enum {
  1061. OPT_in_place = 1 << 0,
  1062. };
  1063. unsigned opt;
  1064. llist_t *opt_e, *opt_f;
  1065. int status = EXIT_SUCCESS;
  1066. INIT_G();
  1067. /* destroy command strings on exit */
  1068. if (ENABLE_FEATURE_CLEAN_UP) atexit(sed_free_and_close_stuff);
  1069. /* Lie to autoconf when it starts asking stupid questions. */
  1070. if (argv[1] && !strcmp(argv[1], "--version")) {
  1071. puts("This is not GNU sed version 4.0");
  1072. return 0;
  1073. }
  1074. /* do normal option parsing */
  1075. opt_e = opt_f = NULL;
  1076. opt_complementary = "e::f::" /* can occur multiple times */
  1077. "nn"; /* count -n */
  1078. opt = getopt32(argv, "irne:f:", &opt_e, &opt_f,
  1079. &G.be_quiet); /* counter for -n */
  1080. //argc -= optind;
  1081. argv += optind;
  1082. if (opt & OPT_in_place) { // -i
  1083. atexit(cleanup_outname);
  1084. }
  1085. if (opt & 0x2) G.regex_type |= REG_EXTENDED; // -r
  1086. //if (opt & 0x4) G.be_quiet++; // -n
  1087. while (opt_e) { // -e
  1088. add_cmd_block(llist_pop(&opt_e));
  1089. }
  1090. while (opt_f) { // -f
  1091. char *line;
  1092. FILE *cmdfile;
  1093. cmdfile = xfopen(llist_pop(&opt_f), "r");
  1094. while ((line = xmalloc_fgetline(cmdfile)) != NULL) {
  1095. add_cmd(line);
  1096. free(line);
  1097. }
  1098. fclose(cmdfile);
  1099. }
  1100. /* if we didn't get a pattern from -e or -f, use argv[0] */
  1101. if (!(opt & 0x18)) {
  1102. if (!*argv)
  1103. bb_show_usage();
  1104. add_cmd_block(*argv++);
  1105. }
  1106. /* Flush any unfinished commands. */
  1107. add_cmd("");
  1108. /* By default, we write to stdout */
  1109. G.nonstdout = stdout;
  1110. /* argv[0..(argc-1)] should be names of file to process. If no
  1111. * files were specified or '-' was specified, take input from stdin.
  1112. * Otherwise, we process all the files specified. */
  1113. if (argv[0] == NULL) {
  1114. if (opt & OPT_in_place)
  1115. bb_error_msg_and_die(bb_msg_requires_arg, "-i");
  1116. add_input_file(stdin);
  1117. process_files();
  1118. } else {
  1119. int i;
  1120. FILE *file;
  1121. for (i = 0; argv[i]; i++) {
  1122. struct stat statbuf;
  1123. int nonstdoutfd;
  1124. if (LONE_DASH(argv[i]) && !(opt & OPT_in_place)) {
  1125. add_input_file(stdin);
  1126. process_files();
  1127. continue;
  1128. }
  1129. file = fopen_or_warn(argv[i], "r");
  1130. if (!file) {
  1131. status = EXIT_FAILURE;
  1132. continue;
  1133. }
  1134. if (!(opt & OPT_in_place)) {
  1135. add_input_file(file);
  1136. continue;
  1137. }
  1138. G.outname = xasprintf("%sXXXXXX", argv[i]);
  1139. nonstdoutfd = mkstemp(G.outname);
  1140. if (-1 == nonstdoutfd)
  1141. bb_perror_msg_and_die("cannot create temp file %s", G.outname);
  1142. G.nonstdout = fdopen(nonstdoutfd, "w");
  1143. /* Set permissions of output file */
  1144. fstat(fileno(file), &statbuf);
  1145. fchmod(nonstdoutfd, statbuf.st_mode);
  1146. add_input_file(file);
  1147. process_files();
  1148. fclose(G.nonstdout);
  1149. G.nonstdout = stdout;
  1150. /* unlink(argv[i]); */
  1151. xrename(G.outname, argv[i]);
  1152. free(G.outname);
  1153. G.outname = NULL;
  1154. }
  1155. if (G.input_file_count > G.current_input_file)
  1156. process_files();
  1157. }
  1158. return status;
  1159. }