sed.c 36 KB

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