sed.c 43 KB

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