sed.c 42 KB

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