sed.c 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291
  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 <bug1@iinet.net.au>
  9. * Copyright (C) 2003,2004 by Rob Landley <rob@landley.net>
  10. *
  11. * MAINTAINER: Rob Landley <rob@landley.net>
  12. *
  13. * Licensed under GPL version 2, see file LICENSE in this tarball for details.
  14. */
  15. /* Code overview.
  16. Files are laid out to avoid unnecessary function declarations. So for
  17. example, every function add_cmd calls occurs before add_cmd in this file.
  18. add_cmd() is called on each line of sed command text (from a file or from
  19. the command line). It calls get_address() and parse_cmd_args(). The
  20. resulting sed_cmd_t structures are appended to a linked list
  21. (bbg.sed_cmd_head/bbg.sed_cmd_tail).
  22. add_input_file() adds a FILE * to the list of input files. We need to
  23. know all input sources ahead of time to find the last line for the $ match.
  24. process_files() does actual sedding, reading data lines from each input FILE *
  25. (which could be stdin) and applying the sed command list (sed_cmd_head) to
  26. each of the resulting lines.
  27. sed_main() is where external code calls into this, with a command line.
  28. */
  29. /*
  30. Supported features and commands in this version of sed:
  31. - comments ('#')
  32. - address matching: num|/matchstr/[,num|/matchstr/|$]command
  33. - commands: (p)rint, (d)elete, (s)ubstitue (with g & I flags)
  34. - edit commands: (a)ppend, (i)nsert, (c)hange
  35. - file commands: (r)ead
  36. - backreferences in substitution expressions (\0, \1, \2...\9)
  37. - grouped commands: {cmd1;cmd2}
  38. - transliteration (y/source-chars/dest-chars/)
  39. - pattern space hold space storing / swapping (g, h, x)
  40. - labels / branching (: label, b, t, T)
  41. (Note: Specifying an address (range) to match is *optional*; commands
  42. default to the whole pattern space if no specific address match was
  43. requested.)
  44. Todo:
  45. - Create a wrapper around regex to make libc's regex conform with sed
  46. Reference http://www.opengroup.org/onlinepubs/007904975/utilities/sed.html
  47. */
  48. #include "busybox.h"
  49. #include "xregex.h"
  50. /* Each sed command turns into one of these structures. */
  51. typedef struct sed_cmd_s {
  52. /* Ordered by alignment requirements: currently 36 bytes on x86 */
  53. /* address storage */
  54. regex_t *beg_match; /* sed -e '/match/cmd' */
  55. regex_t *end_match; /* sed -e '/match/,/end_match/cmd' */
  56. regex_t *sub_match; /* For 's/sub_match/string/' */
  57. int beg_line; /* 'sed 1p' 0 == apply commands to all lines */
  58. int end_line; /* 'sed 1,3p' 0 == one line only. -1 = last line ($) */
  59. FILE *file; /* File (sw) command writes to, -1 for none. */
  60. char *string; /* Data string for (saicytb) commands. */
  61. unsigned short which_match; /* (s) Which match to replace (0 for all) */
  62. /* Bitfields (gcc won't group them if we don't) */
  63. unsigned int invert:1; /* the '!' after the address */
  64. unsigned int in_match:1; /* Next line also included in match? */
  65. unsigned int sub_p:1; /* (s) print option */
  66. int last_char; /* Last line written by (sw) had no '\n' */
  67. /* GENERAL FIELDS */
  68. char cmd; /* The command char: abcdDgGhHilnNpPqrstwxy:={} */
  69. struct sed_cmd_s *next; /* Next command (linked list, NULL terminated) */
  70. } sed_cmd_t;
  71. static const char *const semicolon_whitespace = "; \n\r\t\v";
  72. struct sed_globals {
  73. /* options */
  74. int be_quiet, regex_type;
  75. FILE *nonstdout;
  76. char *outname, *hold_space;
  77. /* List of input files */
  78. int input_file_count, current_input_file;
  79. FILE **input_file_list;
  80. regmatch_t regmatch[10];
  81. regex_t *previous_regex_ptr;
  82. /* linked list of sed commands */
  83. sed_cmd_t sed_cmd_head, *sed_cmd_tail;
  84. /* Linked list of append lines */
  85. llist_t *append_head;
  86. char *add_cmd_line;
  87. struct pipeline {
  88. char *buf; /* Space to hold string */
  89. int idx; /* Space used */
  90. int len; /* Space allocated */
  91. } pipeline;
  92. } bbg;
  93. #if ENABLE_FEATURE_CLEAN_UP
  94. static void sed_free_and_close_stuff(void)
  95. {
  96. sed_cmd_t *sed_cmd = bbg.sed_cmd_head.next;
  97. llist_free(bbg.append_head, free);
  98. while (sed_cmd) {
  99. sed_cmd_t *sed_cmd_next = sed_cmd->next;
  100. if (sed_cmd->file)
  101. xprint_and_close_file(sed_cmd->file);
  102. if (sed_cmd->beg_match) {
  103. regfree(sed_cmd->beg_match);
  104. free(sed_cmd->beg_match);
  105. }
  106. if (sed_cmd->end_match) {
  107. regfree(sed_cmd->end_match);
  108. free(sed_cmd->end_match);
  109. }
  110. if (sed_cmd->sub_match) {
  111. regfree(sed_cmd->sub_match);
  112. free(sed_cmd->sub_match);
  113. }
  114. free(sed_cmd->string);
  115. free(sed_cmd);
  116. sed_cmd = sed_cmd_next;
  117. }
  118. if (bbg.hold_space) free(bbg.hold_space);
  119. while (bbg.current_input_file < bbg.input_file_count)
  120. fclose(bbg.input_file_list[bbg.current_input_file++]);
  121. }
  122. #else
  123. void sed_free_and_close_stuff(void);
  124. #endif
  125. /* If something bad happens during -i operation, delete temp file */
  126. static void cleanup_outname(void)
  127. {
  128. if (bbg.outname) unlink(bbg.outname);
  129. }
  130. /* strdup, replacing "\n" with '\n', and "\delimiter" with 'delimiter' */
  131. static void parse_escapes(char *dest, char *string, int len, char from, char to)
  132. {
  133. int i = 0;
  134. while (i < len) {
  135. if (string[i] == '\\') {
  136. if (!to || string[i+1] == from) {
  137. *dest++ = to ? to : string[i+1];
  138. i += 2;
  139. continue;
  140. }
  141. *dest++ = string[i++];
  142. }
  143. *dest++ = string[i++];
  144. }
  145. *dest = 0;
  146. }
  147. static char *copy_parsing_escapes(char *string, int len)
  148. {
  149. char *dest = xmalloc(len + 1);
  150. parse_escapes(dest, string, len, 'n', '\n');
  151. return dest;
  152. }
  153. /*
  154. * index_of_next_unescaped_regexp_delim - walks left to right through a string
  155. * beginning at a specified index and returns the index of the next regular
  156. * expression delimiter (typically a forward * slash ('/')) not preceded by
  157. * a backslash ('\'). A negative delimiter disables square bracket checking.
  158. */
  159. static int index_of_next_unescaped_regexp_delim(int delimiter, char *str)
  160. {
  161. int bracket = -1;
  162. int escaped = 0;
  163. int idx = 0;
  164. char ch;
  165. if (delimiter < 0) {
  166. bracket--;
  167. delimiter = -delimiter;
  168. }
  169. for (; (ch = str[idx]); idx++) {
  170. if (bracket >= 0) {
  171. if (ch == ']' && !(bracket == idx - 1 || (bracket == idx - 2
  172. && str[idx - 1] == '^')))
  173. bracket = -1;
  174. } else if (escaped)
  175. escaped = 0;
  176. else if (ch == '\\')
  177. escaped = 1;
  178. else if (bracket == -1 && ch == '[')
  179. bracket = idx;
  180. else if (ch == delimiter)
  181. return idx;
  182. }
  183. /* if we make it to here, we've hit the end of the string */
  184. bb_error_msg_and_die("unmatched '%c'", delimiter);
  185. }
  186. /*
  187. * Returns the index of the third delimiter
  188. */
  189. static int parse_regex_delim(char *cmdstr, char **match, char **replace)
  190. {
  191. char *cmdstr_ptr = cmdstr;
  192. char delimiter;
  193. int idx = 0;
  194. /* verify that the 's' or 'y' is followed by something. That something
  195. * (typically a 'slash') is now our regexp delimiter... */
  196. if (*cmdstr == '\0')
  197. bb_error_msg_and_die("bad format in substitution expression");
  198. delimiter = *cmdstr_ptr++;
  199. /* save the match string */
  200. idx = index_of_next_unescaped_regexp_delim(delimiter, cmdstr_ptr);
  201. *match = copy_parsing_escapes(cmdstr_ptr, idx);
  202. /* save the replacement string */
  203. cmdstr_ptr += idx + 1;
  204. idx = index_of_next_unescaped_regexp_delim(-delimiter, cmdstr_ptr);
  205. *replace = copy_parsing_escapes(cmdstr_ptr, idx);
  206. return ((cmdstr_ptr - cmdstr) + idx);
  207. }
  208. /*
  209. * returns the index in the string just past where the address ends.
  210. */
  211. static int get_address(char *my_str, int *linenum, regex_t ** regex)
  212. {
  213. char *pos = my_str;
  214. if (isdigit(*my_str)) {
  215. *linenum = strtol(my_str, &pos, 10);
  216. /* endstr shouldnt ever equal NULL */
  217. } else if (*my_str == '$') {
  218. *linenum = -1;
  219. pos++;
  220. } else if (*my_str == '/' || *my_str == '\\') {
  221. int next;
  222. char delimiter;
  223. char *temp;
  224. delimiter = '/';
  225. if (*my_str == '\\') delimiter = *++pos;
  226. next = index_of_next_unescaped_regexp_delim(delimiter, ++pos);
  227. temp = copy_parsing_escapes(pos, next);
  228. *regex = xmalloc(sizeof(regex_t));
  229. xregcomp(*regex, temp, bbg.regex_type|REG_NEWLINE);
  230. free(temp);
  231. /* Move position to next character after last delimiter */
  232. pos += (next+1);
  233. }
  234. return pos - my_str;
  235. }
  236. /* Grab a filename. Whitespace at start is skipped, then goes to EOL. */
  237. static int parse_file_cmd(sed_cmd_t *sed_cmd, char *filecmdstr, char **retval)
  238. {
  239. int start = 0, idx, hack = 0;
  240. /* Skip whitespace, then grab filename to end of line */
  241. while (isspace(filecmdstr[start])) start++;
  242. idx = start;
  243. while (filecmdstr[idx] && filecmdstr[idx] != '\n') idx++;
  244. /* If lines glued together, put backslash back. */
  245. if (filecmdstr[idx] == '\n') hack = 1;
  246. if (idx == start)
  247. bb_error_msg_and_die("empty filename");
  248. *retval = xstrndup(filecmdstr+start, idx-start+hack+1);
  249. if (hack) (*retval)[idx] = '\\';
  250. return idx;
  251. }
  252. static int parse_subst_cmd(sed_cmd_t *sed_cmd, char *substr)
  253. {
  254. int cflags = bbg.regex_type;
  255. char *match;
  256. int idx = 0;
  257. /*
  258. * A substitution command should look something like this:
  259. * s/match/replace/ #gIpw
  260. * || | |||
  261. * mandatory optional
  262. */
  263. idx = parse_regex_delim(substr, &match, &sed_cmd->string);
  264. /* determine the number of back references in the match string */
  265. /* Note: we compute this here rather than in the do_subst_command()
  266. * function to save processor time, at the expense of a little more memory
  267. * (4 bits) per sed_cmd */
  268. /* process the flags */
  269. sed_cmd->which_match = 1;
  270. while (substr[++idx]) {
  271. /* Parse match number */
  272. if (isdigit(substr[idx])) {
  273. if (match[0] != '^') {
  274. /* Match 0 treated as all, multiple matches we take the last one. */
  275. char *pos = substr + idx;
  276. /* FIXME: error check? */
  277. sed_cmd->which_match = (unsigned short)strtol(substr+idx, &pos, 10);
  278. idx = pos - substr;
  279. }
  280. continue;
  281. }
  282. /* Skip spaces */
  283. if (isspace(substr[idx])) continue;
  284. switch (substr[idx]) {
  285. /* Replace all occurrences */
  286. case 'g':
  287. if (match[0] != '^') sed_cmd->which_match = 0;
  288. break;
  289. /* Print pattern space */
  290. case 'p':
  291. sed_cmd->sub_p = 1;
  292. break;
  293. /* Write to file */
  294. case 'w':
  295. {
  296. char *temp;
  297. idx += parse_file_cmd(sed_cmd, substr+idx, &temp);
  298. break;
  299. }
  300. /* Ignore case (gnu exension) */
  301. case 'I':
  302. cflags |= REG_ICASE;
  303. break;
  304. /* Comment */
  305. case '#':
  306. while (substr[++idx]) /*skip all*/;
  307. /* Fall through */
  308. /* End of command */
  309. case ';':
  310. case '}':
  311. goto out;
  312. default:
  313. bb_error_msg_and_die("bad option in substitution expression");
  314. }
  315. }
  316. out:
  317. /* compile the match string into a regex */
  318. if (*match != '\0') {
  319. /* If match is empty, we use last regex used at runtime */
  320. sed_cmd->sub_match = xmalloc(sizeof(regex_t));
  321. xregcomp(sed_cmd->sub_match, match, cflags);
  322. }
  323. free(match);
  324. return idx;
  325. }
  326. /*
  327. * Process the commands arguments
  328. */
  329. static char *parse_cmd_args(sed_cmd_t *sed_cmd, char *cmdstr)
  330. {
  331. /* handle (s)ubstitution command */
  332. if (sed_cmd->cmd == 's')
  333. cmdstr += parse_subst_cmd(sed_cmd, cmdstr);
  334. /* handle edit cmds: (a)ppend, (i)nsert, and (c)hange */
  335. else if (strchr("aic", sed_cmd->cmd)) {
  336. if ((sed_cmd->end_line || sed_cmd->end_match) && sed_cmd->cmd != 'c')
  337. bb_error_msg_and_die
  338. ("only a beginning address can be specified for edit commands");
  339. for (;;) {
  340. if (*cmdstr == '\n' || *cmdstr == '\\') {
  341. cmdstr++;
  342. break;
  343. } else if (isspace(*cmdstr))
  344. cmdstr++;
  345. else
  346. break;
  347. }
  348. sed_cmd->string = xstrdup(cmdstr);
  349. parse_escapes(sed_cmd->string, sed_cmd->string, strlen(cmdstr), 0, 0);
  350. cmdstr += strlen(cmdstr);
  351. /* handle file cmds: (r)ead */
  352. } else if (strchr("rw", sed_cmd->cmd)) {
  353. if (sed_cmd->end_line || sed_cmd->end_match)
  354. bb_error_msg_and_die("command only uses one address");
  355. cmdstr += parse_file_cmd(sed_cmd, cmdstr, &sed_cmd->string);
  356. if (sed_cmd->cmd == 'w')
  357. sed_cmd->file = xfopen(sed_cmd->string, "w");
  358. /* handle branch commands */
  359. } else if (strchr(":btT", sed_cmd->cmd)) {
  360. int length;
  361. cmdstr = skip_whitespace(cmdstr);
  362. length = strcspn(cmdstr, semicolon_whitespace);
  363. if (length) {
  364. sed_cmd->string = xstrndup(cmdstr, length);
  365. cmdstr += length;
  366. }
  367. }
  368. /* translation command */
  369. else if (sed_cmd->cmd == 'y') {
  370. char *match, *replace;
  371. int i = cmdstr[0];
  372. cmdstr += parse_regex_delim(cmdstr, &match, &replace)+1;
  373. /* \n already parsed, but \delimiter needs unescaping. */
  374. parse_escapes(match, match, strlen(match), i, i);
  375. parse_escapes(replace, replace, strlen(replace), i, i);
  376. sed_cmd->string = xzalloc((strlen(match) + 1) * 2);
  377. for (i = 0; match[i] && replace[i]; i++) {
  378. sed_cmd->string[i*2] = match[i];
  379. sed_cmd->string[i*2+1] = replace[i];
  380. }
  381. free(match);
  382. free(replace);
  383. }
  384. /* if it wasnt a single-letter command that takes no arguments
  385. * then it must be an invalid command.
  386. */
  387. else if (strchr("dDgGhHlnNpPqx={}", sed_cmd->cmd) == 0) {
  388. bb_error_msg_and_die("unsupported command %c", sed_cmd->cmd);
  389. }
  390. /* give back whatever's left over */
  391. return cmdstr;
  392. }
  393. /* Parse address+command sets, skipping comment lines. */
  394. static void add_cmd(char *cmdstr)
  395. {
  396. sed_cmd_t *sed_cmd;
  397. int temp;
  398. /* Append this line to any unfinished line from last time. */
  399. if (bbg.add_cmd_line) {
  400. cmdstr = xasprintf("%s\n%s", bbg.add_cmd_line, cmdstr);
  401. free(bbg.add_cmd_line);
  402. bbg.add_cmd_line = cmdstr;
  403. }
  404. /* If this line ends with backslash, request next line. */
  405. temp = strlen(cmdstr);
  406. if (temp && cmdstr[temp-1] == '\\') {
  407. if (!bbg.add_cmd_line)
  408. bbg.add_cmd_line = xstrdup(cmdstr);
  409. bbg.add_cmd_line[temp-1] = 0;
  410. return;
  411. }
  412. /* Loop parsing all commands in this line. */
  413. while (*cmdstr) {
  414. /* Skip leading whitespace and semicolons */
  415. cmdstr += strspn(cmdstr, semicolon_whitespace);
  416. /* If no more commands, exit. */
  417. if (!*cmdstr) break;
  418. /* if this is a comment, jump past it and keep going */
  419. if (*cmdstr == '#') {
  420. /* "#n" is the same as using -n on the command line */
  421. if (cmdstr[1] == 'n')
  422. bbg.be_quiet++;
  423. cmdstr = strpbrk(cmdstr, "\n\r");
  424. if (!cmdstr) break;
  425. continue;
  426. }
  427. /* parse the command
  428. * format is: [addr][,addr][!]cmd
  429. * |----||-----||-|
  430. * part1 part2 part3
  431. */
  432. sed_cmd = xzalloc(sizeof(sed_cmd_t));
  433. /* first part (if present) is an address: either a '$', a number or a /regex/ */
  434. cmdstr += get_address(cmdstr, &sed_cmd->beg_line, &sed_cmd->beg_match);
  435. /* second part (if present) will begin with a comma */
  436. if (*cmdstr == ',') {
  437. int idx;
  438. cmdstr++;
  439. idx = get_address(cmdstr, &sed_cmd->end_line, &sed_cmd->end_match);
  440. if (!idx)
  441. bb_error_msg_and_die("no address after comma");
  442. cmdstr += idx;
  443. }
  444. /* skip whitespace before the command */
  445. cmdstr = skip_whitespace(cmdstr);
  446. /* Check for inversion flag */
  447. if (*cmdstr == '!') {
  448. sed_cmd->invert = 1;
  449. cmdstr++;
  450. /* skip whitespace before the command */
  451. cmdstr = skip_whitespace(cmdstr);
  452. }
  453. /* last part (mandatory) will be a command */
  454. if (!*cmdstr)
  455. bb_error_msg_and_die("missing command");
  456. sed_cmd->cmd = *(cmdstr++);
  457. cmdstr = parse_cmd_args(sed_cmd, cmdstr);
  458. /* Add the command to the command array */
  459. bbg.sed_cmd_tail->next = sed_cmd;
  460. bbg.sed_cmd_tail = bbg.sed_cmd_tail->next;
  461. }
  462. /* If we glued multiple lines together, free the memory. */
  463. free(bbg.add_cmd_line);
  464. bbg.add_cmd_line = NULL;
  465. }
  466. /* Append to a string, reallocating memory as necessary. */
  467. #define PIPE_GROW 64
  468. static void pipe_putc(char c)
  469. {
  470. if (bbg.pipeline.idx == bbg.pipeline.len) {
  471. bbg.pipeline.buf = xrealloc(bbg.pipeline.buf,
  472. bbg.pipeline.len + PIPE_GROW);
  473. bbg.pipeline.len += PIPE_GROW;
  474. }
  475. bbg.pipeline.buf[bbg.pipeline.idx++] = c;
  476. }
  477. static void do_subst_w_backrefs(char *line, char *replace)
  478. {
  479. int i,j;
  480. /* go through the replacement string */
  481. for (i = 0; replace[i]; i++) {
  482. /* if we find a backreference (\1, \2, etc.) print the backref'ed * text */
  483. if (replace[i] == '\\') {
  484. unsigned backref = replace[++i] - '0';
  485. if (backref <= 9) {
  486. /* print out the text held in bbg.regmatch[backref] */
  487. if (bbg.regmatch[backref].rm_so != -1) {
  488. j = bbg.regmatch[backref].rm_so;
  489. while (j < bbg.regmatch[backref].rm_eo)
  490. pipe_putc(line[j++]);
  491. }
  492. continue;
  493. }
  494. /* I _think_ it is impossible to get '\' to be
  495. * the last char in replace string. Thus we dont check
  496. * for replace[i] == NUL. (counterexample anyone?) */
  497. /* if we find a backslash escaped character, print the character */
  498. pipe_putc(replace[i]);
  499. continue;
  500. }
  501. /* if we find an unescaped '&' print out the whole matched text. */
  502. if (replace[i] == '&') {
  503. j = bbg.regmatch[0].rm_so;
  504. while (j < bbg.regmatch[0].rm_eo)
  505. pipe_putc(line[j++]);
  506. continue;
  507. }
  508. /* Otherwise just output the character. */
  509. pipe_putc(replace[i]);
  510. }
  511. }
  512. static int do_subst_command(sed_cmd_t *sed_cmd, char **line)
  513. {
  514. char *oldline = *line;
  515. int altered = 0;
  516. int match_count = 0;
  517. regex_t *current_regex;
  518. /* Handle empty regex. */
  519. if (sed_cmd->sub_match == NULL) {
  520. current_regex = bbg.previous_regex_ptr;
  521. if (!current_regex)
  522. bb_error_msg_and_die("no previous regexp");
  523. } else
  524. bbg.previous_regex_ptr = current_regex = sed_cmd->sub_match;
  525. /* Find the first match */
  526. if (REG_NOMATCH == regexec(current_regex, oldline, 10, bbg.regmatch, 0))
  527. return 0;
  528. /* Initialize temporary output buffer. */
  529. bbg.pipeline.buf = xmalloc(PIPE_GROW);
  530. bbg.pipeline.len = PIPE_GROW;
  531. bbg.pipeline.idx = 0;
  532. /* Now loop through, substituting for matches */
  533. do {
  534. int i;
  535. /* Work around bug in glibc regexec, demonstrated by:
  536. echo " a.b" | busybox sed 's [^ .]* x g'
  537. The match_count check is so not to break
  538. echo "hi" | busybox sed 's/^/!/g' */
  539. if (!bbg.regmatch[0].rm_so && !bbg.regmatch[0].rm_eo && match_count) {
  540. pipe_putc(*oldline++);
  541. continue;
  542. }
  543. match_count++;
  544. /* If we aren't interested in this match, output old line to
  545. end of match and continue */
  546. if (sed_cmd->which_match && sed_cmd->which_match != match_count) {
  547. for (i = 0; i < bbg.regmatch[0].rm_eo; i++)
  548. pipe_putc(*oldline++);
  549. continue;
  550. }
  551. /* print everything before the match */
  552. for (i = 0; i < bbg.regmatch[0].rm_so; i++)
  553. pipe_putc(oldline[i]);
  554. /* then print the substitution string */
  555. do_subst_w_backrefs(oldline, sed_cmd->string);
  556. /* advance past the match */
  557. oldline += bbg.regmatch[0].rm_eo;
  558. /* flag that something has changed */
  559. altered++;
  560. /* if we're not doing this globally, get out now */
  561. if (sed_cmd->which_match) break;
  562. } while (*oldline && (regexec(current_regex, oldline, 10, bbg.regmatch, 0) != REG_NOMATCH));
  563. /* Copy rest of string into output pipeline */
  564. while (*oldline)
  565. pipe_putc(*oldline++);
  566. pipe_putc(0);
  567. free(*line);
  568. *line = bbg.pipeline.buf;
  569. return altered;
  570. }
  571. /* Set command pointer to point to this label. (Does not handle null label.) */
  572. static sed_cmd_t *branch_to(char *label)
  573. {
  574. sed_cmd_t *sed_cmd;
  575. for (sed_cmd = bbg.sed_cmd_head.next; sed_cmd; sed_cmd = sed_cmd->next) {
  576. if (sed_cmd->cmd == ':' && sed_cmd->string && !strcmp(sed_cmd->string, label)) {
  577. return sed_cmd;
  578. }
  579. }
  580. bb_error_msg_and_die("can't find label for jump to '%s'", label);
  581. }
  582. static void append(char *s)
  583. {
  584. llist_add_to_end(&bbg.append_head, xstrdup(s));
  585. }
  586. static void flush_append(void)
  587. {
  588. char *data;
  589. /* Output appended lines. */
  590. while ((data = (char *)llist_pop(&bbg.append_head))) {
  591. fprintf(bbg.nonstdout, "%s\n", data);
  592. free(data);
  593. }
  594. }
  595. static void add_input_file(FILE *file)
  596. {
  597. bbg.input_file_list = xrealloc(bbg.input_file_list,
  598. (bbg.input_file_count + 1) * sizeof(FILE *));
  599. bbg.input_file_list[bbg.input_file_count++] = file;
  600. }
  601. /* Get next line of input from bbg.input_file_list, flushing append buffer and
  602. * noting if we ran out of files without a newline on the last line we read.
  603. */
  604. static char *get_next_line(int *last_char)
  605. {
  606. char *temp = NULL;
  607. int len, lc;
  608. lc = 0;
  609. flush_append();
  610. while (bbg.current_input_file < bbg.input_file_count) {
  611. /* Read line up to a newline or NUL byte, inclusive,
  612. * return malloc'ed char[]. length of the chunk read
  613. * is stored in len. NULL if EOF/error */
  614. temp = bb_get_chunk_from_file(
  615. bbg.input_file_list[bbg.current_input_file], &len);
  616. if (temp) {
  617. /* len > 0 here, it's ok to do temp[len-1] */
  618. char c = temp[len-1];
  619. if (c == '\n' || c == '\0') {
  620. temp[len-1] = '\0';
  621. lc |= (unsigned char)c;
  622. break;
  623. }
  624. /* will be returned if last line in the file
  625. * doesn't end with either '\n' or '\0' */
  626. lc |= 0x100;
  627. break;
  628. }
  629. /* Close this file and advance to next one */
  630. fclose(bbg.input_file_list[bbg.current_input_file++]);
  631. /* "this is the first line from new input file" */
  632. lc |= 0x200;
  633. }
  634. *last_char = lc;
  635. return temp;
  636. }
  637. /* Output line of text. */
  638. /* Note:
  639. * The tricks with 0x200 and last_puts_char are there to emulate gnu sed.
  640. * Without them, we had this:
  641. * echo -n thingy >z1
  642. * echo -n again >z2
  643. * >znull
  644. * sed "s/i/z/" z1 z2 znull | hexdump -vC
  645. * output:
  646. * gnu sed 4.1.5:
  647. * 00000000 74 68 7a 6e 67 79 0a 61 67 61 7a 6e |thzngy.agazn|
  648. * bbox:
  649. * 00000000 74 68 7a 6e 67 79 61 67 61 7a 6e |thzngyagazn|
  650. */
  651. static int puts_maybe_newline(char *s, FILE *file, int prev_last_char, int last_char)
  652. {
  653. static char last_puts_char;
  654. /* Is this a first line from new file
  655. * and old file didn't end with '\n'? */
  656. if ((last_char & 0x200) && last_puts_char != '\n') {
  657. fputc('\n', file);
  658. last_puts_char = '\n';
  659. }
  660. fputs(s, file);
  661. /* why 'x'? - just something which is not '\n' */
  662. if (s[0])
  663. last_puts_char = 'x';
  664. if (!(last_char & 0x100)) { /* had trailing '\n' or '\0'? */
  665. last_char &= 0xff;
  666. fputc(last_char, file);
  667. last_puts_char = last_char;
  668. }
  669. if (ferror(file)) {
  670. xfunc_error_retval = 4; /* It's what gnu sed exits with... */
  671. bb_error_msg_and_die(bb_msg_write_error);
  672. }
  673. return last_char;
  674. }
  675. #define sed_puts(s, n) \
  676. (prev_last_char = puts_maybe_newline(s, bbg.nonstdout, prev_last_char, n))
  677. /* Process all the lines in all the files */
  678. static void process_files(void)
  679. {
  680. char *pattern_space, *next_line;
  681. int linenum = 0, prev_last_char = 0;
  682. int last_char, next_last_char = 0;
  683. sed_cmd_t *sed_cmd;
  684. int substituted;
  685. /* Prime the pump */
  686. next_line = get_next_line(&next_last_char);
  687. /* go through every line in each file */
  688. again:
  689. substituted = 0;
  690. /* Advance to next line. Stop if out of lines. */
  691. pattern_space = next_line;
  692. if (!pattern_space) return;
  693. last_char = next_last_char;
  694. /* Read one line in advance so we can act on the last line,
  695. * the '$' address */
  696. next_line = get_next_line(&next_last_char);
  697. linenum++;
  698. restart:
  699. /* for every line, go through all the commands */
  700. for (sed_cmd = bbg.sed_cmd_head.next; sed_cmd; sed_cmd = sed_cmd->next) {
  701. int old_matched, matched;
  702. old_matched = sed_cmd->in_match;
  703. /* Determine if this command matches this line: */
  704. /* Are we continuing a previous multi-line match? */
  705. sed_cmd->in_match = sed_cmd->in_match
  706. /* Or is no range necessary? */
  707. || (!sed_cmd->beg_line && !sed_cmd->end_line
  708. && !sed_cmd->beg_match && !sed_cmd->end_match)
  709. /* Or did we match the start of a numerical range? */
  710. || (sed_cmd->beg_line > 0 && (sed_cmd->beg_line == linenum))
  711. /* Or does this line match our begin address regex? */
  712. || (sed_cmd->beg_match &&
  713. !regexec(sed_cmd->beg_match, pattern_space, 0, NULL, 0))
  714. /* Or did we match last line of input? */
  715. || (sed_cmd->beg_line == -1 && next_line == NULL);
  716. /* Snapshot the value */
  717. matched = sed_cmd->in_match;
  718. /* Is this line the end of the current match? */
  719. if (matched) {
  720. sed_cmd->in_match = !(
  721. /* has the ending line come, or is this a single address command? */
  722. (sed_cmd->end_line ?
  723. sed_cmd->end_line == -1 ?
  724. !next_line
  725. : (sed_cmd->end_line <= linenum)
  726. : !sed_cmd->end_match
  727. )
  728. /* or does this line matches our last address regex */
  729. || (sed_cmd->end_match && old_matched
  730. && (regexec(sed_cmd->end_match,
  731. pattern_space, 0, NULL, 0) == 0))
  732. );
  733. }
  734. /* Skip blocks of commands we didn't match. */
  735. if (sed_cmd->cmd == '{') {
  736. if (sed_cmd->invert ? matched : !matched)
  737. while (sed_cmd && sed_cmd->cmd != '}')
  738. sed_cmd = sed_cmd->next;
  739. if (!sed_cmd) bb_error_msg_and_die("unterminated {");
  740. continue;
  741. }
  742. /* Okay, so did this line match? */
  743. if (sed_cmd->invert ? !matched : matched) {
  744. /* Update last used regex in case a blank substitute BRE is found */
  745. if (sed_cmd->beg_match) {
  746. bbg.previous_regex_ptr = sed_cmd->beg_match;
  747. }
  748. /* actual sedding */
  749. switch (sed_cmd->cmd) {
  750. /* Print line number */
  751. case '=':
  752. fprintf(bbg.nonstdout, "%d\n", linenum);
  753. break;
  754. /* Write the current pattern space up to the first newline */
  755. case 'P':
  756. {
  757. char *tmp = strchr(pattern_space, '\n');
  758. if (tmp) {
  759. *tmp = '\0';
  760. sed_puts(pattern_space, 1);
  761. *tmp = '\n';
  762. break;
  763. }
  764. /* Fall Through */
  765. }
  766. /* Write the current pattern space to output */
  767. case 'p':
  768. sed_puts(pattern_space, last_char);
  769. break;
  770. /* Delete up through first newline */
  771. case 'D':
  772. {
  773. char *tmp = strchr(pattern_space, '\n');
  774. if (tmp) {
  775. tmp = xstrdup(tmp+1);
  776. free(pattern_space);
  777. pattern_space = tmp;
  778. goto restart;
  779. }
  780. }
  781. /* discard this line. */
  782. case 'd':
  783. goto discard_line;
  784. /* Substitute with regex */
  785. case 's':
  786. if (!do_subst_command(sed_cmd, &pattern_space))
  787. break;
  788. substituted |= 1;
  789. /* handle p option */
  790. if (sed_cmd->sub_p)
  791. sed_puts(pattern_space, last_char);
  792. /* handle w option */
  793. if (sed_cmd->file)
  794. sed_cmd->last_char = puts_maybe_newline(
  795. pattern_space, sed_cmd->file,
  796. sed_cmd->last_char, last_char);
  797. break;
  798. /* Append line to linked list to be printed later */
  799. case 'a':
  800. append(sed_cmd->string);
  801. break;
  802. /* Insert text before this line */
  803. case 'i':
  804. sed_puts(sed_cmd->string, 1);
  805. break;
  806. /* Cut and paste text (replace) */
  807. case 'c':
  808. /* Only triggers on last line of a matching range. */
  809. if (!sed_cmd->in_match)
  810. sed_puts(sed_cmd->string, 0);
  811. goto discard_line;
  812. /* Read file, append contents to output */
  813. case 'r':
  814. {
  815. FILE *rfile;
  816. rfile = fopen(sed_cmd->string, "r");
  817. if (rfile) {
  818. char *line;
  819. while ((line = xmalloc_getline(rfile))
  820. != NULL)
  821. append(line);
  822. xprint_and_close_file(rfile);
  823. }
  824. break;
  825. }
  826. /* Write pattern space to file. */
  827. case 'w':
  828. sed_cmd->last_char = puts_maybe_newline(
  829. pattern_space, sed_cmd->file,
  830. sed_cmd->last_char, last_char);
  831. break;
  832. /* Read next line from input */
  833. case 'n':
  834. if (!bbg.be_quiet)
  835. sed_puts(pattern_space, last_char);
  836. if (next_line) {
  837. free(pattern_space);
  838. pattern_space = next_line;
  839. last_char = next_last_char;
  840. next_line = get_next_line(&next_last_char);
  841. linenum++;
  842. break;
  843. }
  844. /* fall through */
  845. /* Quit. End of script, end of input. */
  846. case 'q':
  847. /* Exit the outer while loop */
  848. free(next_line);
  849. next_line = NULL;
  850. goto discard_commands;
  851. /* Append the next line to the current line */
  852. case 'N':
  853. {
  854. int len;
  855. /* If no next line, jump to end of script and exit. */
  856. if (next_line == NULL) {
  857. /* Jump to end of script and exit */
  858. free(next_line);
  859. next_line = NULL;
  860. goto discard_line;
  861. /* append next_line, read new next_line. */
  862. }
  863. len = strlen(pattern_space);
  864. pattern_space = realloc(pattern_space, len + strlen(next_line) + 2);
  865. pattern_space[len] = '\n';
  866. strcpy(pattern_space + len+1, next_line);
  867. last_char = next_last_char;
  868. next_line = get_next_line(&next_last_char);
  869. linenum++;
  870. break;
  871. }
  872. /* Test/branch if substitution occurred */
  873. case 't':
  874. if (!substituted) break;
  875. substituted = 0;
  876. /* Fall through */
  877. /* Test/branch if substitution didn't occur */
  878. case 'T':
  879. if (substituted) break;
  880. /* Fall through */
  881. /* Branch to label */
  882. case 'b':
  883. if (!sed_cmd->string) goto discard_commands;
  884. else sed_cmd = branch_to(sed_cmd->string);
  885. break;
  886. /* Transliterate characters */
  887. case 'y':
  888. {
  889. int i, j;
  890. for (i = 0; pattern_space[i]; i++) {
  891. for (j = 0; sed_cmd->string[j]; j += 2) {
  892. if (pattern_space[i] == sed_cmd->string[j]) {
  893. pattern_space[i] = sed_cmd->string[j + 1];
  894. break;
  895. }
  896. }
  897. }
  898. break;
  899. }
  900. case 'g': /* Replace pattern space with hold space */
  901. free(pattern_space);
  902. pattern_space = xstrdup(bbg.hold_space ? bbg.hold_space : "");
  903. break;
  904. case 'G': /* Append newline and hold space to pattern space */
  905. {
  906. int pattern_space_size = 2;
  907. int hold_space_size = 0;
  908. if (pattern_space)
  909. pattern_space_size += strlen(pattern_space);
  910. if (bbg.hold_space)
  911. hold_space_size = strlen(bbg.hold_space);
  912. pattern_space = xrealloc(pattern_space,
  913. pattern_space_size + hold_space_size);
  914. if (pattern_space_size == 2)
  915. pattern_space[0] = 0;
  916. strcat(pattern_space, "\n");
  917. if (bbg.hold_space)
  918. strcat(pattern_space, bbg.hold_space);
  919. last_char = '\n';
  920. break;
  921. }
  922. case 'h': /* Replace hold space with pattern space */
  923. free(bbg.hold_space);
  924. bbg.hold_space = xstrdup(pattern_space);
  925. break;
  926. case 'H': /* Append newline and pattern space to hold space */
  927. {
  928. int hold_space_size = 2;
  929. int pattern_space_size = 0;
  930. if (bbg.hold_space)
  931. hold_space_size += strlen(bbg.hold_space);
  932. if (pattern_space)
  933. pattern_space_size = strlen(pattern_space);
  934. bbg.hold_space = xrealloc(bbg.hold_space,
  935. hold_space_size + pattern_space_size);
  936. if (hold_space_size == 2)
  937. *bbg.hold_space = 0;
  938. strcat(bbg.hold_space, "\n");
  939. if (pattern_space)
  940. strcat(bbg.hold_space, pattern_space);
  941. break;
  942. }
  943. case 'x': /* Exchange hold and pattern space */
  944. {
  945. char *tmp = pattern_space;
  946. pattern_space = bbg.hold_space ? : xzalloc(1);
  947. last_char = '\n';
  948. bbg.hold_space = tmp;
  949. break;
  950. }
  951. }
  952. }
  953. }
  954. /*
  955. * exit point from sedding...
  956. */
  957. discard_commands:
  958. /* we will print the line unless we were told to be quiet ('-n')
  959. or if the line was suppressed (ala 'd'elete) */
  960. if (!bbg.be_quiet) sed_puts(pattern_space, last_char);
  961. /* Delete and such jump here. */
  962. discard_line:
  963. flush_append();
  964. free(pattern_space);
  965. goto again;
  966. }
  967. /* It is possible to have a command line argument with embedded
  968. newlines. This counts as multiple command lines. */
  969. static void add_cmd_block(char *cmdstr)
  970. {
  971. int go = 1;
  972. char *temp = xstrdup(cmdstr), *temp2 = temp;
  973. while (go) {
  974. int len = strcspn(temp2, "\n");
  975. if (!temp2[len]) go = 0;
  976. else temp2[len] = 0;
  977. add_cmd(temp2);
  978. temp2 += len+1;
  979. }
  980. free(temp);
  981. }
  982. static void add_cmds_link(llist_t *opt_e)
  983. {
  984. if (!opt_e) return;
  985. add_cmds_link(opt_e->link);
  986. add_cmd_block(opt_e->data);
  987. free(opt_e);
  988. }
  989. static void add_files_link(llist_t *opt_f)
  990. {
  991. char *line;
  992. FILE *cmdfile;
  993. if (!opt_f) return;
  994. add_files_link(opt_f->link);
  995. cmdfile = xfopen(opt_f->data, "r");
  996. while ((line = xmalloc_getline(cmdfile)) != NULL) {
  997. add_cmd(line);
  998. free(line);
  999. }
  1000. xprint_and_close_file(cmdfile);
  1001. free(opt_f);
  1002. }
  1003. int sed_main(int argc, char **argv)
  1004. {
  1005. enum {
  1006. OPT_in_place = 1 << 0,
  1007. };
  1008. unsigned opt;
  1009. llist_t *opt_e, *opt_f;
  1010. int status = EXIT_SUCCESS;
  1011. bbg.sed_cmd_tail = &bbg.sed_cmd_head;
  1012. /* destroy command strings on exit */
  1013. if (ENABLE_FEATURE_CLEAN_UP) atexit(sed_free_and_close_stuff);
  1014. /* Lie to autoconf when it starts asking stupid questions. */
  1015. if (argc == 2 && !strcmp(argv[1], "--version")) {
  1016. puts("This is not GNU sed version 4.0");
  1017. return 0;
  1018. }
  1019. /* do normal option parsing */
  1020. opt_e = opt_f = NULL;
  1021. opt_complementary = "e::f::" /* can occur multiple times */
  1022. "nn"; /* count -n */
  1023. opt = getopt32(argc, argv, "irne:f:", &opt_e, &opt_f,
  1024. &bbg.be_quiet); /* counter for -n */
  1025. argc -= optind;
  1026. argv += optind;
  1027. if (opt & OPT_in_place) { // -i
  1028. atexit(cleanup_outname);
  1029. }
  1030. if (opt & 0x2) bbg.regex_type |= REG_EXTENDED; // -r
  1031. //if (opt & 0x4) bbg.be_quiet++; // -n
  1032. if (opt & 0x8) { // -e
  1033. /* getopt32 reverses order of arguments, handle it */
  1034. add_cmds_link(opt_e);
  1035. }
  1036. if (opt & 0x10) { // -f
  1037. /* getopt32 reverses order of arguments, handle it */
  1038. add_files_link(opt_f);
  1039. }
  1040. /* if we didn't get a pattern from -e or -f, use argv[0] */
  1041. if (!(opt & 0x18)) {
  1042. if (!argc)
  1043. bb_show_usage();
  1044. add_cmd_block(*argv++);
  1045. argc--;
  1046. }
  1047. /* Flush any unfinished commands. */
  1048. add_cmd("");
  1049. /* By default, we write to stdout */
  1050. bbg.nonstdout = stdout;
  1051. /* argv[0..(argc-1)] should be names of file to process. If no
  1052. * files were specified or '-' was specified, take input from stdin.
  1053. * Otherwise, we process all the files specified. */
  1054. if (argv[0] == NULL) {
  1055. if (opt & OPT_in_place)
  1056. bb_error_msg_and_die(bb_msg_requires_arg, "-i");
  1057. add_input_file(stdin);
  1058. process_files();
  1059. } else {
  1060. int i;
  1061. FILE *file;
  1062. for (i = 0; i < argc; i++) {
  1063. struct stat statbuf;
  1064. int nonstdoutfd;
  1065. if (LONE_DASH(argv[i]) && !(opt & OPT_in_place)) {
  1066. add_input_file(stdin);
  1067. process_files();
  1068. continue;
  1069. }
  1070. file = fopen_or_warn(argv[i], "r");
  1071. if (!file) {
  1072. status = EXIT_FAILURE;
  1073. continue;
  1074. }
  1075. if (!(opt & OPT_in_place)) {
  1076. add_input_file(file);
  1077. continue;
  1078. }
  1079. bbg.outname = xasprintf("%sXXXXXX", argv[i]);
  1080. nonstdoutfd = mkstemp(bbg.outname);
  1081. if (-1 == nonstdoutfd)
  1082. bb_error_msg_and_die("no temp file");
  1083. bbg.nonstdout = fdopen(nonstdoutfd, "w");
  1084. /* Set permissions of output file */
  1085. fstat(fileno(file), &statbuf);
  1086. fchmod(nonstdoutfd, statbuf.st_mode);
  1087. add_input_file(file);
  1088. process_files();
  1089. fclose(bbg.nonstdout);
  1090. bbg.nonstdout = stdout;
  1091. /* unlink(argv[i]); */
  1092. // FIXME: error check / message?
  1093. rename(bbg.outname, argv[i]);
  1094. free(bbg.outname);
  1095. bbg.outname = 0;
  1096. }
  1097. if (bbg.input_file_count > bbg.current_input_file)
  1098. process_files();
  1099. }
  1100. return status;
  1101. }