PageRenderTime 67ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/gnu/lib/libregex/regcomp.c

https://bitbucket.org/freebsd/freebsd-head/
C | 3924 lines | 3135 code | 310 blank | 479 comment | 993 complexity | 744e7746d7c578df2d001fa8adab820b MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, BSD-3-Clause, LGPL-2.0, LGPL-2.1, BSD-2-Clause, 0BSD, JSON, AGPL-1.0, GPL-2.0

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

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