sed.c 38 KB

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