sed.c 41 KB

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