3
0

sed.c 35 KB

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