3
0

sed.c 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  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)
  742. 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. /* For every line, go through all the commands */
  749. restart:
  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. //bb_error_msg("cmd:'%c' matched:%d beg_line:%d end_line:%d linenum:%d",
  768. //sed_cmd->cmd, matched, sed_cmd->beg_line, sed_cmd->end_line, linenum);
  769. /* Is this line the end of the current match? */
  770. if (matched) {
  771. /* once matched, "n,xxx" range is dead, disabling it */
  772. if (sed_cmd->beg_line > 0)
  773. sed_cmd->beg_line = -2;
  774. sed_cmd->in_match = !(
  775. /* has the ending line come, or is this a single address command? */
  776. (sed_cmd->end_line ?
  777. sed_cmd->end_line == -1 ?
  778. !next_line
  779. : (sed_cmd->end_line <= linenum)
  780. : !sed_cmd->end_match
  781. )
  782. /* or does this line matches our last address regex */
  783. || (sed_cmd->end_match && old_matched
  784. && (regexec(sed_cmd->end_match,
  785. pattern_space, 0, NULL, 0) == 0))
  786. );
  787. }
  788. /* Skip blocks of commands we didn't match */
  789. if (sed_cmd->cmd == '{') {
  790. if (sed_cmd->invert ? matched : !matched) {
  791. while (sed_cmd->cmd != '}') {
  792. sed_cmd = sed_cmd->next;
  793. if (!sed_cmd)
  794. bb_error_msg_and_die("unterminated {");
  795. }
  796. }
  797. continue;
  798. }
  799. /* Okay, so did this line match? */
  800. if (sed_cmd->invert ? matched : !matched)
  801. continue; /* no */
  802. /* Update last used regex in case a blank substitute BRE is found */
  803. if (sed_cmd->beg_match) {
  804. G.previous_regex_ptr = sed_cmd->beg_match;
  805. }
  806. /* actual sedding */
  807. switch (sed_cmd->cmd) {
  808. /* Print line number */
  809. case '=':
  810. fprintf(G.nonstdout, "%d\n", linenum);
  811. break;
  812. /* Write the current pattern space up to the first newline */
  813. case 'P':
  814. {
  815. char *tmp = strchr(pattern_space, '\n');
  816. if (tmp) {
  817. *tmp = '\0';
  818. /* TODO: explain why '\n' below */
  819. sed_puts(pattern_space, '\n');
  820. *tmp = '\n';
  821. break;
  822. }
  823. /* Fall Through */
  824. }
  825. /* Write the current pattern space to output */
  826. case 'p':
  827. /* NB: we print this _before_ the last line
  828. * (of current file) is printed. Even if
  829. * that line is nonterminated, we print
  830. * '\n' here (gnu sed does the same) */
  831. sed_puts(pattern_space, '\n');
  832. break;
  833. /* Delete up through first newline */
  834. case 'D':
  835. {
  836. char *tmp = strchr(pattern_space, '\n');
  837. if (tmp) {
  838. tmp = xstrdup(tmp+1);
  839. free(pattern_space);
  840. pattern_space = tmp;
  841. goto restart;
  842. }
  843. }
  844. /* discard this line. */
  845. case 'd':
  846. goto discard_line;
  847. /* Substitute with regex */
  848. case 's':
  849. if (!do_subst_command(sed_cmd, &pattern_space))
  850. break;
  851. substituted |= 1;
  852. /* handle p option */
  853. if (sed_cmd->sub_p)
  854. sed_puts(pattern_space, last_gets_char);
  855. /* handle w option */
  856. if (sed_cmd->sw_file)
  857. puts_maybe_newline(
  858. pattern_space, sed_cmd->sw_file,
  859. &sed_cmd->sw_last_char, last_gets_char);
  860. break;
  861. /* Append line to linked list to be printed later */
  862. case 'a':
  863. append(sed_cmd->string);
  864. break;
  865. /* Insert text before this line */
  866. case 'i':
  867. sed_puts(sed_cmd->string, '\n');
  868. break;
  869. /* Cut and paste text (replace) */
  870. case 'c':
  871. /* Only triggers on last line of a matching range. */
  872. if (!sed_cmd->in_match)
  873. sed_puts(sed_cmd->string, NO_EOL_CHAR);
  874. goto discard_line;
  875. /* Read file, append contents to output */
  876. case 'r':
  877. {
  878. FILE *rfile;
  879. rfile = fopen_for_read(sed_cmd->string);
  880. if (rfile) {
  881. char *line;
  882. while ((line = xmalloc_fgetline(rfile))
  883. != NULL)
  884. append(line);
  885. xprint_and_close_file(rfile);
  886. }
  887. break;
  888. }
  889. /* Write pattern space to file. */
  890. case 'w':
  891. puts_maybe_newline(
  892. pattern_space, sed_cmd->sw_file,
  893. &sed_cmd->sw_last_char, last_gets_char);
  894. break;
  895. /* Read next line from input */
  896. case 'n':
  897. if (!G.be_quiet)
  898. sed_puts(pattern_space, last_gets_char);
  899. if (next_line) {
  900. free(pattern_space);
  901. pattern_space = next_line;
  902. last_gets_char = next_gets_char;
  903. next_line = get_next_line(&next_gets_char);
  904. substituted = 0;
  905. linenum++;
  906. break;
  907. }
  908. /* fall through */
  909. /* Quit. End of script, end of input. */
  910. case 'q':
  911. /* Exit the outer while loop */
  912. free(next_line);
  913. next_line = NULL;
  914. goto discard_commands;
  915. /* Append the next line to the current line */
  916. case 'N':
  917. {
  918. int len;
  919. /* If no next line, jump to end of script and exit. */
  920. if (next_line == NULL) {
  921. /* Jump to end of script and exit */
  922. free(next_line);
  923. next_line = NULL;
  924. goto discard_line;
  925. /* append next_line, read new next_line. */
  926. }
  927. len = strlen(pattern_space);
  928. pattern_space = realloc(pattern_space, len + strlen(next_line) + 2);
  929. pattern_space[len] = '\n';
  930. strcpy(pattern_space + len+1, next_line);
  931. last_gets_char = next_gets_char;
  932. next_line = get_next_line(&next_gets_char);
  933. linenum++;
  934. break;
  935. }
  936. /* Test/branch if substitution occurred */
  937. case 't':
  938. if (!substituted) break;
  939. substituted = 0;
  940. /* Fall through */
  941. /* Test/branch if substitution didn't occur */
  942. case 'T':
  943. if (substituted) break;
  944. /* Fall through */
  945. /* Branch to label */
  946. case 'b':
  947. if (!sed_cmd->string) goto discard_commands;
  948. else sed_cmd = branch_to(sed_cmd->string);
  949. break;
  950. /* Transliterate characters */
  951. case 'y':
  952. {
  953. int i, j;
  954. for (i = 0; pattern_space[i]; i++) {
  955. for (j = 0; sed_cmd->string[j]; j += 2) {
  956. if (pattern_space[i] == sed_cmd->string[j]) {
  957. pattern_space[i] = sed_cmd->string[j + 1];
  958. break;
  959. }
  960. }
  961. }
  962. break;
  963. }
  964. case 'g': /* Replace pattern space with hold space */
  965. free(pattern_space);
  966. pattern_space = xstrdup(G.hold_space ? G.hold_space : "");
  967. break;
  968. case 'G': /* Append newline and hold space to pattern space */
  969. {
  970. int pattern_space_size = 2;
  971. int hold_space_size = 0;
  972. if (pattern_space)
  973. pattern_space_size += strlen(pattern_space);
  974. if (G.hold_space)
  975. hold_space_size = strlen(G.hold_space);
  976. pattern_space = xrealloc(pattern_space,
  977. pattern_space_size + hold_space_size);
  978. if (pattern_space_size == 2)
  979. pattern_space[0] = 0;
  980. strcat(pattern_space, "\n");
  981. if (G.hold_space)
  982. strcat(pattern_space, G.hold_space);
  983. last_gets_char = '\n';
  984. break;
  985. }
  986. case 'h': /* Replace hold space with pattern space */
  987. free(G.hold_space);
  988. G.hold_space = xstrdup(pattern_space);
  989. break;
  990. case 'H': /* Append newline and pattern space to hold space */
  991. {
  992. int hold_space_size = 2;
  993. int pattern_space_size = 0;
  994. if (G.hold_space)
  995. hold_space_size += strlen(G.hold_space);
  996. if (pattern_space)
  997. pattern_space_size = strlen(pattern_space);
  998. G.hold_space = xrealloc(G.hold_space,
  999. hold_space_size + pattern_space_size);
  1000. if (hold_space_size == 2)
  1001. *G.hold_space = 0;
  1002. strcat(G.hold_space, "\n");
  1003. if (pattern_space)
  1004. strcat(G.hold_space, pattern_space);
  1005. break;
  1006. }
  1007. case 'x': /* Exchange hold and pattern space */
  1008. {
  1009. char *tmp = pattern_space;
  1010. pattern_space = G.hold_space ? : xzalloc(1);
  1011. last_gets_char = '\n';
  1012. G.hold_space = tmp;
  1013. break;
  1014. }
  1015. } /* switch */
  1016. } /* for each cmd */
  1017. /*
  1018. * Exit point from sedding...
  1019. */
  1020. discard_commands:
  1021. /* we will print the line unless we were told to be quiet ('-n')
  1022. or if the line was suppressed (ala 'd'elete) */
  1023. if (!G.be_quiet)
  1024. sed_puts(pattern_space, last_gets_char);
  1025. /* Delete and such jump here. */
  1026. discard_line:
  1027. flush_append();
  1028. free(pattern_space);
  1029. goto again;
  1030. }
  1031. /* It is possible to have a command line argument with embedded
  1032. * newlines. This counts as multiple command lines.
  1033. * However, newline can be escaped: 's/e/z\<newline>z/'
  1034. * We check for this.
  1035. */
  1036. static void add_cmd_block(char *cmdstr)
  1037. {
  1038. char *sv, *eol;
  1039. cmdstr = sv = xstrdup(cmdstr);
  1040. do {
  1041. eol = strchr(cmdstr, '\n');
  1042. next:
  1043. if (eol) {
  1044. /* Count preceding slashes */
  1045. int slashes = 0;
  1046. char *sl = eol;
  1047. while (sl != cmdstr && *--sl == '\\')
  1048. slashes++;
  1049. /* Odd number of preceding slashes - newline is escaped */
  1050. if (slashes & 1) {
  1051. overlapping_strcpy(eol - 1, eol);
  1052. eol = strchr(eol, '\n');
  1053. goto next;
  1054. }
  1055. *eol = '\0';
  1056. }
  1057. add_cmd(cmdstr);
  1058. cmdstr = eol + 1;
  1059. } while (eol);
  1060. free(sv);
  1061. }
  1062. int sed_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1063. int sed_main(int argc UNUSED_PARAM, char **argv)
  1064. {
  1065. enum {
  1066. OPT_in_place = 1 << 0,
  1067. };
  1068. unsigned opt;
  1069. llist_t *opt_e, *opt_f;
  1070. int status = EXIT_SUCCESS;
  1071. INIT_G();
  1072. /* destroy command strings on exit */
  1073. if (ENABLE_FEATURE_CLEAN_UP) atexit(sed_free_and_close_stuff);
  1074. /* Lie to autoconf when it starts asking stupid questions. */
  1075. if (argv[1] && !strcmp(argv[1], "--version")) {
  1076. puts("This is not GNU sed version 4.0");
  1077. return 0;
  1078. }
  1079. /* do normal option parsing */
  1080. opt_e = opt_f = NULL;
  1081. opt_complementary = "e::f::" /* can occur multiple times */
  1082. "nn"; /* count -n */
  1083. opt = getopt32(argv, "irne:f:", &opt_e, &opt_f,
  1084. &G.be_quiet); /* counter for -n */
  1085. //argc -= optind;
  1086. argv += optind;
  1087. if (opt & OPT_in_place) { // -i
  1088. atexit(cleanup_outname);
  1089. }
  1090. if (opt & 0x2) G.regex_type |= REG_EXTENDED; // -r
  1091. //if (opt & 0x4) G.be_quiet++; // -n
  1092. while (opt_e) { // -e
  1093. add_cmd_block(llist_pop(&opt_e));
  1094. }
  1095. while (opt_f) { // -f
  1096. char *line;
  1097. FILE *cmdfile;
  1098. cmdfile = xfopen_for_read(llist_pop(&opt_f));
  1099. while ((line = xmalloc_fgetline(cmdfile)) != NULL) {
  1100. add_cmd(line);
  1101. free(line);
  1102. }
  1103. fclose(cmdfile);
  1104. }
  1105. /* if we didn't get a pattern from -e or -f, use argv[0] */
  1106. if (!(opt & 0x18)) {
  1107. if (!*argv)
  1108. bb_show_usage();
  1109. add_cmd_block(*argv++);
  1110. }
  1111. /* Flush any unfinished commands. */
  1112. add_cmd("");
  1113. /* By default, we write to stdout */
  1114. G.nonstdout = stdout;
  1115. /* argv[0..(argc-1)] should be names of file to process. If no
  1116. * files were specified or '-' was specified, take input from stdin.
  1117. * Otherwise, we process all the files specified. */
  1118. if (argv[0] == NULL) {
  1119. if (opt & OPT_in_place)
  1120. bb_error_msg_and_die(bb_msg_requires_arg, "-i");
  1121. add_input_file(stdin);
  1122. process_files();
  1123. } else {
  1124. int i;
  1125. FILE *file;
  1126. for (i = 0; argv[i]; i++) {
  1127. struct stat statbuf;
  1128. int nonstdoutfd;
  1129. if (LONE_DASH(argv[i]) && !(opt & OPT_in_place)) {
  1130. add_input_file(stdin);
  1131. process_files();
  1132. continue;
  1133. }
  1134. file = fopen_or_warn(argv[i], "r");
  1135. if (!file) {
  1136. status = EXIT_FAILURE;
  1137. continue;
  1138. }
  1139. if (!(opt & OPT_in_place)) {
  1140. add_input_file(file);
  1141. continue;
  1142. }
  1143. G.outname = xasprintf("%sXXXXXX", argv[i]);
  1144. nonstdoutfd = mkstemp(G.outname);
  1145. if (-1 == nonstdoutfd)
  1146. bb_perror_msg_and_die("cannot create temp file %s", G.outname);
  1147. G.nonstdout = fdopen(nonstdoutfd, "w");
  1148. /* Set permissions of output file */
  1149. fstat(fileno(file), &statbuf);
  1150. fchmod(nonstdoutfd, statbuf.st_mode);
  1151. add_input_file(file);
  1152. process_files();
  1153. fclose(G.nonstdout);
  1154. G.nonstdout = stdout;
  1155. /* unlink(argv[i]); */
  1156. xrename(G.outname, argv[i]);
  1157. free(G.outname);
  1158. G.outname = NULL;
  1159. }
  1160. if (G.input_file_count > G.current_input_file)
  1161. process_files();
  1162. }
  1163. return status;
  1164. }