sed.c 33 KB

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