PageRenderTime 54ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/sed/compile.c

https://github.com/aosm/text_cmds
C | 933 lines | 742 code | 49 blank | 142 comment | 297 complexity | b7ac6694414f520015929c4568405886 MD5 | raw file
Possible License(s): GPL-2.0
  1. /*-
  2. * Copyright (c) 1992 Diomidis Spinellis.
  3. * Copyright (c) 1992, 1993
  4. * The Regents of the University of California. All rights reserved.
  5. *
  6. * This code is derived from software contributed to Berkeley by
  7. * Diomidis Spinellis of Imperial College, University of London.
  8. *
  9. * Redistribution and use in source and binary forms, with or without
  10. * modification, are permitted provided that the following conditions
  11. * are met:
  12. * 1. Redistributions of source code must retain the above copyright
  13. * notice, this list of conditions and the following disclaimer.
  14. * 2. Redistributions in binary form must reproduce the above copyright
  15. * notice, this list of conditions and the following disclaimer in the
  16. * documentation and/or other materials provided with the distribution.
  17. * 4. Neither the name of the University nor the names of its contributors
  18. * may be used to endorse or promote products derived from this software
  19. * without specific prior written permission.
  20. *
  21. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  22. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  23. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  24. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  25. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  26. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  27. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  28. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  29. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  30. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  31. * SUCH DAMAGE.
  32. */
  33. #include <sys/cdefs.h>
  34. __FBSDID("$FreeBSD: src/usr.bin/sed/compile.c,v 1.28 2005/08/04 10:05:11 dds Exp $");
  35. #ifndef lint
  36. static const char sccsid[] = "@(#)compile.c 8.1 (Berkeley) 6/6/93";
  37. #endif
  38. #include <sys/types.h>
  39. #include <sys/stat.h>
  40. #include <ctype.h>
  41. #include <err.h>
  42. #include <errno.h>
  43. #include <fcntl.h>
  44. #include <limits.h>
  45. #include <regex.h>
  46. #include <stdio.h>
  47. #include <stdlib.h>
  48. #include <string.h>
  49. #include <wchar.h>
  50. #include "defs.h"
  51. #include "extern.h"
  52. #ifdef __APPLE__
  53. #include <get_compat.h>
  54. #else
  55. #define COMPAT_MODE(a,b) (1)
  56. #endif /* __APPLE__ */
  57. #define LHSZ 128
  58. #define LHMASK (LHSZ - 1)
  59. static struct labhash {
  60. struct labhash *lh_next;
  61. u_int lh_hash;
  62. struct s_command *lh_cmd;
  63. int lh_ref;
  64. } *labels[LHSZ];
  65. static char *compile_addr(char *, struct s_addr *);
  66. static char *compile_ccl(char **, char *);
  67. static char *compile_delimited(char *, char *, int);
  68. static char *compile_flags(char *, struct s_subst *);
  69. static char *compile_re(char *, regex_t **);
  70. static char *compile_subst(char *, struct s_subst *);
  71. static char *compile_text(void);
  72. static char *compile_tr(char *, struct s_tr **);
  73. static struct s_command
  74. **compile_stream(struct s_command **);
  75. static char *duptoeol(char *, const char *);
  76. static void enterlabel(struct s_command *);
  77. static struct s_command
  78. *findlabel(char *);
  79. static void fixuplabel(struct s_command *, struct s_command *);
  80. static void uselabel(void);
  81. /*
  82. * Command specification. This is used to drive the command parser.
  83. */
  84. struct s_format {
  85. char code; /* Command code */
  86. int naddr; /* Number of address args */
  87. enum e_args args; /* Argument type */
  88. };
  89. static struct s_format cmd_fmts[] = {
  90. {'{', 2, GROUP},
  91. {'}', 0, ENDGROUP},
  92. {'a', 1, TEXT},
  93. {'b', 2, BRANCH},
  94. {'c', 2, TEXT},
  95. {'d', 2, EMPTY},
  96. {'D', 2, EMPTY},
  97. {'g', 2, EMPTY},
  98. {'G', 2, EMPTY},
  99. {'h', 2, EMPTY},
  100. {'H', 2, EMPTY},
  101. {'i', 1, TEXT},
  102. {'l', 2, EMPTY},
  103. {'n', 2, EMPTY},
  104. {'N', 2, EMPTY},
  105. {'p', 2, EMPTY},
  106. {'P', 2, EMPTY},
  107. {'q', 1, EMPTY},
  108. {'r', 1, RFILE},
  109. {'s', 2, SUBST},
  110. {'t', 2, BRANCH},
  111. {'w', 2, WFILE},
  112. {'x', 2, EMPTY},
  113. {'y', 2, TR},
  114. {'!', 2, NONSEL},
  115. {':', 0, LABEL},
  116. {'#', 0, COMMENT},
  117. {'=', 1, EMPTY},
  118. {'\0', 0, COMMENT},
  119. };
  120. /* The compiled program. */
  121. struct s_command *prog;
  122. /*
  123. * Compile the program into prog.
  124. * Initialise appends.
  125. */
  126. void
  127. compile(void)
  128. {
  129. *compile_stream(&prog) = NULL;
  130. fixuplabel(prog, NULL);
  131. uselabel();
  132. if (appendnum == 0)
  133. appends = NULL;
  134. else if ((appends = malloc(sizeof(struct s_appends) * appendnum)) ==
  135. NULL)
  136. err(1, "malloc");
  137. if ((match = malloc((maxnsub + 1) * sizeof(regmatch_t))) == NULL)
  138. err(1, "malloc");
  139. }
  140. #define EATSPACE() do { \
  141. if (p) \
  142. while (*p && isspace((unsigned char)*p)) \
  143. p++; \
  144. } while (0)
  145. static struct s_command **
  146. compile_stream(struct s_command **link)
  147. {
  148. char *p;
  149. static char lbuf[_POSIX2_LINE_MAX + 1]; /* To save stack */
  150. struct s_command *cmd, *cmd2, *stack;
  151. struct s_format *fp;
  152. int naddr; /* Number of addresses */
  153. stack = 0;
  154. for (;;) {
  155. if ((p = cu_fgets(lbuf, sizeof(lbuf), NULL)) == NULL) {
  156. if (stack != 0)
  157. errx(1, "%lu: %s: unexpected EOF (pending }'s)",
  158. linenum, fname);
  159. return (link);
  160. }
  161. semicolon: EATSPACE();
  162. if (p) {
  163. if (*p == '#' || *p == '\0')
  164. continue;
  165. else if (*p == ';') {
  166. p++;
  167. goto semicolon;
  168. }
  169. }
  170. if ((*link = cmd = malloc(sizeof(struct s_command))) == NULL)
  171. err(1, "malloc");
  172. link = &cmd->next;
  173. cmd->nonsel = cmd->inrange = 0;
  174. /* First parse the addresses */
  175. naddr = 0;
  176. /* Valid characters to start an address */
  177. #define addrchar(c) (strchr("0123456789/\\$", (c)))
  178. if (addrchar(*p)) {
  179. naddr++;
  180. if ((cmd->a1 = malloc(sizeof(struct s_addr))) == NULL)
  181. err(1, "malloc");
  182. p = compile_addr(p, cmd->a1);
  183. EATSPACE(); /* EXTENSION */
  184. if (*p == ',') {
  185. p++;
  186. EATSPACE(); /* EXTENSION */
  187. naddr++;
  188. if ((cmd->a2 = malloc(sizeof(struct s_addr)))
  189. == NULL)
  190. err(1, "malloc");
  191. p = compile_addr(p, cmd->a2);
  192. EATSPACE();
  193. } else
  194. cmd->a2 = 0;
  195. } else
  196. cmd->a1 = cmd->a2 = 0;
  197. nonsel: /* Now parse the command */
  198. if (!*p)
  199. errx(1, "%lu: %s: command expected", linenum, fname);
  200. cmd->code = *p;
  201. for (fp = cmd_fmts; fp->code; fp++)
  202. if (fp->code == *p)
  203. break;
  204. if (!fp->code)
  205. errx(1, "%lu: %s: invalid command code %c", linenum, fname, *p);
  206. if (naddr > fp->naddr)
  207. errx(1,
  208. "%lu: %s: command %c expects up to %d address(es), found %d",
  209. linenum, fname, *p, fp->naddr, naddr);
  210. switch (fp->args) {
  211. case NONSEL: /* ! */
  212. p++;
  213. EATSPACE();
  214. cmd->nonsel = ! cmd->nonsel;
  215. goto nonsel;
  216. case GROUP: /* { */
  217. p++;
  218. EATSPACE();
  219. cmd->next = stack;
  220. stack = cmd;
  221. link = &cmd->u.c;
  222. if (*p)
  223. goto semicolon;
  224. break;
  225. case ENDGROUP:
  226. /*
  227. * Short-circuit command processing, since end of
  228. * group is really just a noop.
  229. */
  230. cmd->nonsel = 1;
  231. if (stack == 0)
  232. errx(1, "%lu: %s: unexpected }", linenum, fname);
  233. cmd2 = stack;
  234. stack = cmd2->next;
  235. cmd2->next = cmd;
  236. /*FALLTHROUGH*/
  237. case EMPTY: /* d D g G h H l n N p P q x = \0 */
  238. p++;
  239. EATSPACE();
  240. if (*p == ';') {
  241. p++;
  242. link = &cmd->next;
  243. goto semicolon;
  244. }
  245. if (*p)
  246. errx(1, "%lu: %s: extra characters at the end of %c command",
  247. linenum, fname, cmd->code);
  248. break;
  249. case TEXT: /* a c i */
  250. p++;
  251. EATSPACE();
  252. if (*p != '\\')
  253. errx(1,
  254. "%lu: %s: command %c expects \\ followed by text", linenum, fname, cmd->code);
  255. p++;
  256. EATSPACE();
  257. if (*p)
  258. errx(1,
  259. "%lu: %s: extra characters after \\ at the end of %c command",
  260. linenum, fname, cmd->code);
  261. cmd->t = compile_text();
  262. break;
  263. case COMMENT: /* \0 # */
  264. break;
  265. case WFILE: /* w */
  266. p++;
  267. EATSPACE();
  268. if (*p == '\0')
  269. errx(1, "%lu: %s: filename expected", linenum, fname);
  270. cmd->t = duptoeol(p, "w command");
  271. if (aflag)
  272. cmd->u.fd = -1;
  273. else if ((cmd->u.fd = open(p,
  274. O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
  275. DEFFILEMODE)) == -1)
  276. err(1, "%s", p);
  277. break;
  278. case RFILE: /* r */
  279. p++;
  280. EATSPACE();
  281. if (*p == '\0')
  282. errx(1, "%lu: %s: filename expected", linenum, fname);
  283. else
  284. cmd->t = duptoeol(p, "read command");
  285. break;
  286. case BRANCH: /* b t */
  287. p++;
  288. EATSPACE();
  289. if (*p == '\0')
  290. cmd->t = NULL;
  291. else
  292. cmd->t = duptoeol(p, "branch");
  293. break;
  294. case LABEL: /* : */
  295. p++;
  296. EATSPACE();
  297. cmd->t = duptoeol(p, "label");
  298. if (strlen(p) == 0)
  299. errx(1, "%lu: %s: empty label", linenum, fname);
  300. enterlabel(cmd);
  301. break;
  302. case SUBST: /* s */
  303. p++;
  304. if (*p == '\0' || *p == '\\')
  305. errx(1,
  306. "%lu: %s: substitute pattern can not be delimited by newline or backslash",
  307. linenum, fname);
  308. if ((cmd->u.s = malloc(sizeof(struct s_subst))) == NULL)
  309. err(1, "malloc");
  310. p = compile_re(p, &cmd->u.s->re);
  311. if (p == NULL)
  312. errx(1,
  313. "%lu: %s: unterminated substitute pattern", linenum, fname);
  314. --p;
  315. p = compile_subst(p, cmd->u.s);
  316. p = compile_flags(p, cmd->u.s);
  317. EATSPACE();
  318. if (*p == ';') {
  319. p++;
  320. link = &cmd->next;
  321. goto semicolon;
  322. }
  323. break;
  324. case TR: /* y */
  325. p++;
  326. p = compile_tr(p, &cmd->u.y);
  327. EATSPACE();
  328. if (*p == ';') {
  329. p++;
  330. link = &cmd->next;
  331. goto semicolon;
  332. }
  333. if (*p)
  334. errx(1,
  335. "%lu: %s: extra text at the end of a transform command", linenum, fname);
  336. break;
  337. }
  338. }
  339. }
  340. /*
  341. * Get a delimited string. P points to the delimeter of the string; d points
  342. * to a buffer area. Newline and delimiter escapes are processed; other
  343. * escapes are ignored.
  344. *
  345. * Returns a pointer to the first character after the final delimiter or NULL
  346. * in the case of a non-terminated string. The character array d is filled
  347. * with the processed string.
  348. */
  349. static char *
  350. compile_delimited(char *p, char *d, int is_tr)
  351. {
  352. char c;
  353. c = *p++;
  354. if (c == '\0')
  355. return (NULL);
  356. else if (c == '\\')
  357. errx(1, "%lu: %s: \\ can not be used as a string delimiter",
  358. linenum, fname);
  359. else if (c == '\n')
  360. errx(1, "%lu: %s: newline can not be used as a string delimiter",
  361. linenum, fname);
  362. while (*p) {
  363. if (*p == '[' && c != *p) {
  364. if ((d = compile_ccl(&p, d)) == NULL)
  365. errx(1, "%lu: %s: unbalanced brackets ([])", linenum, fname);
  366. continue;
  367. } else if (*p == '\\' && p[1] == '[') {
  368. *d++ = *p++;
  369. } else if (*p == '\\' && p[1] == c)
  370. p++;
  371. else if (*p == '\\' && p[1] == 'n') {
  372. *d++ = '\n';
  373. p += 2;
  374. continue;
  375. } else if (*p == '\\' && p[1] == '\\')
  376. if (COMPAT_MODE("bin/sed", "Unix2003") && is_tr) {
  377. p++;
  378. } else {
  379. *d++ = *p++;
  380. }
  381. else if (*p == c) {
  382. *d = '\0';
  383. return (p + 1);
  384. }
  385. *d++ = *p++;
  386. }
  387. return (NULL);
  388. }
  389. /* compile_ccl: expand a POSIX character class */
  390. static char *
  391. compile_ccl(char **sp, char *t)
  392. {
  393. int c, d;
  394. char *s = *sp;
  395. *t++ = *s++;
  396. if (*s == '^')
  397. *t++ = *s++;
  398. if (*s == ']')
  399. *t++ = *s++;
  400. for (; *s && (*t = *s) != ']'; s++, t++)
  401. if (*s == '[' && ((d = *(s+1)) == '.' || d == ':' || d == '=')) {
  402. *++t = *++s, t++, s++;
  403. for (c = *s; (*t = *s) != ']' || c != d; s++, t++)
  404. if ((c = *s) == '\0')
  405. return NULL;
  406. }
  407. return (*s == ']') ? *sp = ++s, ++t : NULL;
  408. }
  409. /*
  410. * Get a regular expression. P points to the delimiter of the regular
  411. * expression; repp points to the address of a regexp pointer. Newline
  412. * and delimiter escapes are processed; other escapes are ignored.
  413. * Returns a pointer to the first character after the final delimiter
  414. * or NULL in the case of a non terminated regular expression. The regexp
  415. * pointer is set to the compiled regular expression.
  416. * Cflags are passed to regcomp.
  417. */
  418. static char *
  419. compile_re(char *p, regex_t **repp)
  420. {
  421. int eval;
  422. char re[_POSIX2_LINE_MAX + 1];
  423. p = compile_delimited(p, re, 0);
  424. if (p && strlen(re) == 0) {
  425. *repp = NULL;
  426. return (p);
  427. }
  428. if ((*repp = malloc(sizeof(regex_t))) == NULL)
  429. err(1, "malloc");
  430. if (p && (eval = regcomp(*repp, re, rflags)) != 0)
  431. errx(1, "%lu: %s: RE error: %s",
  432. linenum, fname, strregerror(eval, *repp));
  433. if (maxnsub < (*repp)->re_nsub)
  434. maxnsub = (*repp)->re_nsub;
  435. return (p);
  436. }
  437. /*
  438. * Compile the substitution string of a regular expression and set res to
  439. * point to a saved copy of it. Nsub is the number of parenthesized regular
  440. * expressions.
  441. */
  442. static char *
  443. compile_subst(char *p, struct s_subst *s)
  444. {
  445. static char lbuf[_POSIX2_LINE_MAX + 1];
  446. int asize, size;
  447. u_char ref;
  448. char c, *text, *op, *sp;
  449. int more = 1, sawesc = 0;
  450. c = *p++; /* Terminator character */
  451. if (c == '\0')
  452. return (NULL);
  453. s->maxbref = 0;
  454. s->linenum = linenum;
  455. asize = 2 * _POSIX2_LINE_MAX + 1;
  456. if ((text = malloc(asize)) == NULL)
  457. err(1, "malloc");
  458. size = 0;
  459. do {
  460. op = sp = text + size;
  461. for (; *p; p++) {
  462. if (*p == '\\' || sawesc) {
  463. /*
  464. * If this is a continuation from the last
  465. * buffer, we won't have a character to
  466. * skip over.
  467. */
  468. if (sawesc)
  469. sawesc = 0;
  470. else
  471. p++;
  472. if (*p == '\0') {
  473. /*
  474. * This escaped character is continued
  475. * in the next part of the line. Note
  476. * this fact, then cause the loop to
  477. * exit w/ normal EOL case and reenter
  478. * above with the new buffer.
  479. */
  480. sawesc = 1;
  481. p--;
  482. continue;
  483. } else if (strchr("123456789", *p) != NULL) {
  484. *sp++ = '\\';
  485. ref = *p - '0';
  486. if (s->re != NULL &&
  487. ref > s->re->re_nsub)
  488. errx(1, "%lu: %s: \\%c not defined in the RE",
  489. linenum, fname, *p);
  490. if (s->maxbref < ref)
  491. s->maxbref = ref;
  492. } else if (*p == '&' || *p == '\\')
  493. *sp++ = '\\';
  494. } else if (*p == c) {
  495. if (*++p == '\0' && more) {
  496. if (cu_fgets(lbuf, sizeof(lbuf), &more))
  497. p = lbuf;
  498. }
  499. *sp++ = '\0';
  500. size += sp - op;
  501. if ((s->new = realloc(text, size)) == NULL)
  502. err(1, "realloc");
  503. return (p);
  504. } else if (*p == '\n') {
  505. errx(1,
  506. "%lu: %s: unescaped newline inside substitute pattern", linenum, fname);
  507. /* NOTREACHED */
  508. }
  509. *sp++ = *p;
  510. }
  511. size += sp - op;
  512. if (asize - size < _POSIX2_LINE_MAX + 1) {
  513. asize *= 2;
  514. if ((text = realloc(text, asize)) == NULL)
  515. err(1, "realloc");
  516. }
  517. } while (cu_fgets(p = lbuf, sizeof(lbuf), &more));
  518. errx(1, "%lu: %s: unterminated substitute in regular expression",
  519. linenum, fname);
  520. /* NOTREACHED */
  521. }
  522. /*
  523. * Compile the flags of the s command
  524. */
  525. static char *
  526. compile_flags(char *p, struct s_subst *s)
  527. {
  528. int gn; /* True if we have seen g or n */
  529. unsigned long nval;
  530. char wfile[_POSIX2_LINE_MAX + 1], *q;
  531. s->n = 1; /* Default */
  532. s->p = 0;
  533. s->wfile = NULL;
  534. s->wfd = -1;
  535. for (gn = 0;;) {
  536. EATSPACE(); /* EXTENSION */
  537. switch (*p) {
  538. case 'g':
  539. if (gn)
  540. errx(1,
  541. "%lu: %s: more than one number or 'g' in substitute flags", linenum, fname);
  542. gn = 1;
  543. s->n = 0;
  544. break;
  545. case '\0':
  546. case '\n':
  547. case ';':
  548. return (p);
  549. case 'p':
  550. s->p = 1;
  551. break;
  552. case '1': case '2': case '3':
  553. case '4': case '5': case '6':
  554. case '7': case '8': case '9':
  555. if (gn)
  556. errx(1,
  557. "%lu: %s: more than one number or 'g' in substitute flags", linenum, fname);
  558. gn = 1;
  559. errno = 0;
  560. nval = strtol(p, &p, 10);
  561. if (errno == ERANGE || nval > INT_MAX)
  562. errx(1,
  563. "%lu: %s: overflow in the 'N' substitute flag", linenum, fname);
  564. s->n = nval;
  565. p--;
  566. break;
  567. case 'w':
  568. p++;
  569. #ifdef HISTORIC_PRACTICE
  570. if (*p != ' ') {
  571. warnx("%lu: %s: space missing before w wfile", linenum, fname);
  572. return (p);
  573. }
  574. #endif
  575. EATSPACE();
  576. q = wfile;
  577. while (*p) {
  578. if (*p == '\n')
  579. break;
  580. *q++ = *p++;
  581. }
  582. *q = '\0';
  583. if (q == wfile)
  584. errx(1, "%lu: %s: no wfile specified", linenum, fname);
  585. s->wfile = strdup(wfile);
  586. if (!aflag && (s->wfd = open(wfile,
  587. O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
  588. DEFFILEMODE)) == -1)
  589. err(1, "%s", wfile);
  590. return (p);
  591. default:
  592. errx(1, "%lu: %s: bad flag in substitute command: '%c'",
  593. linenum, fname, *p);
  594. break;
  595. }
  596. p++;
  597. }
  598. }
  599. /*
  600. * Compile a translation set of strings into a lookup table.
  601. */
  602. static char *
  603. compile_tr(char *p, struct s_tr **py)
  604. {
  605. struct s_tr *y;
  606. int i;
  607. const char *op, *np;
  608. char old[_POSIX2_LINE_MAX + 1];
  609. char new[_POSIX2_LINE_MAX + 1];
  610. size_t oclen, oldlen, nclen, newlen;
  611. mbstate_t mbs1, mbs2;
  612. if ((*py = y = malloc(sizeof(*y))) == NULL)
  613. err(1, NULL);
  614. y->multis = NULL;
  615. y->nmultis = 0;
  616. if (*p == '\0' || *p == '\\')
  617. errx(1,
  618. "%lu: %s: transform pattern can not be delimited by newline or backslash",
  619. linenum, fname);
  620. p = compile_delimited(p, old, 1);
  621. if (p == NULL)
  622. errx(1, "%lu: %s: unterminated transform source string",
  623. linenum, fname);
  624. p = compile_delimited(p - 1, new, 1);
  625. if (p == NULL)
  626. errx(1, "%lu: %s: unterminated transform target string",
  627. linenum, fname);
  628. EATSPACE();
  629. op = old;
  630. oldlen = mbsrtowcs(NULL, &op, 0, NULL);
  631. if (oldlen == (size_t)-1)
  632. err(1, NULL);
  633. np = new;
  634. newlen = mbsrtowcs(NULL, &np, 0, NULL);
  635. if (newlen == (size_t)-1)
  636. err(1, NULL);
  637. if (newlen != oldlen)
  638. errx(1, "%lu: %s: transform strings are not the same length",
  639. linenum, fname);
  640. if (MB_CUR_MAX == 1) {
  641. /*
  642. * The single-byte encoding case is easy: generate a
  643. * lookup table.
  644. */
  645. for (i = 0; i <= UCHAR_MAX; i++)
  646. y->bytetab[i] = (char)i;
  647. for (; *op; op++, np++)
  648. y->bytetab[(u_char)*op] = *np;
  649. } else {
  650. /*
  651. * Multi-byte encoding case: generate a lookup table as
  652. * above, but only for single-byte characters. The first
  653. * bytes of multi-byte characters have their lookup table
  654. * entries set to 0, which causes do_tr() to search through
  655. * an auxiliary vector of multi-byte mappings.
  656. */
  657. memset(&mbs1, 0, sizeof(mbs1));
  658. memset(&mbs2, 0, sizeof(mbs2));
  659. for (i = 0; i <= UCHAR_MAX; i++)
  660. y->bytetab[i] = (btowc(i) != WEOF) ? i : 0;
  661. while (*op != '\0') {
  662. oclen = mbrlen(op, MB_LEN_MAX, &mbs1);
  663. if (oclen == (size_t)-1 || oclen == (size_t)-2)
  664. errc(1, EILSEQ, NULL);
  665. nclen = mbrlen(np, MB_LEN_MAX, &mbs2);
  666. if (nclen == (size_t)-1 || nclen == (size_t)-2)
  667. errc(1, EILSEQ, NULL);
  668. if (oclen == 1 && nclen == 1)
  669. y->bytetab[(u_char)*op] = *np;
  670. else {
  671. y->bytetab[(u_char)*op] = 0;
  672. y->multis = realloc(y->multis,
  673. (y->nmultis + 1) * sizeof(*y->multis));
  674. if (y->multis == NULL)
  675. err(1, NULL);
  676. i = y->nmultis++;
  677. y->multis[i].fromlen = oclen;
  678. memcpy(y->multis[i].from, op, oclen);
  679. y->multis[i].tolen = nclen;
  680. memcpy(y->multis[i].to, np, nclen);
  681. }
  682. op += oclen;
  683. np += nclen;
  684. }
  685. }
  686. return (p);
  687. }
  688. /*
  689. * Compile the text following an a or i command.
  690. */
  691. static char *
  692. compile_text(void)
  693. {
  694. int asize, esc_nl, size;
  695. char *text, *p, *op, *s;
  696. char lbuf[_POSIX2_LINE_MAX + 1];
  697. asize = 2 * _POSIX2_LINE_MAX + 1;
  698. if ((text = malloc(asize)) == NULL)
  699. err(1, "malloc");
  700. size = 0;
  701. while (cu_fgets(lbuf, sizeof(lbuf), NULL)) {
  702. op = s = text + size;
  703. p = lbuf;
  704. EATSPACE();
  705. for (esc_nl = 0; *p != '\0'; p++) {
  706. if (*p == '\\' && p[1] != '\0' && *++p == '\n')
  707. esc_nl = 1;
  708. *s++ = *p;
  709. }
  710. size += s - op;
  711. if (!esc_nl) {
  712. *s = '\0';
  713. break;
  714. }
  715. if (asize - size < _POSIX2_LINE_MAX + 1) {
  716. asize *= 2;
  717. if ((text = realloc(text, asize)) == NULL)
  718. err(1, "realloc");
  719. }
  720. }
  721. text[size] = '\0';
  722. if ((p = realloc(text, size + 1)) == NULL)
  723. err(1, "realloc");
  724. return (p);
  725. }
  726. /*
  727. * Get an address and return a pointer to the first character after
  728. * it. Fill the structure pointed to according to the address.
  729. */
  730. static char *
  731. compile_addr(char *p, struct s_addr *a)
  732. {
  733. char *end;
  734. switch (*p) {
  735. case '\\': /* Context address */
  736. ++p;
  737. /* FALLTHROUGH */
  738. case '/': /* Context address */
  739. p = compile_re(p, &a->u.r);
  740. if (p == NULL)
  741. errx(1, "%lu: %s: unterminated regular expression", linenum, fname);
  742. a->type = AT_RE;
  743. return (p);
  744. case '$': /* Last line */
  745. a->type = AT_LAST;
  746. return (p + 1);
  747. /* Line number */
  748. case '0': case '1': case '2': case '3': case '4':
  749. case '5': case '6': case '7': case '8': case '9':
  750. a->type = AT_LINE;
  751. a->u.l = strtol(p, &end, 10);
  752. return (end);
  753. default:
  754. errx(1, "%lu: %s: expected context address", linenum, fname);
  755. return (NULL);
  756. }
  757. }
  758. /*
  759. * duptoeol --
  760. * Return a copy of all the characters up to \n or \0.
  761. */
  762. static char *
  763. duptoeol(char *s, const char *ctype)
  764. {
  765. size_t len;
  766. int ws;
  767. char *p, *start;
  768. ws = 0;
  769. for (start = s; *s != '\0' && *s != '\n'; ++s)
  770. ws = isspace((unsigned char)*s);
  771. *s = '\0';
  772. if (ws)
  773. warnx("%lu: %s: whitespace after %s", linenum, fname, ctype);
  774. len = s - start + 1;
  775. if ((p = malloc(len)) == NULL)
  776. err(1, "malloc");
  777. return (memmove(p, start, len));
  778. }
  779. /*
  780. * Convert goto label names to addresses, and count a and r commands, in
  781. * the given subset of the script. Free the memory used by labels in b
  782. * and t commands (but not by :).
  783. *
  784. * TODO: Remove } nodes
  785. */
  786. static void
  787. fixuplabel(struct s_command *cp, struct s_command *end)
  788. {
  789. for (; cp != end; cp = cp->next)
  790. switch (cp->code) {
  791. case 'a':
  792. case 'r':
  793. appendnum++;
  794. break;
  795. case 'b':
  796. case 't':
  797. /* Resolve branch target. */
  798. if (cp->t == NULL) {
  799. cp->u.c = NULL;
  800. break;
  801. }
  802. if ((cp->u.c = findlabel(cp->t)) == NULL)
  803. errx(1, "%lu: %s: undefined label '%s'", linenum, fname, cp->t);
  804. free(cp->t);
  805. break;
  806. case '{':
  807. /* Do interior commands. */
  808. fixuplabel(cp->u.c, cp->next);
  809. break;
  810. }
  811. }
  812. /*
  813. * Associate the given command label for later lookup.
  814. */
  815. static void
  816. enterlabel(struct s_command *cp)
  817. {
  818. struct labhash **lhp, *lh;
  819. u_char *p;
  820. u_int h, c;
  821. for (h = 0, p = (u_char *)cp->t; (c = *p) != 0; p++)
  822. h = (h << 5) + h + c;
  823. lhp = &labels[h & LHMASK];
  824. for (lh = *lhp; lh != NULL; lh = lh->lh_next)
  825. if (lh->lh_hash == h && strcmp(cp->t, lh->lh_cmd->t) == 0)
  826. errx(1, "%lu: %s: duplicate label '%s'", linenum, fname, cp->t);
  827. if ((lh = malloc(sizeof *lh)) == NULL)
  828. err(1, "malloc");
  829. lh->lh_next = *lhp;
  830. lh->lh_hash = h;
  831. lh->lh_cmd = cp;
  832. lh->lh_ref = 0;
  833. *lhp = lh;
  834. }
  835. /*
  836. * Find the label contained in the command l in the command linked
  837. * list cp. L is excluded from the search. Return NULL if not found.
  838. */
  839. static struct s_command *
  840. findlabel(char *name)
  841. {
  842. struct labhash *lh;
  843. u_char *p;
  844. u_int h, c;
  845. for (h = 0, p = (u_char *)name; (c = *p) != 0; p++)
  846. h = (h << 5) + h + c;
  847. for (lh = labels[h & LHMASK]; lh != NULL; lh = lh->lh_next) {
  848. if (lh->lh_hash == h && strcmp(name, lh->lh_cmd->t) == 0) {
  849. lh->lh_ref = 1;
  850. return (lh->lh_cmd);
  851. }
  852. }
  853. return (NULL);
  854. }
  855. /*
  856. * Warn about any unused labels. As a side effect, release the label hash
  857. * table space.
  858. */
  859. static void
  860. uselabel(void)
  861. {
  862. struct labhash *lh, *next;
  863. int i;
  864. for (i = 0; i < LHSZ; i++) {
  865. for (lh = labels[i]; lh != NULL; lh = next) {
  866. next = lh->lh_next;
  867. /*
  868. * The following exists only to pass VSC test 101, which expects
  869. * stderr to be empty. The standard actually says:
  870. *
  871. * "Implementors are encouraged to provide warning messages about
  872. * labels that are never used or jumps to labels that do not exist."
  873. */
  874. if (COMPAT_MODE("bin/sed", "Unix2003")) {
  875. free(lh);
  876. continue;
  877. }
  878. if (!lh->lh_ref)
  879. warnx("%lu: %s: unused label '%s'",
  880. linenum, fname, lh->lh_cmd->t);
  881. free(lh);
  882. }
  883. }
  884. }