sed.c 32 KB

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