3
0

sed.c 41 KB

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