sed.c 42 KB

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