sed.c 37 KB

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