sed.c 43 KB

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