PageRenderTime 59ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/amanda/tags/3_1_0_mac01/gnulib/regcomp.c

#
C | 2263 lines | 1787 code | 190 blank | 286 comment | 512 complexity | 9748506f8e4cb1963a6668f77af7e158 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. /* Extended regular expression matching and search library.
  2. Copyright (C) 2002,2003,2004,2005,2006,2007,2008,2009
  3. Free Software Foundation, Inc.
  4. This file is part of the GNU C Library.
  5. Contributed by Isamu Hasegawa <isamu@yamato.ibm.com>.
  6. This program is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2, or (at your option)
  9. any later version.
  10. This program is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License along
  15. with this program; if not, write to the Free Software Foundation,
  16. Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
  17. static reg_errcode_t re_compile_internal (regex_t *preg, const char * pattern,
  18. size_t length, reg_syntax_t syntax);
  19. static void re_compile_fastmap_iter (regex_t *bufp,
  20. const re_dfastate_t *init_state,
  21. char *fastmap);
  22. static reg_errcode_t init_dfa (re_dfa_t *dfa, size_t pat_len);
  23. #ifdef RE_ENABLE_I18N
  24. static void free_charset (re_charset_t *cset);
  25. #endif /* RE_ENABLE_I18N */
  26. static void free_workarea_compile (regex_t *preg);
  27. static reg_errcode_t create_initial_state (re_dfa_t *dfa);
  28. #ifdef RE_ENABLE_I18N
  29. static void optimize_utf8 (re_dfa_t *dfa);
  30. #endif
  31. static reg_errcode_t analyze (regex_t *preg);
  32. static reg_errcode_t preorder (bin_tree_t *root,
  33. reg_errcode_t (fn (void *, bin_tree_t *)),
  34. void *extra);
  35. static reg_errcode_t postorder (bin_tree_t *root,
  36. reg_errcode_t (fn (void *, bin_tree_t *)),
  37. void *extra);
  38. static reg_errcode_t optimize_subexps (void *extra, bin_tree_t *node);
  39. static reg_errcode_t lower_subexps (void *extra, bin_tree_t *node);
  40. static bin_tree_t *lower_subexp (reg_errcode_t *err, regex_t *preg,
  41. bin_tree_t *node);
  42. static reg_errcode_t calc_first (void *extra, bin_tree_t *node);
  43. static reg_errcode_t calc_next (void *extra, bin_tree_t *node);
  44. static reg_errcode_t link_nfa_nodes (void *extra, bin_tree_t *node);
  45. static Idx duplicate_node (re_dfa_t *dfa, Idx org_idx, unsigned int constraint);
  46. static Idx search_duplicated_node (const re_dfa_t *dfa, Idx org_node,
  47. unsigned int constraint);
  48. static reg_errcode_t calc_eclosure (re_dfa_t *dfa);
  49. static reg_errcode_t calc_eclosure_iter (re_node_set *new_set, re_dfa_t *dfa,
  50. Idx node, bool root);
  51. static reg_errcode_t calc_inveclosure (re_dfa_t *dfa);
  52. static Idx fetch_number (re_string_t *input, re_token_t *token,
  53. reg_syntax_t syntax);
  54. static int peek_token (re_token_t *token, re_string_t *input,
  55. reg_syntax_t syntax) internal_function;
  56. static bin_tree_t *parse (re_string_t *regexp, regex_t *preg,
  57. reg_syntax_t syntax, reg_errcode_t *err);
  58. static bin_tree_t *parse_reg_exp (re_string_t *regexp, regex_t *preg,
  59. re_token_t *token, reg_syntax_t syntax,
  60. Idx nest, reg_errcode_t *err);
  61. static bin_tree_t *parse_branch (re_string_t *regexp, regex_t *preg,
  62. re_token_t *token, reg_syntax_t syntax,
  63. Idx nest, reg_errcode_t *err);
  64. static bin_tree_t *parse_expression (re_string_t *regexp, regex_t *preg,
  65. re_token_t *token, reg_syntax_t syntax,
  66. Idx nest, reg_errcode_t *err);
  67. static bin_tree_t *parse_sub_exp (re_string_t *regexp, regex_t *preg,
  68. re_token_t *token, reg_syntax_t syntax,
  69. Idx nest, reg_errcode_t *err);
  70. static bin_tree_t *parse_dup_op (bin_tree_t *dup_elem, re_string_t *regexp,
  71. re_dfa_t *dfa, re_token_t *token,
  72. reg_syntax_t syntax, reg_errcode_t *err);
  73. static bin_tree_t *parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa,
  74. re_token_t *token, reg_syntax_t syntax,
  75. reg_errcode_t *err);
  76. static reg_errcode_t parse_bracket_element (bracket_elem_t *elem,
  77. re_string_t *regexp,
  78. re_token_t *token, int token_len,
  79. re_dfa_t *dfa,
  80. reg_syntax_t syntax,
  81. bool accept_hyphen);
  82. static reg_errcode_t parse_bracket_symbol (bracket_elem_t *elem,
  83. re_string_t *regexp,
  84. re_token_t *token);
  85. #ifdef RE_ENABLE_I18N
  86. static reg_errcode_t build_equiv_class (bitset_t sbcset,
  87. re_charset_t *mbcset,
  88. Idx *equiv_class_alloc,
  89. const unsigned char *name);
  90. static reg_errcode_t build_charclass (RE_TRANSLATE_TYPE trans,
  91. bitset_t sbcset,
  92. re_charset_t *mbcset,
  93. Idx *char_class_alloc,
  94. const unsigned char *class_name,
  95. reg_syntax_t syntax);
  96. #else /* not RE_ENABLE_I18N */
  97. static reg_errcode_t build_equiv_class (bitset_t sbcset,
  98. const unsigned char *name);
  99. static reg_errcode_t build_charclass (RE_TRANSLATE_TYPE trans,
  100. bitset_t sbcset,
  101. const unsigned char *class_name,
  102. reg_syntax_t syntax);
  103. #endif /* not RE_ENABLE_I18N */
  104. static bin_tree_t *build_charclass_op (re_dfa_t *dfa,
  105. RE_TRANSLATE_TYPE trans,
  106. const unsigned char *class_name,
  107. const unsigned char *extra,
  108. bool non_match, reg_errcode_t *err);
  109. static bin_tree_t *create_tree (re_dfa_t *dfa,
  110. bin_tree_t *left, bin_tree_t *right,
  111. re_token_type_t type);
  112. static bin_tree_t *create_token_tree (re_dfa_t *dfa,
  113. bin_tree_t *left, bin_tree_t *right,
  114. const re_token_t *token);
  115. static bin_tree_t *duplicate_tree (const bin_tree_t *src, re_dfa_t *dfa);
  116. static void free_token (re_token_t *node);
  117. static reg_errcode_t free_tree (void *extra, bin_tree_t *node);
  118. static reg_errcode_t mark_opt_subexp (void *extra, bin_tree_t *node);
  119. /* This table gives an error message for each of the error codes listed
  120. in regex.h. Obviously the order here has to be same as there.
  121. POSIX doesn't require that we do anything for REG_NOERROR,
  122. but why not be nice? */
  123. static const char __re_error_msgid[] =
  124. {
  125. #define REG_NOERROR_IDX 0
  126. gettext_noop ("Success") /* REG_NOERROR */
  127. "\0"
  128. #define REG_NOMATCH_IDX (REG_NOERROR_IDX + sizeof "Success")
  129. gettext_noop ("No match") /* REG_NOMATCH */
  130. "\0"
  131. #define REG_BADPAT_IDX (REG_NOMATCH_IDX + sizeof "No match")
  132. gettext_noop ("Invalid regular expression") /* REG_BADPAT */
  133. "\0"
  134. #define REG_ECOLLATE_IDX (REG_BADPAT_IDX + sizeof "Invalid regular expression")
  135. gettext_noop ("Invalid collation character") /* REG_ECOLLATE */
  136. "\0"
  137. #define REG_ECTYPE_IDX (REG_ECOLLATE_IDX + sizeof "Invalid collation character")
  138. gettext_noop ("Invalid character class name") /* REG_ECTYPE */
  139. "\0"
  140. #define REG_EESCAPE_IDX (REG_ECTYPE_IDX + sizeof "Invalid character class name")
  141. gettext_noop ("Trailing backslash") /* REG_EESCAPE */
  142. "\0"
  143. #define REG_ESUBREG_IDX (REG_EESCAPE_IDX + sizeof "Trailing backslash")
  144. gettext_noop ("Invalid back reference") /* REG_ESUBREG */
  145. "\0"
  146. #define REG_EBRACK_IDX (REG_ESUBREG_IDX + sizeof "Invalid back reference")
  147. gettext_noop ("Unmatched [ or [^") /* REG_EBRACK */
  148. "\0"
  149. #define REG_EPAREN_IDX (REG_EBRACK_IDX + sizeof "Unmatched [ or [^")
  150. gettext_noop ("Unmatched ( or \\(") /* REG_EPAREN */
  151. "\0"
  152. #define REG_EBRACE_IDX (REG_EPAREN_IDX + sizeof "Unmatched ( or \\(")
  153. gettext_noop ("Unmatched \\{") /* REG_EBRACE */
  154. "\0"
  155. #define REG_BADBR_IDX (REG_EBRACE_IDX + sizeof "Unmatched \\{")
  156. gettext_noop ("Invalid content of \\{\\}") /* REG_BADBR */
  157. "\0"
  158. #define REG_ERANGE_IDX (REG_BADBR_IDX + sizeof "Invalid content of \\{\\}")
  159. gettext_noop ("Invalid range end") /* REG_ERANGE */
  160. "\0"
  161. #define REG_ESPACE_IDX (REG_ERANGE_IDX + sizeof "Invalid range end")
  162. gettext_noop ("Memory exhausted") /* REG_ESPACE */
  163. "\0"
  164. #define REG_BADRPT_IDX (REG_ESPACE_IDX + sizeof "Memory exhausted")
  165. gettext_noop ("Invalid preceding regular expression") /* REG_BADRPT */
  166. "\0"
  167. #define REG_EEND_IDX (REG_BADRPT_IDX + sizeof "Invalid preceding regular expression")
  168. gettext_noop ("Premature end of regular expression") /* REG_EEND */
  169. "\0"
  170. #define REG_ESIZE_IDX (REG_EEND_IDX + sizeof "Premature end of regular expression")
  171. gettext_noop ("Regular expression too big") /* REG_ESIZE */
  172. "\0"
  173. #define REG_ERPAREN_IDX (REG_ESIZE_IDX + sizeof "Regular expression too big")
  174. gettext_noop ("Unmatched ) or \\)") /* REG_ERPAREN */
  175. };
  176. static const size_t __re_error_msgid_idx[] =
  177. {
  178. REG_NOERROR_IDX,
  179. REG_NOMATCH_IDX,
  180. REG_BADPAT_IDX,
  181. REG_ECOLLATE_IDX,
  182. REG_ECTYPE_IDX,
  183. REG_EESCAPE_IDX,
  184. REG_ESUBREG_IDX,
  185. REG_EBRACK_IDX,
  186. REG_EPAREN_IDX,
  187. REG_EBRACE_IDX,
  188. REG_BADBR_IDX,
  189. REG_ERANGE_IDX,
  190. REG_ESPACE_IDX,
  191. REG_BADRPT_IDX,
  192. REG_EEND_IDX,
  193. REG_ESIZE_IDX,
  194. REG_ERPAREN_IDX
  195. };
  196. /* Entry points for GNU code. */
  197. /* re_compile_pattern is the GNU regular expression compiler: it
  198. compiles PATTERN (of length LENGTH) and puts the result in BUFP.
  199. Returns 0 if the pattern was valid, otherwise an error string.
  200. Assumes the `allocated' (and perhaps `buffer') and `translate' fields
  201. are set in BUFP on entry. */
  202. #ifdef _LIBC
  203. const char *
  204. re_compile_pattern (pattern, length, bufp)
  205. const char *pattern;
  206. size_t length;
  207. struct re_pattern_buffer *bufp;
  208. #else /* size_t might promote */
  209. const char *
  210. re_compile_pattern (const char *pattern, size_t length,
  211. struct re_pattern_buffer *bufp)
  212. #endif
  213. {
  214. reg_errcode_t ret;
  215. /* And GNU code determines whether or not to get register information
  216. by passing null for the REGS argument to re_match, etc., not by
  217. setting no_sub, unless RE_NO_SUB is set. */
  218. bufp->no_sub = !!(re_syntax_options & RE_NO_SUB);
  219. /* Match anchors at newline. */
  220. bufp->newline_anchor = 1;
  221. ret = re_compile_internal (bufp, pattern, length, re_syntax_options);
  222. if (!ret)
  223. return NULL;
  224. return gettext (__re_error_msgid + __re_error_msgid_idx[(int) ret]);
  225. }
  226. #ifdef _LIBC
  227. weak_alias (__re_compile_pattern, re_compile_pattern)
  228. #endif
  229. /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
  230. also be assigned to arbitrarily: each pattern buffer stores its own
  231. syntax, so it can be changed between regex compilations. */
  232. /* This has no initializer because initialized variables in Emacs
  233. become read-only after dumping. */
  234. reg_syntax_t re_syntax_options;
  235. /* Specify the precise syntax of regexps for compilation. This provides
  236. for compatibility for various utilities which historically have
  237. different, incompatible syntaxes.
  238. The argument SYNTAX is a bit mask comprised of the various bits
  239. defined in regex.h. We return the old syntax. */
  240. reg_syntax_t
  241. re_set_syntax (syntax)
  242. reg_syntax_t syntax;
  243. {
  244. reg_syntax_t ret = re_syntax_options;
  245. re_syntax_options = syntax;
  246. return ret;
  247. }
  248. #ifdef _LIBC
  249. weak_alias (__re_set_syntax, re_set_syntax)
  250. #endif
  251. int
  252. re_compile_fastmap (bufp)
  253. struct re_pattern_buffer *bufp;
  254. {
  255. re_dfa_t *dfa = (re_dfa_t *) bufp->buffer;
  256. char *fastmap = bufp->fastmap;
  257. memset (fastmap, '\0', sizeof (char) * SBC_MAX);
  258. re_compile_fastmap_iter (bufp, dfa->init_state, fastmap);
  259. if (dfa->init_state != dfa->init_state_word)
  260. re_compile_fastmap_iter (bufp, dfa->init_state_word, fastmap);
  261. if (dfa->init_state != dfa->init_state_nl)
  262. re_compile_fastmap_iter (bufp, dfa->init_state_nl, fastmap);
  263. if (dfa->init_state != dfa->init_state_begbuf)
  264. re_compile_fastmap_iter (bufp, dfa->init_state_begbuf, fastmap);
  265. bufp->fastmap_accurate = 1;
  266. return 0;
  267. }
  268. #ifdef _LIBC
  269. weak_alias (__re_compile_fastmap, re_compile_fastmap)
  270. #endif
  271. static inline void
  272. __attribute ((always_inline))
  273. re_set_fastmap (char *fastmap, bool icase, int ch)
  274. {
  275. fastmap[ch] = 1;
  276. if (icase)
  277. fastmap[tolower (ch)] = 1;
  278. }
  279. /* Helper function for re_compile_fastmap.
  280. Compile fastmap for the initial_state INIT_STATE. */
  281. static void
  282. re_compile_fastmap_iter (regex_t *bufp, const re_dfastate_t *init_state,
  283. char *fastmap)
  284. {
  285. re_dfa_t *dfa = (re_dfa_t *) bufp->buffer;
  286. Idx node_cnt;
  287. bool icase = (dfa->mb_cur_max == 1 && (bufp->syntax & RE_ICASE));
  288. for (node_cnt = 0; node_cnt < init_state->nodes.nelem; ++node_cnt)
  289. {
  290. Idx node = init_state->nodes.elems[node_cnt];
  291. re_token_type_t type = dfa->nodes[node].type;
  292. if (type == CHARACTER)
  293. {
  294. re_set_fastmap (fastmap, icase, dfa->nodes[node].opr.c);
  295. #ifdef RE_ENABLE_I18N
  296. if ((bufp->syntax & RE_ICASE) && dfa->mb_cur_max > 1)
  297. {
  298. unsigned char buf[MB_LEN_MAX];
  299. unsigned char *p;
  300. wchar_t wc;
  301. mbstate_t state;
  302. p = buf;
  303. *p++ = dfa->nodes[node].opr.c;
  304. while (++node < dfa->nodes_len
  305. && dfa->nodes[node].type == CHARACTER
  306. && dfa->nodes[node].mb_partial)
  307. *p++ = dfa->nodes[node].opr.c;
  308. memset (&state, '\0', sizeof (state));
  309. if (__mbrtowc (&wc, (const char *) buf, p - buf,
  310. &state) == p - buf
  311. && (__wcrtomb ((char *) buf, towlower (wc), &state)
  312. != (size_t) -1))
  313. re_set_fastmap (fastmap, false, buf[0]);
  314. }
  315. #endif
  316. }
  317. else if (type == SIMPLE_BRACKET)
  318. {
  319. int i, ch;
  320. for (i = 0, ch = 0; i < BITSET_WORDS; ++i)
  321. {
  322. int j;
  323. bitset_word_t w = dfa->nodes[node].opr.sbcset[i];
  324. for (j = 0; j < BITSET_WORD_BITS; ++j, ++ch)
  325. if (w & ((bitset_word_t) 1 << j))
  326. re_set_fastmap (fastmap, icase, ch);
  327. }
  328. }
  329. #ifdef RE_ENABLE_I18N
  330. else if (type == COMPLEX_BRACKET)
  331. {
  332. re_charset_t *cset = dfa->nodes[node].opr.mbcset;
  333. Idx i;
  334. # ifdef _LIBC
  335. /* See if we have to try all bytes which start multiple collation
  336. elements.
  337. e.g. In da_DK, we want to catch 'a' since "aa" is a valid
  338. collation element, and don't catch 'b' since 'b' is
  339. the only collation element which starts from 'b' (and
  340. it is caught by SIMPLE_BRACKET). */
  341. if (_NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES) != 0
  342. && (cset->ncoll_syms || cset->nranges))
  343. {
  344. const int32_t *table = (const int32_t *)
  345. _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
  346. for (i = 0; i < SBC_MAX; ++i)
  347. if (table[i] < 0)
  348. re_set_fastmap (fastmap, icase, i);
  349. }
  350. # endif /* _LIBC */
  351. /* See if we have to start the match at all multibyte characters,
  352. i.e. where we would not find an invalid sequence. This only
  353. applies to multibyte character sets; for single byte character
  354. sets, the SIMPLE_BRACKET again suffices. */
  355. if (dfa->mb_cur_max > 1
  356. && (cset->nchar_classes || cset->non_match
  357. # ifdef _LIBC
  358. || cset->nequiv_classes
  359. # endif /* _LIBC */
  360. ))
  361. {
  362. unsigned char c = 0;
  363. do
  364. {
  365. mbstate_t mbs;
  366. memset (&mbs, 0, sizeof (mbs));
  367. if (__mbrtowc (NULL, (char *) &c, 1, &mbs) == (size_t) -2)
  368. re_set_fastmap (fastmap, false, (int) c);
  369. }
  370. while (++c != 0);
  371. }
  372. else
  373. {
  374. /* ... Else catch all bytes which can start the mbchars. */
  375. for (i = 0; i < cset->nmbchars; ++i)
  376. {
  377. char buf[256];
  378. mbstate_t state;
  379. memset (&state, '\0', sizeof (state));
  380. if (__wcrtomb (buf, cset->mbchars[i], &state) != (size_t) -1)
  381. re_set_fastmap (fastmap, icase, *(unsigned char *) buf);
  382. if ((bufp->syntax & RE_ICASE) && dfa->mb_cur_max > 1)
  383. {
  384. if (__wcrtomb (buf, towlower (cset->mbchars[i]), &state)
  385. != (size_t) -1)
  386. re_set_fastmap (fastmap, false, *(unsigned char *) buf);
  387. }
  388. }
  389. }
  390. }
  391. #endif /* RE_ENABLE_I18N */
  392. else if (type == OP_PERIOD
  393. #ifdef RE_ENABLE_I18N
  394. || type == OP_UTF8_PERIOD
  395. #endif /* RE_ENABLE_I18N */
  396. || type == END_OF_RE)
  397. {
  398. memset (fastmap, '\1', sizeof (char) * SBC_MAX);
  399. if (type == END_OF_RE)
  400. bufp->can_be_null = 1;
  401. return;
  402. }
  403. }
  404. }
  405. /* Entry point for POSIX code. */
  406. /* regcomp takes a regular expression as a string and compiles it.
  407. PREG is a regex_t *. We do not expect any fields to be initialized,
  408. since POSIX says we shouldn't. Thus, we set
  409. `buffer' to the compiled pattern;
  410. `used' to the length of the compiled pattern;
  411. `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
  412. REG_EXTENDED bit in CFLAGS is set; otherwise, to
  413. RE_SYNTAX_POSIX_BASIC;
  414. `newline_anchor' to REG_NEWLINE being set in CFLAGS;
  415. `fastmap' to an allocated space for the fastmap;
  416. `fastmap_accurate' to zero;
  417. `re_nsub' to the number of subexpressions in PATTERN.
  418. PATTERN is the address of the pattern string.
  419. CFLAGS is a series of bits which affect compilation.
  420. If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
  421. use POSIX basic syntax.
  422. If REG_NEWLINE is set, then . and [^...] don't match newline.
  423. Also, regexec will try a match beginning after every newline.
  424. If REG_ICASE is set, then we considers upper- and lowercase
  425. versions of letters to be equivalent when matching.
  426. If REG_NOSUB is set, then when PREG is passed to regexec, that
  427. routine will report only success or failure, and nothing about the
  428. registers.
  429. It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
  430. the return codes and their meanings.) */
  431. int
  432. regcomp (preg, pattern, cflags)
  433. regex_t *_Restrict_ preg;
  434. const char *_Restrict_ pattern;
  435. int cflags;
  436. {
  437. reg_errcode_t ret;
  438. reg_syntax_t syntax = ((cflags & REG_EXTENDED) ? RE_SYNTAX_POSIX_EXTENDED
  439. : RE_SYNTAX_POSIX_BASIC);
  440. preg->buffer = NULL;
  441. preg->allocated = 0;
  442. preg->used = 0;
  443. /* Try to allocate space for the fastmap. */
  444. preg->fastmap = re_malloc (char, SBC_MAX);
  445. if (BE (preg->fastmap == NULL, 0))
  446. return REG_ESPACE;
  447. syntax |= (cflags & REG_ICASE) ? RE_ICASE : 0;
  448. /* If REG_NEWLINE is set, newlines are treated differently. */
  449. if (cflags & REG_NEWLINE)
  450. { /* REG_NEWLINE implies neither . nor [^...] match newline. */
  451. syntax &= ~RE_DOT_NEWLINE;
  452. syntax |= RE_HAT_LISTS_NOT_NEWLINE;
  453. /* It also changes the matching behavior. */
  454. preg->newline_anchor = 1;
  455. }
  456. else
  457. preg->newline_anchor = 0;
  458. preg->no_sub = !!(cflags & REG_NOSUB);
  459. preg->translate = NULL;
  460. ret = re_compile_internal (preg, pattern, strlen (pattern), syntax);
  461. /* POSIX doesn't distinguish between an unmatched open-group and an
  462. unmatched close-group: both are REG_EPAREN. */
  463. if (ret == REG_ERPAREN)
  464. ret = REG_EPAREN;
  465. /* We have already checked preg->fastmap != NULL. */
  466. if (BE (ret == REG_NOERROR, 1))
  467. /* Compute the fastmap now, since regexec cannot modify the pattern
  468. buffer. This function never fails in this implementation. */
  469. (void) re_compile_fastmap (preg);
  470. else
  471. {
  472. /* Some error occurred while compiling the expression. */
  473. re_free (preg->fastmap);
  474. preg->fastmap = NULL;
  475. }
  476. return (int) ret;
  477. }
  478. #ifdef _LIBC
  479. weak_alias (__regcomp, regcomp)
  480. #endif
  481. /* Returns a message corresponding to an error code, ERRCODE, returned
  482. from either regcomp or regexec. We don't use PREG here. */
  483. #ifdef _LIBC
  484. size_t
  485. regerror (errcode, preg, errbuf, errbuf_size)
  486. int errcode;
  487. const regex_t *_Restrict_ preg;
  488. char *_Restrict_ errbuf;
  489. size_t errbuf_size;
  490. #else /* size_t might promote */
  491. size_t
  492. regerror (int errcode, const regex_t *_Restrict_ preg,
  493. char *_Restrict_ errbuf, size_t errbuf_size)
  494. #endif
  495. {
  496. const char *msg;
  497. size_t msg_size;
  498. if (BE (errcode < 0
  499. || errcode >= (int) (sizeof (__re_error_msgid_idx)
  500. / sizeof (__re_error_msgid_idx[0])), 0))
  501. /* Only error codes returned by the rest of the code should be passed
  502. to this routine. If we are given anything else, or if other regex
  503. code generates an invalid error code, then the program has a bug.
  504. Dump core so we can fix it. */
  505. abort ();
  506. msg = gettext (__re_error_msgid + __re_error_msgid_idx[errcode]);
  507. msg_size = strlen (msg) + 1; /* Includes the null. */
  508. if (BE (errbuf_size != 0, 1))
  509. {
  510. size_t cpy_size = msg_size;
  511. if (BE (msg_size > errbuf_size, 0))
  512. {
  513. cpy_size = errbuf_size - 1;
  514. errbuf[cpy_size] = '\0';
  515. }
  516. memcpy (errbuf, msg, cpy_size);
  517. }
  518. return msg_size;
  519. }
  520. #ifdef _LIBC
  521. weak_alias (__regerror, regerror)
  522. #endif
  523. #ifdef RE_ENABLE_I18N
  524. /* This static array is used for the map to single-byte characters when
  525. UTF-8 is used. Otherwise we would allocate memory just to initialize
  526. it the same all the time. UTF-8 is the preferred encoding so this is
  527. a worthwhile optimization. */
  528. static const bitset_t utf8_sb_map =
  529. {
  530. /* Set the first 128 bits. */
  531. # if 4 * BITSET_WORD_BITS < ASCII_CHARS
  532. # error "bitset_word_t is narrower than 32 bits"
  533. # elif 3 * BITSET_WORD_BITS < ASCII_CHARS
  534. BITSET_WORD_MAX, BITSET_WORD_MAX, BITSET_WORD_MAX,
  535. # elif 2 * BITSET_WORD_BITS < ASCII_CHARS
  536. BITSET_WORD_MAX, BITSET_WORD_MAX,
  537. # elif 1 * BITSET_WORD_BITS < ASCII_CHARS
  538. BITSET_WORD_MAX,
  539. # endif
  540. (BITSET_WORD_MAX
  541. >> (SBC_MAX % BITSET_WORD_BITS == 0
  542. ? 0
  543. : BITSET_WORD_BITS - SBC_MAX % BITSET_WORD_BITS))
  544. };
  545. #endif
  546. static void
  547. free_dfa_content (re_dfa_t *dfa)
  548. {
  549. Idx i, j;
  550. if (dfa->nodes)
  551. for (i = 0; i < dfa->nodes_len; ++i)
  552. free_token (dfa->nodes + i);
  553. re_free (dfa->nexts);
  554. for (i = 0; i < dfa->nodes_len; ++i)
  555. {
  556. if (dfa->eclosures != NULL)
  557. re_node_set_free (dfa->eclosures + i);
  558. if (dfa->inveclosures != NULL)
  559. re_node_set_free (dfa->inveclosures + i);
  560. if (dfa->edests != NULL)
  561. re_node_set_free (dfa->edests + i);
  562. }
  563. re_free (dfa->edests);
  564. re_free (dfa->eclosures);
  565. re_free (dfa->inveclosures);
  566. re_free (dfa->nodes);
  567. if (dfa->state_table)
  568. for (i = 0; i <= dfa->state_hash_mask; ++i)
  569. {
  570. struct re_state_table_entry *entry = dfa->state_table + i;
  571. for (j = 0; j < entry->num; ++j)
  572. {
  573. re_dfastate_t *state = entry->array[j];
  574. free_state (state);
  575. }
  576. re_free (entry->array);
  577. }
  578. re_free (dfa->state_table);
  579. #ifdef RE_ENABLE_I18N
  580. if (dfa->sb_char != utf8_sb_map)
  581. re_free (dfa->sb_char);
  582. #endif
  583. re_free (dfa->subexp_map);
  584. #ifdef DEBUG
  585. re_free (dfa->re_str);
  586. #endif
  587. re_free (dfa);
  588. }
  589. /* Free dynamically allocated space used by PREG. */
  590. void
  591. regfree (preg)
  592. regex_t *preg;
  593. {
  594. re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
  595. if (BE (dfa != NULL, 1))
  596. free_dfa_content (dfa);
  597. preg->buffer = NULL;
  598. preg->allocated = 0;
  599. re_free (preg->fastmap);
  600. preg->fastmap = NULL;
  601. re_free (preg->translate);
  602. preg->translate = NULL;
  603. }
  604. #ifdef _LIBC
  605. weak_alias (__regfree, regfree)
  606. #endif
  607. /* Entry points compatible with 4.2 BSD regex library. We don't define
  608. them unless specifically requested. */
  609. #if defined _REGEX_RE_COMP || defined _LIBC
  610. /* BSD has one and only one pattern buffer. */
  611. static struct re_pattern_buffer re_comp_buf;
  612. char *
  613. # ifdef _LIBC
  614. /* Make these definitions weak in libc, so POSIX programs can redefine
  615. these names if they don't use our functions, and still use
  616. regcomp/regexec above without link errors. */
  617. weak_function
  618. # endif
  619. re_comp (s)
  620. const char *s;
  621. {
  622. reg_errcode_t ret;
  623. char *fastmap;
  624. if (!s)
  625. {
  626. if (!re_comp_buf.buffer)
  627. return gettext ("No previous regular expression");
  628. return 0;
  629. }
  630. if (re_comp_buf.buffer)
  631. {
  632. fastmap = re_comp_buf.fastmap;
  633. re_comp_buf.fastmap = NULL;
  634. __regfree (&re_comp_buf);
  635. memset (&re_comp_buf, '\0', sizeof (re_comp_buf));
  636. re_comp_buf.fastmap = fastmap;
  637. }
  638. if (re_comp_buf.fastmap == NULL)
  639. {
  640. re_comp_buf.fastmap = (char *) malloc (SBC_MAX);
  641. if (re_comp_buf.fastmap == NULL)
  642. return (char *) gettext (__re_error_msgid
  643. + __re_error_msgid_idx[(int) REG_ESPACE]);
  644. }
  645. /* Since `re_exec' always passes NULL for the `regs' argument, we
  646. don't need to initialize the pattern buffer fields which affect it. */
  647. /* Match anchors at newlines. */
  648. re_comp_buf.newline_anchor = 1;
  649. ret = re_compile_internal (&re_comp_buf, s, strlen (s), re_syntax_options);
  650. if (!ret)
  651. return NULL;
  652. /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
  653. return (char *) gettext (__re_error_msgid + __re_error_msgid_idx[(int) ret]);
  654. }
  655. #ifdef _LIBC
  656. libc_freeres_fn (free_mem)
  657. {
  658. __regfree (&re_comp_buf);
  659. }
  660. #endif
  661. #endif /* _REGEX_RE_COMP */
  662. /* Internal entry point.
  663. Compile the regular expression PATTERN, whose length is LENGTH.
  664. SYNTAX indicate regular expression's syntax. */
  665. static reg_errcode_t
  666. re_compile_internal (regex_t *preg, const char * pattern, size_t length,
  667. reg_syntax_t syntax)
  668. {
  669. reg_errcode_t err = REG_NOERROR;
  670. re_dfa_t *dfa;
  671. re_string_t regexp;
  672. /* Initialize the pattern buffer. */
  673. preg->fastmap_accurate = 0;
  674. preg->syntax = syntax;
  675. preg->not_bol = preg->not_eol = 0;
  676. preg->used = 0;
  677. preg->re_nsub = 0;
  678. preg->can_be_null = 0;
  679. preg->regs_allocated = REGS_UNALLOCATED;
  680. /* Initialize the dfa. */
  681. dfa = (re_dfa_t *) preg->buffer;
  682. if (BE (preg->allocated < sizeof (re_dfa_t), 0))
  683. {
  684. /* If zero allocated, but buffer is non-null, try to realloc
  685. enough space. This loses if buffer's address is bogus, but
  686. that is the user's responsibility. If ->buffer is NULL this
  687. is a simple allocation. */
  688. dfa = re_realloc (preg->buffer, re_dfa_t, 1);
  689. if (dfa == NULL)
  690. return REG_ESPACE;
  691. preg->allocated = sizeof (re_dfa_t);
  692. preg->buffer = (unsigned char *) dfa;
  693. }
  694. preg->used = sizeof (re_dfa_t);
  695. err = init_dfa (dfa, length);
  696. if (BE (err != REG_NOERROR, 0))
  697. {
  698. free_dfa_content (dfa);
  699. preg->buffer = NULL;
  700. preg->allocated = 0;
  701. return err;
  702. }
  703. #ifdef DEBUG
  704. /* Note: length+1 will not overflow since it is checked in init_dfa. */
  705. dfa->re_str = re_malloc (char, length + 1);
  706. strncpy (dfa->re_str, pattern, length + 1);
  707. #endif
  708. __libc_lock_init (dfa->lock);
  709. err = re_string_construct (&regexp, pattern, length, preg->translate,
  710. (syntax & RE_ICASE) != 0, dfa);
  711. if (BE (err != REG_NOERROR, 0))
  712. {
  713. re_compile_internal_free_return:
  714. free_workarea_compile (preg);
  715. re_string_destruct (&regexp);
  716. free_dfa_content (dfa);
  717. preg->buffer = NULL;
  718. preg->allocated = 0;
  719. return err;
  720. }
  721. /* Parse the regular expression, and build a structure tree. */
  722. preg->re_nsub = 0;
  723. dfa->str_tree = parse (&regexp, preg, syntax, &err);
  724. if (BE (dfa->str_tree == NULL, 0))
  725. goto re_compile_internal_free_return;
  726. /* Analyze the tree and create the nfa. */
  727. err = analyze (preg);
  728. if (BE (err != REG_NOERROR, 0))
  729. goto re_compile_internal_free_return;
  730. #ifdef RE_ENABLE_I18N
  731. /* If possible, do searching in single byte encoding to speed things up. */
  732. if (dfa->is_utf8 && !(syntax & RE_ICASE) && preg->translate == NULL)
  733. optimize_utf8 (dfa);
  734. #endif
  735. /* Then create the initial state of the dfa. */
  736. err = create_initial_state (dfa);
  737. /* Release work areas. */
  738. free_workarea_compile (preg);
  739. re_string_destruct (&regexp);
  740. if (BE (err != REG_NOERROR, 0))
  741. {
  742. free_dfa_content (dfa);
  743. preg->buffer = NULL;
  744. preg->allocated = 0;
  745. }
  746. return err;
  747. }
  748. /* Initialize DFA. We use the length of the regular expression PAT_LEN
  749. as the initial length of some arrays. */
  750. static reg_errcode_t
  751. init_dfa (re_dfa_t *dfa, size_t pat_len)
  752. {
  753. __re_size_t table_size;
  754. #ifdef RE_ENABLE_I18N
  755. size_t max_i18n_object_size = MAX (sizeof (wchar_t), sizeof (wctype_t));
  756. #else
  757. size_t max_i18n_object_size = 0;
  758. #endif
  759. size_t max_object_size =
  760. MAX (sizeof (struct re_state_table_entry),
  761. MAX (sizeof (re_token_t),
  762. MAX (sizeof (re_node_set),
  763. MAX (sizeof (regmatch_t),
  764. max_i18n_object_size))));
  765. memset (dfa, '\0', sizeof (re_dfa_t));
  766. /* Force allocation of str_tree_storage the first time. */
  767. dfa->str_tree_storage_idx = BIN_TREE_STORAGE_SIZE;
  768. /* Avoid overflows. The extra "/ 2" is for the table_size doubling
  769. calculation below, and for similar doubling calculations
  770. elsewhere. And it's <= rather than <, because some of the
  771. doubling calculations add 1 afterwards. */
  772. if (BE (SIZE_MAX / max_object_size / 2 <= pat_len, 0))
  773. return REG_ESPACE;
  774. dfa->nodes_alloc = pat_len + 1;
  775. dfa->nodes = re_malloc (re_token_t, dfa->nodes_alloc);
  776. /* table_size = 2 ^ ceil(log pat_len) */
  777. for (table_size = 1; ; table_size <<= 1)
  778. if (table_size > pat_len)
  779. break;
  780. dfa->state_table = calloc (sizeof (struct re_state_table_entry), table_size);
  781. dfa->state_hash_mask = table_size - 1;
  782. dfa->mb_cur_max = MB_CUR_MAX;
  783. #ifdef _LIBC
  784. if (dfa->mb_cur_max == 6
  785. && strcmp (_NL_CURRENT (LC_CTYPE, _NL_CTYPE_CODESET_NAME), "UTF-8") == 0)
  786. dfa->is_utf8 = 1;
  787. dfa->map_notascii = (_NL_CURRENT_WORD (LC_CTYPE, _NL_CTYPE_MAP_TO_NONASCII)
  788. != 0);
  789. #else
  790. if (strcmp (locale_charset (), "UTF-8") == 0)
  791. dfa->is_utf8 = 1;
  792. /* We check exhaustively in the loop below if this charset is a
  793. superset of ASCII. */
  794. dfa->map_notascii = 0;
  795. #endif
  796. #ifdef RE_ENABLE_I18N
  797. if (dfa->mb_cur_max > 1)
  798. {
  799. if (dfa->is_utf8)
  800. dfa->sb_char = (re_bitset_ptr_t) utf8_sb_map;
  801. else
  802. {
  803. int i, j, ch;
  804. dfa->sb_char = (re_bitset_ptr_t) calloc (sizeof (bitset_t), 1);
  805. if (BE (dfa->sb_char == NULL, 0))
  806. return REG_ESPACE;
  807. /* Set the bits corresponding to single byte chars. */
  808. for (i = 0, ch = 0; i < BITSET_WORDS; ++i)
  809. for (j = 0; j < BITSET_WORD_BITS; ++j, ++ch)
  810. {
  811. wint_t wch = __btowc (ch);
  812. if (wch != WEOF)
  813. dfa->sb_char[i] |= (bitset_word_t) 1 << j;
  814. # ifndef _LIBC
  815. if (isascii (ch) && wch != ch)
  816. dfa->map_notascii = 1;
  817. # endif
  818. }
  819. }
  820. }
  821. #endif
  822. if (BE (dfa->nodes == NULL || dfa->state_table == NULL, 0))
  823. return REG_ESPACE;
  824. return REG_NOERROR;
  825. }
  826. /* Initialize WORD_CHAR table, which indicate which character is
  827. "word". In this case "word" means that it is the word construction
  828. character used by some operators like "\<", "\>", etc. */
  829. static void
  830. internal_function
  831. init_word_char (re_dfa_t *dfa)
  832. {
  833. int i, j, ch;
  834. dfa->word_ops_used = 1;
  835. for (i = 0, ch = 0; i < BITSET_WORDS; ++i)
  836. for (j = 0; j < BITSET_WORD_BITS; ++j, ++ch)
  837. if (isalnum (ch) || ch == '_')
  838. dfa->word_char[i] |= (bitset_word_t) 1 << j;
  839. }
  840. /* Free the work area which are only used while compiling. */
  841. static void
  842. free_workarea_compile (regex_t *preg)
  843. {
  844. re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
  845. bin_tree_storage_t *storage, *next;
  846. for (storage = dfa->str_tree_storage; storage; storage = next)
  847. {
  848. next = storage->next;
  849. re_free (storage);
  850. }
  851. dfa->str_tree_storage = NULL;
  852. dfa->str_tree_storage_idx = BIN_TREE_STORAGE_SIZE;
  853. dfa->str_tree = NULL;
  854. re_free (dfa->org_indices);
  855. dfa->org_indices = NULL;
  856. }
  857. /* Create initial states for all contexts. */
  858. static reg_errcode_t
  859. create_initial_state (re_dfa_t *dfa)
  860. {
  861. Idx first, i;
  862. reg_errcode_t err;
  863. re_node_set init_nodes;
  864. /* Initial states have the epsilon closure of the node which is
  865. the first node of the regular expression. */
  866. first = dfa->str_tree->first->node_idx;
  867. dfa->init_node = first;
  868. err = re_node_set_init_copy (&init_nodes, dfa->eclosures + first);
  869. if (BE (err != REG_NOERROR, 0))
  870. return err;
  871. /* The back-references which are in initial states can epsilon transit,
  872. since in this case all of the subexpressions can be null.
  873. Then we add epsilon closures of the nodes which are the next nodes of
  874. the back-references. */
  875. if (dfa->nbackref > 0)
  876. for (i = 0; i < init_nodes.nelem; ++i)
  877. {
  878. Idx node_idx = init_nodes.elems[i];
  879. re_token_type_t type = dfa->nodes[node_idx].type;
  880. Idx clexp_idx;
  881. if (type != OP_BACK_REF)
  882. continue;
  883. for (clexp_idx = 0; clexp_idx < init_nodes.nelem; ++clexp_idx)
  884. {
  885. re_token_t *clexp_node;
  886. clexp_node = dfa->nodes + init_nodes.elems[clexp_idx];
  887. if (clexp_node->type == OP_CLOSE_SUBEXP
  888. && clexp_node->opr.idx == dfa->nodes[node_idx].opr.idx)
  889. break;
  890. }
  891. if (clexp_idx == init_nodes.nelem)
  892. continue;
  893. if (type == OP_BACK_REF)
  894. {
  895. Idx dest_idx = dfa->edests[node_idx].elems[0];
  896. if (!re_node_set_contains (&init_nodes, dest_idx))
  897. {
  898. re_node_set_merge (&init_nodes, dfa->eclosures + dest_idx);
  899. i = 0;
  900. }
  901. }
  902. }
  903. /* It must be the first time to invoke acquire_state. */
  904. dfa->init_state = re_acquire_state_context (&err, dfa, &init_nodes, 0);
  905. /* We don't check ERR here, since the initial state must not be NULL. */
  906. if (BE (dfa->init_state == NULL, 0))
  907. return err;
  908. if (dfa->init_state->has_constraint)
  909. {
  910. dfa->init_state_word = re_acquire_state_context (&err, dfa, &init_nodes,
  911. CONTEXT_WORD);
  912. dfa->init_state_nl = re_acquire_state_context (&err, dfa, &init_nodes,
  913. CONTEXT_NEWLINE);
  914. dfa->init_state_begbuf = re_acquire_state_context (&err, dfa,
  915. &init_nodes,
  916. CONTEXT_NEWLINE
  917. | CONTEXT_BEGBUF);
  918. if (BE (dfa->init_state_word == NULL || dfa->init_state_nl == NULL
  919. || dfa->init_state_begbuf == NULL, 0))
  920. return err;
  921. }
  922. else
  923. dfa->init_state_word = dfa->init_state_nl
  924. = dfa->init_state_begbuf = dfa->init_state;
  925. re_node_set_free (&init_nodes);
  926. return REG_NOERROR;
  927. }
  928. #ifdef RE_ENABLE_I18N
  929. /* If it is possible to do searching in single byte encoding instead of UTF-8
  930. to speed things up, set dfa->mb_cur_max to 1, clear is_utf8 and change
  931. DFA nodes where needed. */
  932. static void
  933. optimize_utf8 (re_dfa_t *dfa)
  934. {
  935. Idx node;
  936. int i;
  937. bool mb_chars = false;
  938. bool has_period = false;
  939. for (node = 0; node < dfa->nodes_len; ++node)
  940. switch (dfa->nodes[node].type)
  941. {
  942. case CHARACTER:
  943. if (dfa->nodes[node].opr.c >= ASCII_CHARS)
  944. mb_chars = true;
  945. break;
  946. case ANCHOR:
  947. switch (dfa->nodes[node].opr.ctx_type)
  948. {
  949. case LINE_FIRST:
  950. case LINE_LAST:
  951. case BUF_FIRST:
  952. case BUF_LAST:
  953. break;
  954. default:
  955. /* Word anchors etc. cannot be handled. It's okay to test
  956. opr.ctx_type since constraints (for all DFA nodes) are
  957. created by ORing one or more opr.ctx_type values. */
  958. return;
  959. }
  960. break;
  961. case OP_PERIOD:
  962. has_period = true;
  963. break;
  964. case OP_BACK_REF:
  965. case OP_ALT:
  966. case END_OF_RE:
  967. case OP_DUP_ASTERISK:
  968. case OP_OPEN_SUBEXP:
  969. case OP_CLOSE_SUBEXP:
  970. break;
  971. case COMPLEX_BRACKET:
  972. return;
  973. case SIMPLE_BRACKET:
  974. /* Just double check. */
  975. {
  976. int rshift = (ASCII_CHARS % BITSET_WORD_BITS == 0
  977. ? 0
  978. : BITSET_WORD_BITS - ASCII_CHARS % BITSET_WORD_BITS);
  979. for (i = ASCII_CHARS / BITSET_WORD_BITS; i < BITSET_WORDS; ++i)
  980. {
  981. if (dfa->nodes[node].opr.sbcset[i] >> rshift != 0)
  982. return;
  983. rshift = 0;
  984. }
  985. }
  986. break;
  987. default:
  988. abort ();
  989. }
  990. if (mb_chars || has_period)
  991. for (node = 0; node < dfa->nodes_len; ++node)
  992. {
  993. if (dfa->nodes[node].type == CHARACTER
  994. && dfa->nodes[node].opr.c >= ASCII_CHARS)
  995. dfa->nodes[node].mb_partial = 0;
  996. else if (dfa->nodes[node].type == OP_PERIOD)
  997. dfa->nodes[node].type = OP_UTF8_PERIOD;
  998. }
  999. /* The search can be in single byte locale. */
  1000. dfa->mb_cur_max = 1;
  1001. dfa->is_utf8 = 0;
  1002. dfa->has_mb_node = dfa->nbackref > 0 || has_period;
  1003. }
  1004. #endif
  1005. /* Analyze the structure tree, and calculate "first", "next", "edest",
  1006. "eclosure", and "inveclosure". */
  1007. static reg_errcode_t
  1008. analyze (regex_t *preg)
  1009. {
  1010. re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
  1011. reg_errcode_t ret;
  1012. /* Allocate arrays. */
  1013. dfa->nexts = re_malloc (Idx, dfa->nodes_alloc);
  1014. dfa->org_indices = re_malloc (Idx, dfa->nodes_alloc);
  1015. dfa->edests = re_malloc (re_node_set, dfa->nodes_alloc);
  1016. dfa->eclosures = re_malloc (re_node_set, dfa->nodes_alloc);
  1017. if (BE (dfa->nexts == NULL || dfa->org_indices == NULL || dfa->edests == NULL
  1018. || dfa->eclosures == NULL, 0))
  1019. return REG_ESPACE;
  1020. dfa->subexp_map = re_malloc (Idx, preg->re_nsub);
  1021. if (dfa->subexp_map != NULL)
  1022. {
  1023. Idx i;
  1024. for (i = 0; i < preg->re_nsub; i++)
  1025. dfa->subexp_map[i] = i;
  1026. preorder (dfa->str_tree, optimize_subexps, dfa);
  1027. for (i = 0; i < preg->re_nsub; i++)
  1028. if (dfa->subexp_map[i] != i)
  1029. break;
  1030. if (i == preg->re_nsub)
  1031. {
  1032. free (dfa->subexp_map);
  1033. dfa->subexp_map = NULL;
  1034. }
  1035. }
  1036. ret = postorder (dfa->str_tree, lower_subexps, preg);
  1037. if (BE (ret != REG_NOERROR, 0))
  1038. return ret;
  1039. ret = postorder (dfa->str_tree, calc_first, dfa);
  1040. if (BE (ret != REG_NOERROR, 0))
  1041. return ret;
  1042. preorder (dfa->str_tree, calc_next, dfa);
  1043. ret = preorder (dfa->str_tree, link_nfa_nodes, dfa);
  1044. if (BE (ret != REG_NOERROR, 0))
  1045. return ret;
  1046. ret = calc_eclosure (dfa);
  1047. if (BE (ret != REG_NOERROR, 0))
  1048. return ret;
  1049. /* We only need this during the prune_impossible_nodes pass in regexec.c;
  1050. skip it if p_i_n will not run, as calc_inveclosure can be quadratic. */
  1051. if ((!preg->no_sub && preg->re_nsub > 0 && dfa->has_plural_match)
  1052. || dfa->nbackref)
  1053. {
  1054. dfa->inveclosures = re_malloc (re_node_set, dfa->nodes_len);
  1055. if (BE (dfa->inveclosures == NULL, 0))
  1056. return REG_ESPACE;
  1057. ret = calc_inveclosure (dfa);
  1058. }
  1059. return ret;
  1060. }
  1061. /* Our parse trees are very unbalanced, so we cannot use a stack to
  1062. implement parse tree visits. Instead, we use parent pointers and
  1063. some hairy code in these two functions. */
  1064. static reg_errcode_t
  1065. postorder (bin_tree_t *root, reg_errcode_t (fn (void *, bin_tree_t *)),
  1066. void *extra)
  1067. {
  1068. bin_tree_t *node, *prev;
  1069. for (node = root; ; )
  1070. {
  1071. /* Descend down the tree, preferably to the left (or to the right
  1072. if that's the only child). */
  1073. while (node->left || node->right)
  1074. if (node->left)
  1075. node = node->left;
  1076. else
  1077. node = node->right;
  1078. do
  1079. {
  1080. reg_errcode_t err = fn (extra, node);
  1081. if (BE (err != REG_NOERROR, 0))
  1082. return err;
  1083. if (node->parent == NULL)
  1084. return REG_NOERROR;
  1085. prev = node;
  1086. node = node->parent;
  1087. }
  1088. /* Go up while we have a node that is reached from the right. */
  1089. while (node->right == prev || node->right == NULL);
  1090. node = node->right;
  1091. }
  1092. }
  1093. static reg_errcode_t
  1094. preorder (bin_tree_t *root, reg_errcode_t (fn (void *, bin_tree_t *)),
  1095. void *extra)
  1096. {
  1097. bin_tree_t *node;
  1098. for (node = root; ; )
  1099. {
  1100. reg_errcode_t err = fn (extra, node);
  1101. if (BE (err != REG_NOERROR, 0))
  1102. return err;
  1103. /* Go to the left node, or up and to the right. */
  1104. if (node->left)
  1105. node = node->left;
  1106. else
  1107. {
  1108. bin_tree_t *prev = NULL;
  1109. while (node->right == prev || node->right == NULL)
  1110. {
  1111. prev = node;
  1112. node = node->parent;
  1113. if (!node)
  1114. return REG_NOERROR;
  1115. }
  1116. node = node->right;
  1117. }
  1118. }
  1119. }
  1120. /* Optimization pass: if a SUBEXP is entirely contained, strip it and tell
  1121. re_search_internal to map the inner one's opr.idx to this one's. Adjust
  1122. backreferences as well. Requires a preorder visit. */
  1123. static reg_errcode_t
  1124. optimize_subexps (void *extra, bin_tree_t *node)
  1125. {
  1126. re_dfa_t *dfa = (re_dfa_t *) extra;
  1127. if (node->token.type == OP_BACK_REF && dfa->subexp_map)
  1128. {
  1129. int idx = node->token.opr.idx;
  1130. node->token.opr.idx = dfa->subexp_map[idx];
  1131. dfa->used_bkref_map |= 1 << node->token.opr.idx;
  1132. }
  1133. else if (node->token.type == SUBEXP
  1134. && node->left && node->left->token.type == SUBEXP)
  1135. {
  1136. Idx other_idx = node->left->token.opr.idx;
  1137. node->left = node->left->left;
  1138. if (node->left)
  1139. node->left->parent = node;
  1140. dfa->subexp_map[other_idx] = dfa->subexp_map[node->token.opr.idx];
  1141. if (other_idx < BITSET_WORD_BITS)
  1142. dfa->used_bkref_map &= ~((bitset_word_t) 1 << other_idx);
  1143. }
  1144. return REG_NOERROR;
  1145. }
  1146. /* Lowering pass: Turn each SUBEXP node into the appropriate concatenation
  1147. of OP_OPEN_SUBEXP, the body of the SUBEXP (if any) and OP_CLOSE_SUBEXP. */
  1148. static reg_errcode_t
  1149. lower_subexps (void *extra, bin_tree_t *node)
  1150. {
  1151. regex_t *preg = (regex_t *) extra;
  1152. reg_errcode_t err = REG_NOERROR;
  1153. if (node->left && node->left->token.type == SUBEXP)
  1154. {
  1155. node->left = lower_subexp (&err, preg, node->left);
  1156. if (node->left)
  1157. node->left->parent = node;
  1158. }
  1159. if (node->right && node->right->token.type == SUBEXP)
  1160. {
  1161. node->right = lower_subexp (&err, preg, node->right);
  1162. if (node->right)
  1163. node->right->parent = node;
  1164. }
  1165. return err;
  1166. }
  1167. static bin_tree_t *
  1168. lower_subexp (reg_errcode_t *err, regex_t *preg, bin_tree_t *node)
  1169. {
  1170. re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
  1171. bin_tree_t *body = node->left;
  1172. bin_tree_t *op, *cls, *tree1, *tree;
  1173. if (preg->no_sub
  1174. /* We do not optimize empty subexpressions, because otherwise we may
  1175. have bad CONCAT nodes with NULL children. This is obviously not
  1176. very common, so we do not lose much. An example that triggers
  1177. this case is the sed "script" /\(\)/x. */
  1178. && node->left != NULL
  1179. && (node->token.opr.idx >= BITSET_WORD_BITS
  1180. || !(dfa->used_bkref_map
  1181. & ((bitset_word_t) 1 << node->token.opr.idx))))
  1182. return node->left;
  1183. /* Convert the SUBEXP node to the concatenation of an
  1184. OP_OPEN_SUBEXP, the contents, and an OP_CLOSE_SUBEXP. */
  1185. op = create_tree (dfa, NULL, NULL, OP_OPEN_SUBEXP);
  1186. cls = create_tree (dfa, NULL, NULL, OP_CLOSE_SUBEXP);
  1187. tree1 = body ? create_tree (dfa, body, cls, CONCAT) : cls;
  1188. tree = create_tree (dfa, op, tree1, CONCAT);
  1189. if (BE (tree == NULL || tree1 == NULL || op == NULL || cls == NULL, 0))
  1190. {
  1191. *err = REG_ESPACE;
  1192. return NULL;
  1193. }
  1194. op->token.opr.idx = cls->token.opr.idx = node->token.opr.idx;
  1195. op->token.opt_subexp = cls->token.opt_subexp = node->token.opt_subexp;
  1196. return tree;
  1197. }
  1198. /* Pass 1 in building the NFA: compute FIRST and create unlinked automaton
  1199. nodes. Requires a postorder visit. */
  1200. static reg_errcode_t
  1201. calc_first (void *extra, bin_tree_t *node)
  1202. {
  1203. re_dfa_t *dfa = (re_dfa_t *) extra;
  1204. if (node->token.type == CONCAT)
  1205. {
  1206. node->first = node->left->first;
  1207. node->node_idx = node->left->node_idx;
  1208. }
  1209. else
  1210. {
  1211. node->first = node;
  1212. node->node_idx = re_dfa_add_node (dfa, node->token);
  1213. if (BE (node->node_idx == REG_MISSING, 0))
  1214. return REG_ESPACE;
  1215. if (node->token.type == ANCHOR)
  1216. dfa->nodes[node->node_idx].constraint = node->token.opr.ctx_type;
  1217. }
  1218. return REG_NOERROR;
  1219. }
  1220. /* Pass 2: compute NEXT on the tree. Preorder visit. */
  1221. static reg_errcode_t
  1222. calc_next (void *extra, bin_tree_t *node)
  1223. {
  1224. switch (node->token.type)
  1225. {
  1226. case OP_DUP_ASTERISK:
  1227. node->left->next = node;
  1228. break;
  1229. case CONCAT:
  1230. node->left->next = node->right->first;
  1231. node->right->next = node->next;
  1232. break;
  1233. default:
  1234. if (node->left)
  1235. node->left->next = node->next;
  1236. if (node->right)
  1237. node->right->next = node->next;
  1238. break;
  1239. }
  1240. return REG_NOERROR;
  1241. }
  1242. /* Pass 3: link all DFA nodes to their NEXT node (any order will do). */
  1243. static reg_errcode_t
  1244. link_nfa_nodes (void *extra, bin_tree_t *node)
  1245. {
  1246. re_dfa_t *dfa = (re_dfa_t *) extra;
  1247. Idx idx = node->node_idx;
  1248. reg_errcode_t err = REG_NOERROR;
  1249. switch (node->token.type)
  1250. {
  1251. case CONCAT:
  1252. break;
  1253. case END_OF_RE:
  1254. assert (node->next == NULL);
  1255. break;
  1256. case OP_DUP_ASTERISK:
  1257. case OP_ALT:
  1258. {
  1259. Idx left, right;
  1260. dfa->has_plural_match = 1;
  1261. if (node->left != NULL)
  1262. left = node->left->first->node_idx;
  1263. else
  1264. left = node->next->node_idx;
  1265. if (node->right != NULL)
  1266. right = node->right->first->node_idx;
  1267. else
  1268. right = node->next->node_idx;
  1269. assert (REG_VALID_INDEX (left));
  1270. assert (REG_VALID_INDEX (right));
  1271. err = re_node_set_init_2 (dfa->edests + idx, left, right);
  1272. }
  1273. break;
  1274. case ANCHOR:
  1275. case OP_OPEN_SUBEXP:
  1276. case OP_CLOSE_SUBEXP:
  1277. err = re_node_set_init_1 (dfa->edests + idx, node->next->node_idx);
  1278. break;
  1279. case OP_BACK_REF:
  1280. dfa->nexts[idx] = node->next->node_idx;
  1281. if (node->token.type == OP_BACK_REF)
  1282. re_node_set_init_1 (dfa->edests + idx, dfa->nexts[idx]);
  1283. break;
  1284. default:
  1285. assert (!IS_EPSILON_NODE (node->token.type));
  1286. dfa->nexts[idx] = node->next->node_idx;
  1287. break;
  1288. }
  1289. return err;
  1290. }
  1291. /* Duplicate the epsilon closure of the node ROOT_NODE.
  1292. Note that duplicated nodes have constraint INIT_CONSTRAINT in addition
  1293. to their own constraint. */
  1294. static reg_errcode_t
  1295. internal_function
  1296. duplicate_node_closure (re_dfa_t *dfa, Idx top_org_node, Idx top_clone_node,
  1297. Idx root_node, unsigned int init_constraint)
  1298. {
  1299. Idx org_node, clone_node;
  1300. bool ok;
  1301. unsigned int constraint = init_constraint;
  1302. for (org_node = top_org_node, clone_node = top_clone_node;;)
  1303. {
  1304. Idx org_dest, clone_dest;
  1305. if (dfa->nodes[org_node].type == OP_BACK_REF)
  1306. {
  1307. /* If the back reference epsilon-transit, its destination must
  1308. also have the constraint. Then duplicate the epsilon closure
  1309. of the destination of the back reference, and store it in
  1310. edests of the back reference. */
  1311. org_dest = dfa->nexts[org_node];
  1312. re_node_set_empty (dfa->edests + clone_node);
  1313. clone_dest = duplicate_node (dfa, org_dest, constraint);
  1314. if (BE (clone_dest == REG_MISSING, 0))
  1315. return REG_ESPACE;
  1316. dfa->nexts[clone_node] = dfa->nexts[org_node];
  1317. ok = re_node_set_insert (dfa->edests + clone_node, clone_dest);
  1318. if (BE (! ok, 0))
  1319. return REG_ESPACE;
  1320. }
  1321. else if (dfa->edests[org_node].nelem == 0)
  1322. {
  1323. /* In case of the node can't epsilon-transit, don't duplicate the
  1324. destination and store the original destination as the
  1325. destination of the node. */
  1326. dfa->nexts[clone_node] = dfa->nexts[org_node];
  1327. break;
  1328. }
  1329. else if (dfa->edests[org_node].nelem == 1)
  1330. {
  1331. /* In case of the node can epsilon-transit, and it has only one
  1332. destination. */
  1333. org_dest = dfa->edests[org_node].elems[0];
  1334. re_node_set_empty (dfa->edests + clone_node);
  1335. clone_dest = search_duplicated_node (dfa, org_dest, constraint);
  1336. /* If the node is root_node itself, it means the epsilon closure
  1337. has a loop. Then tie it to the destination of the root_node. */
  1338. if (org_node == root_node && clone_node != org_node)
  1339. {
  1340. ok = re_node_set_insert (dfa->edests + clone_node, org_dest);
  1341. if (BE (! ok, 0))
  1342. return REG_ESPACE;
  1343. break;
  1344. }
  1345. /* In case the node has another constraint, append it. */
  1346. constraint |= dfa->nodes[org_node].constraint;
  1347. clone_dest = duplicate_node (dfa, org_dest, constraint);
  1348. if (BE (clone_dest == REG_MISSING, 0))
  1349. return REG_ESPACE;
  1350. ok = re_node_set_insert (dfa->edests + clone_node, clone_dest);
  1351. if (BE (! ok, 0))
  1352. return REG_ESPACE;
  1353. }
  1354. else /* dfa->edests[org_node].nelem == 2 */
  1355. {
  1356. /* In case of the node can epsilon-transit, and it has two
  1357. destinations. In the bin_tree_t and DFA, that's '|' and '*'. */
  1358. org_dest = dfa->edests[org_node].elems[0];
  1359. re_node_set_empty (dfa->edests + clone_node);
  1360. /* Search for a duplicated node which satisfies the constraint. */
  1361. clone_dest = search_duplicated_node (dfa, org_dest, constraint);
  1362. if (clone_dest == REG_MISSING)
  1363. {
  1364. /* There is no such duplicated node, create a new one. */
  1365. reg_errcode_t err;
  1366. clone_dest = duplicate_node (dfa, org_dest, constraint);
  1367. if (BE (clone_dest == REG_MISSING, 0))
  1368. return REG_ESPACE;
  1369. ok = re_node_set_insert (dfa->edests + clone_node, clone_dest);
  1370. if (BE (! ok, 0))
  1371. return REG_ESPACE;
  1372. err = duplicate_node_closure (dfa, org_dest, clone_dest,
  1373. root_node, constraint);
  1374. if (BE (err != REG_NOERROR, 0))
  1375. return err;
  1376. }
  1377. else
  1378. {
  1379. /* There is a duplicated node which satisfy the constraint,
  1380. use it to avoid infinite loop. */
  1381. ok = re_node_set_insert (dfa->edests + clone_node, clone_dest);
  1382. if (BE (! ok, 0))
  1383. return REG_ESPACE;
  1384. }
  1385. org_dest = dfa->edests[org_node].elems[1];
  1386. clone_dest = duplicate_node (dfa, org_dest, constraint);
  1387. if (BE (clone_dest == REG_MISSING, 0))
  1388. return REG_ESPACE;
  1389. ok = re_node_set_insert (dfa->edests + clone_node, clone_dest);
  1390. if (BE (! ok, 0))
  1391. return REG_ESPACE;
  1392. }
  1393. org_node = org_dest;
  1394. clone_node = clone_dest;
  1395. }
  1396. return REG_NOERROR;
  1397. }
  1398. /* Search for a node which is duplicated from the node ORG_NODE, and
  1399. satisfies the constraint CONSTRAINT. */
  1400. static Idx
  1401. search_duplicated_node (const re_dfa_t *dfa, Idx org_node,
  1402. unsigned int constraint)
  1403. {
  1404. Idx idx;
  1405. for (idx = dfa->nodes_len - 1; dfa->nodes[idx].duplicated && idx > 0; --idx)
  1406. {
  1407. if (org_node == dfa->org_indices[idx]
  1408. && constraint == dfa->nodes[idx].constraint)
  1409. return idx; /* Found. */
  1410. }
  1411. return REG_MISSING; /* Not found. */
  1412. }
  1413. /* Duplicate the node whose index is ORG_IDX and set the constraint CONSTRAINT.
  1414. Return the index of the new node, or REG_MISSING if insufficient storage is
  1415. available. */
  1416. static Idx
  1417. duplicate_node (re_dfa_t *dfa, Idx org_idx, unsigned int constraint)
  1418. {
  1419. Idx dup_idx = re_dfa_add_node (dfa, dfa->nodes[org_idx]);
  1420. if (BE (dup_idx != REG_MISSING, 1))
  1421. {
  1422. dfa->nodes[dup_idx].constraint = constraint;
  1423. dfa->nodes[dup_idx].constraint |= dfa->nodes[org_idx].constraint;
  1424. dfa->nodes[dup_idx].duplicated = 1;
  1425. /* Store the index of the original node. */
  1426. dfa->org_indices[dup_idx] = org_idx;
  1427. }
  1428. return dup_idx;
  1429. }
  1430. static reg_errcode_t
  1431. calc_inveclosure (re_dfa_t *dfa)
  1432. {
  1433. Idx src, idx;
  1434. bool ok;
  1435. for (idx = 0; idx < dfa->nodes_len; ++idx)
  1436. re_node_set_init_empty (dfa->inveclosures + idx);
  1437. for (src = 0; src < dfa->nodes_len; ++src)
  1438. {
  1439. Idx *elems = dfa->eclosures[src].elems;
  1440. for (idx = 0; idx < dfa->eclosures[src].nelem; ++idx)
  1441. {
  1442. ok = re_node_set_insert_last (dfa->inveclosures + elems[idx], src);
  1443. if (BE (! ok, 0))
  1444. return REG_ESPACE;
  1445. }
  1446. }
  1447. return REG_NOERROR;
  1448. }
  1449. /* Calculate "eclosure" for all the node in DFA. */
  1450. static reg_errcode_t
  1451. calc_eclosure (re_dfa_t *dfa)
  1452. {
  1453. Idx node_idx;
  1454. bool incomplete;
  1455. #ifdef DEBUG
  1456. assert (dfa->nodes_len > 0);
  1457. #endif
  1458. incomplete = false;
  1459. /* For each nodes, calculate epsilon closure. */
  1460. for (node_idx = 0; ; ++node_idx)
  1461. {
  1462. reg_errcode_t err;
  1463. re_node_set eclosure_elem;
  1464. if (node_idx == dfa->nodes_len)
  1465. {
  1466. if (!incomplete)
  1467. break;
  1468. incomplete = false;
  1469. node_id

Large files files are truncated, but you can click here to view the full file