sed.c 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370
  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. } FIX_ALIASING;
  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]))
  298. continue;
  299. switch (substr[idx]) {
  300. /* Replace all occurrences */
  301. case 'g':
  302. if (match[0] != '^')
  303. sed_cmd->which_match = 0;
  304. break;
  305. /* Print pattern space */
  306. case 'p':
  307. sed_cmd->sub_p = 1;
  308. break;
  309. /* Write to file */
  310. case 'w':
  311. {
  312. char *temp;
  313. idx += parse_file_cmd(/*sed_cmd,*/ substr+idx, &temp);
  314. break;
  315. }
  316. /* Ignore case (gnu exension) */
  317. case 'I':
  318. cflags |= REG_ICASE;
  319. break;
  320. /* Comment */
  321. case '#':
  322. while (substr[++idx]) /*skip all*/;
  323. /* Fall through */
  324. /* End of command */
  325. case ';':
  326. case '}':
  327. goto out;
  328. default:
  329. bb_error_msg_and_die("bad option in substitution expression");
  330. }
  331. }
  332. out:
  333. /* compile the match string into a regex */
  334. if (*match != '\0') {
  335. /* If match is empty, we use last regex used at runtime */
  336. sed_cmd->sub_match = xmalloc(sizeof(regex_t));
  337. xregcomp(sed_cmd->sub_match, match, cflags);
  338. }
  339. free(match);
  340. return idx;
  341. }
  342. /*
  343. * Process the commands arguments
  344. */
  345. static const char *parse_cmd_args(sed_cmd_t *sed_cmd, const char *cmdstr)
  346. {
  347. /* handle (s)ubstitution command */
  348. if (sed_cmd->cmd == 's')
  349. cmdstr += parse_subst_cmd(sed_cmd, cmdstr);
  350. /* handle edit cmds: (a)ppend, (i)nsert, and (c)hange */
  351. else if (strchr("aic", sed_cmd->cmd)) {
  352. if ((sed_cmd->end_line || sed_cmd->end_match) && sed_cmd->cmd != 'c')
  353. bb_error_msg_and_die("only a beginning address can be specified for edit commands");
  354. for (;;) {
  355. if (*cmdstr == '\n' || *cmdstr == '\\') {
  356. cmdstr++;
  357. break;
  358. }
  359. if (!isspace(*cmdstr))
  360. break;
  361. cmdstr++;
  362. }
  363. sed_cmd->string = xstrdup(cmdstr);
  364. /* "\anychar" -> "anychar" */
  365. parse_escapes(sed_cmd->string, sed_cmd->string, strlen(cmdstr), '\0', '\0');
  366. cmdstr += strlen(cmdstr);
  367. /* handle file cmds: (r)ead */
  368. } else if (strchr("rw", sed_cmd->cmd)) {
  369. if (sed_cmd->end_line || sed_cmd->end_match)
  370. bb_error_msg_and_die("command only uses one address");
  371. cmdstr += parse_file_cmd(/*sed_cmd,*/ cmdstr, &sed_cmd->string);
  372. if (sed_cmd->cmd == 'w') {
  373. sed_cmd->sw_file = xfopen_for_write(sed_cmd->string);
  374. sed_cmd->sw_last_char = '\n';
  375. }
  376. /* handle branch commands */
  377. } else if (strchr(":btT", sed_cmd->cmd)) {
  378. int length;
  379. cmdstr = skip_whitespace(cmdstr);
  380. length = strcspn(cmdstr, semicolon_whitespace);
  381. if (length) {
  382. sed_cmd->string = xstrndup(cmdstr, length);
  383. cmdstr += length;
  384. }
  385. }
  386. /* translation command */
  387. else if (sed_cmd->cmd == 'y') {
  388. char *match, *replace;
  389. int i = cmdstr[0];
  390. cmdstr += parse_regex_delim(cmdstr, &match, &replace)+1;
  391. /* \n already parsed, but \delimiter needs unescaping. */
  392. parse_escapes(match, match, strlen(match), i, i);
  393. parse_escapes(replace, replace, strlen(replace), i, i);
  394. sed_cmd->string = xzalloc((strlen(match) + 1) * 2);
  395. for (i = 0; match[i] && replace[i]; i++) {
  396. sed_cmd->string[i*2] = match[i];
  397. sed_cmd->string[i*2+1] = replace[i];
  398. }
  399. free(match);
  400. free(replace);
  401. }
  402. /* if it wasnt a single-letter command that takes no arguments
  403. * then it must be an invalid command.
  404. */
  405. else if (strchr("dDgGhHlnNpPqx={}", sed_cmd->cmd) == 0) {
  406. bb_error_msg_and_die("unsupported command %c", sed_cmd->cmd);
  407. }
  408. /* give back whatever's left over */
  409. return cmdstr;
  410. }
  411. /* Parse address+command sets, skipping comment lines. */
  412. static void add_cmd(const char *cmdstr)
  413. {
  414. sed_cmd_t *sed_cmd;
  415. int temp;
  416. /* Append this line to any unfinished line from last time. */
  417. if (G.add_cmd_line) {
  418. char *tp = xasprintf("%s\n%s", G.add_cmd_line, cmdstr);
  419. free(G.add_cmd_line);
  420. cmdstr = G.add_cmd_line = tp;
  421. }
  422. /* If this line ends with backslash, request next line. */
  423. temp = strlen(cmdstr);
  424. if (temp && cmdstr[--temp] == '\\') {
  425. if (!G.add_cmd_line)
  426. G.add_cmd_line = xstrdup(cmdstr);
  427. G.add_cmd_line[temp] = '\0';
  428. return;
  429. }
  430. /* Loop parsing all commands in this line. */
  431. while (*cmdstr) {
  432. /* Skip leading whitespace and semicolons */
  433. cmdstr += strspn(cmdstr, semicolon_whitespace);
  434. /* If no more commands, exit. */
  435. if (!*cmdstr) break;
  436. /* if this is a comment, jump past it and keep going */
  437. if (*cmdstr == '#') {
  438. /* "#n" is the same as using -n on the command line */
  439. if (cmdstr[1] == 'n')
  440. G.be_quiet++;
  441. cmdstr = strpbrk(cmdstr, "\n\r");
  442. if (!cmdstr) break;
  443. continue;
  444. }
  445. /* parse the command
  446. * format is: [addr][,addr][!]cmd
  447. * |----||-----||-|
  448. * part1 part2 part3
  449. */
  450. sed_cmd = xzalloc(sizeof(sed_cmd_t));
  451. /* first part (if present) is an address: either a '$', a number or a /regex/ */
  452. cmdstr += get_address(cmdstr, &sed_cmd->beg_line, &sed_cmd->beg_match);
  453. /* second part (if present) will begin with a comma */
  454. if (*cmdstr == ',') {
  455. int idx;
  456. cmdstr++;
  457. idx = get_address(cmdstr, &sed_cmd->end_line, &sed_cmd->end_match);
  458. if (!idx)
  459. bb_error_msg_and_die("no address after comma");
  460. cmdstr += idx;
  461. }
  462. /* skip whitespace before the command */
  463. cmdstr = skip_whitespace(cmdstr);
  464. /* Check for inversion flag */
  465. if (*cmdstr == '!') {
  466. sed_cmd->invert = 1;
  467. cmdstr++;
  468. /* skip whitespace before the command */
  469. cmdstr = skip_whitespace(cmdstr);
  470. }
  471. /* last part (mandatory) will be a command */
  472. if (!*cmdstr)
  473. bb_error_msg_and_die("missing command");
  474. sed_cmd->cmd = *(cmdstr++);
  475. cmdstr = parse_cmd_args(sed_cmd, cmdstr);
  476. /* Add the command to the command array */
  477. G.sed_cmd_tail->next = sed_cmd;
  478. G.sed_cmd_tail = G.sed_cmd_tail->next;
  479. }
  480. /* If we glued multiple lines together, free the memory. */
  481. free(G.add_cmd_line);
  482. G.add_cmd_line = NULL;
  483. }
  484. /* Append to a string, reallocating memory as necessary. */
  485. #define PIPE_GROW 64
  486. static void pipe_putc(char c)
  487. {
  488. if (G.pipeline.idx == G.pipeline.len) {
  489. G.pipeline.buf = xrealloc(G.pipeline.buf,
  490. G.pipeline.len + PIPE_GROW);
  491. G.pipeline.len += PIPE_GROW;
  492. }
  493. G.pipeline.buf[G.pipeline.idx++] = c;
  494. }
  495. static void do_subst_w_backrefs(char *line, char *replace)
  496. {
  497. int i, j;
  498. /* go through the replacement string */
  499. for (i = 0; replace[i]; i++) {
  500. /* if we find a backreference (\1, \2, etc.) print the backref'ed * text */
  501. if (replace[i] == '\\') {
  502. unsigned backref = replace[++i] - '0';
  503. if (backref <= 9) {
  504. /* print out the text held in G.regmatch[backref] */
  505. if (G.regmatch[backref].rm_so != -1) {
  506. j = G.regmatch[backref].rm_so;
  507. while (j < G.regmatch[backref].rm_eo)
  508. pipe_putc(line[j++]);
  509. }
  510. continue;
  511. }
  512. /* I _think_ it is impossible to get '\' to be
  513. * the last char in replace string. Thus we dont check
  514. * for replace[i] == NUL. (counterexample anyone?) */
  515. /* if we find a backslash escaped character, print the character */
  516. pipe_putc(replace[i]);
  517. continue;
  518. }
  519. /* if we find an unescaped '&' print out the whole matched text. */
  520. if (replace[i] == '&') {
  521. j = G.regmatch[0].rm_so;
  522. while (j < G.regmatch[0].rm_eo)
  523. pipe_putc(line[j++]);
  524. continue;
  525. }
  526. /* Otherwise just output the character. */
  527. pipe_putc(replace[i]);
  528. }
  529. }
  530. static int do_subst_command(sed_cmd_t *sed_cmd, char **line_p)
  531. {
  532. char *line = *line_p;
  533. int altered = 0;
  534. unsigned match_count = 0;
  535. regex_t *current_regex;
  536. current_regex = sed_cmd->sub_match;
  537. /* Handle empty regex. */
  538. if (!current_regex) {
  539. current_regex = G.previous_regex_ptr;
  540. if (!current_regex)
  541. bb_error_msg_and_die("no previous regexp");
  542. }
  543. G.previous_regex_ptr = current_regex;
  544. /* Find the first match */
  545. if (REG_NOMATCH == regexec(current_regex, line, 10, G.regmatch, 0))
  546. return 0;
  547. /* Initialize temporary output buffer. */
  548. G.pipeline.buf = xmalloc(PIPE_GROW);
  549. G.pipeline.len = PIPE_GROW;
  550. G.pipeline.idx = 0;
  551. /* Now loop through, substituting for matches */
  552. do {
  553. int i;
  554. /* Work around bug in glibc regexec, demonstrated by:
  555. echo " a.b" | busybox sed 's [^ .]* x g'
  556. The match_count check is so not to break
  557. echo "hi" | busybox sed 's/^/!/g' */
  558. if (!G.regmatch[0].rm_so && !G.regmatch[0].rm_eo && match_count) {
  559. pipe_putc(*line++);
  560. continue;
  561. }
  562. match_count++;
  563. /* If we aren't interested in this match, output old line to
  564. end of match and continue */
  565. if (sed_cmd->which_match
  566. && (sed_cmd->which_match != match_count)
  567. ) {
  568. for (i = 0; i < G.regmatch[0].rm_eo; i++)
  569. pipe_putc(*line++);
  570. continue;
  571. }
  572. /* print everything before the match */
  573. for (i = 0; i < G.regmatch[0].rm_so; i++)
  574. pipe_putc(line[i]);
  575. /* then print the substitution string */
  576. do_subst_w_backrefs(line, sed_cmd->string);
  577. /* advance past the match */
  578. line += G.regmatch[0].rm_eo;
  579. /* flag that something has changed */
  580. altered++;
  581. /* if we're not doing this globally, get out now */
  582. if (sed_cmd->which_match)
  583. break;
  584. //maybe (G.regmatch[0].rm_eo ? REG_NOTBOL : 0) instead of unconditional REG_NOTBOL?
  585. } while (*line && regexec(current_regex, line, 10, G.regmatch, REG_NOTBOL) != REG_NOMATCH);
  586. /* Copy rest of string into output pipeline */
  587. while (1) {
  588. char c = *line++;
  589. pipe_putc(c);
  590. if (c == '\0')
  591. break;
  592. }
  593. free(*line_p);
  594. *line_p = G.pipeline.buf;
  595. return altered;
  596. }
  597. /* Set command pointer to point to this label. (Does not handle null label.) */
  598. static sed_cmd_t *branch_to(char *label)
  599. {
  600. sed_cmd_t *sed_cmd;
  601. for (sed_cmd = G.sed_cmd_head.next; sed_cmd; sed_cmd = sed_cmd->next) {
  602. if (sed_cmd->cmd == ':' && sed_cmd->string && !strcmp(sed_cmd->string, label)) {
  603. return sed_cmd;
  604. }
  605. }
  606. bb_error_msg_and_die("can't find label for jump to '%s'", label);
  607. }
  608. static void append(char *s)
  609. {
  610. llist_add_to_end(&G.append_head, xstrdup(s));
  611. }
  612. static void flush_append(void)
  613. {
  614. char *data;
  615. /* Output appended lines. */
  616. while ((data = (char *)llist_pop(&G.append_head))) {
  617. fprintf(G.nonstdout, "%s\n", data);
  618. free(data);
  619. }
  620. }
  621. static void add_input_file(FILE *file)
  622. {
  623. G.input_file_list = xrealloc_vector(G.input_file_list, 2, G.input_file_count);
  624. G.input_file_list[G.input_file_count++] = file;
  625. }
  626. /* Get next line of input from G.input_file_list, flushing append buffer and
  627. * noting if we ran out of files without a newline on the last line we read.
  628. */
  629. enum {
  630. NO_EOL_CHAR = 1,
  631. LAST_IS_NUL = 2,
  632. };
  633. static char *get_next_line(char *gets_char)
  634. {
  635. char *temp = NULL;
  636. int len;
  637. char gc;
  638. flush_append();
  639. /* will be returned if last line in the file
  640. * doesn't end with either '\n' or '\0' */
  641. gc = NO_EOL_CHAR;
  642. while (G.current_input_file < G.input_file_count) {
  643. FILE *fp = G.input_file_list[G.current_input_file];
  644. /* Read line up to a newline or NUL byte, inclusive,
  645. * return malloc'ed char[]. length of the chunk read
  646. * is stored in len. NULL if EOF/error */
  647. temp = bb_get_chunk_from_file(fp, &len);
  648. if (temp) {
  649. /* len > 0 here, it's ok to do temp[len-1] */
  650. char c = temp[len-1];
  651. if (c == '\n' || c == '\0') {
  652. temp[len-1] = '\0';
  653. gc = c;
  654. if (c == '\0') {
  655. int ch = fgetc(fp);
  656. if (ch != EOF)
  657. ungetc(ch, fp);
  658. else
  659. gc = LAST_IS_NUL;
  660. }
  661. }
  662. /* else we put NO_EOL_CHAR into *gets_char */
  663. break;
  664. /* NB: I had the idea of peeking next file(s) and returning
  665. * NO_EOL_CHAR only if it is the *last* non-empty
  666. * input file. But there is a case where this won't work:
  667. * file1: "a woo\nb woo"
  668. * file2: "c no\nd no"
  669. * sed -ne 's/woo/bang/p' input1 input2 => "a bang\nb bang"
  670. * (note: *no* newline after "b bang"!) */
  671. }
  672. /* Close this file and advance to next one */
  673. fclose(fp);
  674. G.current_input_file++;
  675. }
  676. *gets_char = gc;
  677. return temp;
  678. }
  679. /* Output line of text. */
  680. /* Note:
  681. * The tricks with NO_EOL_CHAR and last_puts_char are there to emulate gnu sed.
  682. * Without them, we had this:
  683. * echo -n thingy >z1
  684. * echo -n again >z2
  685. * >znull
  686. * sed "s/i/z/" z1 z2 znull | hexdump -vC
  687. * output:
  688. * gnu sed 4.1.5:
  689. * 00000000 74 68 7a 6e 67 79 0a 61 67 61 7a 6e |thzngy.agazn|
  690. * bbox:
  691. * 00000000 74 68 7a 6e 67 79 61 67 61 7a 6e |thzngyagazn|
  692. */
  693. static void puts_maybe_newline(char *s, FILE *file, char *last_puts_char, char last_gets_char)
  694. {
  695. char lpc = *last_puts_char;
  696. /* Need to insert a '\n' between two files because first file's
  697. * last line wasn't terminated? */
  698. if (lpc != '\n' && lpc != '\0') {
  699. fputc('\n', file);
  700. lpc = '\n';
  701. }
  702. fputs(s, file);
  703. /* 'x' - just something which is not '\n', '\0' or NO_EOL_CHAR */
  704. if (s[0])
  705. lpc = 'x';
  706. /* had trailing '\0' and it was last char of file? */
  707. if (last_gets_char == LAST_IS_NUL) {
  708. fputc('\0', file);
  709. lpc = 'x'; /* */
  710. } else
  711. /* had trailing '\n' or '\0'? */
  712. if (last_gets_char != NO_EOL_CHAR) {
  713. fputc(last_gets_char, file);
  714. lpc = last_gets_char;
  715. }
  716. if (ferror(file)) {
  717. xfunc_error_retval = 4; /* It's what gnu sed exits with... */
  718. bb_error_msg_and_die(bb_msg_write_error);
  719. }
  720. *last_puts_char = lpc;
  721. }
  722. #define sed_puts(s, n) (puts_maybe_newline(s, G.nonstdout, &last_puts_char, n))
  723. static int beg_match(sed_cmd_t *sed_cmd, const char *pattern_space)
  724. {
  725. int retval = sed_cmd->beg_match && !regexec(sed_cmd->beg_match, pattern_space, 0, NULL, 0);
  726. if (retval)
  727. G.previous_regex_ptr = sed_cmd->beg_match;
  728. return retval;
  729. }
  730. /* Process all the lines in all the files */
  731. static void process_files(void)
  732. {
  733. char *pattern_space, *next_line;
  734. int linenum = 0;
  735. char last_puts_char = '\n';
  736. char last_gets_char, next_gets_char;
  737. sed_cmd_t *sed_cmd;
  738. int substituted;
  739. /* Prime the pump */
  740. next_line = get_next_line(&next_gets_char);
  741. /* Go through every line in each file */
  742. again:
  743. substituted = 0;
  744. /* Advance to next line. Stop if out of lines. */
  745. pattern_space = next_line;
  746. if (!pattern_space)
  747. return;
  748. last_gets_char = next_gets_char;
  749. /* Read one line in advance so we can act on the last line,
  750. * the '$' address */
  751. next_line = get_next_line(&next_gets_char);
  752. linenum++;
  753. /* For every line, go through all the commands */
  754. restart:
  755. for (sed_cmd = G.sed_cmd_head.next; sed_cmd; sed_cmd = sed_cmd->next) {
  756. int old_matched, matched;
  757. old_matched = sed_cmd->in_match;
  758. /* Determine if this command matches this line: */
  759. /* Are we continuing a previous multi-line match? */
  760. sed_cmd->in_match = sed_cmd->in_match
  761. /* Or is no range necessary? */
  762. || (!sed_cmd->beg_line && !sed_cmd->end_line
  763. && !sed_cmd->beg_match && !sed_cmd->end_match)
  764. /* Or did we match the start of a numerical range? */
  765. || (sed_cmd->beg_line > 0 && (sed_cmd->beg_line <= linenum))
  766. /* Or does this line match our begin address regex? */
  767. || (beg_match(sed_cmd, pattern_space))
  768. /* Or did we match last line of input? */
  769. || (sed_cmd->beg_line == -1 && next_line == NULL);
  770. /* Snapshot the value */
  771. matched = sed_cmd->in_match;
  772. //bb_error_msg("cmd:'%c' matched:%d beg_line:%d end_line:%d linenum:%d",
  773. //sed_cmd->cmd, matched, sed_cmd->beg_line, sed_cmd->end_line, linenum);
  774. /* Is this line the end of the current match? */
  775. if (matched) {
  776. /* once matched, "n,xxx" range is dead, disabling it */
  777. if (sed_cmd->beg_line > 0)
  778. sed_cmd->beg_line = -2;
  779. sed_cmd->in_match = !(
  780. /* has the ending line come, or is this a single address command? */
  781. (sed_cmd->end_line ?
  782. sed_cmd->end_line == -1 ?
  783. !next_line
  784. : (sed_cmd->end_line <= linenum)
  785. : !sed_cmd->end_match
  786. )
  787. /* or does this line matches our last address regex */
  788. || (sed_cmd->end_match && old_matched
  789. && (regexec(sed_cmd->end_match,
  790. pattern_space, 0, NULL, 0) == 0))
  791. );
  792. }
  793. /* Skip blocks of commands we didn't match */
  794. if (sed_cmd->cmd == '{') {
  795. if (sed_cmd->invert ? matched : !matched) {
  796. unsigned nest_cnt = 0;
  797. while (1) {
  798. if (sed_cmd->cmd == '{')
  799. nest_cnt++;
  800. if (sed_cmd->cmd == '}') {
  801. nest_cnt--;
  802. if (nest_cnt == 0)
  803. break;
  804. }
  805. sed_cmd = sed_cmd->next;
  806. if (!sed_cmd)
  807. bb_error_msg_and_die("unterminated {");
  808. }
  809. }
  810. continue;
  811. }
  812. /* Okay, so did this line match? */
  813. if (sed_cmd->invert ? matched : !matched)
  814. continue; /* no */
  815. /* Update last used regex in case a blank substitute BRE is found */
  816. if (sed_cmd->beg_match) {
  817. G.previous_regex_ptr = sed_cmd->beg_match;
  818. }
  819. /* actual sedding */
  820. switch (sed_cmd->cmd) {
  821. /* Print line number */
  822. case '=':
  823. fprintf(G.nonstdout, "%d\n", linenum);
  824. break;
  825. /* Write the current pattern space up to the first newline */
  826. case 'P':
  827. {
  828. char *tmp = strchr(pattern_space, '\n');
  829. if (tmp) {
  830. *tmp = '\0';
  831. /* TODO: explain why '\n' below */
  832. sed_puts(pattern_space, '\n');
  833. *tmp = '\n';
  834. break;
  835. }
  836. /* Fall Through */
  837. }
  838. /* Write the current pattern space to output */
  839. case 'p':
  840. /* NB: we print this _before_ the last line
  841. * (of current file) is printed. Even if
  842. * that line is nonterminated, we print
  843. * '\n' here (gnu sed does the same) */
  844. sed_puts(pattern_space, '\n');
  845. break;
  846. /* Delete up through first newline */
  847. case 'D':
  848. {
  849. char *tmp = strchr(pattern_space, '\n');
  850. if (tmp) {
  851. tmp = xstrdup(tmp+1);
  852. free(pattern_space);
  853. pattern_space = tmp;
  854. goto restart;
  855. }
  856. }
  857. /* discard this line. */
  858. case 'd':
  859. goto discard_line;
  860. /* Substitute with regex */
  861. case 's':
  862. if (!do_subst_command(sed_cmd, &pattern_space))
  863. break;
  864. substituted |= 1;
  865. /* handle p option */
  866. if (sed_cmd->sub_p)
  867. sed_puts(pattern_space, last_gets_char);
  868. /* handle w option */
  869. if (sed_cmd->sw_file)
  870. puts_maybe_newline(
  871. pattern_space, sed_cmd->sw_file,
  872. &sed_cmd->sw_last_char, last_gets_char);
  873. break;
  874. /* Append line to linked list to be printed later */
  875. case 'a':
  876. append(sed_cmd->string);
  877. break;
  878. /* Insert text before this line */
  879. case 'i':
  880. sed_puts(sed_cmd->string, '\n');
  881. break;
  882. /* Cut and paste text (replace) */
  883. case 'c':
  884. /* Only triggers on last line of a matching range. */
  885. if (!sed_cmd->in_match)
  886. sed_puts(sed_cmd->string, '\n');
  887. goto discard_line;
  888. /* Read file, append contents to output */
  889. case 'r':
  890. {
  891. FILE *rfile;
  892. rfile = fopen_for_read(sed_cmd->string);
  893. if (rfile) {
  894. char *line;
  895. while ((line = xmalloc_fgetline(rfile))
  896. != NULL)
  897. append(line);
  898. xprint_and_close_file(rfile);
  899. }
  900. break;
  901. }
  902. /* Write pattern space to file. */
  903. case 'w':
  904. puts_maybe_newline(
  905. pattern_space, sed_cmd->sw_file,
  906. &sed_cmd->sw_last_char, last_gets_char);
  907. break;
  908. /* Read next line from input */
  909. case 'n':
  910. if (!G.be_quiet)
  911. sed_puts(pattern_space, last_gets_char);
  912. if (next_line) {
  913. free(pattern_space);
  914. pattern_space = next_line;
  915. last_gets_char = next_gets_char;
  916. next_line = get_next_line(&next_gets_char);
  917. substituted = 0;
  918. linenum++;
  919. break;
  920. }
  921. /* fall through */
  922. /* Quit. End of script, end of input. */
  923. case 'q':
  924. /* Exit the outer while loop */
  925. free(next_line);
  926. next_line = NULL;
  927. goto discard_commands;
  928. /* Append the next line to the current line */
  929. case 'N':
  930. {
  931. int len;
  932. /* If no next line, jump to end of script and exit. */
  933. if (next_line == NULL) {
  934. /* Jump to end of script and exit */
  935. free(next_line);
  936. next_line = NULL;
  937. goto discard_line;
  938. /* append next_line, read new next_line. */
  939. }
  940. len = strlen(pattern_space);
  941. pattern_space = xrealloc(pattern_space, len + strlen(next_line) + 2);
  942. pattern_space[len] = '\n';
  943. strcpy(pattern_space + len+1, next_line);
  944. last_gets_char = next_gets_char;
  945. next_line = get_next_line(&next_gets_char);
  946. linenum++;
  947. break;
  948. }
  949. /* Test/branch if substitution occurred */
  950. case 't':
  951. if (!substituted) break;
  952. substituted = 0;
  953. /* Fall through */
  954. /* Test/branch if substitution didn't occur */
  955. case 'T':
  956. if (substituted) break;
  957. /* Fall through */
  958. /* Branch to label */
  959. case 'b':
  960. if (!sed_cmd->string) goto discard_commands;
  961. else sed_cmd = branch_to(sed_cmd->string);
  962. break;
  963. /* Transliterate characters */
  964. case 'y':
  965. {
  966. int i, j;
  967. for (i = 0; pattern_space[i]; i++) {
  968. for (j = 0; sed_cmd->string[j]; j += 2) {
  969. if (pattern_space[i] == sed_cmd->string[j]) {
  970. pattern_space[i] = sed_cmd->string[j + 1];
  971. break;
  972. }
  973. }
  974. }
  975. break;
  976. }
  977. case 'g': /* Replace pattern space with hold space */
  978. free(pattern_space);
  979. pattern_space = xstrdup(G.hold_space ? G.hold_space : "");
  980. break;
  981. case 'G': /* Append newline and hold space to pattern space */
  982. {
  983. int pattern_space_size = 2;
  984. int hold_space_size = 0;
  985. if (pattern_space)
  986. pattern_space_size += strlen(pattern_space);
  987. if (G.hold_space)
  988. hold_space_size = strlen(G.hold_space);
  989. pattern_space = xrealloc(pattern_space,
  990. pattern_space_size + hold_space_size);
  991. if (pattern_space_size == 2)
  992. pattern_space[0] = 0;
  993. strcat(pattern_space, "\n");
  994. if (G.hold_space)
  995. strcat(pattern_space, G.hold_space);
  996. last_gets_char = '\n';
  997. break;
  998. }
  999. case 'h': /* Replace hold space with pattern space */
  1000. free(G.hold_space);
  1001. G.hold_space = xstrdup(pattern_space);
  1002. break;
  1003. case 'H': /* Append newline and pattern space to hold space */
  1004. {
  1005. int hold_space_size = 2;
  1006. int pattern_space_size = 0;
  1007. if (G.hold_space)
  1008. hold_space_size += strlen(G.hold_space);
  1009. if (pattern_space)
  1010. pattern_space_size = strlen(pattern_space);
  1011. G.hold_space = xrealloc(G.hold_space,
  1012. hold_space_size + pattern_space_size);
  1013. if (hold_space_size == 2)
  1014. *G.hold_space = 0;
  1015. strcat(G.hold_space, "\n");
  1016. if (pattern_space)
  1017. strcat(G.hold_space, pattern_space);
  1018. break;
  1019. }
  1020. case 'x': /* Exchange hold and pattern space */
  1021. {
  1022. char *tmp = pattern_space;
  1023. pattern_space = G.hold_space ? G.hold_space : xzalloc(1);
  1024. last_gets_char = '\n';
  1025. G.hold_space = tmp;
  1026. break;
  1027. }
  1028. } /* switch */
  1029. } /* for each cmd */
  1030. /*
  1031. * Exit point from sedding...
  1032. */
  1033. discard_commands:
  1034. /* we will print the line unless we were told to be quiet ('-n')
  1035. or if the line was suppressed (ala 'd'elete) */
  1036. if (!G.be_quiet)
  1037. sed_puts(pattern_space, last_gets_char);
  1038. /* Delete and such jump here. */
  1039. discard_line:
  1040. flush_append();
  1041. free(pattern_space);
  1042. goto again;
  1043. }
  1044. /* It is possible to have a command line argument with embedded
  1045. * newlines. This counts as multiple command lines.
  1046. * However, newline can be escaped: 's/e/z\<newline>z/'
  1047. * We check for this.
  1048. */
  1049. static void add_cmd_block(char *cmdstr)
  1050. {
  1051. char *sv, *eol;
  1052. cmdstr = sv = xstrdup(cmdstr);
  1053. do {
  1054. eol = strchr(cmdstr, '\n');
  1055. next:
  1056. if (eol) {
  1057. /* Count preceding slashes */
  1058. int slashes = 0;
  1059. char *sl = eol;
  1060. while (sl != cmdstr && *--sl == '\\')
  1061. slashes++;
  1062. /* Odd number of preceding slashes - newline is escaped */
  1063. if (slashes & 1) {
  1064. overlapping_strcpy(eol - 1, eol);
  1065. eol = strchr(eol, '\n');
  1066. goto next;
  1067. }
  1068. *eol = '\0';
  1069. }
  1070. add_cmd(cmdstr);
  1071. cmdstr = eol + 1;
  1072. } while (eol);
  1073. free(sv);
  1074. }
  1075. int sed_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1076. int sed_main(int argc UNUSED_PARAM, char **argv)
  1077. {
  1078. enum {
  1079. OPT_in_place = 1 << 0,
  1080. };
  1081. unsigned opt;
  1082. llist_t *opt_e, *opt_f;
  1083. int status = EXIT_SUCCESS;
  1084. INIT_G();
  1085. /* destroy command strings on exit */
  1086. if (ENABLE_FEATURE_CLEAN_UP) atexit(sed_free_and_close_stuff);
  1087. /* Lie to autoconf when it starts asking stupid questions. */
  1088. if (argv[1] && !strcmp(argv[1], "--version")) {
  1089. puts("This is not GNU sed version 4.0");
  1090. return 0;
  1091. }
  1092. /* do normal option parsing */
  1093. opt_e = opt_f = NULL;
  1094. opt_complementary = "e::f::" /* can occur multiple times */
  1095. "nn"; /* count -n */
  1096. opt = getopt32(argv, "irne:f:", &opt_e, &opt_f,
  1097. &G.be_quiet); /* counter for -n */
  1098. //argc -= optind;
  1099. argv += optind;
  1100. if (opt & OPT_in_place) { // -i
  1101. atexit(cleanup_outname);
  1102. }
  1103. if (opt & 0x2) G.regex_type |= REG_EXTENDED; // -r
  1104. //if (opt & 0x4) G.be_quiet++; // -n
  1105. while (opt_e) { // -e
  1106. add_cmd_block(llist_pop(&opt_e));
  1107. }
  1108. while (opt_f) { // -f
  1109. char *line;
  1110. FILE *cmdfile;
  1111. cmdfile = xfopen_for_read(llist_pop(&opt_f));
  1112. while ((line = xmalloc_fgetline(cmdfile)) != NULL) {
  1113. add_cmd(line);
  1114. free(line);
  1115. }
  1116. fclose(cmdfile);
  1117. }
  1118. /* if we didn't get a pattern from -e or -f, use argv[0] */
  1119. if (!(opt & 0x18)) {
  1120. if (!*argv)
  1121. bb_show_usage();
  1122. add_cmd_block(*argv++);
  1123. }
  1124. /* Flush any unfinished commands. */
  1125. add_cmd("");
  1126. /* By default, we write to stdout */
  1127. G.nonstdout = stdout;
  1128. /* argv[0..(argc-1)] should be names of file to process. If no
  1129. * files were specified or '-' was specified, take input from stdin.
  1130. * Otherwise, we process all the files specified. */
  1131. if (argv[0] == NULL) {
  1132. if (opt & OPT_in_place)
  1133. bb_error_msg_and_die(bb_msg_requires_arg, "-i");
  1134. add_input_file(stdin);
  1135. process_files();
  1136. } else {
  1137. int i;
  1138. FILE *file;
  1139. for (i = 0; argv[i]; i++) {
  1140. struct stat statbuf;
  1141. int nonstdoutfd;
  1142. if (LONE_DASH(argv[i]) && !(opt & OPT_in_place)) {
  1143. add_input_file(stdin);
  1144. process_files();
  1145. continue;
  1146. }
  1147. file = fopen_or_warn(argv[i], "r");
  1148. if (!file) {
  1149. status = EXIT_FAILURE;
  1150. continue;
  1151. }
  1152. if (!(opt & OPT_in_place)) {
  1153. add_input_file(file);
  1154. continue;
  1155. }
  1156. G.outname = xasprintf("%sXXXXXX", argv[i]);
  1157. nonstdoutfd = mkstemp(G.outname);
  1158. if (-1 == nonstdoutfd)
  1159. bb_perror_msg_and_die("can't create temp file %s", G.outname);
  1160. G.nonstdout = xfdopen_for_write(nonstdoutfd);
  1161. /* Set permissions/owner of output file */
  1162. fstat(fileno(file), &statbuf);
  1163. fchmod(nonstdoutfd, statbuf.st_mode);
  1164. fchown(nonstdoutfd, statbuf.st_uid, statbuf.st_gid);
  1165. add_input_file(file);
  1166. process_files();
  1167. fclose(G.nonstdout);
  1168. G.nonstdout = stdout;
  1169. /* unlink(argv[i]); */
  1170. xrename(G.outname, argv[i]);
  1171. free(G.outname);
  1172. G.outname = NULL;
  1173. }
  1174. if (G.input_file_count > G.current_input_file)
  1175. process_files();
  1176. }
  1177. return status;
  1178. }