sed.c 44 KB

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