3
0

sed.c 43 KB

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