sed.c 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629
  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 (12 kb)"
  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: "[-i[SFX]] [-nrE] [-f FILE]... [-e CMD]... [FILE]...\n"
  66. //usage: "or: sed [-i[SFX]] [-nrE] 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 shouldn't 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 extension) */
  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 wasn't 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 don't 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 == ':'
  779. && sed_cmd->string
  780. && strcmp(sed_cmd->string, label) == 0
  781. ) {
  782. return sed_cmd;
  783. }
  784. }
  785. bb_error_msg_and_die("can't find label for jump to '%s'", label);
  786. }
  787. static void append(char *s)
  788. {
  789. llist_add_to_end(&G.append_head, s);
  790. }
  791. /* Output line of text. */
  792. /* Note:
  793. * The tricks with NO_EOL_CHAR and last_puts_char are there to emulate gnu sed.
  794. * Without them, we had this:
  795. * echo -n thingy >z1
  796. * echo -n again >z2
  797. * >znull
  798. * sed "s/i/z/" z1 z2 znull | hexdump -vC
  799. * output:
  800. * gnu sed 4.1.5:
  801. * 00000000 74 68 7a 6e 67 79 0a 61 67 61 7a 6e |thzngy.agazn|
  802. * bbox:
  803. * 00000000 74 68 7a 6e 67 79 61 67 61 7a 6e |thzngyagazn|
  804. */
  805. enum {
  806. NO_EOL_CHAR = 1,
  807. LAST_IS_NUL = 2,
  808. };
  809. static void puts_maybe_newline(char *s, FILE *file, char *last_puts_char, char last_gets_char)
  810. {
  811. char lpc = *last_puts_char;
  812. /* Need to insert a '\n' between two files because first file's
  813. * last line wasn't terminated? */
  814. if (lpc != '\n' && lpc != '\0') {
  815. fputc('\n', file);
  816. lpc = '\n';
  817. }
  818. fputs(s, file);
  819. /* 'x' - just something which is not '\n', '\0' or NO_EOL_CHAR */
  820. if (s[0])
  821. lpc = 'x';
  822. /* had trailing '\0' and it was last char of file? */
  823. if (last_gets_char == LAST_IS_NUL) {
  824. fputc('\0', file);
  825. lpc = 'x'; /* */
  826. } else
  827. /* had trailing '\n' or '\0'? */
  828. if (last_gets_char != NO_EOL_CHAR) {
  829. fputc(last_gets_char, file);
  830. lpc = last_gets_char;
  831. }
  832. if (ferror(file)) {
  833. xfunc_error_retval = 4; /* It's what gnu sed exits with... */
  834. bb_error_msg_and_die(bb_msg_write_error);
  835. }
  836. *last_puts_char = lpc;
  837. }
  838. static void flush_append(char *last_puts_char)
  839. {
  840. char *data;
  841. /* Output appended lines. */
  842. while ((data = (char *)llist_pop(&G.append_head)) != NULL) {
  843. /* Append command does not respect "nonterminated-ness"
  844. * of last line. Try this:
  845. * $ echo -n "woot" | sed -e '/woot/a woo' -
  846. * woot
  847. * woo
  848. * (both lines are terminated with \n)
  849. * Therefore we do not propagate "last_gets_char" here,
  850. * pass '\n' instead:
  851. */
  852. puts_maybe_newline(data, G.nonstdout, last_puts_char, '\n');
  853. free(data);
  854. }
  855. }
  856. /* Get next line of input from G.input_file_list, flushing append buffer and
  857. * noting if we ran out of files without a newline on the last line we read.
  858. */
  859. static char *get_next_line(char *gets_char, char *last_puts_char)
  860. {
  861. char *temp = NULL;
  862. int len;
  863. char gc;
  864. flush_append(last_puts_char);
  865. /* will be returned if last line in the file
  866. * doesn't end with either '\n' or '\0' */
  867. gc = NO_EOL_CHAR;
  868. for (; G.current_input_file <= G.last_input_file; G.current_input_file++) {
  869. FILE *fp = G.current_fp;
  870. if (!fp) {
  871. const char *path = G.input_file_list[G.current_input_file];
  872. fp = stdin;
  873. if (path != bb_msg_standard_input) {
  874. fp = fopen_or_warn(path, "r");
  875. if (!fp) {
  876. G.exitcode = EXIT_FAILURE;
  877. continue;
  878. }
  879. }
  880. G.current_fp = fp;
  881. }
  882. /* Read line up to a newline or NUL byte, inclusive,
  883. * return malloc'ed char[]. length of the chunk read
  884. * is stored in len. NULL if EOF/error */
  885. temp = bb_get_chunk_from_file(fp, &len);
  886. if (temp) {
  887. /* len > 0 here, it's ok to do temp[len-1] */
  888. char c = temp[len-1];
  889. if (c == '\n' || c == '\0') {
  890. temp[len-1] = '\0';
  891. gc = c;
  892. if (c == '\0') {
  893. int ch = fgetc(fp);
  894. if (ch != EOF)
  895. ungetc(ch, fp);
  896. else
  897. gc = LAST_IS_NUL;
  898. }
  899. }
  900. /* else we put NO_EOL_CHAR into *gets_char */
  901. break;
  902. /* NB: I had the idea of peeking next file(s) and returning
  903. * NO_EOL_CHAR only if it is the *last* non-empty
  904. * input file. But there is a case where this won't work:
  905. * file1: "a woo\nb woo"
  906. * file2: "c no\nd no"
  907. * sed -ne 's/woo/bang/p' input1 input2 => "a bang\nb bang"
  908. * (note: *no* newline after "b bang"!) */
  909. }
  910. /* Close this file and advance to next one */
  911. fclose_if_not_stdin(fp);
  912. G.current_fp = NULL;
  913. }
  914. *gets_char = gc;
  915. return temp;
  916. }
  917. #define sed_puts(s, n) (puts_maybe_newline(s, G.nonstdout, &last_puts_char, n))
  918. static int beg_match(sed_cmd_t *sed_cmd, const char *pattern_space)
  919. {
  920. int retval = sed_cmd->beg_match && !regexec(sed_cmd->beg_match, pattern_space, 0, NULL, 0);
  921. if (retval)
  922. G.previous_regex_ptr = sed_cmd->beg_match;
  923. return retval;
  924. }
  925. /* Process all the lines in all the files */
  926. static void process_files(void)
  927. {
  928. char *pattern_space, *next_line;
  929. int linenum = 0;
  930. char last_puts_char = '\n';
  931. char last_gets_char, next_gets_char;
  932. sed_cmd_t *sed_cmd;
  933. int substituted;
  934. /* Prime the pump */
  935. next_line = get_next_line(&next_gets_char, &last_puts_char);
  936. /* Go through every line in each file */
  937. again:
  938. substituted = 0;
  939. /* Advance to next line. Stop if out of lines. */
  940. pattern_space = next_line;
  941. if (!pattern_space)
  942. return;
  943. last_gets_char = next_gets_char;
  944. /* Read one line in advance so we can act on the last line,
  945. * the '$' address */
  946. next_line = get_next_line(&next_gets_char, &last_puts_char);
  947. linenum++;
  948. /* For every line, go through all the commands */
  949. restart:
  950. for (sed_cmd = G.sed_cmd_head; sed_cmd; sed_cmd = sed_cmd->next) {
  951. int old_matched, matched;
  952. old_matched = sed_cmd->in_match;
  953. /* Determine if this command matches this line: */
  954. dbg("match1:%d", sed_cmd->in_match);
  955. dbg("match2:%d", (!sed_cmd->beg_line && !sed_cmd->end_line
  956. && !sed_cmd->beg_match && !sed_cmd->end_match));
  957. dbg("match3:%d", (sed_cmd->beg_line > 0
  958. && (sed_cmd->end_line || sed_cmd->end_match
  959. ? (sed_cmd->beg_line <= linenum)
  960. : (sed_cmd->beg_line == linenum)
  961. )
  962. ));
  963. dbg("match4:%d", (beg_match(sed_cmd, pattern_space)));
  964. dbg("match5:%d", (sed_cmd->beg_line == -1 && next_line == NULL));
  965. /* Are we continuing a previous multi-line match? */
  966. sed_cmd->in_match = sed_cmd->in_match
  967. /* Or is no range necessary? */
  968. || (!sed_cmd->beg_line && !sed_cmd->end_line
  969. && !sed_cmd->beg_match && !sed_cmd->end_match)
  970. /* Or did we match the start of a numerical range? */
  971. || (sed_cmd->beg_line > 0
  972. && (sed_cmd->end_line || sed_cmd->end_match
  973. /* note: even if end is numeric and is < linenum too,
  974. * GNU sed matches! We match too, therefore we don't
  975. * check here that linenum <= end.
  976. * Example:
  977. * printf '1\n2\n3\n4\n' | sed -n '1{N;N;d};1p;2,3p;3p;4p'
  978. * first three input lines are deleted;
  979. * 4th line is matched and printed
  980. * by "2,3" (!) and by "4" ranges
  981. */
  982. ? (sed_cmd->beg_line <= linenum) /* N,end */
  983. : (sed_cmd->beg_line == linenum) /* N */
  984. )
  985. )
  986. /* Or does this line match our begin address regex? */
  987. || (beg_match(sed_cmd, pattern_space))
  988. /* Or did we match last line of input? */
  989. || (sed_cmd->beg_line == -1 && next_line == NULL);
  990. /* Snapshot the value */
  991. matched = sed_cmd->in_match;
  992. dbg("cmd:'%c' matched:%d beg_line:%d end_line:%d linenum:%d",
  993. sed_cmd->cmd, matched, sed_cmd->beg_line, sed_cmd->end_line, linenum);
  994. /* Is this line the end of the current match? */
  995. if (matched) {
  996. if (sed_cmd->end_line <= -2) {
  997. /* address2 is +N, i.e. N lines from beg_line */
  998. sed_cmd->end_line = linenum + (-sed_cmd->end_line - 2);
  999. }
  1000. /* once matched, "n,xxx" range is dead, disabling it */
  1001. if (sed_cmd->beg_line > 0) {
  1002. sed_cmd->beg_line = -2;
  1003. }
  1004. dbg("end1:%d", sed_cmd->end_line ? sed_cmd->end_line == -1
  1005. ? !next_line : (sed_cmd->end_line <= linenum)
  1006. : !sed_cmd->end_match);
  1007. dbg("end2:%d", sed_cmd->end_match && old_matched
  1008. && !regexec(sed_cmd->end_match,pattern_space, 0, NULL, 0));
  1009. sed_cmd->in_match = !(
  1010. /* has the ending line come, or is this a single address command? */
  1011. (sed_cmd->end_line
  1012. ? sed_cmd->end_line == -1
  1013. ? !next_line
  1014. : (sed_cmd->end_line <= linenum)
  1015. : !sed_cmd->end_match
  1016. )
  1017. /* or does this line matches our last address regex */
  1018. || (sed_cmd->end_match && old_matched
  1019. && (regexec(sed_cmd->end_match,
  1020. pattern_space, 0, NULL, 0) == 0)
  1021. )
  1022. );
  1023. }
  1024. /* Skip blocks of commands we didn't match */
  1025. if (sed_cmd->cmd == '{') {
  1026. if (sed_cmd->invert ? matched : !matched) {
  1027. unsigned nest_cnt = 0;
  1028. while (1) {
  1029. if (sed_cmd->cmd == '{')
  1030. nest_cnt++;
  1031. if (sed_cmd->cmd == '}') {
  1032. nest_cnt--;
  1033. if (nest_cnt == 0)
  1034. break;
  1035. }
  1036. sed_cmd = sed_cmd->next;
  1037. if (!sed_cmd)
  1038. bb_error_msg_and_die("unterminated {");
  1039. }
  1040. }
  1041. continue;
  1042. }
  1043. /* Okay, so did this line match? */
  1044. if (sed_cmd->invert ? matched : !matched)
  1045. continue; /* no */
  1046. /* Update last used regex in case a blank substitute BRE is found */
  1047. if (sed_cmd->beg_match) {
  1048. G.previous_regex_ptr = sed_cmd->beg_match;
  1049. }
  1050. /* actual sedding */
  1051. dbg("pattern_space:'%s' next_line:'%s' cmd:%c",
  1052. pattern_space, next_line, sed_cmd->cmd);
  1053. switch (sed_cmd->cmd) {
  1054. /* Print line number */
  1055. case '=':
  1056. fprintf(G.nonstdout, "%d\n", linenum);
  1057. break;
  1058. /* Write the current pattern space up to the first newline */
  1059. case 'P':
  1060. {
  1061. char *tmp = strchr(pattern_space, '\n');
  1062. if (tmp) {
  1063. *tmp = '\0';
  1064. /* TODO: explain why '\n' below */
  1065. sed_puts(pattern_space, '\n');
  1066. *tmp = '\n';
  1067. break;
  1068. }
  1069. /* Fall Through */
  1070. }
  1071. /* Write the current pattern space to output */
  1072. case 'p':
  1073. /* NB: we print this _before_ the last line
  1074. * (of current file) is printed. Even if
  1075. * that line is nonterminated, we print
  1076. * '\n' here (gnu sed does the same) */
  1077. sed_puts(pattern_space, '\n');
  1078. break;
  1079. /* Delete up through first newline */
  1080. case 'D':
  1081. {
  1082. char *tmp = strchr(pattern_space, '\n');
  1083. if (tmp) {
  1084. overlapping_strcpy(pattern_space, tmp + 1);
  1085. goto restart;
  1086. }
  1087. }
  1088. /* discard this line. */
  1089. case 'd':
  1090. goto discard_line;
  1091. /* Substitute with regex */
  1092. case 's':
  1093. if (!do_subst_command(sed_cmd, &pattern_space))
  1094. break;
  1095. dbg("do_subst_command succeeded:'%s'", pattern_space);
  1096. substituted |= 1;
  1097. /* handle p option */
  1098. if (sed_cmd->sub_p)
  1099. sed_puts(pattern_space, last_gets_char);
  1100. /* handle w option */
  1101. if (sed_cmd->sw_file)
  1102. puts_maybe_newline(
  1103. pattern_space, sed_cmd->sw_file,
  1104. &sed_cmd->sw_last_char, last_gets_char);
  1105. break;
  1106. /* Append line to linked list to be printed later */
  1107. case 'a':
  1108. append(xstrdup(sed_cmd->string));
  1109. break;
  1110. /* Insert text before this line */
  1111. case 'i':
  1112. sed_puts(sed_cmd->string, '\n');
  1113. break;
  1114. /* Cut and paste text (replace) */
  1115. case 'c':
  1116. /* Only triggers on last line of a matching range. */
  1117. if (!sed_cmd->in_match)
  1118. sed_puts(sed_cmd->string, '\n');
  1119. goto discard_line;
  1120. /* Read file, append contents to output */
  1121. case 'r':
  1122. {
  1123. FILE *rfile;
  1124. rfile = fopen_for_read(sed_cmd->string);
  1125. if (rfile) {
  1126. char *line;
  1127. while ((line = xmalloc_fgetline(rfile))
  1128. != NULL)
  1129. append(line);
  1130. fclose(rfile);
  1131. }
  1132. break;
  1133. }
  1134. /* Write pattern space to file. */
  1135. case 'w':
  1136. puts_maybe_newline(
  1137. pattern_space, sed_cmd->sw_file,
  1138. &sed_cmd->sw_last_char, last_gets_char);
  1139. break;
  1140. /* Read next line from input */
  1141. case 'n':
  1142. if (!G.be_quiet)
  1143. sed_puts(pattern_space, last_gets_char);
  1144. if (next_line == NULL) {
  1145. /* If no next line, jump to end of script and exit. */
  1146. goto discard_line;
  1147. }
  1148. free(pattern_space);
  1149. pattern_space = next_line;
  1150. last_gets_char = next_gets_char;
  1151. next_line = get_next_line(&next_gets_char, &last_puts_char);
  1152. substituted = 0;
  1153. linenum++;
  1154. break;
  1155. /* Quit. End of script, end of input. */
  1156. case 'q':
  1157. /* Exit the outer while loop */
  1158. free(next_line);
  1159. next_line = NULL;
  1160. goto discard_commands;
  1161. /* Append the next line to the current line */
  1162. case 'N':
  1163. {
  1164. int len;
  1165. /* If no next line, jump to end of script and exit. */
  1166. /* http://www.gnu.org/software/sed/manual/sed.html:
  1167. * "Most versions of sed exit without printing anything
  1168. * when the N command is issued on the last line of
  1169. * a file. GNU sed prints pattern space before exiting
  1170. * unless of course the -n command switch has been
  1171. * specified. This choice is by design."
  1172. */
  1173. if (next_line == NULL) {
  1174. //goto discard_line;
  1175. goto discard_commands; /* GNU behavior */
  1176. }
  1177. /* Append next_line, read new next_line. */
  1178. len = strlen(pattern_space);
  1179. pattern_space = xrealloc(pattern_space, len + strlen(next_line) + 2);
  1180. pattern_space[len] = '\n';
  1181. strcpy(pattern_space + len+1, next_line);
  1182. last_gets_char = next_gets_char;
  1183. next_line = get_next_line(&next_gets_char, &last_puts_char);
  1184. linenum++;
  1185. break;
  1186. }
  1187. /* Test/branch if substitution occurred */
  1188. case 't':
  1189. if (!substituted) break;
  1190. substituted = 0;
  1191. /* Fall through */
  1192. /* Test/branch if substitution didn't occur */
  1193. case 'T':
  1194. if (substituted) break;
  1195. /* Fall through */
  1196. /* Branch to label */
  1197. case 'b':
  1198. if (!sed_cmd->string) goto discard_commands;
  1199. else sed_cmd = branch_to(sed_cmd->string);
  1200. break;
  1201. /* Transliterate characters */
  1202. case 'y':
  1203. {
  1204. int i, j;
  1205. for (i = 0; pattern_space[i]; i++) {
  1206. for (j = 0; sed_cmd->string[j]; j += 2) {
  1207. if (pattern_space[i] == sed_cmd->string[j]) {
  1208. pattern_space[i] = sed_cmd->string[j + 1];
  1209. break;
  1210. }
  1211. }
  1212. }
  1213. break;
  1214. }
  1215. case 'g': /* Replace pattern space with hold space */
  1216. free(pattern_space);
  1217. pattern_space = xstrdup(G.hold_space ? G.hold_space : "");
  1218. break;
  1219. case 'G': /* Append newline and hold space to pattern space */
  1220. {
  1221. int pattern_space_size = 2;
  1222. int hold_space_size = 0;
  1223. if (pattern_space)
  1224. pattern_space_size += strlen(pattern_space);
  1225. if (G.hold_space)
  1226. hold_space_size = strlen(G.hold_space);
  1227. pattern_space = xrealloc(pattern_space,
  1228. pattern_space_size + hold_space_size);
  1229. if (pattern_space_size == 2)
  1230. pattern_space[0] = 0;
  1231. strcat(pattern_space, "\n");
  1232. if (G.hold_space)
  1233. strcat(pattern_space, G.hold_space);
  1234. last_gets_char = '\n';
  1235. break;
  1236. }
  1237. case 'h': /* Replace hold space with pattern space */
  1238. free(G.hold_space);
  1239. G.hold_space = xstrdup(pattern_space);
  1240. break;
  1241. case 'H': /* Append newline and pattern space to hold space */
  1242. {
  1243. int hold_space_size = 2;
  1244. int pattern_space_size = 0;
  1245. if (G.hold_space)
  1246. hold_space_size += strlen(G.hold_space);
  1247. if (pattern_space)
  1248. pattern_space_size = strlen(pattern_space);
  1249. G.hold_space = xrealloc(G.hold_space,
  1250. hold_space_size + pattern_space_size);
  1251. if (hold_space_size == 2)
  1252. *G.hold_space = 0;
  1253. strcat(G.hold_space, "\n");
  1254. if (pattern_space)
  1255. strcat(G.hold_space, pattern_space);
  1256. break;
  1257. }
  1258. case 'x': /* Exchange hold and pattern space */
  1259. {
  1260. char *tmp = pattern_space;
  1261. pattern_space = G.hold_space ? G.hold_space : xzalloc(1);
  1262. last_gets_char = '\n';
  1263. G.hold_space = tmp;
  1264. break;
  1265. }
  1266. } /* switch */
  1267. } /* for each cmd */
  1268. /*
  1269. * Exit point from sedding...
  1270. */
  1271. discard_commands:
  1272. /* we will print the line unless we were told to be quiet ('-n')
  1273. or if the line was suppressed (ala 'd'elete) */
  1274. if (!G.be_quiet)
  1275. sed_puts(pattern_space, last_gets_char);
  1276. /* Delete and such jump here. */
  1277. discard_line:
  1278. flush_append(&last_puts_char /*,last_gets_char*/);
  1279. free(pattern_space);
  1280. goto again;
  1281. }
  1282. /* It is possible to have a command line argument with embedded
  1283. * newlines. This counts as multiple command lines.
  1284. * However, newline can be escaped: 's/e/z\<newline>z/'
  1285. * add_cmd() handles this.
  1286. */
  1287. static void add_cmd_block(char *cmdstr)
  1288. {
  1289. char *sv, *eol;
  1290. cmdstr = sv = xstrdup(cmdstr);
  1291. do {
  1292. eol = strchr(cmdstr, '\n');
  1293. if (eol)
  1294. *eol = '\0';
  1295. add_cmd(cmdstr);
  1296. cmdstr = eol + 1;
  1297. } while (eol);
  1298. free(sv);
  1299. }
  1300. int sed_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1301. int sed_main(int argc UNUSED_PARAM, char **argv)
  1302. {
  1303. unsigned opt;
  1304. llist_t *opt_e, *opt_f;
  1305. char *opt_i;
  1306. #if ENABLE_LONG_OPTS
  1307. static const char sed_longopts[] ALIGN1 =
  1308. /* name has_arg short */
  1309. "in-place\0" Optional_argument "i"
  1310. "regexp-extended\0" No_argument "r"
  1311. "quiet\0" No_argument "n"
  1312. "silent\0" No_argument "n"
  1313. "expression\0" Required_argument "e"
  1314. "file\0" Required_argument "f";
  1315. #endif
  1316. INIT_G();
  1317. /* destroy command strings on exit */
  1318. if (ENABLE_FEATURE_CLEAN_UP) atexit(sed_free_and_close_stuff);
  1319. /* Lie to autoconf when it starts asking stupid questions. */
  1320. if (argv[1] && strcmp(argv[1], "--version") == 0) {
  1321. puts("This is not GNU sed version 4.0");
  1322. return 0;
  1323. }
  1324. /* do normal option parsing */
  1325. opt_e = opt_f = NULL;
  1326. opt_i = NULL;
  1327. /* -i must be first, to match OPT_in_place definition */
  1328. /* -E is a synonym of -r:
  1329. * GNU sed 4.2.1 mentions it in neither --help
  1330. * nor manpage, but does recognize it.
  1331. */
  1332. opt = getopt32long(argv, "^"
  1333. "i::rEne:*f:*"
  1334. "\0" "nn"/*count -n*/,
  1335. sed_longopts,
  1336. &opt_i, &opt_e, &opt_f,
  1337. &G.be_quiet); /* counter for -n */
  1338. //argc -= optind;
  1339. argv += optind;
  1340. if (opt & OPT_in_place) { // -i
  1341. atexit(cleanup_outname);
  1342. }
  1343. if (opt & (2|4))
  1344. G.regex_type |= REG_EXTENDED; // -r or -E
  1345. //if (opt & 8)
  1346. // G.be_quiet++; // -n (implemented with a counter instead)
  1347. while (opt_e) { // -e
  1348. add_cmd_block(llist_pop(&opt_e));
  1349. }
  1350. while (opt_f) { // -f
  1351. char *line;
  1352. FILE *cmdfile;
  1353. cmdfile = xfopen_stdin(llist_pop(&opt_f));
  1354. while ((line = xmalloc_fgetline(cmdfile)) != NULL) {
  1355. add_cmd(line);
  1356. free(line);
  1357. }
  1358. fclose_if_not_stdin(cmdfile);
  1359. }
  1360. /* if we didn't get a pattern from -e or -f, use argv[0] */
  1361. if (!(opt & 0x30)) {
  1362. if (!*argv)
  1363. bb_show_usage();
  1364. add_cmd_block(*argv++);
  1365. }
  1366. /* Flush any unfinished commands. */
  1367. add_cmd("");
  1368. /* By default, we write to stdout */
  1369. G.nonstdout = stdout;
  1370. /* argv[0..(argc-1)] should be names of file to process. If no
  1371. * files were specified or '-' was specified, take input from stdin.
  1372. * Otherwise, we process all the files specified. */
  1373. G.input_file_list = argv;
  1374. if (!argv[0]) {
  1375. if (opt & OPT_in_place)
  1376. bb_error_msg_and_die(bb_msg_requires_arg, "-i");
  1377. argv[0] = (char*)bb_msg_standard_input;
  1378. /* G.last_input_file = 0; - already is */
  1379. } else {
  1380. goto start;
  1381. for (; *argv; argv++) {
  1382. struct stat statbuf;
  1383. int nonstdoutfd;
  1384. sed_cmd_t *sed_cmd;
  1385. G.last_input_file++;
  1386. start:
  1387. if (!(opt & OPT_in_place)) {
  1388. if (LONE_DASH(*argv)) {
  1389. *argv = (char*)bb_msg_standard_input;
  1390. process_files();
  1391. }
  1392. continue;
  1393. }
  1394. /* -i: process each FILE separately: */
  1395. if (stat(*argv, &statbuf) != 0) {
  1396. bb_simple_perror_msg(*argv);
  1397. G.exitcode = EXIT_FAILURE;
  1398. G.current_input_file++;
  1399. continue;
  1400. }
  1401. G.outname = xasprintf("%sXXXXXX", *argv);
  1402. nonstdoutfd = xmkstemp(G.outname);
  1403. G.nonstdout = xfdopen_for_write(nonstdoutfd);
  1404. /* Set permissions/owner of output file */
  1405. /* chmod'ing AFTER chown would preserve suid/sgid bits,
  1406. * but GNU sed 4.2.1 does not preserve them either */
  1407. fchmod(nonstdoutfd, statbuf.st_mode);
  1408. fchown(nonstdoutfd, statbuf.st_uid, statbuf.st_gid);
  1409. process_files();
  1410. fclose(G.nonstdout);
  1411. G.nonstdout = stdout;
  1412. if (opt_i) {
  1413. char *backupname = xasprintf("%s%s", *argv, opt_i);
  1414. xrename(*argv, backupname);
  1415. free(backupname);
  1416. }
  1417. /* else unlink(*argv); - rename below does this */
  1418. xrename(G.outname, *argv); //TODO: rollback backup on error?
  1419. free(G.outname);
  1420. G.outname = NULL;
  1421. /* Fix disabled range matches and mangled ",+N" ranges */
  1422. for (sed_cmd = G.sed_cmd_head; sed_cmd; sed_cmd = sed_cmd->next) {
  1423. sed_cmd->beg_line = sed_cmd->beg_line_orig;
  1424. sed_cmd->end_line = sed_cmd->end_line_orig;
  1425. }
  1426. }
  1427. /* Here, to handle "sed 'cmds' nonexistent_file" case we did:
  1428. * if (G.current_input_file[G.current_input_file] == NULL)
  1429. * return G.exitcode;
  1430. * but it's not needed since process_files() works correctly
  1431. * in this case too. */
  1432. }
  1433. process_files();
  1434. return G.exitcode;
  1435. }