PageRenderTime 56ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 2ms

/LotsaGlass/GLObject/Data management/regex.c

https://code.google.com/p/lotsablankers/
C | 10689 lines | 8466 code | 922 blank | 1301 comment | 2532 complexity | 7cd64486ca5a35e4d4301e2360a0a241 MD5 | raw file
  1. /* Extended regular expression matching and search library.
  2. Copyright (C) 2002, 2003, 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. #ifdef HAVE_CONFIG_H
  18. #include "config.h"
  19. #endif
  20. #include <stdbool.h>
  21. #define __USE_GNU
  22. /* Make sure noone compiles this code with a C++ compiler. */
  23. #ifdef __cplusplus
  24. # error "This is C code, use a C compiler"
  25. #endif
  26. #ifdef _LIBC
  27. /* We have to keep the namespace clean. */
  28. # define regfree(preg) __regfree (preg)
  29. # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
  30. # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
  31. # define regerror(errcode, preg, errbuf, errbuf_size) \
  32. __regerror(errcode, preg, errbuf, errbuf_size)
  33. # define re_set_registers(bu, re, nu, st, en) \
  34. __re_set_registers (bu, re, nu, st, en)
  35. # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
  36. __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
  37. # define re_match(bufp, string, size, pos, regs) \
  38. __re_match (bufp, string, size, pos, regs)
  39. # define re_search(bufp, string, size, startpos, range, regs) \
  40. __re_search (bufp, string, size, startpos, range, regs)
  41. # define re_compile_pattern(pattern, length, bufp) \
  42. __re_compile_pattern (pattern, length, bufp)
  43. # define re_set_syntax(syntax) __re_set_syntax (syntax)
  44. # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
  45. __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
  46. # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
  47. # include "../locale/localeinfo.h"
  48. #endif
  49. /* On some systems, limits.h sets RE_DUP_MAX to a lower value than
  50. GNU regex allows. Include it before <regex.h>, which correctly
  51. #undefs RE_DUP_MAX and sets it to the right value. */
  52. #include <limits.h>
  53. #include "regex.h"
  54. /* Extended regular expression matching and search library.
  55. Copyright (C) 2002, 2003, 2004, 2005, 2007 Free Software Foundation, Inc.
  56. This file is part of the GNU C Library.
  57. Contributed by Isamu Hasegawa <isamu@yamato.ibm.com>.
  58. The GNU C Library is free software; you can redistribute it and/or
  59. modify it under the terms of the GNU Lesser General Public
  60. License as published by the Free Software Foundation; either
  61. version 2.1 of the License, or (at your option) any later version.
  62. The GNU C Library is distributed in the hope that it will be useful,
  63. but WITHOUT ANY WARRANTY; without even the implied warranty of
  64. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  65. Lesser General Public License for more details.
  66. You should have received a copy of the GNU Lesser General Public
  67. License along with the GNU C Library; if not, write to the Free
  68. Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  69. 02111-1307 USA. */
  70. #ifndef _REGEX_INTERNAL_H
  71. #define _REGEX_INTERNAL_H 1
  72. #include <assert.h>
  73. #include <ctype.h>
  74. #include <stdio.h>
  75. #include <stdlib.h>
  76. #include <string.h>
  77. #if defined HAVE_LANGINFO_H || defined HAVE_LANGINFO_CODESET || defined _LIBC
  78. # include <langinfo.h>
  79. #endif
  80. #if defined HAVE_LOCALE_H || defined _LIBC
  81. # include <locale.h>
  82. #endif
  83. #if defined HAVE_WCHAR_H || defined _LIBC
  84. # include <wchar.h>
  85. #endif /* HAVE_WCHAR_H || _LIBC */
  86. #if defined HAVE_WCTYPE_H || defined _LIBC
  87. # include <wctype.h>
  88. #endif /* HAVE_WCTYPE_H || _LIBC */
  89. #if defined HAVE_STDBOOL_H || defined _LIBC
  90. # include <stdbool.h>
  91. #endif /* HAVE_STDBOOL_H || _LIBC */
  92. #if defined HAVE_STDINT_H || defined _LIBC
  93. # include <stdint.h>
  94. #endif /* HAVE_STDINT_H || _LIBC */
  95. #if defined _LIBC
  96. # include <bits/libc-lock.h>
  97. #else
  98. # define __libc_lock_define(CLASS,NAME)
  99. # define __libc_lock_init(NAME) do { } while (0)
  100. # define __libc_lock_lock(NAME) do { } while (0)
  101. # define __libc_lock_unlock(NAME) do { } while (0)
  102. #endif
  103. /* In case that the system doesn't have isblank(). */
  104. #if !defined _LIBC && !defined HAVE_ISBLANK && !defined isblank
  105. # define isblank(ch) ((ch) == ' ' || (ch) == '\t')
  106. #endif
  107. #ifdef _LIBC
  108. # ifndef _RE_DEFINE_LOCALE_FUNCTIONS
  109. # define _RE_DEFINE_LOCALE_FUNCTIONS 1
  110. # include <locale/localeinfo.h>
  111. # include <locale/elem-hash.h>
  112. # include <locale/coll-lookup.h>
  113. # endif
  114. #endif
  115. /* This is for other GNU distributions with internationalized messages. */
  116. #if (HAVE_LIBINTL_H && ENABLE_NLS) || defined _LIBC
  117. # include <libintl.h>
  118. # ifdef _LIBC
  119. # undef gettext
  120. # define gettext(msgid) \
  121. INTUSE(__dcgettext) (_libc_intl_domainname, msgid, LC_MESSAGES)
  122. # endif
  123. #else
  124. # define gettext(msgid) (msgid)
  125. #endif
  126. #ifndef gettext_noop
  127. /* This define is so xgettext can find the internationalizable
  128. strings. */
  129. # define gettext_noop(String) String
  130. #endif
  131. /* For loser systems without the definition. */
  132. #ifndef SIZE_MAX
  133. # define SIZE_MAX ((size_t) -1)
  134. #endif
  135. #if (defined MB_CUR_MAX && HAVE_LOCALE_H && HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_WCRTOMB && HAVE_MBRTOWC && HAVE_WCSCOLL) || _LIBC
  136. # define RE_ENABLE_I18N
  137. #endif
  138. #if __GNUC__ >= 3
  139. # define BE(expr, val) __builtin_expect (expr, val)
  140. #else
  141. # define BE(expr, val) (expr)
  142. # define inline
  143. #endif
  144. /* Number of single byte character. */
  145. #define SBC_MAX 256
  146. #define COLL_ELEM_LEN_MAX 8
  147. /* The character which represents newline. */
  148. #define NEWLINE_CHAR '\n'
  149. #define WIDE_NEWLINE_CHAR L'\n'
  150. /* Rename to standard API for using out of glibc. */
  151. #ifndef _LIBC
  152. # define __wctype wctype
  153. # define __iswctype iswctype
  154. # define __btowc btowc
  155. # define __mempcpy mempcpy
  156. # define __wcrtomb wcrtomb
  157. # define __regfree regfree
  158. # define attribute_hidden
  159. #endif /* not _LIBC */
  160. #ifdef __GNUC__
  161. # define __attribute(arg) __attribute__ (arg)
  162. #else
  163. # define __attribute(arg)
  164. #endif
  165. extern const char __re_error_msgid[] attribute_hidden;
  166. extern const size_t __re_error_msgid_idx[] attribute_hidden;
  167. /* An integer used to represent a set of bits. It must be unsigned,
  168. and must be at least as wide as unsigned int. */
  169. typedef unsigned long int bitset_word_t;
  170. /* All bits set in a bitset_word_t. */
  171. #define BITSET_WORD_MAX ULONG_MAX
  172. /* Number of bits in a bitset_word_t. */
  173. #define BITSET_WORD_BITS (sizeof (bitset_word_t) * CHAR_BIT)
  174. /* Number of bitset_word_t in a bit_set. */
  175. #define BITSET_WORDS (SBC_MAX / BITSET_WORD_BITS)
  176. typedef bitset_word_t bitset_t[BITSET_WORDS];
  177. typedef bitset_word_t *re_bitset_ptr_t;
  178. typedef const bitset_word_t *re_const_bitset_ptr_t;
  179. #define bitset_set(set,i) \
  180. (set[i / BITSET_WORD_BITS] |= (bitset_word_t) 1 << i % BITSET_WORD_BITS)
  181. #define bitset_clear(set,i) \
  182. (set[i / BITSET_WORD_BITS] &= ~((bitset_word_t) 1 << i % BITSET_WORD_BITS))
  183. #define bitset_contain(set,i) \
  184. (set[i / BITSET_WORD_BITS] & ((bitset_word_t) 1 << i % BITSET_WORD_BITS))
  185. #define bitset_empty(set) memset (set, '\0', sizeof (bitset_t))
  186. #define bitset_set_all(set) memset (set, '\xff', sizeof (bitset_t))
  187. #define bitset_copy(dest,src) memcpy (dest, src, sizeof (bitset_t))
  188. #define PREV_WORD_CONSTRAINT 0x0001
  189. #define PREV_NOTWORD_CONSTRAINT 0x0002
  190. #define NEXT_WORD_CONSTRAINT 0x0004
  191. #define NEXT_NOTWORD_CONSTRAINT 0x0008
  192. #define PREV_NEWLINE_CONSTRAINT 0x0010
  193. #define NEXT_NEWLINE_CONSTRAINT 0x0020
  194. #define PREV_BEGBUF_CONSTRAINT 0x0040
  195. #define NEXT_ENDBUF_CONSTRAINT 0x0080
  196. #define WORD_DELIM_CONSTRAINT 0x0100
  197. #define NOT_WORD_DELIM_CONSTRAINT 0x0200
  198. typedef enum
  199. {
  200. INSIDE_WORD = PREV_WORD_CONSTRAINT | NEXT_WORD_CONSTRAINT,
  201. WORD_FIRST = PREV_NOTWORD_CONSTRAINT | NEXT_WORD_CONSTRAINT,
  202. WORD_LAST = PREV_WORD_CONSTRAINT | NEXT_NOTWORD_CONSTRAINT,
  203. INSIDE_NOTWORD = PREV_NOTWORD_CONSTRAINT | NEXT_NOTWORD_CONSTRAINT,
  204. LINE_FIRST = PREV_NEWLINE_CONSTRAINT,
  205. LINE_LAST = NEXT_NEWLINE_CONSTRAINT,
  206. BUF_FIRST = PREV_BEGBUF_CONSTRAINT,
  207. BUF_LAST = NEXT_ENDBUF_CONSTRAINT,
  208. WORD_DELIM = WORD_DELIM_CONSTRAINT,
  209. NOT_WORD_DELIM = NOT_WORD_DELIM_CONSTRAINT
  210. } re_context_type;
  211. typedef struct
  212. {
  213. int alloc;
  214. int nelem;
  215. int *elems;
  216. } re_node_set;
  217. typedef enum
  218. {
  219. NON_TYPE = 0,
  220. /* Node type, These are used by token, node, tree. */
  221. CHARACTER = 1,
  222. END_OF_RE = 2,
  223. SIMPLE_BRACKET = 3,
  224. OP_BACK_REF = 4,
  225. OP_PERIOD = 5,
  226. #ifdef RE_ENABLE_I18N
  227. COMPLEX_BRACKET = 6,
  228. OP_UTF8_PERIOD = 7,
  229. #endif /* RE_ENABLE_I18N */
  230. /* We define EPSILON_BIT as a macro so that OP_OPEN_SUBEXP is used
  231. when the debugger shows values of this enum type. */
  232. #define EPSILON_BIT 8
  233. OP_OPEN_SUBEXP = EPSILON_BIT | 0,
  234. OP_CLOSE_SUBEXP = EPSILON_BIT | 1,
  235. OP_ALT = EPSILON_BIT | 2,
  236. OP_DUP_ASTERISK = EPSILON_BIT | 3,
  237. ANCHOR = EPSILON_BIT | 4,
  238. /* Tree type, these are used only by tree. */
  239. CONCAT = 16,
  240. SUBEXP = 17,
  241. /* Token type, these are used only by token. */
  242. OP_DUP_PLUS = 18,
  243. OP_DUP_QUESTION,
  244. OP_OPEN_BRACKET,
  245. OP_CLOSE_BRACKET,
  246. OP_CHARSET_RANGE,
  247. OP_OPEN_DUP_NUM,
  248. OP_CLOSE_DUP_NUM,
  249. OP_NON_MATCH_LIST,
  250. OP_OPEN_COLL_ELEM,
  251. OP_CLOSE_COLL_ELEM,
  252. OP_OPEN_EQUIV_CLASS,
  253. OP_CLOSE_EQUIV_CLASS,
  254. OP_OPEN_CHAR_CLASS,
  255. OP_CLOSE_CHAR_CLASS,
  256. OP_WORD,
  257. OP_NOTWORD,
  258. OP_SPACE,
  259. OP_NOTSPACE,
  260. BACK_SLASH
  261. } re_token_type_t;
  262. #ifdef RE_ENABLE_I18N
  263. typedef struct
  264. {
  265. /* Multibyte characters. */
  266. wchar_t *mbchars;
  267. /* Collating symbols. */
  268. # ifdef _LIBC
  269. int32_t *coll_syms;
  270. # endif
  271. /* Equivalence classes. */
  272. # ifdef _LIBC
  273. int32_t *equiv_classes;
  274. # endif
  275. /* Range expressions. */
  276. # ifdef _LIBC
  277. uint32_t *range_starts;
  278. uint32_t *range_ends;
  279. # else /* not _LIBC */
  280. wchar_t *range_starts;
  281. wchar_t *range_ends;
  282. # endif /* not _LIBC */
  283. /* Character classes. */
  284. wctype_t *char_classes;
  285. /* If this character set is the non-matching list. */
  286. unsigned int non_match : 1;
  287. /* # of multibyte characters. */
  288. int nmbchars;
  289. /* # of collating symbols. */
  290. int ncoll_syms;
  291. /* # of equivalence classes. */
  292. int nequiv_classes;
  293. /* # of range expressions. */
  294. int nranges;
  295. /* # of character classes. */
  296. int nchar_classes;
  297. } re_charset_t;
  298. #endif /* RE_ENABLE_I18N */
  299. typedef struct
  300. {
  301. union
  302. {
  303. unsigned char c; /* for CHARACTER */
  304. re_bitset_ptr_t sbcset; /* for SIMPLE_BRACKET */
  305. #ifdef RE_ENABLE_I18N
  306. re_charset_t *mbcset; /* for COMPLEX_BRACKET */
  307. #endif /* RE_ENABLE_I18N */
  308. int idx; /* for BACK_REF */
  309. re_context_type ctx_type; /* for ANCHOR */
  310. } opr;
  311. #if __GNUC__ >= 2
  312. re_token_type_t type : 8;
  313. #else
  314. re_token_type_t type;
  315. #endif
  316. unsigned int constraint : 10; /* context constraint */
  317. unsigned int duplicated : 1;
  318. unsigned int opt_subexp : 1;
  319. #ifdef RE_ENABLE_I18N
  320. unsigned int accept_mb : 1;
  321. /* These 2 bits can be moved into the union if needed (e.g. if running out
  322. of bits; move opr.c to opr.c.c and move the flags to opr.c.flags). */
  323. unsigned int mb_partial : 1;
  324. #endif
  325. unsigned int word_char : 1;
  326. } re_token_t;
  327. #define IS_EPSILON_NODE(type) ((type) & EPSILON_BIT)
  328. struct re_string_t
  329. {
  330. /* Indicate the raw buffer which is the original string passed as an
  331. argument of regexec(), re_search(), etc.. */
  332. const unsigned char *raw_mbs;
  333. /* Store the multibyte string. In case of "case insensitive mode" like
  334. REG_ICASE, upper cases of the string are stored, otherwise MBS points
  335. the same address that RAW_MBS points. */
  336. unsigned char *mbs;
  337. #ifdef RE_ENABLE_I18N
  338. /* Store the wide character string which is corresponding to MBS. */
  339. wint_t *wcs;
  340. int *offsets;
  341. mbstate_t cur_state;
  342. #endif
  343. /* Index in RAW_MBS. Each character mbs[i] corresponds to
  344. raw_mbs[raw_mbs_idx + i]. */
  345. int raw_mbs_idx;
  346. /* The length of the valid characters in the buffers. */
  347. int valid_len;
  348. /* The corresponding number of bytes in raw_mbs array. */
  349. int valid_raw_len;
  350. /* The length of the buffers MBS and WCS. */
  351. int bufs_len;
  352. /* The index in MBS, which is updated by re_string_fetch_byte. */
  353. int cur_idx;
  354. /* length of RAW_MBS array. */
  355. int raw_len;
  356. /* This is RAW_LEN - RAW_MBS_IDX + VALID_LEN - VALID_RAW_LEN. */
  357. int len;
  358. /* End of the buffer may be shorter than its length in the cases such
  359. as re_match_2, re_search_2. Then, we use STOP for end of the buffer
  360. instead of LEN. */
  361. int raw_stop;
  362. /* This is RAW_STOP - RAW_MBS_IDX adjusted through OFFSETS. */
  363. int stop;
  364. /* The context of mbs[0]. We store the context independently, since
  365. the context of mbs[0] may be different from raw_mbs[0], which is
  366. the beginning of the input string. */
  367. unsigned int tip_context;
  368. /* The translation passed as a part of an argument of re_compile_pattern. */
  369. RE_TRANSLATE_TYPE trans;
  370. /* Copy of re_dfa_t's word_char. */
  371. re_const_bitset_ptr_t word_char;
  372. /* 1 if REG_ICASE. */
  373. unsigned char icase;
  374. unsigned char is_utf8;
  375. unsigned char map_notascii;
  376. unsigned char mbs_allocated;
  377. unsigned char offsets_needed;
  378. unsigned char newline_anchor;
  379. unsigned char word_ops_used;
  380. int mb_cur_max;
  381. };
  382. typedef struct re_string_t re_string_t;
  383. struct re_dfa_t;
  384. typedef struct re_dfa_t re_dfa_t;
  385. #ifndef _LIBC
  386. # ifdef __i386__
  387. # define internal_function __attribute ((regparm (3), stdcall))
  388. # else
  389. # define internal_function
  390. # endif
  391. #endif
  392. #ifndef NOT_IN_libc
  393. static reg_errcode_t re_string_realloc_buffers (re_string_t *pstr,
  394. int new_buf_len)
  395. internal_function;
  396. # ifdef RE_ENABLE_I18N
  397. static void build_wcs_buffer (re_string_t *pstr) internal_function;
  398. static int build_wcs_upper_buffer (re_string_t *pstr) internal_function;
  399. # endif /* RE_ENABLE_I18N */
  400. static void build_upper_buffer (re_string_t *pstr) internal_function;
  401. static void re_string_translate_buffer (re_string_t *pstr) internal_function;
  402. static unsigned int re_string_context_at (const re_string_t *input, int idx,
  403. int eflags)
  404. internal_function __attribute ((pure));
  405. #endif
  406. #define re_string_peek_byte(pstr, offset) \
  407. ((pstr)->mbs[(pstr)->cur_idx + offset])
  408. #define re_string_fetch_byte(pstr) \
  409. ((pstr)->mbs[(pstr)->cur_idx++])
  410. #define re_string_first_byte(pstr, idx) \
  411. ((idx) == (pstr)->valid_len || (pstr)->wcs[idx] != WEOF)
  412. #define re_string_is_single_byte_char(pstr, idx) \
  413. ((pstr)->wcs[idx] != WEOF && ((pstr)->valid_len == (idx) + 1 \
  414. || (pstr)->wcs[(idx) + 1] != WEOF))
  415. #define re_string_eoi(pstr) ((pstr)->stop <= (pstr)->cur_idx)
  416. #define re_string_cur_idx(pstr) ((pstr)->cur_idx)
  417. #define re_string_get_buffer(pstr) ((pstr)->mbs)
  418. #define re_string_length(pstr) ((pstr)->len)
  419. #define re_string_byte_at(pstr,idx) ((pstr)->mbs[idx])
  420. #define re_string_skip_bytes(pstr,idx) ((pstr)->cur_idx += (idx))
  421. #define re_string_set_index(pstr,idx) ((pstr)->cur_idx = (idx))
  422. //#include <alloca.h>
  423. #ifndef _LIBC
  424. # if HAVE_ALLOCA
  425. /* The OS usually guarantees only one guard page at the bottom of the stack,
  426. and a page size can be as small as 4096 bytes. So we cannot safely
  427. allocate anything larger than 4096 bytes. Also care for the possibility
  428. of a few compiler-allocated temporary stack slots. */
  429. # define __libc_use_alloca(n) ((n) < 4032)
  430. # else
  431. /* alloca is implemented with malloc, so just use malloc. */
  432. # define __libc_use_alloca(n) 0
  433. # endif
  434. #endif
  435. #define re_malloc(t,n) ((t *) malloc ((n) * sizeof (t)))
  436. #define re_realloc(p,t,n) ((t *) realloc (p, (n) * sizeof (t)))
  437. #define re_free(p) free (p)
  438. struct bin_tree_t
  439. {
  440. struct bin_tree_t *parent;
  441. struct bin_tree_t *left;
  442. struct bin_tree_t *right;
  443. struct bin_tree_t *first;
  444. struct bin_tree_t *next;
  445. re_token_t token;
  446. /* `node_idx' is the index in dfa->nodes, if `type' == 0.
  447. Otherwise `type' indicate the type of this node. */
  448. int node_idx;
  449. };
  450. typedef struct bin_tree_t bin_tree_t;
  451. #define BIN_TREE_STORAGE_SIZE \
  452. ((1024 - sizeof (void *)) / sizeof (bin_tree_t))
  453. struct bin_tree_storage_t
  454. {
  455. struct bin_tree_storage_t *next;
  456. bin_tree_t data[BIN_TREE_STORAGE_SIZE];
  457. };
  458. typedef struct bin_tree_storage_t bin_tree_storage_t;
  459. #define CONTEXT_WORD 1
  460. #define CONTEXT_NEWLINE (CONTEXT_WORD << 1)
  461. #define CONTEXT_BEGBUF (CONTEXT_NEWLINE << 1)
  462. #define CONTEXT_ENDBUF (CONTEXT_BEGBUF << 1)
  463. #define IS_WORD_CONTEXT(c) ((c) & CONTEXT_WORD)
  464. #define IS_NEWLINE_CONTEXT(c) ((c) & CONTEXT_NEWLINE)
  465. #define IS_BEGBUF_CONTEXT(c) ((c) & CONTEXT_BEGBUF)
  466. #define IS_ENDBUF_CONTEXT(c) ((c) & CONTEXT_ENDBUF)
  467. #define IS_ORDINARY_CONTEXT(c) ((c) == 0)
  468. #define IS_WORD_CHAR(ch) (isalnum (ch) || (ch) == '_')
  469. #define IS_NEWLINE(ch) ((ch) == NEWLINE_CHAR)
  470. #define IS_WIDE_WORD_CHAR(ch) (iswalnum (ch) || (ch) == L'_')
  471. #define IS_WIDE_NEWLINE(ch) ((ch) == WIDE_NEWLINE_CHAR)
  472. #define NOT_SATISFY_PREV_CONSTRAINT(constraint,context) \
  473. ((((constraint) & PREV_WORD_CONSTRAINT) && !IS_WORD_CONTEXT (context)) \
  474. || ((constraint & PREV_NOTWORD_CONSTRAINT) && IS_WORD_CONTEXT (context)) \
  475. || ((constraint & PREV_NEWLINE_CONSTRAINT) && !IS_NEWLINE_CONTEXT (context))\
  476. || ((constraint & PREV_BEGBUF_CONSTRAINT) && !IS_BEGBUF_CONTEXT (context)))
  477. #define NOT_SATISFY_NEXT_CONSTRAINT(constraint,context) \
  478. ((((constraint) & NEXT_WORD_CONSTRAINT) && !IS_WORD_CONTEXT (context)) \
  479. || (((constraint) & NEXT_NOTWORD_CONSTRAINT) && IS_WORD_CONTEXT (context)) \
  480. || (((constraint) & NEXT_NEWLINE_CONSTRAINT) && !IS_NEWLINE_CONTEXT (context)) \
  481. || (((constraint) & NEXT_ENDBUF_CONSTRAINT) && !IS_ENDBUF_CONTEXT (context)))
  482. struct re_dfastate_t
  483. {
  484. unsigned int hash;
  485. re_node_set nodes;
  486. re_node_set non_eps_nodes;
  487. re_node_set inveclosure;
  488. re_node_set *entrance_nodes;
  489. struct re_dfastate_t **trtable, **word_trtable;
  490. unsigned int context : 4;
  491. unsigned int halt : 1;
  492. /* If this state can accept `multi byte'.
  493. Note that we refer to multibyte characters, and multi character
  494. collating elements as `multi byte'. */
  495. unsigned int accept_mb : 1;
  496. /* If this state has backreference node(s). */
  497. unsigned int has_backref : 1;
  498. unsigned int has_constraint : 1;
  499. };
  500. typedef struct re_dfastate_t re_dfastate_t;
  501. struct re_state_table_entry
  502. {
  503. int num;
  504. int alloc;
  505. re_dfastate_t **array;
  506. };
  507. /* Array type used in re_sub_match_last_t and re_sub_match_top_t. */
  508. typedef struct
  509. {
  510. int next_idx;
  511. int alloc;
  512. re_dfastate_t **array;
  513. } state_array_t;
  514. /* Store information about the node NODE whose type is OP_CLOSE_SUBEXP. */
  515. typedef struct
  516. {
  517. int node;
  518. int str_idx; /* The position NODE match at. */
  519. state_array_t path;
  520. } re_sub_match_last_t;
  521. /* Store information about the node NODE whose type is OP_OPEN_SUBEXP.
  522. And information about the node, whose type is OP_CLOSE_SUBEXP,
  523. corresponding to NODE is stored in LASTS. */
  524. typedef struct
  525. {
  526. int str_idx;
  527. int node;
  528. state_array_t *path;
  529. int alasts; /* Allocation size of LASTS. */
  530. int nlasts; /* The number of LASTS. */
  531. re_sub_match_last_t **lasts;
  532. } re_sub_match_top_t;
  533. struct re_backref_cache_entry
  534. {
  535. int node;
  536. int str_idx;
  537. int subexp_from;
  538. int subexp_to;
  539. char more;
  540. char unused;
  541. unsigned short int eps_reachable_subexps_map;
  542. };
  543. typedef struct
  544. {
  545. /* The string object corresponding to the input string. */
  546. re_string_t input;
  547. #if defined _LIBC || (defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L)
  548. const re_dfa_t *const dfa;
  549. #else
  550. const re_dfa_t *dfa;
  551. #endif
  552. /* EFLAGS of the argument of regexec. */
  553. int eflags;
  554. /* Where the matching ends. */
  555. int match_last;
  556. int last_node;
  557. /* The state log used by the matcher. */
  558. re_dfastate_t **state_log;
  559. int state_log_top;
  560. /* Back reference cache. */
  561. int nbkref_ents;
  562. int abkref_ents;
  563. struct re_backref_cache_entry *bkref_ents;
  564. int max_mb_elem_len;
  565. int nsub_tops;
  566. int asub_tops;
  567. re_sub_match_top_t **sub_tops;
  568. } re_match_context_t;
  569. typedef struct
  570. {
  571. re_dfastate_t **sifted_states;
  572. re_dfastate_t **limited_states;
  573. int last_node;
  574. int last_str_idx;
  575. re_node_set limits;
  576. } re_sift_context_t;
  577. struct re_fail_stack_ent_t
  578. {
  579. int idx;
  580. int node;
  581. regmatch_t *regs;
  582. re_node_set eps_via_nodes;
  583. };
  584. struct re_fail_stack_t
  585. {
  586. int num;
  587. int alloc;
  588. struct re_fail_stack_ent_t *stack;
  589. };
  590. struct re_dfa_t
  591. {
  592. re_token_t *nodes;
  593. size_t nodes_alloc;
  594. size_t nodes_len;
  595. int *nexts;
  596. int *org_indices;
  597. re_node_set *edests;
  598. re_node_set *eclosures;
  599. re_node_set *inveclosures;
  600. struct re_state_table_entry *state_table;
  601. re_dfastate_t *init_state;
  602. re_dfastate_t *init_state_word;
  603. re_dfastate_t *init_state_nl;
  604. re_dfastate_t *init_state_begbuf;
  605. bin_tree_t *str_tree;
  606. bin_tree_storage_t *str_tree_storage;
  607. re_bitset_ptr_t sb_char;
  608. int str_tree_storage_idx;
  609. /* number of subexpressions `re_nsub' is in regex_t. */
  610. unsigned int state_hash_mask;
  611. int init_node;
  612. int nbackref; /* The number of backreference in this dfa. */
  613. /* Bitmap expressing which backreference is used. */
  614. bitset_word_t used_bkref_map;
  615. bitset_word_t completed_bkref_map;
  616. unsigned int has_plural_match : 1;
  617. /* If this dfa has "multibyte node", which is a backreference or
  618. a node which can accept multibyte character or multi character
  619. collating element. */
  620. unsigned int has_mb_node : 1;
  621. unsigned int is_utf8 : 1;
  622. unsigned int map_notascii : 1;
  623. unsigned int word_ops_used : 1;
  624. int mb_cur_max;
  625. bitset_t word_char;
  626. reg_syntax_t syntax;
  627. int *subexp_map;
  628. #ifdef DEBUG
  629. char* re_str;
  630. #endif
  631. __libc_lock_define (, lock)
  632. };
  633. #define re_node_set_init_empty(set) memset (set, '\0', sizeof (re_node_set))
  634. #define re_node_set_remove(set,id) \
  635. (re_node_set_remove_at (set, re_node_set_contains (set, id) - 1))
  636. #define re_node_set_empty(p) ((p)->nelem = 0)
  637. #define re_node_set_free(set) re_free ((set)->elems)
  638. typedef enum
  639. {
  640. SB_CHAR,
  641. MB_CHAR,
  642. EQUIV_CLASS,
  643. COLL_SYM,
  644. CHAR_CLASS
  645. } bracket_elem_type;
  646. typedef struct
  647. {
  648. bracket_elem_type type;
  649. union
  650. {
  651. unsigned char ch;
  652. unsigned char *name;
  653. wchar_t wch;
  654. } opr;
  655. } bracket_elem_t;
  656. /* Inline functions for bitset operation. */
  657. static inline void
  658. bitset_not (bitset_t set)
  659. {
  660. int bitset_i;
  661. for (bitset_i = 0; bitset_i < BITSET_WORDS; ++bitset_i)
  662. set[bitset_i] = ~set[bitset_i];
  663. }
  664. static inline void
  665. bitset_merge (bitset_t dest, const bitset_t src)
  666. {
  667. int bitset_i;
  668. for (bitset_i = 0; bitset_i < BITSET_WORDS; ++bitset_i)
  669. dest[bitset_i] |= src[bitset_i];
  670. }
  671. static inline void
  672. bitset_mask (bitset_t dest, const bitset_t src)
  673. {
  674. int bitset_i;
  675. for (bitset_i = 0; bitset_i < BITSET_WORDS; ++bitset_i)
  676. dest[bitset_i] &= src[bitset_i];
  677. }
  678. #ifdef RE_ENABLE_I18N
  679. /* Inline functions for re_string. */
  680. static inline int
  681. internal_function __attribute ((pure))
  682. re_string_char_size_at (const re_string_t *pstr, int idx)
  683. {
  684. int byte_idx;
  685. if (pstr->mb_cur_max == 1)
  686. return 1;
  687. for (byte_idx = 1; idx + byte_idx < pstr->valid_len; ++byte_idx)
  688. if (pstr->wcs[idx + byte_idx] != WEOF)
  689. break;
  690. return byte_idx;
  691. }
  692. static inline wint_t
  693. internal_function __attribute ((pure))
  694. re_string_wchar_at (const re_string_t *pstr, int idx)
  695. {
  696. if (pstr->mb_cur_max == 1)
  697. return (wint_t) pstr->mbs[idx];
  698. return (wint_t) pstr->wcs[idx];
  699. }
  700. # ifndef NOT_IN_libc
  701. static int
  702. internal_function __attribute ((pure))
  703. re_string_elem_size_at (const re_string_t *pstr, int idx)
  704. {
  705. # ifdef _LIBC
  706. const unsigned char *p, *extra;
  707. const int32_t *table, *indirect;
  708. int32_t tmp;
  709. # include <locale/weight.h>
  710. uint_fast32_t nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
  711. if (nrules != 0)
  712. {
  713. table = (const int32_t *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
  714. extra = (const unsigned char *)
  715. _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
  716. indirect = (const int32_t *) _NL_CURRENT (LC_COLLATE,
  717. _NL_COLLATE_INDIRECTMB);
  718. p = pstr->mbs + idx;
  719. tmp = findidx (&p);
  720. return p - pstr->mbs - idx;
  721. }
  722. else
  723. # endif /* _LIBC */
  724. return 1;
  725. }
  726. # endif
  727. #endif /* RE_ENABLE_I18N */
  728. #endif /* _REGEX_INTERNAL_H */
  729. /* Extended regular expression matching and search library.
  730. Copyright (C) 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
  731. This file is part of the GNU C Library.
  732. Contributed by Isamu Hasegawa <isamu@yamato.ibm.com>.
  733. The GNU C Library is free software; you can redistribute it and/or
  734. modify it under the terms of the GNU Lesser General Public
  735. License as published by the Free Software Foundation; either
  736. version 2.1 of the License, or (at your option) any later version.
  737. The GNU C Library is distributed in the hope that it will be useful,
  738. but WITHOUT ANY WARRANTY; without even the implied warranty of
  739. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  740. Lesser General Public License for more details.
  741. You should have received a copy of the GNU Lesser General Public
  742. License along with the GNU C Library; if not, write to the Free
  743. Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  744. 02111-1307 USA. */
  745. static void re_string_construct_common (const char *str, int len,
  746. re_string_t *pstr,
  747. RE_TRANSLATE_TYPE trans, int icase,
  748. const re_dfa_t *dfa) internal_function;
  749. static re_dfastate_t *create_ci_newstate (const re_dfa_t *dfa,
  750. const re_node_set *nodes,
  751. unsigned int hash) internal_function;
  752. static re_dfastate_t *create_cd_newstate (const re_dfa_t *dfa,
  753. const re_node_set *nodes,
  754. unsigned int context,
  755. unsigned int hash) internal_function;
  756. /* Functions for string operation. */
  757. /* This function allocate the buffers. It is necessary to call
  758. re_string_reconstruct before using the object. */
  759. static reg_errcode_t
  760. internal_function
  761. re_string_allocate (re_string_t *pstr, const char *str, int len, int init_len,
  762. RE_TRANSLATE_TYPE trans, int icase, const re_dfa_t *dfa)
  763. {
  764. reg_errcode_t ret;
  765. int init_buf_len;
  766. /* Ensure at least one character fits into the buffers. */
  767. if (init_len < dfa->mb_cur_max)
  768. init_len = dfa->mb_cur_max;
  769. init_buf_len = (len + 1 < init_len) ? len + 1: init_len;
  770. re_string_construct_common (str, len, pstr, trans, icase, dfa);
  771. ret = re_string_realloc_buffers (pstr, init_buf_len);
  772. if (BE (ret != REG_NOERROR, 0))
  773. return ret;
  774. pstr->word_char = dfa->word_char;
  775. pstr->word_ops_used = dfa->word_ops_used;
  776. pstr->mbs = pstr->mbs_allocated ? pstr->mbs : (unsigned char *) str;
  777. pstr->valid_len = (pstr->mbs_allocated || dfa->mb_cur_max > 1) ? 0 : len;
  778. pstr->valid_raw_len = pstr->valid_len;
  779. return REG_NOERROR;
  780. }
  781. /* This function allocate the buffers, and initialize them. */
  782. static reg_errcode_t
  783. internal_function
  784. re_string_construct (re_string_t *pstr, const char *str, int len,
  785. RE_TRANSLATE_TYPE trans, int icase, const re_dfa_t *dfa)
  786. {
  787. reg_errcode_t ret;
  788. memset (pstr, '\0', sizeof (re_string_t));
  789. re_string_construct_common (str, len, pstr, trans, icase, dfa);
  790. if (len > 0)
  791. {
  792. ret = re_string_realloc_buffers (pstr, len + 1);
  793. if (BE (ret != REG_NOERROR, 0))
  794. return ret;
  795. }
  796. pstr->mbs = pstr->mbs_allocated ? pstr->mbs : (unsigned char *) str;
  797. if (icase)
  798. {
  799. #ifdef RE_ENABLE_I18N
  800. if (dfa->mb_cur_max > 1)
  801. {
  802. while (1)
  803. {
  804. ret = build_wcs_upper_buffer (pstr);
  805. if (BE (ret != REG_NOERROR, 0))
  806. return ret;
  807. if (pstr->valid_raw_len >= len)
  808. break;
  809. if (pstr->bufs_len > pstr->valid_len + dfa->mb_cur_max)
  810. break;
  811. ret = re_string_realloc_buffers (pstr, pstr->bufs_len * 2);
  812. if (BE (ret != REG_NOERROR, 0))
  813. return ret;
  814. }
  815. }
  816. else
  817. #endif /* RE_ENABLE_I18N */
  818. build_upper_buffer (pstr);
  819. }
  820. else
  821. {
  822. #ifdef RE_ENABLE_I18N
  823. if (dfa->mb_cur_max > 1)
  824. build_wcs_buffer (pstr);
  825. else
  826. #endif /* RE_ENABLE_I18N */
  827. {
  828. if (trans != NULL)
  829. re_string_translate_buffer (pstr);
  830. else
  831. {
  832. pstr->valid_len = pstr->bufs_len;
  833. pstr->valid_raw_len = pstr->bufs_len;
  834. }
  835. }
  836. }
  837. return REG_NOERROR;
  838. }
  839. /* Helper functions for re_string_allocate, and re_string_construct. */
  840. static reg_errcode_t
  841. internal_function
  842. re_string_realloc_buffers (re_string_t *pstr, int new_buf_len)
  843. {
  844. #ifdef RE_ENABLE_I18N
  845. if (pstr->mb_cur_max > 1)
  846. {
  847. wint_t *new_wcs = re_realloc (pstr->wcs, wint_t, new_buf_len);
  848. if (BE (new_wcs == NULL, 0))
  849. return REG_ESPACE;
  850. pstr->wcs = new_wcs;
  851. if (pstr->offsets != NULL)
  852. {
  853. int *new_offsets = re_realloc (pstr->offsets, int, new_buf_len);
  854. if (BE (new_offsets == NULL, 0))
  855. return REG_ESPACE;
  856. pstr->offsets = new_offsets;
  857. }
  858. }
  859. #endif /* RE_ENABLE_I18N */
  860. if (pstr->mbs_allocated)
  861. {
  862. unsigned char *new_mbs = re_realloc (pstr->mbs, unsigned char,
  863. new_buf_len);
  864. if (BE (new_mbs == NULL, 0))
  865. return REG_ESPACE;
  866. pstr->mbs = new_mbs;
  867. }
  868. pstr->bufs_len = new_buf_len;
  869. return REG_NOERROR;
  870. }
  871. static void
  872. internal_function
  873. re_string_construct_common (const char *str, int len, re_string_t *pstr,
  874. RE_TRANSLATE_TYPE trans, int icase,
  875. const re_dfa_t *dfa)
  876. {
  877. pstr->raw_mbs = (const unsigned char *) str;
  878. pstr->len = len;
  879. pstr->raw_len = len;
  880. pstr->trans = trans;
  881. pstr->icase = icase ? 1 : 0;
  882. pstr->mbs_allocated = (trans != NULL || icase);
  883. pstr->mb_cur_max = dfa->mb_cur_max;
  884. pstr->is_utf8 = dfa->is_utf8;
  885. pstr->map_notascii = dfa->map_notascii;
  886. pstr->stop = pstr->len;
  887. pstr->raw_stop = pstr->stop;
  888. }
  889. #ifdef RE_ENABLE_I18N
  890. /* Build wide character buffer PSTR->WCS.
  891. If the byte sequence of the string are:
  892. <mb1>(0), <mb1>(1), <mb2>(0), <mb2>(1), <sb3>
  893. Then wide character buffer will be:
  894. <wc1> , WEOF , <wc2> , WEOF , <wc3>
  895. We use WEOF for padding, they indicate that the position isn't
  896. a first byte of a multibyte character.
  897. Note that this function assumes PSTR->VALID_LEN elements are already
  898. built and starts from PSTR->VALID_LEN. */
  899. static void
  900. internal_function
  901. build_wcs_buffer (re_string_t *pstr)
  902. {
  903. #ifdef _LIBC
  904. unsigned char buf[MB_LEN_MAX];
  905. assert (MB_LEN_MAX >= pstr->mb_cur_max);
  906. #else
  907. unsigned char buf[64];
  908. #endif
  909. mbstate_t prev_st;
  910. int byte_idx, end_idx, remain_len;
  911. size_t mbclen;
  912. /* Build the buffers from pstr->valid_len to either pstr->len or
  913. pstr->bufs_len. */
  914. end_idx = (pstr->bufs_len > pstr->len) ? pstr->len : pstr->bufs_len;
  915. for (byte_idx = pstr->valid_len; byte_idx < end_idx;)
  916. {
  917. wchar_t wc;
  918. const char *p;
  919. remain_len = end_idx - byte_idx;
  920. prev_st = pstr->cur_state;
  921. /* Apply the translation if we need. */
  922. if (BE (pstr->trans != NULL, 0))
  923. {
  924. int i, ch;
  925. for (i = 0; i < pstr->mb_cur_max && i < remain_len; ++i)
  926. {
  927. ch = pstr->raw_mbs [pstr->raw_mbs_idx + byte_idx + i];
  928. buf[i] = pstr->mbs[byte_idx + i] = pstr->trans[ch];
  929. }
  930. p = (const char *) buf;
  931. }
  932. else
  933. p = (const char *) pstr->raw_mbs + pstr->raw_mbs_idx + byte_idx;
  934. mbclen = mbrtowc (&wc, p, remain_len, &pstr->cur_state);
  935. if (BE (mbclen == (size_t) -2, 0))
  936. {
  937. /* The buffer doesn't have enough space, finish to build. */
  938. pstr->cur_state = prev_st;
  939. break;
  940. }
  941. else if (BE (mbclen == (size_t) -1 || mbclen == 0, 0))
  942. {
  943. /* We treat these cases as a singlebyte character. */
  944. mbclen = 1;
  945. wc = (wchar_t) pstr->raw_mbs[pstr->raw_mbs_idx + byte_idx];
  946. if (BE (pstr->trans != NULL, 0))
  947. wc = pstr->trans[wc];
  948. pstr->cur_state = prev_st;
  949. }
  950. /* Write wide character and padding. */
  951. pstr->wcs[byte_idx++] = wc;
  952. /* Write paddings. */
  953. for (remain_len = byte_idx + mbclen - 1; byte_idx < remain_len ;)
  954. pstr->wcs[byte_idx++] = WEOF;
  955. }
  956. pstr->valid_len = byte_idx;
  957. pstr->valid_raw_len = byte_idx;
  958. }
  959. /* Build wide character buffer PSTR->WCS like build_wcs_buffer,
  960. but for REG_ICASE. */
  961. static reg_errcode_t
  962. internal_function
  963. build_wcs_upper_buffer (re_string_t *pstr)
  964. {
  965. mbstate_t prev_st;
  966. int src_idx, byte_idx, end_idx, remain_len;
  967. size_t mbclen;
  968. #ifdef _LIBC
  969. char buf[MB_LEN_MAX];
  970. assert (MB_LEN_MAX >= pstr->mb_cur_max);
  971. #else
  972. char buf[64];
  973. #endif
  974. byte_idx = pstr->valid_len;
  975. end_idx = (pstr->bufs_len > pstr->len) ? pstr->len : pstr->bufs_len;
  976. /* The following optimization assumes that ASCII characters can be
  977. mapped to wide characters with a simple cast. */
  978. if (! pstr->map_notascii && pstr->trans == NULL && !pstr->offsets_needed)
  979. {
  980. while (byte_idx < end_idx)
  981. {
  982. wchar_t wc;
  983. if (isascii (pstr->raw_mbs[pstr->raw_mbs_idx + byte_idx])
  984. && mbsinit (&pstr->cur_state))
  985. {
  986. /* In case of a singlebyte character. */
  987. pstr->mbs[byte_idx]
  988. = toupper (pstr->raw_mbs[pstr->raw_mbs_idx + byte_idx]);
  989. /* The next step uses the assumption that wchar_t is encoded
  990. ASCII-safe: all ASCII values can be converted like this. */
  991. pstr->wcs[byte_idx] = (wchar_t) pstr->mbs[byte_idx];
  992. ++byte_idx;
  993. continue;
  994. }
  995. remain_len = end_idx - byte_idx;
  996. prev_st = pstr->cur_state;
  997. mbclen = mbrtowc (&wc,
  998. ((const char *) pstr->raw_mbs + pstr->raw_mbs_idx
  999. + byte_idx), remain_len, &pstr->cur_state);
  1000. if (BE (mbclen + 2 > 2, 1))
  1001. {
  1002. wchar_t wcu = wc;
  1003. if (iswlower (wc))
  1004. {
  1005. size_t mbcdlen;
  1006. wcu = towupper (wc);
  1007. mbcdlen = wcrtomb (buf, wcu, &prev_st);
  1008. if (BE (mbclen == mbcdlen, 1))
  1009. memcpy (pstr->mbs + byte_idx, buf, mbclen);
  1010. else
  1011. {
  1012. src_idx = byte_idx;
  1013. goto offsets_needed;
  1014. }
  1015. }
  1016. else
  1017. memcpy (pstr->mbs + byte_idx,
  1018. pstr->raw_mbs + pstr->raw_mbs_idx + byte_idx, mbclen);
  1019. pstr->wcs[byte_idx++] = wcu;
  1020. /* Write paddings. */
  1021. for (remain_len = byte_idx + mbclen - 1; byte_idx < remain_len ;)
  1022. pstr->wcs[byte_idx++] = WEOF;
  1023. }
  1024. else if (mbclen == (size_t) -1 || mbclen == 0)
  1025. {
  1026. /* It is an invalid character or '\0'. Just use the byte. */
  1027. int ch = pstr->raw_mbs[pstr->raw_mbs_idx + byte_idx];
  1028. pstr->mbs[byte_idx] = ch;
  1029. /* And also cast it to wide char. */
  1030. pstr->wcs[byte_idx++] = (wchar_t) ch;
  1031. if (BE (mbclen == (size_t) -1, 0))
  1032. pstr->cur_state = prev_st;
  1033. }
  1034. else
  1035. {
  1036. /* The buffer doesn't have enough space, finish to build. */
  1037. pstr->cur_state = prev_st;
  1038. break;
  1039. }
  1040. }
  1041. pstr->valid_len = byte_idx;
  1042. pstr->valid_raw_len = byte_idx;
  1043. return REG_NOERROR;
  1044. }
  1045. else
  1046. for (src_idx = pstr->valid_raw_len; byte_idx < end_idx;)
  1047. {
  1048. wchar_t wc;
  1049. const char *p;
  1050. offsets_needed:
  1051. remain_len = end_idx - byte_idx;
  1052. prev_st = pstr->cur_state;
  1053. if (BE (pstr->trans != NULL, 0))
  1054. {
  1055. int i, ch;
  1056. for (i = 0; i < pstr->mb_cur_max && i < remain_len; ++i)
  1057. {
  1058. ch = pstr->raw_mbs [pstr->raw_mbs_idx + src_idx + i];
  1059. buf[i] = pstr->trans[ch];
  1060. }
  1061. p = (const char *) buf;
  1062. }
  1063. else
  1064. p = (const char *) pstr->raw_mbs + pstr->raw_mbs_idx + src_idx;
  1065. mbclen = mbrtowc (&wc, p, remain_len, &pstr->cur_state);
  1066. if (BE (mbclen + 2 > 2, 1))
  1067. {
  1068. wchar_t wcu = wc;
  1069. if (iswlower (wc))
  1070. {
  1071. size_t mbcdlen;
  1072. wcu = towupper (wc);
  1073. mbcdlen = wcrtomb ((char *) buf, wcu, &prev_st);
  1074. if (BE (mbclen == mbcdlen, 1))
  1075. memcpy (pstr->mbs + byte_idx, buf, mbclen);
  1076. else if (mbcdlen != (size_t) -1)
  1077. {
  1078. size_t i;
  1079. if (byte_idx + mbcdlen > pstr->bufs_len)
  1080. {
  1081. pstr->cur_state = prev_st;
  1082. break;
  1083. }
  1084. if (pstr->offsets == NULL)
  1085. {
  1086. pstr->offsets = re_malloc (int, pstr->bufs_len);
  1087. if (pstr->offsets == NULL)
  1088. return REG_ESPACE;
  1089. }
  1090. if (!pstr->offsets_needed)
  1091. {
  1092. for (i = 0; i < (size_t) byte_idx; ++i)
  1093. pstr->offsets[i] = i;
  1094. pstr->offsets_needed = 1;
  1095. }
  1096. memcpy (pstr->mbs + byte_idx, buf, mbcdlen);
  1097. pstr->wcs[byte_idx] = wcu;
  1098. pstr->offsets[byte_idx] = src_idx;
  1099. for (i = 1; i < mbcdlen; ++i)
  1100. {
  1101. pstr->offsets[byte_idx + i]
  1102. = src_idx + (i < mbclen ? i : mbclen - 1);
  1103. pstr->wcs[byte_idx + i] = WEOF;
  1104. }
  1105. pstr->len += mbcdlen - mbclen;
  1106. if (pstr->raw_stop > src_idx)
  1107. pstr->stop += mbcdlen - mbclen;
  1108. end_idx = (pstr->bufs_len > pstr->len)
  1109. ? pstr->len : pstr->bufs_len;
  1110. byte_idx += mbcdlen;
  1111. src_idx += mbclen;
  1112. continue;
  1113. }
  1114. else
  1115. memcpy (pstr->mbs + byte_idx, p, mbclen);
  1116. }
  1117. else
  1118. memcpy (pstr->mbs + byte_idx, p, mbclen);
  1119. if (BE (pstr->offsets_needed != 0, 0))
  1120. {
  1121. size_t i;
  1122. for (i = 0; i < mbclen; ++i)
  1123. pstr->offsets[byte_idx + i] = src_idx + i;
  1124. }
  1125. src_idx += mbclen;
  1126. pstr->wcs[byte_idx++] = wcu;
  1127. /* Write paddings. */
  1128. for (remain_len = byte_idx + mbclen - 1; byte_idx < remain_len ;)
  1129. pstr->wcs[byte_idx++] = WEOF;
  1130. }
  1131. else if (mbclen == (size_t) -1 || mbclen == 0)
  1132. {
  1133. /* It is an invalid character or '\0'. Just use the byte. */
  1134. int ch = pstr->raw_mbs[pstr->raw_mbs_idx + src_idx];
  1135. if (BE (pstr->trans != NULL, 0))
  1136. ch = pstr->trans [ch];
  1137. pstr->mbs[byte_idx] = ch;
  1138. if (BE (pstr->offsets_needed != 0, 0))
  1139. pstr->offsets[byte_idx] = src_idx;
  1140. ++src_idx;
  1141. /* And also cast it to wide char. */
  1142. pstr->wcs[byte_idx++] = (wchar_t) ch;
  1143. if (BE (mbclen == (size_t) -1, 0))
  1144. pstr->cur_state = prev_st;
  1145. }
  1146. else
  1147. {
  1148. /* The buffer doesn't have enough space, finish to build. */
  1149. pstr->cur_state = prev_st;
  1150. break;
  1151. }
  1152. }
  1153. pstr->valid_len = byte_idx;
  1154. pstr->valid_raw_len = src_idx;
  1155. return REG_NOERROR;
  1156. }
  1157. /* Skip characters until the index becomes greater than NEW_RAW_IDX.
  1158. Return the index. */
  1159. static int
  1160. internal_function
  1161. re_string_skip_chars (re_string_t *pstr, int new_raw_idx, wint_t *last_wc)
  1162. {
  1163. mbstate_t prev_st;
  1164. int rawbuf_idx;
  1165. size_t mbclen;
  1166. wchar_t wc = WEOF;
  1167. /* Skip the characters which are not necessary to check. */
  1168. for (rawbuf_idx = pstr->raw_mbs_idx + pstr->valid_raw_len;
  1169. rawbuf_idx < new_raw_idx;)
  1170. {
  1171. int remain_len;
  1172. remain_len = pstr->len - rawbuf_idx;
  1173. prev_st = pstr->cur_state;
  1174. mbclen = mbrtowc (&wc, (const char *) pstr->raw_mbs + rawbuf_idx,
  1175. remain_len, &pstr->cur_state);
  1176. if (BE (mbclen == (size_t) -2 || mbclen == (size_t) -1 || mbclen == 0, 0))
  1177. {
  1178. /* We treat these cases as a single byte character. */
  1179. if (mbclen == 0 || remain_len == 0)
  1180. wc = L'\0';
  1181. else
  1182. wc = *(unsigned char *) (pstr->raw_mbs + rawbuf_idx);
  1183. mbclen = 1;
  1184. pstr->cur_state = prev_st;
  1185. }
  1186. /* Then proceed the next character. */
  1187. rawbuf_idx += mbclen;
  1188. }
  1189. *last_wc = (wint_t) wc;
  1190. return rawbuf_idx;
  1191. }
  1192. #endif /* RE_ENABLE_I18N */
  1193. /* Build the buffer PSTR->MBS, and apply the translation if we need.
  1194. This function is used in case of REG_ICASE. */
  1195. static void
  1196. internal_function
  1197. build_upper_buffer (re_string_t *pstr)
  1198. {
  1199. int char_idx, end_idx;
  1200. end_idx = (pstr->bufs_len > pstr->len) ? pstr->len : pstr->bufs_len;
  1201. for (char_idx = pstr->valid_len; char_idx < end_idx; ++char_idx)
  1202. {
  1203. int ch = pstr->raw_mbs[pstr->raw_mbs_idx + char_idx];
  1204. if (BE (pstr->trans != NULL, 0))
  1205. ch = pstr->trans[ch];
  1206. if (islower (ch))
  1207. pstr->mbs[char_idx] = toupper (ch);
  1208. else
  1209. pstr->mbs[char_idx] = ch;
  1210. }
  1211. pstr->valid_len = char_idx;
  1212. pstr->valid_raw_len = char_idx;
  1213. }
  1214. /* Apply TRANS to the buffer in PSTR. */
  1215. static void
  1216. internal_function
  1217. re_string_translate_buffer (re_string_t *pstr)
  1218. {
  1219. int buf_idx, end_idx;
  1220. end_idx = (pstr->bufs_len > pstr->len) ? pstr->len : pstr->bufs_len;
  1221. for (buf_idx = pstr->valid_len; buf_idx < end_idx; ++buf_idx)
  1222. {
  1223. int ch = pstr->raw_mbs[pstr->raw_mbs_idx + buf_idx];
  1224. pstr->mbs[buf_idx] = pstr->trans[ch];
  1225. }
  1226. pstr->valid_len = buf_idx;
  1227. pstr->valid_raw_len = buf_idx;
  1228. }
  1229. /* This function re-construct the buffers.
  1230. Concretely, convert to wide character in case of pstr->mb_cur_max > 1,
  1231. convert to upper case in case of REG_ICASE, apply translation. */
  1232. static reg_errcode_t
  1233. internal_function
  1234. re_string_reconstruct (re_string_t *pstr, int idx, int eflags)
  1235. {
  1236. int offset = idx - pstr->raw_mbs_idx;
  1237. if (BE (offset < 0, 0))
  1238. {
  1239. /* Reset buffer. */
  1240. #ifdef RE_ENABLE_I18N
  1241. if (pstr->mb_cur_max > 1)
  1242. memset (&pstr->cur_state, '\0', sizeof (mbstate_t));
  1243. #endif /* RE_ENABLE_I18N */
  1244. pstr->len = pstr->raw_len;
  1245. pstr->stop = pstr->raw_stop;
  1246. pstr->valid_len = 0;
  1247. pstr->raw_mbs_idx = 0;
  1248. pstr->valid_raw_len = 0;
  1249. pstr->offsets_needed = 0;
  1250. pstr->tip_context = ((eflags & REG_NOTBOL) ? CONTEXT_BEGBUF
  1251. : CONTEXT_NEWLINE | CONTEXT_BEGBUF);
  1252. if (!pstr->mbs_allocated)
  1253. pstr->mbs = (unsigned char *) pstr->raw_mbs;
  1254. offset = idx;
  1255. }
  1256. if (BE (offset != 0, 1))
  1257. {
  1258. /* Should the already checked characters be kept? */
  1259. if (BE (offset < pstr->valid_raw_len, 1))
  1260. {
  1261. /* Yes, move them to the front of the buffer. */
  1262. #ifdef RE_ENABLE_I18N
  1263. if (BE (pstr->offsets_needed, 0))
  1264. {
  1265. int low = 0, high = pstr->valid_len, mid;
  1266. do
  1267. {
  1268. mid = (high + low) / 2;
  1269. if (pstr->offsets[mid] > offset)
  1270. high = mid;
  1271. else if (pstr->offsets[mid] < offset)
  1272. low = mid + 1;
  1273. else
  1274. break;
  1275. }
  1276. while (low < high);
  1277. if (pstr->offsets[mid] < offset)
  1278. ++mid;
  1279. pstr->tip_context = re_string_context_at (pstr, mid - 1,
  1280. eflags);
  1281. /* This can be quite complicated, so handle specially
  1282. only the common and easy case where the character with
  1283. different length representation of lower and upper
  1284. case is present at or after offset. */
  1285. if (pstr->valid_len > offset
  1286. && mid == offset && pstr->offsets[mid] == offset)
  1287. {
  1288. memmove (pstr->wcs, pstr->wcs + offset,
  1289. (pstr->valid_len - offset) * sizeof (wint_t));
  1290. memmove (pstr->mbs, pstr->mbs + offset, pstr->valid_len - offset);
  1291. pstr->valid_len -= offset;
  1292. pstr->valid_raw_len -= offset;
  1293. for (low = 0; low < pstr->valid_len; low++)
  1294. pstr->offsets[low] = pstr->offsets[low + offset] - offset;
  1295. }
  1296. else
  1297. {
  1298. /* Otherwise, just find out how long the partial multibyte
  1299. character at offset is and fill it with WEOF/255. */
  1300. pstr->len = pstr->raw_len - idx + offset;
  1301. pstr->stop = pstr->raw_stop - idx + offset;
  1302. pstr->offsets_needed = 0;
  1303. while (mid > 0 && pstr->offsets[mid - 1] == offset)
  1304. --mid;
  1305. while (mid < pstr->valid_len)
  1306. if (pstr->wcs[mid] != WEOF)
  1307. break;
  1308. else
  1309. ++mid;
  1310. if (mid == pstr->valid_len)
  1311. pstr->valid_len = 0;
  1312. else
  1313. {
  1314. pstr->valid_len = pstr->offsets[mid] - offset;
  1315. if (pstr->valid_len)
  1316. {
  1317. for (low = 0; low < pstr->valid_len; ++low)
  1318. pstr->wcs[low] = WEOF;
  1319. memset (pstr->mbs, 255, pstr->valid_len);
  1320. }
  1321. }
  1322. pstr->valid_raw_len = pstr->valid_len;
  1323. }
  1324. }
  1325. else
  1326. #endif
  1327. {
  1328. pstr->tip_context = re_string_context_at (pstr, offset - 1,
  1329. eflags);
  1330. #ifdef RE_ENABLE_I18N
  1331. if (pstr->mb_cur_max > 1)
  1332. memmove (pstr->wcs, pstr->wcs + offset,
  1333. (pstr->valid_len - offset) * sizeof (wint_t));
  1334. #endif /* RE_ENABLE_I18N */
  1335. if (BE (pstr->mbs_allocated, 0))
  1336. memmove (pstr->mbs, pstr->mbs + offset,
  1337. pstr->valid_len - offset);
  1338. pstr->valid_len -= offset;
  1339. pstr->valid_raw_len -= offset;
  1340. #if DEBUG
  1341. assert (pstr->valid_len > 0);
  1342. #endif
  1343. }
  1344. }
  1345. else
  1346. {
  1347. /* No, skip all characters until IDX. */
  1348. int prev_valid_len = pstr->valid_len;
  1349. #ifdef RE_ENABLE_I18N
  1350. if (BE (pstr->offsets_needed, 0))
  1351. {
  1352. pstr->len = pstr->raw_len - idx + offset;
  1353. pstr->stop = pstr->raw_stop - idx + offset;
  1354. pstr->offsets_needed = 0;
  1355. }
  1356. #endif
  1357. pstr->valid_len = 0;
  1358. #ifdef RE_ENABLE_I18N
  1359. if (pstr->mb_cur_max > 1)
  1360. {
  1361. int wcs_idx;
  1362. wint_t wc = WEOF;
  1363. if (pstr->is_utf8)
  1364. {
  1365. const unsigned char *raw, *p, *q, *end;
  1366. /* Special case UTF-8. Multi-byte chars start with any
  1367. byte other than 0x80 - 0xbf. */
  1368. raw = pstr->raw_mbs + pstr->raw_mbs_idx;
  1369. end = raw + (offset - pstr->mb_cur_max);
  1370. if (end < pstr->raw_mbs)
  1371. end = pstr->raw_mbs;
  1372. p = raw + offset - 1;
  1373. #ifdef _LIBC
  1374. /* We know the wchar_t encoding is UCS4, so for the simple
  1375. case, ASCII characters, skip the conversion step. */
  1376. if (isascii (*p) && BE (pstr->trans == NULL, 1))
  1377. {
  1378. memset (&pstr->cur_state, '\0', sizeof (mbstate_t));
  1379. /* pstr->valid_len = 0; */
  1380. wc = (wchar_t) *p;
  1381. }
  1382. else
  1383. #endif
  1384. for (; p >= end; --p)
  1385. if ((*p & 0xc0) != 0x80)
  1386. {
  1387. mbstate_t cur_state;
  1388. wchar_t wc2;
  1389. int mlen = raw + pstr->len - p;
  1390. unsigned char buf[6];
  1391. size_t mbclen;
  1392. q = p;
  1393. if (BE (pstr->trans != NULL, 0))
  1394. {
  1395. int i = mlen < 6 ? mlen : 6;
  1396. while (--i >= 0)
  1397. buf[i] = pstr->trans[p[i]];
  1398. q = buf;
  1399. }
  1400. /* XXX Don't use mbrtowc, we know which conversion
  1401. to use (UTF-8 -> UCS4). */
  1402. memset (&cur_state, 0, sizeof (cur_state));
  1403. mbclen = mbrtowc (&wc2, (const char *) p, mlen,
  1404. &cur_state);
  1405. if (raw + offset - p <= mbclen
  1406. && mbclen < (size_t) -2)
  1407. {
  1408. memset (&pstr->cur_state, '\0',
  1409. sizeof (mbstate_t));
  1410. pstr->valid_len = mbclen - (raw + offset - p);
  1411. wc = wc2;
  1412. }
  1413. break;
  1414. }
  1415. }
  1416. if (wc == WEOF)
  1417. pstr->valid_len = re_string_skip_chars (pstr, idx, &wc) - idx;
  1418. if (wc == WEOF)
  1419. pstr->tip_context
  1420. = re_string_context_at (pstr, prev_valid_len - 1, eflags);
  1421. else
  1422. pstr->tip_context = ((BE (pstr->word_ops_used != 0, 0)
  1423. && IS_WIDE_WORD_CHAR (wc))
  1424. ? CONTEXT_WORD
  1425. : ((IS_WIDE_NEWLINE (wc)
  1426. && pstr->newline_anchor)
  1427. ? CONTEXT_NEWLINE : 0));
  1428. if (BE (pstr->valid_len, 0))
  1429. {
  1430. for (wcs_idx = 0; wcs_idx < pstr->valid_len; ++wcs_idx)
  1431. pstr->wcs[wcs_idx] = WEOF;
  1432. if (pstr->mbs_allocated)
  1433. memset (pstr->mbs, 255, pstr->valid_len);
  1434. }
  1435. pstr->valid_raw_len = pstr->valid_len;
  1436. }
  1437. else
  1438. #endif /* RE_ENABLE_I18N */
  1439. {
  1440. int c = pstr->raw_mbs[pstr->raw_mbs_idx + offset - 1];
  1441. pstr->valid_raw_len = 0;
  1442. if (pstr->trans)
  1443. c = pstr->trans[c];
  1444. pstr->tip_context = (bitset_contain (pstr->word_char, c)
  1445. ? CONTEXT_WORD
  1446. : ((IS_NEWLINE (c) && pstr->newline_anchor)
  1447. ? CONTEXT_NEWLINE : 0));
  1448. }
  1449. }
  1450. if (!BE (pstr->mbs_allocated, 0))
  1451. pstr->mbs += offset;
  1452. }
  1453. pstr->raw_mbs_idx = idx;
  1454. pstr->len -= offset;
  1455. pstr->stop -= offset;
  1456. /* Then build the buffers. */
  1457. #ifdef RE_ENABLE_I18N
  1458. if (pstr->mb_cur_max > 1)
  1459. {
  1460. if (pstr->icase)
  1461. {
  1462. reg_errcode_t ret = build_wcs_upper_buffer (pstr);
  1463. if (BE (ret != REG_NOERROR, 0))
  1464. return ret;
  1465. }
  1466. else
  1467. build_wcs_buffer (pstr);
  1468. }
  1469. else
  1470. #endif /* RE_ENABLE_I18N */
  1471. if (BE (pstr->mbs_allocated, 0))
  1472. {
  1473. if (pstr->icase)
  1474. build_upper_buffer (pstr);
  1475. else if (pstr->trans != NULL)
  1476. re_string_translate_buffer (pstr);
  1477. }
  1478. else
  1479. pstr->valid_len = pstr->len;
  1480. pstr->cur_idx = 0;
  1481. return REG_NOERROR;
  1482. }
  1483. static unsigned char
  1484. internal_function __attribute ((pure))
  1485. re_string_peek_byte_case (const re_string_t *pstr, int idx)
  1486. {
  1487. int ch, off;
  1488. /* Handle the common (easiest) cases first. */
  1489. if (BE (!pstr->mbs_allocated, 1))
  1490. return re_string_peek_byte (pstr, idx);
  1491. #ifdef RE_ENABLE_I18N
  1492. if (pstr->mb_cur_max > 1
  1493. && ! re_string_is_single_byte_char (pstr, pstr->cur_idx + idx))
  1494. return re_string_peek_byte (pstr, idx);
  1495. #endif
  1496. off = pstr->cur_idx + idx;
  1497. #ifdef RE_ENABLE_I18N
  1498. if (pstr->offsets_needed)
  1499. off = pstr->offsets[off];
  1500. #endif
  1501. ch = pstr->raw_mbs[pstr->raw_mbs_idx + off];
  1502. #ifdef RE_ENABLE_I18N
  1503. /* Ensure that e.g. for tr_TR.UTF-8 BACKSLASH DOTLESS SMALL LETTER I
  1504. this function returns CAPITAL LETTER I instead of first byte of
  1505. DOTLESS SMALL LETTER I. The latter would confuse the parser,
  1506. since peek_byte_case doesn't advance cur_idx in any way. */
  1507. if (pstr->offsets_needed && !isascii (ch))
  1508. return re_string_peek_byte (pstr, idx);
  1509. #endif
  1510. return ch;
  1511. }
  1512. static unsigned char
  1513. internal_function __attribute ((pure))
  1514. re_string_fetch_byte_case (re_string_t *pstr)
  1515. {
  1516. if (BE (!pstr->mbs_allocated, 1))
  1517. return re_string_fetch_byte (pstr);
  1518. #ifdef RE_ENABLE_I18N
  1519. if (pstr->offsets_needed)
  1520. {
  1521. int off, ch;
  1522. /* For tr_TR.UTF-8 [[:islower:]] there is
  1523. [[: CAPITAL LETTER I WITH DOT lower:]] in mbs. Skip
  1524. in that case the whole multi-byte character and return
  1525. the original letter. On the other side, with
  1526. [[: DOTLESS SMALL LETTER I return [[:I, as doing
  1527. anything else would complicate things too much. */
  1528. if (!re_string_first_byte (pstr, pstr->cur_idx))
  1529. return re_string_fetch_byte (pstr);
  1530. off = pstr->offsets[pstr->cur_idx];
  1531. ch = pstr->raw_mbs[pstr->raw_mbs_idx + off];
  1532. if (! isascii (ch))
  1533. return re_string_fetch_byte (pstr);
  1534. re_string_skip_bytes (pstr,
  1535. re_string_char_size_at (pstr, pstr->cur_idx));
  1536. return ch;
  1537. }
  1538. #endif
  1539. return pstr->raw_mbs[pstr->raw_mbs_idx + pstr->cur_idx++];
  1540. }
  1541. static void
  1542. internal_function
  1543. re_string_destruct (re_string_t *pstr)
  1544. {
  1545. #ifdef RE_ENABLE_I18N
  1546. re_free (pstr->wcs);
  1547. re_free (pstr->offsets);
  1548. #endif /* RE_ENABLE_I18N */
  1549. if (pstr->mbs_allocated)
  1550. re_free (pstr->mbs);
  1551. }
  1552. /* Return the context at IDX in INPUT. */
  1553. static unsigned int
  1554. internal_function
  1555. re_string_context_at (const re_string_t *input, int idx, int eflags)
  1556. {
  1557. int c;
  1558. if (BE (idx < 0, 0))
  1559. /* In this case, we use the value stored in input->tip_context,
  1560. since we can't know the character in input->mbs[-1] here. */
  1561. return input->tip_context;
  1562. if (BE (idx == input->len, 0))
  1563. return ((eflags & REG_NOTEOL) ? CONTEXT_ENDBUF
  1564. : CONTEXT_NEWLINE | CONTEXT_ENDBUF);
  1565. #ifdef RE_ENABLE_I18N
  1566. if (input->mb_cur_max > 1)
  1567. {
  1568. wint_t wc;
  1569. int wc_idx = idx;
  1570. while(input->wcs[wc_idx] == WEOF)
  1571. {
  1572. #ifdef DEBUG
  1573. /* It must not happen. */
  1574. assert (wc_idx >= 0);
  1575. #endif
  1576. --wc_idx;
  1577. if (wc_idx < 0)
  1578. return input->tip_context;
  1579. }
  1580. wc = input->wcs[wc_idx];
  1581. if (BE (input->word_ops_used != 0, 0) && IS_WIDE_WORD_CHAR (wc))
  1582. return CONTEXT_WORD;
  1583. return (IS_WIDE_NEWLINE (wc) && input->newline_anchor
  1584. ? CONTEXT_NEWLINE : 0);
  1585. }
  1586. else
  1587. #endif
  1588. {
  1589. c = re_string_byte_at (input, idx);
  1590. if (bitset_contain (input->word_char, c))
  1591. return CONTEXT_WORD;
  1592. return IS_NEWLINE (c) && input->newline_anchor ? CONTEXT_NEWLINE : 0;
  1593. }
  1594. }
  1595. /* Functions for set operation. */
  1596. static reg_errcode_t
  1597. internal_function
  1598. re_node_set_alloc (re_node_set *set, int size)
  1599. {
  1600. set->alloc = size;
  1601. set->nelem = 0;
  1602. set->elems = re_malloc (int, size);
  1603. if (BE (set->elems == NULL, 0))
  1604. return REG_ESPACE;
  1605. return REG_NOERROR;
  1606. }
  1607. static reg_errcode_t
  1608. internal_function
  1609. re_node_set_init_1 (re_node_set *set, int elem)
  1610. {
  1611. set->alloc = 1;
  1612. set->nelem = 1;
  1613. set->elems = re_malloc (int, 1);
  1614. if (BE (set->elems == NULL, 0))
  1615. {
  1616. set->alloc = set->nelem = 0;
  1617. return REG_ESPACE;
  1618. }
  1619. set->elems[0] = elem;
  1620. return REG_NOERROR;
  1621. }
  1622. static reg_errcode_t
  1623. internal_function
  1624. re_node_set_init_2 (re_node_set *set, int elem1, int elem2)
  1625. {
  1626. set->alloc = 2;
  1627. set->elems = re_malloc (int, 2);
  1628. if (BE (set->elems == NULL, 0))
  1629. return REG_ESPACE;
  1630. if (elem1 == elem2)
  1631. {
  1632. set->nelem = 1;
  1633. set->elems[0] = elem1;
  1634. }
  1635. else
  1636. {
  1637. set->nelem = 2;
  1638. if (elem1 < elem2)
  1639. {
  1640. set->elems[0] = elem1;
  1641. set->elems[1] = elem2;
  1642. }
  1643. else
  1644. {
  1645. set->elems[0] = elem2;
  1646. set->elems[1] = elem1;
  1647. }
  1648. }
  1649. return REG_NOERROR;
  1650. }
  1651. static reg_errcode_t
  1652. internal_function
  1653. re_node_set_init_copy (re_node_set *dest, const re_node_set *src)
  1654. {
  1655. dest->nelem = src->nelem;
  1656. if (src->nelem > 0)
  1657. {
  1658. dest->alloc = dest->nelem;
  1659. dest->elems = re_malloc (int, dest->alloc);
  1660. if (BE (dest->elems == NULL, 0))
  1661. {
  1662. dest->alloc = dest->nelem = 0;
  1663. return REG_ESPACE;
  1664. }
  1665. memcpy (dest->elems, src->elems, src->nelem * sizeof (int));
  1666. }
  1667. else
  1668. re_node_set_init_empty (dest);
  1669. return REG_NOERROR;
  1670. }
  1671. /* Calculate the intersection of the sets SRC1 and SRC2. And merge it to
  1672. DEST. Return value indicate the error code or REG_NOERROR if succeeded.
  1673. Note: We assume dest->elems is NULL, when dest->alloc is 0. */
  1674. static reg_errcode_t
  1675. internal_function
  1676. re_node_set_add_intersect (re_node_set *dest, const re_node_set *src1,
  1677. const re_node_set *src2)
  1678. {
  1679. int i1, i2, is, id, delta, sbase;
  1680. if (src1->nelem == 0 || src2->nelem == 0)
  1681. return REG_NOERROR;
  1682. /* We need dest->nelem + 2 * elems_in_intersection; this is a
  1683. conservative estimate. */
  1684. if (src1->nelem + src2->nelem + dest->nelem > dest->alloc)
  1685. {
  1686. int new_alloc = src1->nelem + src2->nelem + dest->alloc;
  1687. int *new_elems = re_realloc (dest->elems, int, new_alloc);
  1688. if (BE (new_elems == NULL, 0))
  1689. return REG_ESPACE;
  1690. dest->elems = new_elems;
  1691. dest->alloc = new_alloc;
  1692. }
  1693. /* Find the items in the intersection of SRC1 and SRC2, and copy
  1694. into the top of DEST those that are not already in DEST itself. */
  1695. sbase = dest->nelem + src1->nelem + src2->nelem;
  1696. i1 = src1->nelem - 1;
  1697. i2 = src2->nelem - 1;
  1698. id = dest->nelem - 1;
  1699. for (;;)
  1700. {
  1701. if (src1->elems[i1] == src2->elems[i2])
  1702. {
  1703. /* Try to find the item in DEST. Maybe we could binary search? */
  1704. while (id >= 0 && dest->elems[id] > src1->elems[i1])
  1705. --id;
  1706. if (id < 0 || dest->elems[id] != src1->elems[i1])
  1707. dest->elems[--sbase] = src1->elems[i1];
  1708. if (--i1 < 0 || --i2 < 0)
  1709. break;
  1710. }
  1711. /* Lower the highest of the two items. */
  1712. else if (src1->elems[i1] < src2->elems[i2])
  1713. {
  1714. if (--i2 < 0)
  1715. break;
  1716. }
  1717. else
  1718. {
  1719. if (--i1 < 0)
  1720. break;
  1721. }
  1722. }
  1723. id = dest->nelem - 1;
  1724. is = dest->nelem + src1->nelem + src2->nelem - 1;
  1725. delta = is - sbase + 1;
  1726. /* Now copy. When DELTA becomes zero, the remaining
  1727. DEST elements are already in place; this is more or
  1728. less the same loop that is in re_node_set_merge. */
  1729. dest->nelem += delta;
  1730. if (delta > 0 && id >= 0)
  1731. for (;;)
  1732. {
  1733. if (dest->elems[is] > dest->elems[id])
  1734. {
  1735. /* Copy from the top. */
  1736. dest->elems[id + delta--] = dest->elems[is--];
  1737. if (delta == 0)
  1738. break;
  1739. }
  1740. else
  1741. {
  1742. /* Slide from the bottom. */
  1743. dest->elems[id + delta] = dest->elems[id];
  1744. if (--id < 0)
  1745. break;
  1746. }
  1747. }
  1748. /* Copy remaining SRC elements. */
  1749. memcpy (dest->elems, dest->elems + sbase, delta * sizeof (int));
  1750. return REG_NOERROR;
  1751. }
  1752. /* Calculate the union set of the sets SRC1 and SRC2. And store it to
  1753. DEST. Return value indicate the error code or REG_NOERROR if succeeded. */
  1754. static reg_errcode_t
  1755. internal_function
  1756. re_node_set_init_union (re_node_set *dest, const re_node_set *src1,
  1757. const re_node_set *src2)
  1758. {
  1759. int i1, i2, id;
  1760. if (src1 != NULL && src1->nelem > 0 && src2 != NULL && src2->nelem > 0)
  1761. {
  1762. dest->alloc = src1->nelem + src2->nelem;
  1763. dest->elems = re_malloc (int, dest->alloc);
  1764. if (BE (dest->elems == NULL, 0))
  1765. return REG_ESPACE;
  1766. }
  1767. else
  1768. {
  1769. if (src1 != NULL && src1->nelem > 0)
  1770. return re_node_set_init_copy (dest, src1);
  1771. else if (src2 != NULL && src2->nelem > 0)
  1772. return re_node_set_init_copy (dest, src2);
  1773. else
  1774. re_node_set_init_empty (dest);
  1775. return REG_NOERROR;
  1776. }
  1777. for (i1 = i2 = id = 0 ; i1 < src1->nelem && i2 < src2->nelem ;)
  1778. {
  1779. if (src1->elems[i1] > src2->elems[i2])
  1780. {
  1781. dest->elems[id++] = src2->elems[i2++];
  1782. continue;
  1783. }
  1784. if (src1->elems[i1] == src2->elems[i2])
  1785. ++i2;
  1786. dest->elems[id++] = src1->elems[i1++];
  1787. }
  1788. if (i1 < src1->nelem)
  1789. {
  1790. memcpy (dest->elems + id, src1->elems + i1,
  1791. (src1->nelem - i1) * sizeof (int));
  1792. id += src1->nelem - i1;
  1793. }
  1794. else if (i2 < src2->nelem)
  1795. {
  1796. memcpy (dest->elems + id, src2->elems + i2,
  1797. (src2->nelem - i2) * sizeof (int));
  1798. id += src2->nelem - i2;
  1799. }
  1800. dest->nelem = id;
  1801. return REG_NOERROR;
  1802. }
  1803. /* Calculate the union set of the sets DEST and SRC. And store it to
  1804. DEST. Return value indicate the error code or REG_NOERROR if succeeded. */
  1805. static reg_errcode_t
  1806. internal_function
  1807. re_node_set_merge (re_node_set *dest, const re_node_set *src)
  1808. {
  1809. int is, id, sbase, delta;
  1810. if (src == NULL || src->nelem == 0)
  1811. return REG_NOERROR;
  1812. if (dest->alloc < 2 * src->nelem + dest->nelem)
  1813. {
  1814. int new_alloc = 2 * (src->nelem + dest->alloc);
  1815. int *new_buffer = re_realloc (dest->elems, int, new_alloc);
  1816. if (BE (new_buffer == NULL, 0))
  1817. return REG_ESPACE;
  1818. dest->elems = new_buffer;
  1819. dest->alloc = new_alloc;
  1820. }
  1821. if (BE (dest->nelem == 0, 0))
  1822. {
  1823. dest->nelem = src->nelem;
  1824. memcpy (dest->elems, src->elems, src->nelem * sizeof (int));
  1825. return REG_NOERROR;
  1826. }
  1827. /* Copy into the top of DEST the items of SRC that are not
  1828. found in DEST. Maybe we could binary search in DEST? */
  1829. for (sbase = dest->nelem + 2 * src->nelem,
  1830. is = src->nelem - 1, id = dest->nelem - 1; is >= 0 && id >= 0; )
  1831. {
  1832. if (dest->elems[id] == src->elems[is])
  1833. is--, id--;
  1834. else if (dest->elems[id] < src->elems[is])
  1835. dest->elems[--sbase] = src->elems[is--];
  1836. else /* if (dest->elems[id] > src->elems[is]) */
  1837. --id;
  1838. }
  1839. if (is >= 0)
  1840. {
  1841. /* If DEST is exhausted, the remaining items of SRC must be unique. */
  1842. sbase -= is + 1;
  1843. memcpy (dest->elems + sbase, src->elems, (is + 1) * sizeof (int));
  1844. }
  1845. id = dest->nelem - 1;
  1846. is = dest->nelem + 2 * src->nelem - 1;
  1847. delta = is - sbase + 1;
  1848. if (delta == 0)
  1849. return REG_NOERROR;
  1850. /* Now copy. When DELTA becomes zero, the remaining
  1851. DEST elements are already in place. */
  1852. dest->nelem += delta;
  1853. for (;;)
  1854. {
  1855. if (dest->elems[is] > dest->elems[id])
  1856. {
  1857. /* Copy from the top. */
  1858. dest->elems[id + delta--] = dest->elems[is--];
  1859. if (delta == 0)
  1860. break;
  1861. }
  1862. else
  1863. {
  1864. /* Slide from the bottom. */
  1865. dest->elems[id + delta] = dest->elems[id];
  1866. if (--id < 0)
  1867. {
  1868. /* Copy remaining SRC elements. */
  1869. memcpy (dest->elems, dest->elems + sbase,
  1870. delta * sizeof (int));
  1871. break;
  1872. }
  1873. }
  1874. }
  1875. return REG_NOERROR;
  1876. }
  1877. /* Insert the new element ELEM to the re_node_set* SET.
  1878. SET should not already have ELEM.
  1879. return -1 if an error is occured, return 1 otherwise. */
  1880. static int
  1881. internal_function
  1882. re_node_set_insert (re_node_set *set, int elem)
  1883. {
  1884. int idx;
  1885. /* In case the set is empty. */
  1886. if (set->alloc == 0)
  1887. {
  1888. if (BE (re_node_set_init_1 (set, elem) == REG_NOERROR, 1))
  1889. return 1;
  1890. else
  1891. return -1;
  1892. }
  1893. if (BE (set->nelem, 0) == 0)
  1894. {
  1895. /* We already guaranteed above that set->alloc != 0. */
  1896. set->elems[0] = elem;
  1897. ++set->nelem;
  1898. return 1;
  1899. }
  1900. /* Realloc if we need. */
  1901. if (set->alloc == set->nelem)
  1902. {
  1903. int *new_elems;
  1904. set->alloc = set->alloc * 2;
  1905. new_elems = re_realloc (set->elems, int, set->alloc);
  1906. if (BE (new_elems == NULL, 0))
  1907. return -1;
  1908. set->elems = new_elems;
  1909. }
  1910. /* Move the elements which follows the new element. Test the
  1911. first element separately to skip a check in the inner loop. */
  1912. if (elem < set->elems[0])
  1913. {
  1914. idx = 0;
  1915. for (idx = set->nelem; idx > 0; idx--)
  1916. set->elems[idx] = set->elems[idx - 1];
  1917. }
  1918. else
  1919. {
  1920. for (idx = set->nelem; set->elems[idx - 1] > elem; idx--)
  1921. set->elems[idx] = set->elems[idx - 1];
  1922. }
  1923. /* Insert the new element. */
  1924. set->elems[idx] = elem;
  1925. ++set->nelem;
  1926. return 1;
  1927. }
  1928. /* Insert the new element ELEM to the re_node_set* SET.
  1929. SET should not already have any element greater than or equal to ELEM.
  1930. Return -1 if an error is occured, return 1 otherwise. */
  1931. static int
  1932. internal_function
  1933. re_node_set_insert_last (re_node_set *set, int elem)
  1934. {
  1935. /* Realloc if we need. */
  1936. if (set->alloc == set->nelem)
  1937. {
  1938. int *new_elems;
  1939. set->alloc = (set->alloc + 1) * 2;
  1940. new_elems = re_realloc (set->elems, int, set->alloc);
  1941. if (BE (new_elems == NULL, 0))
  1942. return -1;
  1943. set->elems = new_elems;
  1944. }
  1945. /* Insert the new element. */
  1946. set->elems[set->nelem++] = elem;
  1947. return 1;
  1948. }
  1949. /* Compare two node sets SET1 and SET2.
  1950. return 1 if SET1 and SET2 are equivalent, return 0 otherwise. */
  1951. static int
  1952. internal_function __attribute ((pure))
  1953. re_node_set_compare (const re_node_set *set1, const re_node_set *set2)
  1954. {
  1955. int i;
  1956. if (set1 == NULL || set2 == NULL || set1->nelem != set2->nelem)
  1957. return 0;
  1958. for (i = set1->nelem ; --i >= 0 ; )
  1959. if (set1->elems[i] != set2->elems[i])
  1960. return 0;
  1961. return 1;
  1962. }
  1963. /* Return (idx + 1) if SET contains the element ELEM, return 0 otherwise. */
  1964. static int
  1965. internal_function __attribute ((pure))
  1966. re_node_set_contains (const re_node_set *set, int elem)
  1967. {
  1968. unsigned int idx, right, mid;
  1969. if (set->nelem <= 0)
  1970. return 0;
  1971. /* Binary search the element. */
  1972. idx = 0;
  1973. right = set->nelem - 1;
  1974. while (idx < right)
  1975. {
  1976. mid = (idx + right) / 2;
  1977. if (set->elems[mid] < elem)
  1978. idx = mid + 1;
  1979. else
  1980. right = mid;
  1981. }
  1982. return set->elems[idx] == elem ? idx + 1 : 0;
  1983. }
  1984. static void
  1985. internal_function
  1986. re_node_set_remove_at (re_node_set *set, int idx)
  1987. {
  1988. if (idx < 0 || idx >= set->nelem)
  1989. return;
  1990. --set->nelem;
  1991. for (; idx < set->nelem; idx++)
  1992. set->elems[idx] = set->elems[idx + 1];
  1993. }
  1994. /* Add the token TOKEN to dfa->nodes, and return the index of the token.
  1995. Or return -1, if an error will be occured. */
  1996. static int
  1997. internal_function
  1998. re_dfa_add_node (re_dfa_t *dfa, re_token_t token)
  1999. {
  2000. int type = token.type;
  2001. if (BE (dfa->nodes_len >= dfa->nodes_alloc, 0))
  2002. {
  2003. size_t new_nodes_alloc = dfa->nodes_alloc * 2;
  2004. int *new_nexts, *new_indices;
  2005. re_node_set *new_edests, *new_eclosures;
  2006. re_token_t *new_nodes;
  2007. /* Avoid overflows. */
  2008. if (BE (new_nodes_alloc < dfa->nodes_alloc, 0))
  2009. return -1;
  2010. new_nodes = re_realloc (dfa->nodes, re_token_t, new_nodes_alloc);
  2011. if (BE (new_nodes == NULL, 0))
  2012. return -1;
  2013. dfa->nodes = new_nodes;
  2014. new_nexts = re_realloc (dfa->nexts, int, new_nodes_alloc);
  2015. new_indices = re_realloc (dfa->org_indices, int, new_nodes_alloc);
  2016. new_edests = re_realloc (dfa->edests, re_node_set, new_nodes_alloc);
  2017. new_eclosures = re_realloc (dfa->eclosures, re_node_set, new_nodes_alloc);
  2018. if (BE (new_nexts == NULL || new_indices == NULL
  2019. || new_edests == NULL || new_eclosures == NULL, 0))
  2020. return -1;
  2021. dfa->nexts = new_nexts;
  2022. dfa->org_indices = new_indices;
  2023. dfa->edests = new_edests;
  2024. dfa->eclosures = new_eclosures;
  2025. dfa->nodes_alloc = new_nodes_alloc;
  2026. }
  2027. dfa->nodes[dfa->nodes_len] = token;
  2028. dfa->nodes[dfa->nodes_len].constraint = 0;
  2029. #ifdef RE_ENABLE_I18N
  2030. dfa->nodes[dfa->nodes_len].accept_mb =
  2031. (type == OP_PERIOD && dfa->mb_cur_max > 1) || type == COMPLEX_BRACKET;
  2032. #endif
  2033. dfa->nexts[dfa->nodes_len] = -1;
  2034. re_node_set_init_empty (dfa->edests + dfa->nodes_len);
  2035. re_node_set_init_empty (dfa->eclosures + dfa->nodes_len);
  2036. return dfa->nodes_len++;
  2037. }
  2038. static inline unsigned int
  2039. internal_function
  2040. calc_state_hash (const re_node_set *nodes, unsigned int context)
  2041. {
  2042. unsigned int hash = nodes->nelem + context;
  2043. int i;
  2044. for (i = 0 ; i < nodes->nelem ; i++)
  2045. hash += nodes->elems[i];
  2046. return hash;
  2047. }
  2048. /* Search for the state whose node_set is equivalent to NODES.
  2049. Return the pointer to the state, if we found it in the DFA.
  2050. Otherwise create the new one and return it. In case of an error
  2051. return NULL and set the error code in ERR.
  2052. Note: - We assume NULL as the invalid state, then it is possible that
  2053. return value is NULL and ERR is REG_NOERROR.
  2054. - We never return non-NULL value in case of any errors, it is for
  2055. optimization. */
  2056. static re_dfastate_t *
  2057. internal_function
  2058. re_acquire_state (reg_errcode_t *err, const re_dfa_t *dfa,
  2059. const re_node_set *nodes)
  2060. {
  2061. unsigned int hash;
  2062. re_dfastate_t *new_state;
  2063. struct re_state_table_entry *spot;
  2064. int i;
  2065. if (BE (nodes->nelem == 0, 0))
  2066. {
  2067. *err = REG_NOERROR;
  2068. return NULL;
  2069. }
  2070. hash = calc_state_hash (nodes, 0);
  2071. spot = dfa->state_table + (hash & dfa->state_hash_mask);
  2072. for (i = 0 ; i < spot->num ; i++)
  2073. {
  2074. re_dfastate_t *state = spot->array[i];
  2075. if (hash != state->hash)
  2076. continue;
  2077. if (re_node_set_compare (&state->nodes, nodes))
  2078. return state;
  2079. }
  2080. /* There are no appropriate state in the dfa, create the new one. */
  2081. new_state = create_ci_newstate (dfa, nodes, hash);
  2082. if (BE (new_state == NULL, 0))
  2083. *err = REG_ESPACE;
  2084. return new_state;
  2085. }
  2086. /* Search for the state whose node_set is equivalent to NODES and
  2087. whose context is equivalent to CONTEXT.
  2088. Return the pointer to the state, if we found it in the DFA.
  2089. Otherwise create the new one and return it. In case of an error
  2090. return NULL and set the error code in ERR.
  2091. Note: - We assume NULL as the invalid state, then it is possible that
  2092. return value is NULL and ERR is REG_NOERROR.
  2093. - We never return non-NULL value in case of any errors, it is for
  2094. optimization. */
  2095. static re_dfastate_t *
  2096. internal_function
  2097. re_acquire_state_context (reg_errcode_t *err, const re_dfa_t *dfa,
  2098. const re_node_set *nodes, unsigned int context)
  2099. {
  2100. unsigned int hash;
  2101. re_dfastate_t *new_state;
  2102. struct re_state_table_entry *spot;
  2103. int i;
  2104. if (nodes->nelem == 0)
  2105. {
  2106. *err = REG_NOERROR;
  2107. return NULL;
  2108. }
  2109. hash = calc_state_hash (nodes, context);
  2110. spot = dfa->state_table + (hash & dfa->state_hash_mask);
  2111. for (i = 0 ; i < spot->num ; i++)
  2112. {
  2113. re_dfastate_t *state = spot->array[i];
  2114. if (state->hash == hash
  2115. && state->context == context
  2116. && re_node_set_compare (state->entrance_nodes, nodes))
  2117. return state;
  2118. }
  2119. /* There are no appropriate state in `dfa', create the new one. */
  2120. new_state = create_cd_newstate (dfa, nodes, context, hash);
  2121. if (BE (new_state == NULL, 0))
  2122. *err = REG_ESPACE;
  2123. return new_state;
  2124. }
  2125. /* Finish initialization of the new state NEWSTATE, and using its hash value
  2126. HASH put in the appropriate bucket of DFA's state table. Return value
  2127. indicates the error code if failed. */
  2128. static reg_errcode_t
  2129. register_state (const re_dfa_t *dfa, re_dfastate_t *newstate,
  2130. unsigned int hash)
  2131. {
  2132. struct re_state_table_entry *spot;
  2133. reg_errcode_t err;
  2134. int i;
  2135. newstate->hash = hash;
  2136. err = re_node_set_alloc (&newstate->non_eps_nodes, newstate->nodes.nelem);
  2137. if (BE (err != REG_NOERROR, 0))
  2138. return REG_ESPACE;
  2139. for (i = 0; i < newstate->nodes.nelem; i++)
  2140. {
  2141. int elem = newstate->nodes.elems[i];
  2142. if (!IS_EPSILON_NODE (dfa->nodes[elem].type))
  2143. re_node_set_insert_last (&newstate->non_eps_nodes, elem);
  2144. }
  2145. spot = dfa->state_table + (hash & dfa->state_hash_mask);
  2146. if (BE (spot->alloc <= spot->num, 0))
  2147. {
  2148. int new_alloc = 2 * spot->num + 2;
  2149. re_dfastate_t **new_array = re_realloc (spot->array, re_dfastate_t *,
  2150. new_alloc);
  2151. if (BE (new_array == NULL, 0))
  2152. return REG_ESPACE;
  2153. spot->array = new_array;
  2154. spot->alloc = new_alloc;
  2155. }
  2156. spot->array[spot->num++] = newstate;
  2157. return REG_NOERROR;
  2158. }
  2159. static void
  2160. free_state (re_dfastate_t *state)
  2161. {
  2162. re_node_set_free (&state->non_eps_nodes);
  2163. re_node_set_free (&state->inveclosure);
  2164. if (state->entrance_nodes != &state->nodes)
  2165. {
  2166. re_node_set_free (state->entrance_nodes);
  2167. re_free (state->entrance_nodes);
  2168. }
  2169. re_node_set_free (&state->nodes);
  2170. re_free (state->word_trtable);
  2171. re_free (state->trtable);
  2172. re_free (state);
  2173. }
  2174. /* Create the new state which is independ of contexts.
  2175. Return the new state if succeeded, otherwise return NULL. */
  2176. static re_dfastate_t *
  2177. internal_function
  2178. create_ci_newstate (const re_dfa_t *dfa, const re_node_set *nodes,
  2179. unsigned int hash)
  2180. {
  2181. int i;
  2182. reg_errcode_t err;
  2183. re_dfastate_t *newstate;
  2184. newstate = (re_dfastate_t *) calloc (sizeof (re_dfastate_t), 1);
  2185. if (BE (newstate == NULL, 0))
  2186. return NULL;
  2187. err = re_node_set_init_copy (&newstate->nodes, nodes);
  2188. if (BE (err != REG_NOERROR, 0))
  2189. {
  2190. re_free (newstate);
  2191. return NULL;
  2192. }
  2193. newstate->entrance_nodes = &newstate->nodes;
  2194. for (i = 0 ; i < nodes->nelem ; i++)
  2195. {
  2196. re_token_t *node = dfa->nodes + nodes->elems[i];
  2197. re_token_type_t type = node->type;
  2198. if (type == CHARACTER && !node->constraint)
  2199. continue;
  2200. #ifdef RE_ENABLE_I18N
  2201. newstate->accept_mb |= node->accept_mb;
  2202. #endif /* RE_ENABLE_I18N */
  2203. /* If the state has the halt node, the state is a halt state. */
  2204. if (type == END_OF_RE)
  2205. newstate->halt = 1;
  2206. else if (type == OP_BACK_REF)
  2207. newstate->has_backref = 1;
  2208. else if (type == ANCHOR || node->constraint)
  2209. newstate->has_constraint = 1;
  2210. }
  2211. err = register_state (dfa, newstate, hash);
  2212. if (BE (err != REG_NOERROR, 0))
  2213. {
  2214. free_state (newstate);
  2215. newstate = NULL;
  2216. }
  2217. return newstate;
  2218. }
  2219. /* Create the new state which is depend on the context CONTEXT.
  2220. Return the new state if succeeded, otherwise return NULL. */
  2221. static re_dfastate_t *
  2222. internal_function
  2223. create_cd_newstate (const re_dfa_t *dfa, const re_node_set *nodes,
  2224. unsigned int context, unsigned int hash)
  2225. {
  2226. int i, nctx_nodes = 0;
  2227. reg_errcode_t err;
  2228. re_dfastate_t *newstate;
  2229. newstate = (re_dfastate_t *) calloc (sizeof (re_dfastate_t), 1);
  2230. if (BE (newstate == NULL, 0))
  2231. return NULL;
  2232. err = re_node_set_init_copy (&newstate->nodes, nodes);
  2233. if (BE (err != REG_NOERROR, 0))
  2234. {
  2235. re_free (newstate);
  2236. return NULL;
  2237. }
  2238. newstate->context = context;
  2239. newstate->entrance_nodes = &newstate->nodes;
  2240. for (i = 0 ; i < nodes->nelem ; i++)
  2241. {
  2242. re_token_t *node = dfa->nodes + nodes->elems[i];
  2243. re_token_type_t type = node->type;
  2244. unsigned int constraint = node->constraint;
  2245. if (type == CHARACTER && !constraint)
  2246. continue;
  2247. #ifdef RE_ENABLE_I18N
  2248. newstate->accept_mb |= node->accept_mb;
  2249. #endif /* RE_ENABLE_I18N */
  2250. /* If the state has the halt node, the state is a halt state. */
  2251. if (type == END_OF_RE)
  2252. newstate->halt = 1;
  2253. else if (type == OP_BACK_REF)
  2254. newstate->has_backref = 1;
  2255. if (constraint)
  2256. {
  2257. if (newstate->entrance_nodes == &newstate->nodes)
  2258. {
  2259. newstate->entrance_nodes = re_malloc (re_node_set, 1);
  2260. if (BE (newstate->entrance_nodes == NULL, 0))
  2261. {
  2262. free_state (newstate);
  2263. return NULL;
  2264. }
  2265. re_node_set_init_copy (newstate->entrance_nodes, nodes);
  2266. nctx_nodes = 0;
  2267. newstate->has_constraint = 1;
  2268. }
  2269. if (NOT_SATISFY_PREV_CONSTRAINT (constraint,context))
  2270. {
  2271. re_node_set_remove_at (&newstate->nodes, i - nctx_nodes);
  2272. ++nctx_nodes;
  2273. }
  2274. }
  2275. }
  2276. err = register_state (dfa, newstate, hash);
  2277. if (BE (err != REG_NOERROR, 0))
  2278. {
  2279. free_state (newstate);
  2280. newstate = NULL;
  2281. }
  2282. return newstate;
  2283. }
  2284. /* Extended regular expression matching and search library.
  2285. Copyright (C) 2002,2003,2004,2005,2006,2007 Free Software Foundation, Inc.
  2286. This file is part of the GNU C Library.
  2287. Contributed by Isamu Hasegawa <isamu@yamato.ibm.com>.
  2288. The GNU C Library is free software; you can redistribute it and/or
  2289. modify it under the terms of the GNU Lesser General Public
  2290. License as published by the Free Software Foundation; either
  2291. version 2.1 of the License, or (at your option) any later version.
  2292. The GNU C Library is distributed in the hope that it will be useful,
  2293. but WITHOUT ANY WARRANTY; without even the implied warranty of
  2294. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  2295. Lesser General Public License for more details.
  2296. You should have received a copy of the GNU Lesser General Public
  2297. License along with the GNU C Library; if not, write to the Free
  2298. Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  2299. 02111-1307 USA. */
  2300. static reg_errcode_t re_compile_internal (regex_t *preg, const char * pattern,
  2301. size_t length, reg_syntax_t syntax);
  2302. static void re_compile_fastmap_iter (regex_t *bufp,
  2303. const re_dfastate_t *init_state,
  2304. char *fastmap);
  2305. static reg_errcode_t init_dfa (re_dfa_t *dfa, size_t pat_len);
  2306. #ifdef RE_ENABLE_I18N
  2307. static void free_charset (re_charset_t *cset);
  2308. #endif /* RE_ENABLE_I18N */
  2309. static void free_workarea_compile (regex_t *preg);
  2310. static reg_errcode_t create_initial_state (re_dfa_t *dfa);
  2311. #ifdef RE_ENABLE_I18N
  2312. static void optimize_utf8 (re_dfa_t *dfa);
  2313. #endif
  2314. static reg_errcode_t analyze (regex_t *preg);
  2315. static reg_errcode_t preorder (bin_tree_t *root,
  2316. reg_errcode_t (fn (void *, bin_tree_t *)),
  2317. void *extra);
  2318. static reg_errcode_t postorder (bin_tree_t *root,
  2319. reg_errcode_t (fn (void *, bin_tree_t *)),
  2320. void *extra);
  2321. static reg_errcode_t optimize_subexps (void *extra, bin_tree_t *node);
  2322. static reg_errcode_t lower_subexps (void *extra, bin_tree_t *node);
  2323. static bin_tree_t *lower_subexp (reg_errcode_t *err, regex_t *preg,
  2324. bin_tree_t *node);
  2325. static reg_errcode_t calc_first (void *extra, bin_tree_t *node);
  2326. static reg_errcode_t calc_next (void *extra, bin_tree_t *node);
  2327. static reg_errcode_t link_nfa_nodes (void *extra, bin_tree_t *node);
  2328. static int duplicate_node (re_dfa_t *dfa, int org_idx, unsigned int constraint);
  2329. static int search_duplicated_node (const re_dfa_t *dfa, int org_node,
  2330. unsigned int constraint);
  2331. static reg_errcode_t calc_eclosure (re_dfa_t *dfa);
  2332. static reg_errcode_t calc_eclosure_iter (re_node_set *new_set, re_dfa_t *dfa,
  2333. int node, int root);
  2334. static reg_errcode_t calc_inveclosure (re_dfa_t *dfa);
  2335. static int fetch_number (re_string_t *input, re_token_t *token,
  2336. reg_syntax_t syntax);
  2337. static int peek_token (re_token_t *token, re_string_t *input,
  2338. reg_syntax_t syntax) internal_function;
  2339. static bin_tree_t *parse (re_string_t *regexp, regex_t *preg,
  2340. reg_syntax_t syntax, reg_errcode_t *err);
  2341. static bin_tree_t *parse_reg_exp (re_string_t *regexp, regex_t *preg,
  2342. re_token_t *token, reg_syntax_t syntax,
  2343. int nest, reg_errcode_t *err);
  2344. static bin_tree_t *parse_branch (re_string_t *regexp, regex_t *preg,
  2345. re_token_t *token, reg_syntax_t syntax,
  2346. int nest, reg_errcode_t *err);
  2347. static bin_tree_t *parse_expression (re_string_t *regexp, regex_t *preg,
  2348. re_token_t *token, reg_syntax_t syntax,
  2349. int nest, reg_errcode_t *err);
  2350. static bin_tree_t *parse_sub_exp (re_string_t *regexp, regex_t *preg,
  2351. re_token_t *token, reg_syntax_t syntax,
  2352. int nest, reg_errcode_t *err);
  2353. static bin_tree_t *parse_dup_op (bin_tree_t *dup_elem, re_string_t *regexp,
  2354. re_dfa_t *dfa, re_token_t *token,
  2355. reg_syntax_t syntax, reg_errcode_t *err);
  2356. static bin_tree_t *parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa,
  2357. re_token_t *token, reg_syntax_t syntax,
  2358. reg_errcode_t *err);
  2359. static reg_errcode_t parse_bracket_element (bracket_elem_t *elem,
  2360. re_string_t *regexp,
  2361. re_token_t *token, int token_len,
  2362. re_dfa_t *dfa,
  2363. reg_syntax_t syntax,
  2364. int accept_hyphen);
  2365. static reg_errcode_t parse_bracket_symbol (bracket_elem_t *elem,
  2366. re_string_t *regexp,
  2367. re_token_t *token);
  2368. #ifdef RE_ENABLE_I18N
  2369. static reg_errcode_t build_equiv_class (bitset_t sbcset,
  2370. re_charset_t *mbcset,
  2371. int *equiv_class_alloc,
  2372. const unsigned char *name);
  2373. static reg_errcode_t build_charclass (RE_TRANSLATE_TYPE trans,
  2374. bitset_t sbcset,
  2375. re_charset_t *mbcset,
  2376. int *char_class_alloc,
  2377. const unsigned char *class_name,
  2378. reg_syntax_t syntax);
  2379. #else /* not RE_ENABLE_I18N */
  2380. static reg_errcode_t build_equiv_class (bitset_t sbcset,
  2381. const unsigned char *name);
  2382. static reg_errcode_t build_charclass (RE_TRANSLATE_TYPE trans,
  2383. bitset_t sbcset,
  2384. const unsigned char *class_name,
  2385. reg_syntax_t syntax);
  2386. #endif /* not RE_ENABLE_I18N */
  2387. static bin_tree_t *build_charclass_op (re_dfa_t *dfa,
  2388. RE_TRANSLATE_TYPE trans,
  2389. const unsigned char *class_name,
  2390. const unsigned char *extra,
  2391. int non_match, reg_errcode_t *err);
  2392. static bin_tree_t *create_tree (re_dfa_t *dfa,
  2393. bin_tree_t *left, bin_tree_t *right,
  2394. re_token_type_t type);
  2395. static bin_tree_t *create_token_tree (re_dfa_t *dfa,
  2396. bin_tree_t *left, bin_tree_t *right,
  2397. const re_token_t *token);
  2398. static bin_tree_t *duplicate_tree (const bin_tree_t *src, re_dfa_t *dfa);
  2399. static void free_token (re_token_t *node);
  2400. static reg_errcode_t free_tree (void *extra, bin_tree_t *node);
  2401. static reg_errcode_t mark_opt_subexp (void *extra, bin_tree_t *node);
  2402. /* This table gives an error message for each of the error codes listed
  2403. in regex.h. Obviously the order here has to be same as there.
  2404. POSIX doesn't require that we do anything for REG_NOERROR,
  2405. but why not be nice? */
  2406. const char __re_error_msgid[] attribute_hidden =
  2407. {
  2408. #define REG_NOERROR_IDX 0
  2409. gettext_noop ("Success") /* REG_NOERROR */
  2410. "\0"
  2411. #define REG_NOMATCH_IDX (REG_NOERROR_IDX + sizeof "Success")
  2412. gettext_noop ("No match") /* REG_NOMATCH */
  2413. "\0"
  2414. #define REG_BADPAT_IDX (REG_NOMATCH_IDX + sizeof "No match")
  2415. gettext_noop ("Invalid regular expression") /* REG_BADPAT */
  2416. "\0"
  2417. #define REG_ECOLLATE_IDX (REG_BADPAT_IDX + sizeof "Invalid regular expression")
  2418. gettext_noop ("Invalid collation character") /* REG_ECOLLATE */
  2419. "\0"
  2420. #define REG_ECTYPE_IDX (REG_ECOLLATE_IDX + sizeof "Invalid collation character")
  2421. gettext_noop ("Invalid character class name") /* REG_ECTYPE */
  2422. "\0"
  2423. #define REG_EESCAPE_IDX (REG_ECTYPE_IDX + sizeof "Invalid character class name")
  2424. gettext_noop ("Trailing backslash") /* REG_EESCAPE */
  2425. "\0"
  2426. #define REG_ESUBREG_IDX (REG_EESCAPE_IDX + sizeof "Trailing backslash")
  2427. gettext_noop ("Invalid back reference") /* REG_ESUBREG */
  2428. "\0"
  2429. #define REG_EBRACK_IDX (REG_ESUBREG_IDX + sizeof "Invalid back reference")
  2430. gettext_noop ("Unmatched [ or [^") /* REG_EBRACK */
  2431. "\0"
  2432. #define REG_EPAREN_IDX (REG_EBRACK_IDX + sizeof "Unmatched [ or [^")
  2433. gettext_noop ("Unmatched ( or \\(") /* REG_EPAREN */
  2434. "\0"
  2435. #define REG_EBRACE_IDX (REG_EPAREN_IDX + sizeof "Unmatched ( or \\(")
  2436. gettext_noop ("Unmatched \\{") /* REG_EBRACE */
  2437. "\0"
  2438. #define REG_BADBR_IDX (REG_EBRACE_IDX + sizeof "Unmatched \\{")
  2439. gettext_noop ("Invalid content of \\{\\}") /* REG_BADBR */
  2440. "\0"
  2441. #define REG_ERANGE_IDX (REG_BADBR_IDX + sizeof "Invalid content of \\{\\}")
  2442. gettext_noop ("Invalid range end") /* REG_ERANGE */
  2443. "\0"
  2444. #define REG_ESPACE_IDX (REG_ERANGE_IDX + sizeof "Invalid range end")
  2445. gettext_noop ("Memory exhausted") /* REG_ESPACE */
  2446. "\0"
  2447. #define REG_BADRPT_IDX (REG_ESPACE_IDX + sizeof "Memory exhausted")
  2448. gettext_noop ("Invalid preceding regular expression") /* REG_BADRPT */
  2449. "\0"
  2450. #define REG_EEND_IDX (REG_BADRPT_IDX + sizeof "Invalid preceding regular expression")
  2451. gettext_noop ("Premature end of regular expression") /* REG_EEND */
  2452. "\0"
  2453. #define REG_ESIZE_IDX (REG_EEND_IDX + sizeof "Premature end of regular expression")
  2454. gettext_noop ("Regular expression too big") /* REG_ESIZE */
  2455. "\0"
  2456. #define REG_ERPAREN_IDX (REG_ESIZE_IDX + sizeof "Regular expression too big")
  2457. gettext_noop ("Unmatched ) or \\)") /* REG_ERPAREN */
  2458. };
  2459. const size_t __re_error_msgid_idx[] attribute_hidden =
  2460. {
  2461. REG_NOERROR_IDX,
  2462. REG_NOMATCH_IDX,
  2463. REG_BADPAT_IDX,
  2464. REG_ECOLLATE_IDX,
  2465. REG_ECTYPE_IDX,
  2466. REG_EESCAPE_IDX,
  2467. REG_ESUBREG_IDX,
  2468. REG_EBRACK_IDX,
  2469. REG_EPAREN_IDX,
  2470. REG_EBRACE_IDX,
  2471. REG_BADBR_IDX,
  2472. REG_ERANGE_IDX,
  2473. REG_ESPACE_IDX,
  2474. REG_BADRPT_IDX,
  2475. REG_EEND_IDX,
  2476. REG_ESIZE_IDX,
  2477. REG_ERPAREN_IDX
  2478. };
  2479. /* Entry points for GNU code. */
  2480. /* re_compile_pattern is the GNU regular expression compiler: it
  2481. compiles PATTERN (of length LENGTH) and puts the result in BUFP.
  2482. Returns 0 if the pattern was valid, otherwise an error string.
  2483. Assumes the `allocated' (and perhaps `buffer') and `translate' fields
  2484. are set in BUFP on entry. */
  2485. const char *
  2486. re_compile_pattern (pattern, length, bufp)
  2487. const char *pattern;
  2488. size_t length;
  2489. struct re_pattern_buffer *bufp;
  2490. {
  2491. reg_errcode_t ret;
  2492. /* And GNU code determines whether or not to get register information
  2493. by passing null for the REGS argument to re_match, etc., not by
  2494. setting no_sub, unless RE_NO_SUB is set. */
  2495. bufp->no_sub = !!(re_syntax_options & RE_NO_SUB);
  2496. /* Match anchors at newline. */
  2497. bufp->newline_anchor = 1;
  2498. ret = re_compile_internal (bufp, pattern, length, re_syntax_options);
  2499. if (!ret)
  2500. return NULL;
  2501. return gettext (__re_error_msgid + __re_error_msgid_idx[(int) ret]);
  2502. }
  2503. #ifdef _LIBC
  2504. weak_alias (__re_compile_pattern, re_compile_pattern)
  2505. #endif
  2506. /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
  2507. also be assigned to arbitrarily: each pattern buffer stores its own
  2508. syntax, so it can be changed between regex compilations. */
  2509. /* This has no initializer because initialized variables in Emacs
  2510. become read-only after dumping. */
  2511. reg_syntax_t re_syntax_options;
  2512. /* Specify the precise syntax of regexps for compilation. This provides
  2513. for compatibility for various utilities which historically have
  2514. different, incompatible syntaxes.
  2515. The argument SYNTAX is a bit mask comprised of the various bits
  2516. defined in regex.h. We return the old syntax. */
  2517. reg_syntax_t
  2518. re_set_syntax (syntax)
  2519. reg_syntax_t syntax;
  2520. {
  2521. reg_syntax_t ret = re_syntax_options;
  2522. re_syntax_options = syntax;
  2523. return ret;
  2524. }
  2525. #ifdef _LIBC
  2526. weak_alias (__re_set_syntax, re_set_syntax)
  2527. #endif
  2528. int
  2529. re_compile_fastmap (bufp)
  2530. struct re_pattern_buffer *bufp;
  2531. {
  2532. re_dfa_t *dfa = (re_dfa_t *) bufp->buffer;
  2533. char *fastmap = bufp->fastmap;
  2534. memset (fastmap, '\0', sizeof (char) * SBC_MAX);
  2535. re_compile_fastmap_iter (bufp, dfa->init_state, fastmap);
  2536. if (dfa->init_state != dfa->init_state_word)
  2537. re_compile_fastmap_iter (bufp, dfa->init_state_word, fastmap);
  2538. if (dfa->init_state != dfa->init_state_nl)
  2539. re_compile_fastmap_iter (bufp, dfa->init_state_nl, fastmap);
  2540. if (dfa->init_state != dfa->init_state_begbuf)
  2541. re_compile_fastmap_iter (bufp, dfa->init_state_begbuf, fastmap);
  2542. bufp->fastmap_accurate = 1;
  2543. return 0;
  2544. }
  2545. #ifdef _LIBC
  2546. weak_alias (__re_compile_fastmap, re_compile_fastmap)
  2547. #endif
  2548. static inline void
  2549. __attribute ((always_inline))
  2550. re_set_fastmap (char *fastmap, int icase, int ch)
  2551. {
  2552. fastmap[ch] = 1;
  2553. if (icase)
  2554. fastmap[tolower (ch)] = 1;
  2555. }
  2556. /* Helper function for re_compile_fastmap.
  2557. Compile fastmap for the initial_state INIT_STATE. */
  2558. static void
  2559. re_compile_fastmap_iter (regex_t *bufp, const re_dfastate_t *init_state,
  2560. char *fastmap)
  2561. {
  2562. re_dfa_t *dfa = (re_dfa_t *) bufp->buffer;
  2563. int node_cnt;
  2564. int icase = (dfa->mb_cur_max == 1 && (bufp->syntax & RE_ICASE));
  2565. for (node_cnt = 0; node_cnt < init_state->nodes.nelem; ++node_cnt)
  2566. {
  2567. int node = init_state->nodes.elems[node_cnt];
  2568. re_token_type_t type = dfa->nodes[node].type;
  2569. if (type == CHARACTER)
  2570. {
  2571. re_set_fastmap (fastmap, icase, dfa->nodes[node].opr.c);
  2572. #ifdef RE_ENABLE_I18N
  2573. if ((bufp->syntax & RE_ICASE) && dfa->mb_cur_max > 1)
  2574. {
  2575. unsigned char *buf = alloca (dfa->mb_cur_max), *p;
  2576. wchar_t wc;
  2577. mbstate_t state;
  2578. p = buf;
  2579. *p++ = dfa->nodes[node].opr.c;
  2580. while (++node < dfa->nodes_len
  2581. && dfa->nodes[node].type == CHARACTER
  2582. && dfa->nodes[node].mb_partial)
  2583. *p++ = dfa->nodes[node].opr.c;
  2584. memset (&state, '\0', sizeof (state));
  2585. if (mbrtowc (&wc, (const char *) buf, p - buf,
  2586. &state) == p - buf
  2587. && (__wcrtomb ((char *) buf, towlower (wc), &state)
  2588. != (size_t) -1))
  2589. re_set_fastmap (fastmap, 0, buf[0]);
  2590. }
  2591. #endif
  2592. }
  2593. else if (type == SIMPLE_BRACKET)
  2594. {
  2595. int i, ch;
  2596. for (i = 0, ch = 0; i < BITSET_WORDS; ++i)
  2597. {
  2598. int j;
  2599. bitset_word_t w = dfa->nodes[node].opr.sbcset[i];
  2600. for (j = 0; j < BITSET_WORD_BITS; ++j, ++ch)
  2601. if (w & ((bitset_word_t) 1 << j))
  2602. re_set_fastmap (fastmap, icase, ch);
  2603. }
  2604. }
  2605. #ifdef RE_ENABLE_I18N
  2606. else if (type == COMPLEX_BRACKET)
  2607. {
  2608. int i;
  2609. re_charset_t *cset = dfa->nodes[node].opr.mbcset;
  2610. if (cset->non_match || cset->ncoll_syms || cset->nequiv_classes
  2611. || cset->nranges || cset->nchar_classes)
  2612. {
  2613. # ifdef _LIBC
  2614. if (_NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES) != 0)
  2615. {
  2616. /* In this case we want to catch the bytes which are
  2617. the first byte of any collation elements.
  2618. e.g. In da_DK, we want to catch 'a' since "aa"
  2619. is a valid collation element, and don't catch
  2620. 'b' since 'b' is the only collation element
  2621. which starts from 'b'. */
  2622. const int32_t *table = (const int32_t *)
  2623. _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
  2624. for (i = 0; i < SBC_MAX; ++i)
  2625. if (table[i] < 0)
  2626. re_set_fastmap (fastmap, icase, i);
  2627. }
  2628. # else
  2629. if (dfa->mb_cur_max > 1)
  2630. for (i = 0; i < SBC_MAX; ++i)
  2631. if (__btowc (i) == WEOF)
  2632. re_set_fastmap (fastmap, icase, i);
  2633. # endif /* not _LIBC */
  2634. }
  2635. for (i = 0; i < cset->nmbchars; ++i)
  2636. {
  2637. char buf[256];
  2638. mbstate_t state;
  2639. memset (&state, '\0', sizeof (state));
  2640. if (__wcrtomb (buf, cset->mbchars[i], &state) != (size_t) -1)
  2641. re_set_fastmap (fastmap, icase, *(unsigned char *) buf);
  2642. if ((bufp->syntax & RE_ICASE) && dfa->mb_cur_max > 1)
  2643. {
  2644. if (__wcrtomb (buf, towlower (cset->mbchars[i]), &state)
  2645. != (size_t) -1)
  2646. re_set_fastmap (fastmap, 0, *(unsigned char *) buf);
  2647. }
  2648. }
  2649. }
  2650. #endif /* RE_ENABLE_I18N */
  2651. else if (type == OP_PERIOD
  2652. #ifdef RE_ENABLE_I18N
  2653. || type == OP_UTF8_PERIOD
  2654. #endif /* RE_ENABLE_I18N */
  2655. || type == END_OF_RE)
  2656. {
  2657. memset (fastmap, '\1', sizeof (char) * SBC_MAX);
  2658. if (type == END_OF_RE)
  2659. bufp->can_be_null = 1;
  2660. return;
  2661. }
  2662. }
  2663. }
  2664. /* Entry point for POSIX code. */
  2665. /* regcomp takes a regular expression as a string and compiles it.
  2666. PREG is a regex_t *. We do not expect any fields to be initialized,
  2667. since POSIX says we shouldn't. Thus, we set
  2668. `buffer' to the compiled pattern;
  2669. `used' to the length of the compiled pattern;
  2670. `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
  2671. REG_EXTENDED bit in CFLAGS is set; otherwise, to
  2672. RE_SYNTAX_POSIX_BASIC;
  2673. `newline_anchor' to REG_NEWLINE being set in CFLAGS;
  2674. `fastmap' to an allocated space for the fastmap;
  2675. `fastmap_accurate' to zero;
  2676. `re_nsub' to the number of subexpressions in PATTERN.
  2677. PATTERN is the address of the pattern string.
  2678. CFLAGS is a series of bits which affect compilation.
  2679. If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
  2680. use POSIX basic syntax.
  2681. If REG_NEWLINE is set, then . and [^...] don't match newline.
  2682. Also, regexec will try a match beginning after every newline.
  2683. If REG_ICASE is set, then we considers upper- and lowercase
  2684. versions of letters to be equivalent when matching.
  2685. If REG_NOSUB is set, then when PREG is passed to regexec, that
  2686. routine will report only success or failure, and nothing about the
  2687. registers.
  2688. It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
  2689. the return codes and their meanings.) */
  2690. int
  2691. regcomp (preg, pattern, cflags)
  2692. regex_t *__restrict preg;
  2693. const char *__restrict pattern;
  2694. int cflags;
  2695. {
  2696. reg_errcode_t ret;
  2697. reg_syntax_t syntax = ((cflags & REG_EXTENDED) ? RE_SYNTAX_POSIX_EXTENDED
  2698. : RE_SYNTAX_POSIX_BASIC);
  2699. preg->buffer = NULL;
  2700. preg->allocated = 0;
  2701. preg->used = 0;
  2702. /* Try to allocate space for the fastmap. */
  2703. preg->fastmap = re_malloc (char, SBC_MAX);
  2704. if (BE (preg->fastmap == NULL, 0))
  2705. return REG_ESPACE;
  2706. syntax |= (cflags & REG_ICASE) ? RE_ICASE : 0;
  2707. /* If REG_NEWLINE is set, newlines are treated differently. */
  2708. if (cflags & REG_NEWLINE)
  2709. { /* REG_NEWLINE implies neither . nor [^...] match newline. */
  2710. syntax &= ~RE_DOT_NEWLINE;
  2711. syntax |= RE_HAT_LISTS_NOT_NEWLINE;
  2712. /* It also changes the matching behavior. */
  2713. preg->newline_anchor = 1;
  2714. }
  2715. else
  2716. preg->newline_anchor = 0;
  2717. preg->no_sub = !!(cflags & REG_NOSUB);
  2718. preg->translate = NULL;
  2719. ret = re_compile_internal (preg, pattern, strlen (pattern), syntax);
  2720. /* POSIX doesn't distinguish between an unmatched open-group and an
  2721. unmatched close-group: both are REG_EPAREN. */
  2722. if (ret == REG_ERPAREN)
  2723. ret = REG_EPAREN;
  2724. /* We have already checked preg->fastmap != NULL. */
  2725. if (BE (ret == REG_NOERROR, 1))
  2726. /* Compute the fastmap now, since regexec cannot modify the pattern
  2727. buffer. This function never fails in this implementation. */
  2728. (void) re_compile_fastmap (preg);
  2729. else
  2730. {
  2731. /* Some error occurred while compiling the expression. */
  2732. re_free (preg->fastmap);
  2733. preg->fastmap = NULL;
  2734. }
  2735. return (int) ret;
  2736. }
  2737. #ifdef _LIBC
  2738. weak_alias (__regcomp, regcomp)
  2739. #endif
  2740. /* Returns a message corresponding to an error code, ERRCODE, returned
  2741. from either regcomp or regexec. We don't use PREG here. */
  2742. size_t
  2743. regerror (errcode, preg, errbuf, errbuf_size)
  2744. int errcode;
  2745. const regex_t *__restrict preg;
  2746. char *__restrict errbuf;
  2747. size_t errbuf_size;
  2748. {
  2749. const char *msg;
  2750. size_t msg_size;
  2751. if (BE (errcode < 0
  2752. || errcode >= (int) (sizeof (__re_error_msgid_idx)
  2753. / sizeof (__re_error_msgid_idx[0])), 0))
  2754. /* Only error codes returned by the rest of the code should be passed
  2755. to this routine. If we are given anything else, or if other regex
  2756. code generates an invalid error code, then the program has a bug.
  2757. Dump core so we can fix it. */
  2758. abort ();
  2759. msg = gettext (__re_error_msgid + __re_error_msgid_idx[errcode]);
  2760. msg_size = strlen (msg) + 1; /* Includes the null. */
  2761. if (BE (errbuf_size != 0, 1))
  2762. {
  2763. if (BE (msg_size > errbuf_size, 0))
  2764. {
  2765. #if defined HAVE_MEMPCPY || defined _LIBC
  2766. *((char *) __mempcpy (errbuf, msg, errbuf_size - 1)) = '\0';
  2767. #else
  2768. memcpy (errbuf, msg, errbuf_size - 1);
  2769. errbuf[errbuf_size - 1] = 0;
  2770. #endif
  2771. }
  2772. else
  2773. memcpy (errbuf, msg, msg_size);
  2774. }
  2775. return msg_size;
  2776. }
  2777. #ifdef _LIBC
  2778. weak_alias (__regerror, regerror)
  2779. #endif
  2780. #ifdef RE_ENABLE_I18N
  2781. /* This static array is used for the map to single-byte characters when
  2782. UTF-8 is used. Otherwise we would allocate memory just to initialize
  2783. it the same all the time. UTF-8 is the preferred encoding so this is
  2784. a worthwhile optimization. */
  2785. static const bitset_t utf8_sb_map =
  2786. {
  2787. /* Set the first 128 bits. */
  2788. [0 ... 0x80 / BITSET_WORD_BITS - 1] = BITSET_WORD_MAX
  2789. };
  2790. #endif
  2791. static void
  2792. free_dfa_content (re_dfa_t *dfa)
  2793. {
  2794. int i, j;
  2795. if (dfa->nodes)
  2796. for (i = 0; i < dfa->nodes_len; ++i)
  2797. free_token (dfa->nodes + i);
  2798. re_free (dfa->nexts);
  2799. for (i = 0; i < dfa->nodes_len; ++i)
  2800. {
  2801. if (dfa->eclosures != NULL)
  2802. re_node_set_free (dfa->eclosures + i);
  2803. if (dfa->inveclosures != NULL)
  2804. re_node_set_free (dfa->inveclosures + i);
  2805. if (dfa->edests != NULL)
  2806. re_node_set_free (dfa->edests + i);
  2807. }
  2808. re_free (dfa->edests);
  2809. re_free (dfa->eclosures);
  2810. re_free (dfa->inveclosures);
  2811. re_free (dfa->nodes);
  2812. if (dfa->state_table)
  2813. for (i = 0; i <= dfa->state_hash_mask; ++i)
  2814. {
  2815. struct re_state_table_entry *entry = dfa->state_table + i;
  2816. for (j = 0; j < entry->num; ++j)
  2817. {
  2818. re_dfastate_t *state = entry->array[j];
  2819. free_state (state);
  2820. }
  2821. re_free (entry->array);
  2822. }
  2823. re_free (dfa->state_table);
  2824. #ifdef RE_ENABLE_I18N
  2825. if (dfa->sb_char != utf8_sb_map)
  2826. re_free (dfa->sb_char);
  2827. #endif
  2828. re_free (dfa->subexp_map);
  2829. #ifdef DEBUG
  2830. re_free (dfa->re_str);
  2831. #endif
  2832. re_free (dfa);
  2833. }
  2834. /* Free dynamically allocated space used by PREG. */
  2835. void
  2836. regfree (preg)
  2837. regex_t *preg;
  2838. {
  2839. re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
  2840. if (BE (dfa != NULL, 1))
  2841. free_dfa_content (dfa);
  2842. preg->buffer = NULL;
  2843. preg->allocated = 0;
  2844. re_free (preg->fastmap);
  2845. preg->fastmap = NULL;
  2846. re_free (preg->translate);
  2847. preg->translate = NULL;
  2848. }
  2849. #ifdef _LIBC
  2850. weak_alias (__regfree, regfree)
  2851. #endif
  2852. /* Entry points compatible with 4.2 BSD regex library. We don't define
  2853. them unless specifically requested. */
  2854. #if defined _REGEX_RE_COMP || defined _LIBC
  2855. /* BSD has one and only one pattern buffer. */
  2856. static struct re_pattern_buffer re_comp_buf;
  2857. char *
  2858. # ifdef _LIBC
  2859. /* Make these definitions weak in libc, so POSIX programs can redefine
  2860. these names if they don't use our functions, and still use
  2861. regcomp/regexec above without link errors. */
  2862. weak_function
  2863. # endif
  2864. re_comp (s)
  2865. const char *s;
  2866. {
  2867. reg_errcode_t ret;
  2868. char *fastmap;
  2869. if (!s)
  2870. {
  2871. if (!re_comp_buf.buffer)
  2872. return gettext ("No previous regular expression");
  2873. return 0;
  2874. }
  2875. if (re_comp_buf.buffer)
  2876. {
  2877. fastmap = re_comp_buf.fastmap;
  2878. re_comp_buf.fastmap = NULL;
  2879. __regfree (&re_comp_buf);
  2880. memset (&re_comp_buf, '\0', sizeof (re_comp_buf));
  2881. re_comp_buf.fastmap = fastmap;
  2882. }
  2883. if (re_comp_buf.fastmap == NULL)
  2884. {
  2885. re_comp_buf.fastmap = (char *) malloc (SBC_MAX);
  2886. if (re_comp_buf.fastmap == NULL)
  2887. return (char *) gettext (__re_error_msgid
  2888. + __re_error_msgid_idx[(int) REG_ESPACE]);
  2889. }
  2890. /* Since `re_exec' always passes NULL for the `regs' argument, we
  2891. don't need to initialize the pattern buffer fields which affect it. */
  2892. /* Match anchors at newlines. */
  2893. re_comp_buf.newline_anchor = 1;
  2894. ret = re_compile_internal (&re_comp_buf, s, strlen (s), re_syntax_options);
  2895. if (!ret)
  2896. return NULL;
  2897. /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
  2898. return (char *) gettext (__re_error_msgid + __re_error_msgid_idx[(int) ret]);
  2899. }
  2900. #ifdef _LIBC
  2901. libc_freeres_fn (free_mem)
  2902. {
  2903. __regfree (&re_comp_buf);
  2904. }
  2905. #endif
  2906. #endif /* _REGEX_RE_COMP */
  2907. /* Internal entry point.
  2908. Compile the regular expression PATTERN, whose length is LENGTH.
  2909. SYNTAX indicate regular expression's syntax. */
  2910. static reg_errcode_t
  2911. re_compile_internal (regex_t *preg, const char * pattern, size_t length,
  2912. reg_syntax_t syntax)
  2913. {
  2914. reg_errcode_t err = REG_NOERROR;
  2915. re_dfa_t *dfa;
  2916. re_string_t regexp;
  2917. /* Initialize the pattern buffer. */
  2918. preg->fastmap_accurate = 0;
  2919. preg->syntax = syntax;
  2920. preg->not_bol = preg->not_eol = 0;
  2921. preg->used = 0;
  2922. preg->re_nsub = 0;
  2923. preg->can_be_null = 0;
  2924. preg->regs_allocated = REGS_UNALLOCATED;
  2925. /* Initialize the dfa. */
  2926. dfa = (re_dfa_t *) preg->buffer;
  2927. if (BE (preg->allocated < sizeof (re_dfa_t), 0))
  2928. {
  2929. /* If zero allocated, but buffer is non-null, try to realloc
  2930. enough space. This loses if buffer's address is bogus, but
  2931. that is the user's responsibility. If ->buffer is NULL this
  2932. is a simple allocation. */
  2933. dfa = re_realloc (preg->buffer, re_dfa_t, 1);
  2934. if (dfa == NULL)
  2935. return REG_ESPACE;
  2936. preg->allocated = sizeof (re_dfa_t);
  2937. preg->buffer = (unsigned char *) dfa;
  2938. }
  2939. preg->used = sizeof (re_dfa_t);
  2940. err = init_dfa (dfa, length);
  2941. if (BE (err != REG_NOERROR, 0))
  2942. {
  2943. free_dfa_content (dfa);
  2944. preg->buffer = NULL;
  2945. preg->allocated = 0;
  2946. return err;
  2947. }
  2948. #ifdef DEBUG
  2949. /* Note: length+1 will not overflow since it is checked in init_dfa. */
  2950. dfa->re_str = re_malloc (char, length + 1);
  2951. strncpy (dfa->re_str, pattern, length + 1);
  2952. #endif
  2953. __libc_lock_init (dfa->lock);
  2954. err = re_string_construct (&regexp, pattern, length, preg->translate,
  2955. syntax & RE_ICASE, dfa);
  2956. if (BE (err != REG_NOERROR, 0))
  2957. {
  2958. re_compile_internal_free_return:
  2959. free_workarea_compile (preg);
  2960. re_string_destruct (&regexp);
  2961. free_dfa_content (dfa);
  2962. preg->buffer = NULL;
  2963. preg->allocated = 0;
  2964. return err;
  2965. }
  2966. /* Parse the regular expression, and build a structure tree. */
  2967. preg->re_nsub = 0;
  2968. dfa->str_tree = parse (&regexp, preg, syntax, &err);
  2969. if (BE (dfa->str_tree == NULL, 0))
  2970. goto re_compile_internal_free_return;
  2971. /* Analyze the tree and create the nfa. */
  2972. err = analyze (preg);
  2973. if (BE (err != REG_NOERROR, 0))
  2974. goto re_compile_internal_free_return;
  2975. #ifdef RE_ENABLE_I18N
  2976. /* If possible, do searching in single byte encoding to speed things up. */
  2977. if (dfa->is_utf8 && !(syntax & RE_ICASE) && preg->translate == NULL)
  2978. optimize_utf8 (dfa);
  2979. #endif
  2980. /* Then create the initial state of the dfa. */
  2981. err = create_initial_state (dfa);
  2982. /* Release work areas. */
  2983. free_workarea_compile (preg);
  2984. re_string_destruct (&regexp);
  2985. if (BE (err != REG_NOERROR, 0))
  2986. {
  2987. free_dfa_content (dfa);
  2988. preg->buffer = NULL;
  2989. preg->allocated = 0;
  2990. }
  2991. return err;
  2992. }
  2993. /* Initialize DFA. We use the length of the regular expression PAT_LEN
  2994. as the initial length of some arrays. */
  2995. static reg_errcode_t
  2996. init_dfa (re_dfa_t *dfa, size_t pat_len)
  2997. {
  2998. unsigned int table_size;
  2999. #ifndef _LIBC
  3000. char *codeset_name;
  3001. #endif
  3002. memset (dfa, '\0', sizeof (re_dfa_t));
  3003. /* Force allocation of str_tree_storage the first time. */
  3004. dfa->str_tree_storage_idx = BIN_TREE_STORAGE_SIZE;
  3005. /* Avoid overflows. */
  3006. if (pat_len == SIZE_MAX)
  3007. return REG_ESPACE;
  3008. dfa->nodes_alloc = pat_len + 1;
  3009. dfa->nodes = re_malloc (re_token_t, dfa->nodes_alloc);
  3010. /* table_size = 2 ^ ceil(log pat_len) */
  3011. for (table_size = 1; ; table_size <<= 1)
  3012. if (table_size > pat_len)
  3013. break;
  3014. dfa->state_table = calloc (sizeof (struct re_state_table_entry), table_size);
  3015. dfa->state_hash_mask = table_size - 1;
  3016. dfa->mb_cur_max = MB_CUR_MAX;
  3017. #ifdef _LIBC
  3018. if (dfa->mb_cur_max == 6
  3019. && strcmp (_NL_CURRENT (LC_CTYPE, _NL_CTYPE_CODESET_NAME), "UTF-8") == 0)
  3020. dfa->is_utf8 = 1;
  3021. dfa->map_notascii = (_NL_CURRENT_WORD (LC_CTYPE, _NL_CTYPE_MAP_TO_NONASCII)
  3022. != 0);
  3023. #else
  3024. # ifdef HAVE_LANGINFO_CODESET
  3025. codeset_name = nl_langinfo (CODESET);
  3026. # else
  3027. codeset_name = getenv ("LC_ALL");
  3028. if (codeset_name == NULL || codeset_name[0] == '\0')
  3029. codeset_name = getenv ("LC_CTYPE");
  3030. if (codeset_name == NULL || codeset_name[0] == '\0')
  3031. codeset_name = getenv ("LANG");
  3032. if (codeset_name == NULL)
  3033. codeset_name = "";
  3034. else if (strchr (codeset_name, '.') != NULL)
  3035. codeset_name = strchr (codeset_name, '.') + 1;
  3036. # endif
  3037. if (strcasecmp (codeset_name, "UTF-8") == 0
  3038. || strcasecmp (codeset_name, "UTF8") == 0)
  3039. dfa->is_utf8 = 1;
  3040. /* We check exhaustively in the loop below if this charset is a
  3041. superset of ASCII. */
  3042. dfa->map_notascii = 0;
  3043. #endif
  3044. #ifdef RE_ENABLE_I18N
  3045. if (dfa->mb_cur_max > 1)
  3046. {
  3047. if (dfa->is_utf8)
  3048. dfa->sb_char = (re_bitset_ptr_t) utf8_sb_map;
  3049. else
  3050. {
  3051. int i, j, ch;
  3052. dfa->sb_char = (re_bitset_ptr_t) calloc (sizeof (bitset_t), 1);
  3053. if (BE (dfa->sb_char == NULL, 0))
  3054. return REG_ESPACE;
  3055. /* Set the bits corresponding to single byte chars. */
  3056. for (i = 0, ch = 0; i < BITSET_WORDS; ++i)
  3057. for (j = 0; j < BITSET_WORD_BITS; ++j, ++ch)
  3058. {
  3059. wint_t wch = __btowc (ch);
  3060. if (wch != WEOF)
  3061. dfa->sb_char[i] |= (bitset_word_t) 1 << j;
  3062. # ifndef _LIBC
  3063. if (isascii (ch) && wch != ch)
  3064. dfa->map_notascii = 1;
  3065. # endif
  3066. }
  3067. }
  3068. }
  3069. #endif
  3070. if (BE (dfa->nodes == NULL || dfa->state_table == NULL, 0))
  3071. return REG_ESPACE;
  3072. return REG_NOERROR;
  3073. }
  3074. /* Initialize WORD_CHAR table, which indicate which character is
  3075. "word". In this case "word" means that it is the word construction
  3076. character used by some operators like "\<", "\>", etc. */
  3077. static void
  3078. internal_function
  3079. init_word_char (re_dfa_t *dfa)
  3080. {
  3081. int i, j, ch;
  3082. dfa->word_ops_used = 1;
  3083. for (i = 0, ch = 0; i < BITSET_WORDS; ++i)
  3084. for (j = 0; j < BITSET_WORD_BITS; ++j, ++ch)
  3085. if (isalnum (ch) || ch == '_')
  3086. dfa->word_char[i] |= (bitset_word_t) 1 << j;
  3087. }
  3088. /* Free the work area which are only used while compiling. */
  3089. static void
  3090. free_workarea_compile (regex_t *preg)
  3091. {
  3092. re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
  3093. bin_tree_storage_t *storage, *next;
  3094. for (storage = dfa->str_tree_storage; storage; storage = next)
  3095. {
  3096. next = storage->next;
  3097. re_free (storage);
  3098. }
  3099. dfa->str_tree_storage = NULL;
  3100. dfa->str_tree_storage_idx = BIN_TREE_STORAGE_SIZE;
  3101. dfa->str_tree = NULL;
  3102. re_free (dfa->org_indices);
  3103. dfa->org_indices = NULL;
  3104. }
  3105. /* Create initial states for all contexts. */
  3106. static reg_errcode_t
  3107. create_initial_state (re_dfa_t *dfa)
  3108. {
  3109. int first, i;
  3110. reg_errcode_t err;
  3111. re_node_set init_nodes;
  3112. /* Initial states have the epsilon closure of the node which is
  3113. the first node of the regular expression. */
  3114. first = dfa->str_tree->first->node_idx;
  3115. dfa->init_node = first;
  3116. err = re_node_set_init_copy (&init_nodes, dfa->eclosures + first);
  3117. if (BE (err != REG_NOERROR, 0))
  3118. return err;
  3119. /* The back-references which are in initial states can epsilon transit,
  3120. since in this case all of the subexpressions can be null.
  3121. Then we add epsilon closures of the nodes which are the next nodes of
  3122. the back-references. */
  3123. if (dfa->nbackref > 0)
  3124. for (i = 0; i < init_nodes.nelem; ++i)
  3125. {
  3126. int node_idx = init_nodes.elems[i];
  3127. re_token_type_t type = dfa->nodes[node_idx].type;
  3128. int clexp_idx;
  3129. if (type != OP_BACK_REF)
  3130. continue;
  3131. for (clexp_idx = 0; clexp_idx < init_nodes.nelem; ++clexp_idx)
  3132. {
  3133. re_token_t *clexp_node;
  3134. clexp_node = dfa->nodes + init_nodes.elems[clexp_idx];
  3135. if (clexp_node->type == OP_CLOSE_SUBEXP
  3136. && clexp_node->opr.idx == dfa->nodes[node_idx].opr.idx)
  3137. break;
  3138. }
  3139. if (clexp_idx == init_nodes.nelem)
  3140. continue;
  3141. if (type == OP_BACK_REF)
  3142. {
  3143. int dest_idx = dfa->edests[node_idx].elems[0];
  3144. if (!re_node_set_contains (&init_nodes, dest_idx))
  3145. {
  3146. re_node_set_merge (&init_nodes, dfa->eclosures + dest_idx);
  3147. i = 0;
  3148. }
  3149. }
  3150. }
  3151. /* It must be the first time to invoke acquire_state. */
  3152. dfa->init_state = re_acquire_state_context (&err, dfa, &init_nodes, 0);
  3153. /* We don't check ERR here, since the initial state must not be NULL. */
  3154. if (BE (dfa->init_state == NULL, 0))
  3155. return err;
  3156. if (dfa->init_state->has_constraint)
  3157. {
  3158. dfa->init_state_word = re_acquire_state_context (&err, dfa, &init_nodes,
  3159. CONTEXT_WORD);
  3160. dfa->init_state_nl = re_acquire_state_context (&err, dfa, &init_nodes,
  3161. CONTEXT_NEWLINE);
  3162. dfa->init_state_begbuf = re_acquire_state_context (&err, dfa,
  3163. &init_nodes,
  3164. CONTEXT_NEWLINE
  3165. | CONTEXT_BEGBUF);
  3166. if (BE (dfa->init_state_word == NULL || dfa->init_state_nl == NULL
  3167. || dfa->init_state_begbuf == NULL, 0))
  3168. return err;
  3169. }
  3170. else
  3171. dfa->init_state_word = dfa->init_state_nl
  3172. = dfa->init_state_begbuf = dfa->init_state;
  3173. re_node_set_free (&init_nodes);
  3174. return REG_NOERROR;
  3175. }
  3176. #ifdef RE_ENABLE_I18N
  3177. /* If it is possible to do searching in single byte encoding instead of UTF-8
  3178. to speed things up, set dfa->mb_cur_max to 1, clear is_utf8 and change
  3179. DFA nodes where needed. */
  3180. static void
  3181. optimize_utf8 (re_dfa_t *dfa)
  3182. {
  3183. int node, i, mb_chars = 0, has_period = 0;
  3184. for (node = 0; node < dfa->nodes_len; ++node)
  3185. switch (dfa->nodes[node].type)
  3186. {
  3187. case CHARACTER:
  3188. if (dfa->nodes[node].opr.c >= 0x80)
  3189. mb_chars = 1;
  3190. break;
  3191. case ANCHOR:
  3192. switch (dfa->nodes[node].opr.ctx_type)
  3193. {
  3194. case LINE_FIRST:
  3195. case LINE_LAST:
  3196. case BUF_FIRST:
  3197. case BUF_LAST:
  3198. break;
  3199. default:
  3200. /* Word anchors etc. cannot be handled. It's okay to test
  3201. opr.ctx_type since constraints (for all DFA nodes) are
  3202. created by ORing one or more opr.ctx_type values. */
  3203. return;
  3204. }
  3205. break;
  3206. case OP_PERIOD:
  3207. has_period = 1;
  3208. break;
  3209. case OP_BACK_REF:
  3210. case OP_ALT:
  3211. case END_OF_RE:
  3212. case OP_DUP_ASTERISK:
  3213. case OP_OPEN_SUBEXP:
  3214. case OP_CLOSE_SUBEXP:
  3215. break;
  3216. case COMPLEX_BRACKET:
  3217. return;
  3218. case SIMPLE_BRACKET:
  3219. /* Just double check. The non-ASCII range starts at 0x80. */
  3220. assert (0x80 % BITSET_WORD_BITS == 0);
  3221. for (i = 0x80 / BITSET_WORD_BITS; i < BITSET_WORDS; ++i)
  3222. if (dfa->nodes[node].opr.sbcset[i])
  3223. return;
  3224. break;
  3225. default:
  3226. abort ();
  3227. }
  3228. if (mb_chars || has_period)
  3229. for (node = 0; node < dfa->nodes_len; ++node)
  3230. {
  3231. if (dfa->nodes[node].type == CHARACTER
  3232. && dfa->nodes[node].opr.c >= 0x80)
  3233. dfa->nodes[node].mb_partial = 0;
  3234. else if (dfa->nodes[node].type == OP_PERIOD)
  3235. dfa->nodes[node].type = OP_UTF8_PERIOD;
  3236. }
  3237. /* The search can be in single byte locale. */
  3238. dfa->mb_cur_max = 1;
  3239. dfa->is_utf8 = 0;
  3240. dfa->has_mb_node = dfa->nbackref > 0 || has_period;
  3241. }
  3242. #endif
  3243. /* Analyze the structure tree, and calculate "first", "next", "edest",
  3244. "eclosure", and "inveclosure". */
  3245. static reg_errcode_t
  3246. analyze (regex_t *preg)
  3247. {
  3248. re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
  3249. reg_errcode_t ret;
  3250. /* Allocate arrays. */
  3251. dfa->nexts = re_malloc (int, dfa->nodes_alloc);
  3252. dfa->org_indices = re_malloc (int, dfa->nodes_alloc);
  3253. dfa->edests = re_malloc (re_node_set, dfa->nodes_alloc);
  3254. dfa->eclosures = re_malloc (re_node_set, dfa->nodes_alloc);
  3255. if (BE (dfa->nexts == NULL || dfa->org_indices == NULL || dfa->edests == NULL
  3256. || dfa->eclosures == NULL, 0))
  3257. return REG_ESPACE;
  3258. dfa->subexp_map = re_malloc (int, preg->re_nsub);
  3259. if (dfa->subexp_map != NULL)
  3260. {
  3261. int i;
  3262. for (i = 0; i < preg->re_nsub; i++)
  3263. dfa->subexp_map[i] = i;
  3264. preorder (dfa->str_tree, optimize_subexps, dfa);
  3265. for (i = 0; i < preg->re_nsub; i++)
  3266. if (dfa->subexp_map[i] != i)
  3267. break;
  3268. if (i == preg->re_nsub)
  3269. {
  3270. free (dfa->subexp_map);
  3271. dfa->subexp_map = NULL;
  3272. }
  3273. }
  3274. ret = postorder (dfa->str_tree, lower_subexps, preg);
  3275. if (BE (ret != REG_NOERROR, 0))
  3276. return ret;
  3277. ret = postorder (dfa->str_tree, calc_first, dfa);
  3278. if (BE (ret != REG_NOERROR, 0))
  3279. return ret;
  3280. preorder (dfa->str_tree, calc_next, dfa);
  3281. ret = preorder (dfa->str_tree, link_nfa_nodes, dfa);
  3282. if (BE (ret != REG_NOERROR, 0))
  3283. return ret;
  3284. ret = calc_eclosure (dfa);
  3285. if (BE (ret != REG_NOERROR, 0))
  3286. return ret;
  3287. /* We only need this during the prune_impossible_nodes pass in regexec.c;
  3288. skip it if p_i_n will not run, as calc_inveclosure can be quadratic. */
  3289. if ((!preg->no_sub && preg->re_nsub > 0 && dfa->has_plural_match)
  3290. || dfa->nbackref)
  3291. {
  3292. dfa->inveclosures = re_malloc (re_node_set, dfa->nodes_len);
  3293. if (BE (dfa->inveclosures == NULL, 0))
  3294. return REG_ESPACE;
  3295. ret = calc_inveclosure (dfa);
  3296. }
  3297. return ret;
  3298. }
  3299. /* Our parse trees are very unbalanced, so we cannot use a stack to
  3300. implement parse tree visits. Instead, we use parent pointers and
  3301. some hairy code in these two functions. */
  3302. static reg_errcode_t
  3303. postorder (bin_tree_t *root, reg_errcode_t (fn (void *, bin_tree_t *)),
  3304. void *extra)
  3305. {
  3306. bin_tree_t *node, *prev;
  3307. for (node = root; ; )
  3308. {
  3309. /* Descend down the tree, preferably to the left (or to the right
  3310. if that's the only child). */
  3311. while (node->left || node->right)
  3312. if (node->left)
  3313. node = node->left;
  3314. else
  3315. node = node->right;
  3316. do
  3317. {
  3318. reg_errcode_t err = fn (extra, node);
  3319. if (BE (err != REG_NOERROR, 0))
  3320. return err;
  3321. if (node->parent == NULL)
  3322. return REG_NOERROR;
  3323. prev = node;
  3324. node = node->parent;
  3325. }
  3326. /* Go up while we have a node that is reached from the right. */
  3327. while (node->right == prev || node->right == NULL);
  3328. node = node->right;
  3329. }
  3330. }
  3331. static reg_errcode_t
  3332. preorder (bin_tree_t *root, reg_errcode_t (fn (void *, bin_tree_t *)),
  3333. void *extra)
  3334. {
  3335. bin_tree_t *node;
  3336. for (node = root; ; )
  3337. {
  3338. reg_errcode_t err = fn (extra, node);
  3339. if (BE (err != REG_NOERROR, 0))
  3340. return err;
  3341. /* Go to the left node, or up and to the right. */
  3342. if (node->left)
  3343. node = node->left;
  3344. else
  3345. {
  3346. bin_tree_t *prev = NULL;
  3347. while (node->right == prev || node->right == NULL)
  3348. {
  3349. prev = node;
  3350. node = node->parent;
  3351. if (!node)
  3352. return REG_NOERROR;
  3353. }
  3354. node = node->right;
  3355. }
  3356. }
  3357. }
  3358. /* Optimization pass: if a SUBEXP is entirely contained, strip it and tell
  3359. re_search_internal to map the inner one's opr.idx to this one's. Adjust
  3360. backreferences as well. Requires a preorder visit. */
  3361. static reg_errcode_t
  3362. optimize_subexps (void *extra, bin_tree_t *node)
  3363. {
  3364. re_dfa_t *dfa = (re_dfa_t *) extra;
  3365. if (node->token.type == OP_BACK_REF && dfa->subexp_map)
  3366. {
  3367. int idx = node->token.opr.idx;
  3368. node->token.opr.idx = dfa->subexp_map[idx];
  3369. dfa->used_bkref_map |= 1 << node->token.opr.idx;
  3370. }
  3371. else if (node->token.type == SUBEXP
  3372. && node->left && node->left->token.type == SUBEXP)
  3373. {
  3374. int other_idx = node->left->token.opr.idx;
  3375. node->left = node->left->left;
  3376. if (node->left)
  3377. node->left->parent = node;
  3378. dfa->subexp_map[other_idx] = dfa->subexp_map[node->token.opr.idx];
  3379. if (other_idx < BITSET_WORD_BITS)
  3380. dfa->used_bkref_map &= ~((bitset_word_t) 1 << other_idx);
  3381. }
  3382. return REG_NOERROR;
  3383. }
  3384. /* Lowering pass: Turn each SUBEXP node into the appropriate concatenation
  3385. of OP_OPEN_SUBEXP, the body of the SUBEXP (if any) and OP_CLOSE_SUBEXP. */
  3386. static reg_errcode_t
  3387. lower_subexps (void *extra, bin_tree_t *node)
  3388. {
  3389. regex_t *preg = (regex_t *) extra;
  3390. reg_errcode_t err = REG_NOERROR;
  3391. if (node->left && node->left->token.type == SUBEXP)
  3392. {
  3393. node->left = lower_subexp (&err, preg, node->left);
  3394. if (node->left)
  3395. node->left->parent = node;
  3396. }
  3397. if (node->right && node->right->token.type == SUBEXP)
  3398. {
  3399. node->right = lower_subexp (&err, preg, node->right);
  3400. if (node->right)
  3401. node->right->parent = node;
  3402. }
  3403. return err;
  3404. }
  3405. static bin_tree_t *
  3406. lower_subexp (reg_errcode_t *err, regex_t *preg, bin_tree_t *node)
  3407. {
  3408. re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
  3409. bin_tree_t *body = node->left;
  3410. bin_tree_t *op, *cls, *tree1, *tree;
  3411. if (preg->no_sub
  3412. /* We do not optimize empty subexpressions, because otherwise we may
  3413. have bad CONCAT nodes with NULL children. This is obviously not
  3414. very common, so we do not lose much. An example that triggers
  3415. this case is the sed "script" /\(\)/x. */
  3416. && node->left != NULL
  3417. && (node->token.opr.idx >= BITSET_WORD_BITS
  3418. || !(dfa->used_bkref_map
  3419. & ((bitset_word_t) 1 << node->token.opr.idx))))
  3420. return node->left;
  3421. /* Convert the SUBEXP node to the concatenation of an
  3422. OP_OPEN_SUBEXP, the contents, and an OP_CLOSE_SUBEXP. */
  3423. op = create_tree (dfa, NULL, NULL, OP_OPEN_SUBEXP);
  3424. cls = create_tree (dfa, NULL, NULL, OP_CLOSE_SUBEXP);
  3425. tree1 = body ? create_tree (dfa, body, cls, CONCAT) : cls;
  3426. tree = create_tree (dfa, op, tree1, CONCAT);
  3427. if (BE (tree == NULL || tree1 == NULL || op == NULL || cls == NULL, 0))
  3428. {
  3429. *err = REG_ESPACE;
  3430. return NULL;
  3431. }
  3432. op->token.opr.idx = cls->token.opr.idx = node->token.opr.idx;
  3433. op->token.opt_subexp = cls->token.opt_subexp = node->token.opt_subexp;
  3434. return tree;
  3435. }
  3436. /* Pass 1 in building the NFA: compute FIRST and create unlinked automaton
  3437. nodes. Requires a postorder visit. */
  3438. static reg_errcode_t
  3439. calc_first (void *extra, bin_tree_t *node)
  3440. {
  3441. re_dfa_t *dfa = (re_dfa_t *) extra;
  3442. if (node->token.type == CONCAT)
  3443. {
  3444. node->first = node->left->first;
  3445. node->node_idx = node->left->node_idx;
  3446. }
  3447. else
  3448. {
  3449. node->first = node;
  3450. node->node_idx = re_dfa_add_node (dfa, node->token);
  3451. if (BE (node->node_idx == -1, 0))
  3452. return REG_ESPACE;
  3453. if (node->token.type == ANCHOR)
  3454. dfa->nodes[node->node_idx].constraint = node->token.opr.ctx_type;
  3455. }
  3456. return REG_NOERROR;
  3457. }
  3458. /* Pass 2: compute NEXT on the tree. Preorder visit. */
  3459. static reg_errcode_t
  3460. calc_next (void *extra, bin_tree_t *node)
  3461. {
  3462. switch (node->token.type)
  3463. {
  3464. case OP_DUP_ASTERISK:
  3465. node->left->next = node;
  3466. break;
  3467. case CONCAT:
  3468. node->left->next = node->right->first;
  3469. node->right->next = node->next;
  3470. break;
  3471. default:
  3472. if (node->left)
  3473. node->left->next = node->next;
  3474. if (node->right)
  3475. node->right->next = node->next;
  3476. break;
  3477. }
  3478. return REG_NOERROR;
  3479. }
  3480. /* Pass 3: link all DFA nodes to their NEXT node (any order will do). */
  3481. static reg_errcode_t
  3482. link_nfa_nodes (void *extra, bin_tree_t *node)
  3483. {
  3484. re_dfa_t *dfa = (re_dfa_t *) extra;
  3485. int idx = node->node_idx;
  3486. reg_errcode_t err = REG_NOERROR;
  3487. switch (node->token.type)
  3488. {
  3489. case CONCAT:
  3490. break;
  3491. case END_OF_RE:
  3492. assert (node->next == NULL);
  3493. break;
  3494. case OP_DUP_ASTERISK:
  3495. case OP_ALT:
  3496. {
  3497. int left, right;
  3498. dfa->has_plural_match = 1;
  3499. if (node->left != NULL)
  3500. left = node->left->first->node_idx;
  3501. else
  3502. left = node->next->node_idx;
  3503. if (node->right != NULL)
  3504. right = node->right->first->node_idx;
  3505. else
  3506. right = node->next->node_idx;
  3507. assert (left > -1);
  3508. assert (right > -1);
  3509. err = re_node_set_init_2 (dfa->edests + idx, left, right);
  3510. }
  3511. break;
  3512. case ANCHOR:
  3513. case OP_OPEN_SUBEXP:
  3514. case OP_CLOSE_SUBEXP:
  3515. err = re_node_set_init_1 (dfa->edests + idx, node->next->node_idx);
  3516. break;
  3517. case OP_BACK_REF:
  3518. dfa->nexts[idx] = node->next->node_idx;
  3519. if (node->token.type == OP_BACK_REF)
  3520. re_node_set_init_1 (dfa->edests + idx, dfa->nexts[idx]);
  3521. break;
  3522. default:
  3523. assert (!IS_EPSILON_NODE (node->token.type));
  3524. dfa->nexts[idx] = node->next->node_idx;
  3525. break;
  3526. }
  3527. return err;
  3528. }
  3529. /* Duplicate the epsilon closure of the node ROOT_NODE.
  3530. Note that duplicated nodes have constraint INIT_CONSTRAINT in addition
  3531. to their own constraint. */
  3532. static reg_errcode_t
  3533. internal_function
  3534. duplicate_node_closure (re_dfa_t *dfa, int top_org_node, int top_clone_node,
  3535. int root_node, unsigned int init_constraint)
  3536. {
  3537. int org_node, clone_node, ret;
  3538. unsigned int constraint = init_constraint;
  3539. for (org_node = top_org_node, clone_node = top_clone_node;;)
  3540. {
  3541. int org_dest, clone_dest;
  3542. if (dfa->nodes[org_node].type == OP_BACK_REF)
  3543. {
  3544. /* If the back reference epsilon-transit, its destination must
  3545. also have the constraint. Then duplicate the epsilon closure
  3546. of the destination of the back reference, and store it in
  3547. edests of the back reference. */
  3548. org_dest = dfa->nexts[org_node];
  3549. re_node_set_empty (dfa->edests + clone_node);
  3550. clone_dest = duplicate_node (dfa, org_dest, constraint);
  3551. if (BE (clone_dest == -1, 0))
  3552. return REG_ESPACE;
  3553. dfa->nexts[clone_node] = dfa->nexts[org_node];
  3554. ret = re_node_set_insert (dfa->edests + clone_node, clone_dest);
  3555. if (BE (ret < 0, 0))
  3556. return REG_ESPACE;
  3557. }
  3558. else if (dfa->edests[org_node].nelem == 0)
  3559. {
  3560. /* In case of the node can't epsilon-transit, don't duplicate the
  3561. destination and store the original destination as the
  3562. destination of the node. */
  3563. dfa->nexts[clone_node] = dfa->nexts[org_node];
  3564. break;
  3565. }
  3566. else if (dfa->edests[org_node].nelem == 1)
  3567. {
  3568. /* In case of the node can epsilon-transit, and it has only one
  3569. destination. */
  3570. org_dest = dfa->edests[org_node].elems[0];
  3571. re_node_set_empty (dfa->edests + clone_node);
  3572. /* If the node is root_node itself, it means the epsilon clsoure
  3573. has a loop. Then tie it to the destination of the root_node. */
  3574. if (org_node == root_node && clone_node != org_node)
  3575. {
  3576. ret = re_node_set_insert (dfa->edests + clone_node, org_dest);
  3577. if (BE (ret < 0, 0))
  3578. return REG_ESPACE;
  3579. break;
  3580. }
  3581. /* In case of the node has another constraint, add it. */
  3582. constraint |= dfa->nodes[org_node].constraint;
  3583. clone_dest = duplicate_node (dfa, org_dest, constraint);
  3584. if (BE (clone_dest == -1, 0))
  3585. return REG_ESPACE;
  3586. ret = re_node_set_insert (dfa->edests + clone_node, clone_dest);
  3587. if (BE (ret < 0, 0))
  3588. return REG_ESPACE;
  3589. }
  3590. else /* dfa->edests[org_node].nelem == 2 */
  3591. {
  3592. /* In case of the node can epsilon-transit, and it has two
  3593. destinations. In the bin_tree_t and DFA, that's '|' and '*'. */
  3594. org_dest = dfa->edests[org_node].elems[0];
  3595. re_node_set_empty (dfa->edests + clone_node);
  3596. /* Search for a duplicated node which satisfies the constraint. */
  3597. clone_dest = search_duplicated_node (dfa, org_dest, constraint);
  3598. if (clone_dest == -1)
  3599. {
  3600. /* There is no such duplicated node, create a new one. */
  3601. reg_errcode_t err;
  3602. clone_dest = duplicate_node (dfa, org_dest, constraint);
  3603. if (BE (clone_dest == -1, 0))
  3604. return REG_ESPACE;
  3605. ret = re_node_set_insert (dfa->edests + clone_node, clone_dest);
  3606. if (BE (ret < 0, 0))
  3607. return REG_ESPACE;
  3608. err = duplicate_node_closure (dfa, org_dest, clone_dest,
  3609. root_node, constraint);
  3610. if (BE (err != REG_NOERROR, 0))
  3611. return err;
  3612. }
  3613. else
  3614. {
  3615. /* There is a duplicated node which satisfies the constraint,
  3616. use it to avoid infinite loop. */
  3617. ret = re_node_set_insert (dfa->edests + clone_node, clone_dest);
  3618. if (BE (ret < 0, 0))
  3619. return REG_ESPACE;
  3620. }
  3621. org_dest = dfa->edests[org_node].elems[1];
  3622. clone_dest = duplicate_node (dfa, org_dest, constraint);
  3623. if (BE (clone_dest == -1, 0))
  3624. return REG_ESPACE;
  3625. ret = re_node_set_insert (dfa->edests + clone_node, clone_dest);
  3626. if (BE (ret < 0, 0))
  3627. return REG_ESPACE;
  3628. }
  3629. org_node = org_dest;
  3630. clone_node = clone_dest;
  3631. }
  3632. return REG_NOERROR;
  3633. }
  3634. /* Search for a node which is duplicated from the node ORG_NODE, and
  3635. satisfies the constraint CONSTRAINT. */
  3636. static int
  3637. search_duplicated_node (const re_dfa_t *dfa, int org_node,
  3638. unsigned int constraint)
  3639. {
  3640. int idx;
  3641. for (idx = dfa->nodes_len - 1; dfa->nodes[idx].duplicated && idx > 0; --idx)
  3642. {
  3643. if (org_node == dfa->org_indices[idx]
  3644. && constraint == dfa->nodes[idx].constraint)
  3645. return idx; /* Found. */
  3646. }
  3647. return -1; /* Not found. */
  3648. }
  3649. /* Duplicate the node whose index is ORG_IDX and set the constraint CONSTRAINT.
  3650. Return the index of the new node, or -1 if insufficient storage is
  3651. available. */
  3652. static int
  3653. duplicate_node (re_dfa_t *dfa, int org_idx, unsigned int constraint)
  3654. {
  3655. int dup_idx = re_dfa_add_node (dfa, dfa->nodes[org_idx]);
  3656. if (BE (dup_idx != -1, 1))
  3657. {
  3658. dfa->nodes[dup_idx].constraint = constraint;
  3659. dfa->nodes[dup_idx].constraint |= dfa->nodes[org_idx].constraint;
  3660. dfa->nodes[dup_idx].duplicated = 1;
  3661. /* Store the index of the original node. */
  3662. dfa->org_indices[dup_idx] = org_idx;
  3663. }
  3664. return dup_idx;
  3665. }
  3666. static reg_errcode_t
  3667. calc_inveclosure (re_dfa_t *dfa)
  3668. {
  3669. int src, idx, ret;
  3670. for (idx = 0; idx < dfa->nodes_len; ++idx)
  3671. re_node_set_init_empty (dfa->inveclosures + idx);
  3672. for (src = 0; src < dfa->nodes_len; ++src)
  3673. {
  3674. int *elems = dfa->eclosures[src].elems;
  3675. for (idx = 0; idx < dfa->eclosures[src].nelem; ++idx)
  3676. {
  3677. ret = re_node_set_insert_last (dfa->inveclosures + elems[idx], src);
  3678. if (BE (ret == -1, 0))
  3679. return REG_ESPACE;
  3680. }
  3681. }
  3682. return REG_NOERROR;
  3683. }
  3684. /* Calculate "eclosure" for all the node in DFA. */
  3685. static reg_errcode_t
  3686. calc_eclosure (re_dfa_t *dfa)
  3687. {
  3688. int node_idx, incomplete;
  3689. #ifdef DEBUG
  3690. assert (dfa->nodes_len > 0);
  3691. #endif
  3692. incomplete = 0;
  3693. /* For each nodes, calculate epsilon closure. */
  3694. for (node_idx = 0; ; ++node_idx)
  3695. {
  3696. reg_errcode_t err;
  3697. re_node_set eclosure_elem;
  3698. if (node_idx == dfa->nodes_len)
  3699. {
  3700. if (!incomplete)
  3701. break;
  3702. incomplete = 0;
  3703. node_idx = 0;
  3704. }
  3705. #ifdef DEBUG
  3706. assert (dfa->eclosures[node_idx].nelem != -1);
  3707. #endif
  3708. /* If we have already calculated, skip it. */
  3709. if (dfa->eclosures[node_idx].nelem != 0)
  3710. continue;
  3711. /* Calculate epsilon closure of `node_idx'. */
  3712. err = calc_eclosure_iter (&eclosure_elem, dfa, node_idx, 1);
  3713. if (BE (err != REG_NOERROR, 0))
  3714. return err;
  3715. if (dfa->eclosures[node_idx].nelem == 0)
  3716. {
  3717. incomplete = 1;
  3718. re_node_set_free (&eclosure_elem);
  3719. }
  3720. }
  3721. return REG_NOERROR;
  3722. }
  3723. /* Calculate epsilon closure of NODE. */
  3724. static reg_errcode_t
  3725. calc_eclosure_iter (re_node_set *new_set, re_dfa_t *dfa, int node, int root)
  3726. {
  3727. reg_errcode_t err;
  3728. int i, incomplete;
  3729. re_node_set eclosure;
  3730. incomplete = 0;
  3731. err = re_node_set_alloc (&eclosure, dfa->edests[node].nelem + 1);
  3732. if (BE (err != REG_NOERROR, 0))
  3733. return err;
  3734. /* This indicates that we are calculating this node now.
  3735. We reference this value to avoid infinite loop. */
  3736. dfa->eclosures[node].nelem = -1;
  3737. /* If the current node has constraints, duplicate all nodes
  3738. since they must inherit the constraints. */
  3739. if (dfa->nodes[node].constraint
  3740. && dfa->edests[node].nelem
  3741. && !dfa->nodes[dfa->edests[node].elems[0]].duplicated)
  3742. {
  3743. err = duplicate_node_closure (dfa, node, node, node,
  3744. dfa->nodes[node].constraint);
  3745. if (BE (err != REG_NOERROR, 0))
  3746. return err;
  3747. }
  3748. /* Expand each epsilon destination nodes. */
  3749. if (IS_EPSILON_NODE(dfa->nodes[node].type))
  3750. for (i = 0; i < dfa->edests[node].nelem; ++i)
  3751. {
  3752. re_node_set eclosure_elem;
  3753. int edest = dfa->edests[node].elems[i];
  3754. /* If calculating the epsilon closure of `edest' is in progress,
  3755. return intermediate result. */
  3756. if (dfa->eclosures[edest].nelem == -1)
  3757. {
  3758. incomplete = 1;
  3759. continue;
  3760. }
  3761. /* If we haven't calculated the epsilon closure of `edest' yet,
  3762. calculate now. Otherwise use calculated epsilon closure. */
  3763. if (dfa->eclosures[edest].nelem == 0)
  3764. {
  3765. err = calc_eclosure_iter (&eclosure_elem, dfa, edest, 0);
  3766. if (BE (err != REG_NOERROR, 0))
  3767. return err;
  3768. }
  3769. else
  3770. eclosure_elem = dfa->eclosures[edest];
  3771. /* Merge the epsilon closure of `edest'. */
  3772. re_node_set_merge (&eclosure, &eclosure_elem);
  3773. /* If the epsilon closure of `edest' is incomplete,
  3774. the epsilon closure of this node is also incomplete. */
  3775. if (dfa->eclosures[edest].nelem == 0)
  3776. {
  3777. incomplete = 1;
  3778. re_node_set_free (&eclosure_elem);
  3779. }
  3780. }
  3781. /* Epsilon closures include itself. */
  3782. re_node_set_insert (&eclosure, node);
  3783. if (incomplete && !root)
  3784. dfa->eclosures[node].nelem = 0;
  3785. else
  3786. dfa->eclosures[node] = eclosure;
  3787. *new_set = eclosure;
  3788. return REG_NOERROR;
  3789. }
  3790. /* Functions for token which are used in the parser. */
  3791. /* Fetch a token from INPUT.
  3792. We must not use this function inside bracket expressions. */
  3793. static void
  3794. internal_function
  3795. fetch_token (re_token_t *result, re_string_t *input, reg_syntax_t syntax)
  3796. {
  3797. re_string_skip_bytes (input, peek_token (result, input, syntax));
  3798. }
  3799. /* Peek a token from INPUT, and return the length of the token.
  3800. We must not use this function inside bracket expressions. */
  3801. static int
  3802. internal_function
  3803. peek_token (re_token_t *token, re_string_t *input, reg_syntax_t syntax)
  3804. {
  3805. unsigned char c;
  3806. if (re_string_eoi (input))
  3807. {
  3808. token->type = END_OF_RE;
  3809. return 0;
  3810. }
  3811. c = re_string_peek_byte (input, 0);
  3812. token->opr.c = c;
  3813. token->word_char = 0;
  3814. #ifdef RE_ENABLE_I18N
  3815. token->mb_partial = 0;
  3816. if (input->mb_cur_max > 1 &&
  3817. !re_string_first_byte (input, re_string_cur_idx (input)))
  3818. {
  3819. token->type = CHARACTER;
  3820. token->mb_partial = 1;
  3821. return 1;
  3822. }
  3823. #endif
  3824. if (c == '\\')
  3825. {
  3826. unsigned char c2;
  3827. if (re_string_cur_idx (input) + 1 >= re_string_length (input))
  3828. {
  3829. token->type = BACK_SLASH;
  3830. return 1;
  3831. }
  3832. c2 = re_string_peek_byte_case (input, 1);
  3833. token->opr.c = c2;
  3834. token->type = CHARACTER;
  3835. #ifdef RE_ENABLE_I18N
  3836. if (input->mb_cur_max > 1)
  3837. {
  3838. wint_t wc = re_string_wchar_at (input,
  3839. re_string_cur_idx (input) + 1);
  3840. token->word_char = IS_WIDE_WORD_CHAR (wc) != 0;
  3841. }
  3842. else
  3843. #endif
  3844. token->word_char = IS_WORD_CHAR (c2) != 0;
  3845. switch (c2)
  3846. {
  3847. case '|':
  3848. if (!(syntax & RE_LIMITED_OPS) && !(syntax & RE_NO_BK_VBAR))
  3849. token->type = OP_ALT;
  3850. break;
  3851. case '1': case '2': case '3': case '4': case '5':
  3852. case '6': case '7': case '8': case '9':
  3853. if (!(syntax & RE_NO_BK_REFS))
  3854. {
  3855. token->type = OP_BACK_REF;
  3856. token->opr.idx = c2 - '1';
  3857. }
  3858. break;
  3859. case '<':
  3860. if (!(syntax & RE_NO_GNU_OPS))
  3861. {
  3862. token->type = ANCHOR;
  3863. token->opr.ctx_type = WORD_FIRST;
  3864. }
  3865. break;
  3866. case '>':
  3867. if (!(syntax & RE_NO_GNU_OPS))
  3868. {
  3869. token->type = ANCHOR;
  3870. token->opr.ctx_type = WORD_LAST;
  3871. }
  3872. break;
  3873. case 'b':
  3874. if (!(syntax & RE_NO_GNU_OPS))
  3875. {
  3876. token->type = ANCHOR;
  3877. token->opr.ctx_type = WORD_DELIM;
  3878. }
  3879. break;
  3880. case 'B':
  3881. if (!(syntax & RE_NO_GNU_OPS))
  3882. {
  3883. token->type = ANCHOR;
  3884. token->opr.ctx_type = NOT_WORD_DELIM;
  3885. }
  3886. break;
  3887. case 'w':
  3888. if (!(syntax & RE_NO_GNU_OPS))
  3889. token->type = OP_WORD;
  3890. break;
  3891. case 'W':
  3892. if (!(syntax & RE_NO_GNU_OPS))
  3893. token->type = OP_NOTWORD;
  3894. break;
  3895. case 's':
  3896. if (!(syntax & RE_NO_GNU_OPS))
  3897. token->type = OP_SPACE;
  3898. break;
  3899. case 'S':
  3900. if (!(syntax & RE_NO_GNU_OPS))
  3901. token->type = OP_NOTSPACE;
  3902. break;
  3903. case '`':
  3904. if (!(syntax & RE_NO_GNU_OPS))
  3905. {
  3906. token->type = ANCHOR;
  3907. token->opr.ctx_type = BUF_FIRST;
  3908. }
  3909. break;
  3910. case '\'':
  3911. if (!(syntax & RE_NO_GNU_OPS))
  3912. {
  3913. token->type = ANCHOR;
  3914. token->opr.ctx_type = BUF_LAST;
  3915. }
  3916. break;
  3917. case '(':
  3918. if (!(syntax & RE_NO_BK_PARENS))
  3919. token->type = OP_OPEN_SUBEXP;
  3920. break;
  3921. case ')':
  3922. if (!(syntax & RE_NO_BK_PARENS))
  3923. token->type = OP_CLOSE_SUBEXP;
  3924. break;
  3925. case '+':
  3926. if (!(syntax & RE_LIMITED_OPS) && (syntax & RE_BK_PLUS_QM))
  3927. token->type = OP_DUP_PLUS;
  3928. break;
  3929. case '?':
  3930. if (!(syntax & RE_LIMITED_OPS) && (syntax & RE_BK_PLUS_QM))
  3931. token->type = OP_DUP_QUESTION;
  3932. break;
  3933. case '{':
  3934. if ((syntax & RE_INTERVALS) && (!(syntax & RE_NO_BK_BRACES)))
  3935. token->type = OP_OPEN_DUP_NUM;
  3936. break;
  3937. case '}':
  3938. if ((syntax & RE_INTERVALS) && (!(syntax & RE_NO_BK_BRACES)))
  3939. token->type = OP_CLOSE_DUP_NUM;
  3940. break;
  3941. default:
  3942. break;
  3943. }
  3944. return 2;
  3945. }
  3946. token->type = CHARACTER;
  3947. #ifdef RE_ENABLE_I18N
  3948. if (input->mb_cur_max > 1)
  3949. {
  3950. wint_t wc = re_string_wchar_at (input, re_string_cur_idx (input));
  3951. token->word_char = IS_WIDE_WORD_CHAR (wc) != 0;
  3952. }
  3953. else
  3954. #endif
  3955. token->word_char = IS_WORD_CHAR (token->opr.c);
  3956. switch (c)
  3957. {
  3958. case '\n':
  3959. if (syntax & RE_NEWLINE_ALT)
  3960. token->type = OP_ALT;
  3961. break;
  3962. case '|':
  3963. if (!(syntax & RE_LIMITED_OPS) && (syntax & RE_NO_BK_VBAR))
  3964. token->type = OP_ALT;
  3965. break;
  3966. case '*':
  3967. token->type = OP_DUP_ASTERISK;
  3968. break;
  3969. case '+':
  3970. if (!(syntax & RE_LIMITED_OPS) && !(syntax & RE_BK_PLUS_QM))
  3971. token->type = OP_DUP_PLUS;
  3972. break;
  3973. case '?':
  3974. if (!(syntax & RE_LIMITED_OPS) && !(syntax & RE_BK_PLUS_QM))
  3975. token->type = OP_DUP_QUESTION;
  3976. break;
  3977. case '{':
  3978. if ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
  3979. token->type = OP_OPEN_DUP_NUM;
  3980. break;
  3981. case '}':
  3982. if ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
  3983. token->type = OP_CLOSE_DUP_NUM;
  3984. break;
  3985. case '(':
  3986. if (syntax & RE_NO_BK_PARENS)
  3987. token->type = OP_OPEN_SUBEXP;
  3988. break;
  3989. case ')':
  3990. if (syntax & RE_NO_BK_PARENS)
  3991. token->type = OP_CLOSE_SUBEXP;
  3992. break;
  3993. case '[':
  3994. token->type = OP_OPEN_BRACKET;
  3995. break;
  3996. case '.':
  3997. token->type = OP_PERIOD;
  3998. break;
  3999. case '^':
  4000. if (!(syntax & (RE_CONTEXT_INDEP_ANCHORS | RE_CARET_ANCHORS_HERE)) &&
  4001. re_string_cur_idx (input) != 0)
  4002. {
  4003. char prev = re_string_peek_byte (input, -1);
  4004. if (!(syntax & RE_NEWLINE_ALT) || prev != '\n')
  4005. break;
  4006. }
  4007. token->type = ANCHOR;
  4008. token->opr.ctx_type = LINE_FIRST;
  4009. break;
  4010. case '$':
  4011. if (!(syntax & RE_CONTEXT_INDEP_ANCHORS) &&
  4012. re_string_cur_idx (input) + 1 != re_string_length (input))
  4013. {
  4014. re_token_t next;
  4015. re_string_skip_bytes (input, 1);
  4016. peek_token (&next, input, syntax);
  4017. re_string_skip_bytes (input, -1);
  4018. if (next.type != OP_ALT && next.type != OP_CLOSE_SUBEXP)
  4019. break;
  4020. }
  4021. token->type = ANCHOR;
  4022. token->opr.ctx_type = LINE_LAST;
  4023. break;
  4024. default:
  4025. break;
  4026. }
  4027. return 1;
  4028. }
  4029. /* Peek a token from INPUT, and return the length of the token.
  4030. We must not use this function out of bracket expressions. */
  4031. static int
  4032. internal_function
  4033. peek_token_bracket (re_token_t *token, re_string_t *input, reg_syntax_t syntax)
  4034. {
  4035. unsigned char c;
  4036. if (re_string_eoi (input))
  4037. {
  4038. token->type = END_OF_RE;
  4039. return 0;
  4040. }
  4041. c = re_string_peek_byte (input, 0);
  4042. token->opr.c = c;
  4043. #ifdef RE_ENABLE_I18N
  4044. if (input->mb_cur_max > 1 &&
  4045. !re_string_first_byte (input, re_string_cur_idx (input)))
  4046. {
  4047. token->type = CHARACTER;
  4048. return 1;
  4049. }
  4050. #endif /* RE_ENABLE_I18N */
  4051. if (c == '\\' && (syntax & RE_BACKSLASH_ESCAPE_IN_LISTS)
  4052. && re_string_cur_idx (input) + 1 < re_string_length (input))
  4053. {
  4054. /* In this case, '\' escape a character. */
  4055. unsigned char c2;
  4056. re_string_skip_bytes (input, 1);
  4057. c2 = re_string_peek_byte (input, 0);
  4058. token->opr.c = c2;
  4059. token->type = CHARACTER;
  4060. return 1;
  4061. }
  4062. if (c == '[') /* '[' is a special char in a bracket exps. */
  4063. {
  4064. unsigned char c2;
  4065. int token_len;
  4066. if (re_string_cur_idx (input) + 1 < re_string_length (input))
  4067. c2 = re_string_peek_byte (input, 1);
  4068. else
  4069. c2 = 0;
  4070. token->opr.c = c2;
  4071. token_len = 2;
  4072. switch (c2)
  4073. {
  4074. case '.':
  4075. token->type = OP_OPEN_COLL_ELEM;
  4076. break;
  4077. case '=':
  4078. token->type = OP_OPEN_EQUIV_CLASS;
  4079. break;
  4080. case ':':
  4081. if (syntax & RE_CHAR_CLASSES)
  4082. {
  4083. token->type = OP_OPEN_CHAR_CLASS;
  4084. break;
  4085. }
  4086. /* else fall through. */
  4087. default:
  4088. token->type = CHARACTER;
  4089. token->opr.c = c;
  4090. token_len = 1;
  4091. break;
  4092. }
  4093. return token_len;
  4094. }
  4095. switch (c)
  4096. {
  4097. case '-':
  4098. token->type = OP_CHARSET_RANGE;
  4099. break;
  4100. case ']':
  4101. token->type = OP_CLOSE_BRACKET;
  4102. break;
  4103. case '^':
  4104. token->type = OP_NON_MATCH_LIST;
  4105. break;
  4106. default:
  4107. token->type = CHARACTER;
  4108. }
  4109. return 1;
  4110. }
  4111. /* Functions for parser. */
  4112. /* Entry point of the parser.
  4113. Parse the regular expression REGEXP and return the structure tree.
  4114. If an error is occured, ERR is set by error code, and return NULL.
  4115. This function build the following tree, from regular expression <reg_exp>:
  4116. CAT
  4117. / \
  4118. / \
  4119. <reg_exp> EOR
  4120. CAT means concatenation.
  4121. EOR means end of regular expression. */
  4122. static bin_tree_t *
  4123. parse (re_string_t *regexp, regex_t *preg, reg_syntax_t syntax,
  4124. reg_errcode_t *err)
  4125. {
  4126. re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
  4127. bin_tree_t *tree, *eor, *root;
  4128. re_token_t current_token;
  4129. dfa->syntax = syntax;
  4130. fetch_token (&current_token, regexp, syntax | RE_CARET_ANCHORS_HERE);
  4131. tree = parse_reg_exp (regexp, preg, &current_token, syntax, 0, err);
  4132. if (BE (*err != REG_NOERROR && tree == NULL, 0))
  4133. return NULL;
  4134. eor = create_tree (dfa, NULL, NULL, END_OF_RE);
  4135. if (tree != NULL)
  4136. root = create_tree (dfa, tree, eor, CONCAT);
  4137. else
  4138. root = eor;
  4139. if (BE (eor == NULL || root == NULL, 0))
  4140. {
  4141. *err = REG_ESPACE;
  4142. return NULL;
  4143. }
  4144. return root;
  4145. }
  4146. /* This function build the following tree, from regular expression
  4147. <branch1>|<branch2>:
  4148. ALT
  4149. / \
  4150. / \
  4151. <branch1> <branch2>
  4152. ALT means alternative, which represents the operator `|'. */
  4153. static bin_tree_t *
  4154. parse_reg_exp (re_string_t *regexp, regex_t *preg, re_token_t *token,
  4155. reg_syntax_t syntax, int nest, reg_errcode_t *err)
  4156. {
  4157. re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
  4158. bin_tree_t *tree, *branch = NULL;
  4159. tree = parse_branch (regexp, preg, token, syntax, nest, err);
  4160. if (BE (*err != REG_NOERROR && tree == NULL, 0))
  4161. return NULL;
  4162. while (token->type == OP_ALT)
  4163. {
  4164. fetch_token (token, regexp, syntax | RE_CARET_ANCHORS_HERE);
  4165. if (token->type != OP_ALT && token->type != END_OF_RE
  4166. && (nest == 0 || token->type != OP_CLOSE_SUBEXP))
  4167. {
  4168. branch = parse_branch (regexp, preg, token, syntax, nest, err);
  4169. if (BE (*err != REG_NOERROR && branch == NULL, 0))
  4170. return NULL;
  4171. }
  4172. else
  4173. branch = NULL;
  4174. tree = create_tree (dfa, tree, branch, OP_ALT);
  4175. if (BE (tree == NULL, 0))
  4176. {
  4177. *err = REG_ESPACE;
  4178. return NULL;
  4179. }
  4180. }
  4181. return tree;
  4182. }
  4183. /* This function build the following tree, from regular expression
  4184. <exp1><exp2>:
  4185. CAT
  4186. / \
  4187. / \
  4188. <exp1> <exp2>
  4189. CAT means concatenation. */
  4190. static bin_tree_t *
  4191. parse_branch (re_string_t *regexp, regex_t *preg, re_token_t *token,
  4192. reg_syntax_t syntax, int nest, reg_errcode_t *err)
  4193. {
  4194. bin_tree_t *tree, *exp;
  4195. re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
  4196. tree = parse_expression (regexp, preg, token, syntax, nest, err);
  4197. if (BE (*err != REG_NOERROR && tree == NULL, 0))
  4198. return NULL;
  4199. while (token->type != OP_ALT && token->type != END_OF_RE
  4200. && (nest == 0 || token->type != OP_CLOSE_SUBEXP))
  4201. {
  4202. exp = parse_expression (regexp, preg, token, syntax, nest, err);
  4203. if (BE (*err != REG_NOERROR && exp == NULL, 0))
  4204. {
  4205. return NULL;
  4206. }
  4207. if (tree != NULL && exp != NULL)
  4208. {
  4209. tree = create_tree (dfa, tree, exp, CONCAT);
  4210. if (tree == NULL)
  4211. {
  4212. *err = REG_ESPACE;
  4213. return NULL;
  4214. }
  4215. }
  4216. else if (tree == NULL)
  4217. tree = exp;
  4218. /* Otherwise exp == NULL, we don't need to create new tree. */
  4219. }
  4220. return tree;
  4221. }
  4222. /* This function build the following tree, from regular expression a*:
  4223. *
  4224. |
  4225. a
  4226. */
  4227. static bin_tree_t *
  4228. parse_expression (re_string_t *regexp, regex_t *preg, re_token_t *token,
  4229. reg_syntax_t syntax, int nest, reg_errcode_t *err)
  4230. {
  4231. re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
  4232. bin_tree_t *tree;
  4233. switch (token->type)
  4234. {
  4235. case CHARACTER:
  4236. tree = create_token_tree (dfa, NULL, NULL, token);
  4237. if (BE (tree == NULL, 0))
  4238. {
  4239. *err = REG_ESPACE;
  4240. return NULL;
  4241. }
  4242. #ifdef RE_ENABLE_I18N
  4243. if (dfa->mb_cur_max > 1)
  4244. {
  4245. while (!re_string_eoi (regexp)
  4246. && !re_string_first_byte (regexp, re_string_cur_idx (regexp)))
  4247. {
  4248. bin_tree_t *mbc_remain;
  4249. fetch_token (token, regexp, syntax);
  4250. mbc_remain = create_token_tree (dfa, NULL, NULL, token);
  4251. tree = create_tree (dfa, tree, mbc_remain, CONCAT);
  4252. if (BE (mbc_remain == NULL || tree == NULL, 0))
  4253. {
  4254. *err = REG_ESPACE;
  4255. return NULL;
  4256. }
  4257. }
  4258. }
  4259. #endif
  4260. break;
  4261. case OP_OPEN_SUBEXP:
  4262. tree = parse_sub_exp (regexp, preg, token, syntax, nest + 1, err);
  4263. if (BE (*err != REG_NOERROR && tree == NULL, 0))
  4264. return NULL;
  4265. break;
  4266. case OP_OPEN_BRACKET:
  4267. tree = parse_bracket_exp (regexp, dfa, token, syntax, err);
  4268. if (BE (*err != REG_NOERROR && tree == NULL, 0))
  4269. return NULL;
  4270. break;
  4271. case OP_BACK_REF:
  4272. if (!BE (dfa->completed_bkref_map & (1 << token->opr.idx), 1))
  4273. {
  4274. *err = REG_ESUBREG;
  4275. return NULL;
  4276. }
  4277. dfa->used_bkref_map |= 1 << token->opr.idx;
  4278. tree = create_token_tree (dfa, NULL, NULL, token);
  4279. if (BE (tree == NULL, 0))
  4280. {
  4281. *err = REG_ESPACE;
  4282. return NULL;
  4283. }
  4284. ++dfa->nbackref;
  4285. dfa->has_mb_node = 1;
  4286. break;
  4287. case OP_OPEN_DUP_NUM:
  4288. if (syntax & RE_CONTEXT_INVALID_DUP)
  4289. {
  4290. *err = REG_BADRPT;
  4291. return NULL;
  4292. }
  4293. /* FALLTHROUGH */
  4294. case OP_DUP_ASTERISK:
  4295. case OP_DUP_PLUS:
  4296. case OP_DUP_QUESTION:
  4297. if (syntax & RE_CONTEXT_INVALID_OPS)
  4298. {
  4299. *err = REG_BADRPT;
  4300. return NULL;
  4301. }
  4302. else if (syntax & RE_CONTEXT_INDEP_OPS)
  4303. {
  4304. fetch_token (token, regexp, syntax);
  4305. return parse_expression (regexp, preg, token, syntax, nest, err);
  4306. }
  4307. /* else fall through */
  4308. case OP_CLOSE_SUBEXP:
  4309. if ((token->type == OP_CLOSE_SUBEXP) &&
  4310. !(syntax & RE_UNMATCHED_RIGHT_PAREN_ORD))
  4311. {
  4312. *err = REG_ERPAREN;
  4313. return NULL;
  4314. }
  4315. /* else fall through */
  4316. case OP_CLOSE_DUP_NUM:
  4317. /* We treat it as a normal character. */
  4318. /* Then we can these characters as normal characters. */
  4319. token->type = CHARACTER;
  4320. /* mb_partial and word_char bits should be initialized already
  4321. by peek_token. */
  4322. tree = create_token_tree (dfa, NULL, NULL, token);
  4323. if (BE (tree == NULL, 0))
  4324. {
  4325. *err = REG_ESPACE;
  4326. return NULL;
  4327. }
  4328. break;
  4329. case ANCHOR:
  4330. if ((token->opr.ctx_type
  4331. & (WORD_DELIM | NOT_WORD_DELIM | WORD_FIRST | WORD_LAST))
  4332. && dfa->word_ops_used == 0)
  4333. init_word_char (dfa);
  4334. if (token->opr.ctx_type == WORD_DELIM
  4335. || token->opr.ctx_type == NOT_WORD_DELIM)
  4336. {
  4337. bin_tree_t *tree_first, *tree_last;
  4338. if (token->opr.ctx_type == WORD_DELIM)
  4339. {
  4340. token->opr.ctx_type = WORD_FIRST;
  4341. tree_first = create_token_tree (dfa, NULL, NULL, token);
  4342. token->opr.ctx_type = WORD_LAST;
  4343. }
  4344. else
  4345. {
  4346. token->opr.ctx_type = INSIDE_WORD;
  4347. tree_first = create_token_tree (dfa, NULL, NULL, token);
  4348. token->opr.ctx_type = INSIDE_NOTWORD;
  4349. }
  4350. tree_last = create_token_tree (dfa, NULL, NULL, token);
  4351. tree = create_tree (dfa, tree_first, tree_last, OP_ALT);
  4352. if (BE (tree_first == NULL || tree_last == NULL || tree == NULL, 0))
  4353. {
  4354. *err = REG_ESPACE;
  4355. return NULL;
  4356. }
  4357. }
  4358. else
  4359. {
  4360. tree = create_token_tree (dfa, NULL, NULL, token);
  4361. if (BE (tree == NULL, 0))
  4362. {
  4363. *err = REG_ESPACE;
  4364. return NULL;
  4365. }
  4366. }
  4367. /* We must return here, since ANCHORs can't be followed
  4368. by repetition operators.
  4369. eg. RE"^*" is invalid or "<ANCHOR(^)><CHAR(*)>",
  4370. it must not be "<ANCHOR(^)><REPEAT(*)>". */
  4371. fetch_token (token, regexp, syntax);
  4372. return tree;
  4373. case OP_PERIOD:
  4374. tree = create_token_tree (dfa, NULL, NULL, token);
  4375. if (BE (tree == NULL, 0))
  4376. {
  4377. *err = REG_ESPACE;
  4378. return NULL;
  4379. }
  4380. if (dfa->mb_cur_max > 1)
  4381. dfa->has_mb_node = 1;
  4382. break;
  4383. case OP_WORD:
  4384. case OP_NOTWORD:
  4385. tree = build_charclass_op (dfa, regexp->trans,
  4386. (const unsigned char *) "alnum",
  4387. (const unsigned char *) "_",
  4388. token->type == OP_NOTWORD, err);
  4389. if (BE (*err != REG_NOERROR && tree == NULL, 0))
  4390. return NULL;
  4391. break;
  4392. case OP_SPACE:
  4393. case OP_NOTSPACE:
  4394. tree = build_charclass_op (dfa, regexp->trans,
  4395. (const unsigned char *) "space",
  4396. (const unsigned char *) "",
  4397. token->type == OP_NOTSPACE, err);
  4398. if (BE (*err != REG_NOERROR && tree == NULL, 0))
  4399. return NULL;
  4400. break;
  4401. case OP_ALT:
  4402. case END_OF_RE:
  4403. return NULL;
  4404. case BACK_SLASH:
  4405. *err = REG_EESCAPE;
  4406. return NULL;
  4407. default:
  4408. /* Must not happen? */
  4409. #ifdef DEBUG
  4410. assert (0);
  4411. #endif
  4412. return NULL;
  4413. }
  4414. fetch_token (token, regexp, syntax);
  4415. while (token->type == OP_DUP_ASTERISK || token->type == OP_DUP_PLUS
  4416. || token->type == OP_DUP_QUESTION || token->type == OP_OPEN_DUP_NUM)
  4417. {
  4418. tree = parse_dup_op (tree, regexp, dfa, token, syntax, err);
  4419. if (BE (*err != REG_NOERROR && tree == NULL, 0))
  4420. return NULL;
  4421. /* In BRE consecutive duplications are not allowed. */
  4422. if ((syntax & RE_CONTEXT_INVALID_DUP)
  4423. && (token->type == OP_DUP_ASTERISK
  4424. || token->type == OP_OPEN_DUP_NUM))
  4425. {
  4426. *err = REG_BADRPT;
  4427. return NULL;
  4428. }
  4429. }
  4430. return tree;
  4431. }
  4432. /* This function build the following tree, from regular expression
  4433. (<reg_exp>):
  4434. SUBEXP
  4435. |
  4436. <reg_exp>
  4437. */
  4438. static bin_tree_t *
  4439. parse_sub_exp (re_string_t *regexp, regex_t *preg, re_token_t *token,
  4440. reg_syntax_t syntax, int nest, reg_errcode_t *err)
  4441. {
  4442. re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
  4443. bin_tree_t *tree;
  4444. size_t cur_nsub;
  4445. cur_nsub = preg->re_nsub++;
  4446. fetch_token (token, regexp, syntax | RE_CARET_ANCHORS_HERE);
  4447. /* The subexpression may be a null string. */
  4448. if (token->type == OP_CLOSE_SUBEXP)
  4449. tree = NULL;
  4450. else
  4451. {
  4452. tree = parse_reg_exp (regexp, preg, token, syntax, nest, err);
  4453. if (BE (*err == REG_NOERROR && token->type != OP_CLOSE_SUBEXP, 0))
  4454. *err = REG_EPAREN;
  4455. if (BE (*err != REG_NOERROR, 0))
  4456. return NULL;
  4457. }
  4458. if (cur_nsub <= '9' - '1')
  4459. dfa->completed_bkref_map |= 1 << cur_nsub;
  4460. tree = create_tree (dfa, tree, NULL, SUBEXP);
  4461. if (BE (tree == NULL, 0))
  4462. {
  4463. *err = REG_ESPACE;
  4464. return NULL;
  4465. }
  4466. tree->token.opr.idx = cur_nsub;
  4467. return tree;
  4468. }
  4469. /* This function parse repetition operators like "*", "+", "{1,3}" etc. */
  4470. static bin_tree_t *
  4471. parse_dup_op (bin_tree_t *elem, re_string_t *regexp, re_dfa_t *dfa,
  4472. re_token_t *token, reg_syntax_t syntax, reg_errcode_t *err)
  4473. {
  4474. bin_tree_t *tree = NULL, *old_tree = NULL;
  4475. int i, start, end, start_idx = re_string_cur_idx (regexp);
  4476. re_token_t start_token = *token;
  4477. if (token->type == OP_OPEN_DUP_NUM)
  4478. {
  4479. end = 0;
  4480. start = fetch_number (regexp, token, syntax);
  4481. if (start == -1)
  4482. {
  4483. if (token->type == CHARACTER && token->opr.c == ',')
  4484. start = 0; /* We treat "{,m}" as "{0,m}". */
  4485. else
  4486. {
  4487. *err = REG_BADBR; /* <re>{} is invalid. */
  4488. return NULL;
  4489. }
  4490. }
  4491. if (BE (start != -2, 1))
  4492. {
  4493. /* We treat "{n}" as "{n,n}". */
  4494. end = ((token->type == OP_CLOSE_DUP_NUM) ? start
  4495. : ((token->type == CHARACTER && token->opr.c == ',')
  4496. ? fetch_number (regexp, token, syntax) : -2));
  4497. }
  4498. if (BE (start == -2 || end == -2, 0))
  4499. {
  4500. /* Invalid sequence. */
  4501. if (BE (!(syntax & RE_INVALID_INTERVAL_ORD), 0))
  4502. {
  4503. if (token->type == END_OF_RE)
  4504. *err = REG_EBRACE;
  4505. else
  4506. *err = REG_BADBR;
  4507. return NULL;
  4508. }
  4509. /* If the syntax bit is set, rollback. */
  4510. re_string_set_index (regexp, start_idx);
  4511. *token = start_token;
  4512. token->type = CHARACTER;
  4513. /* mb_partial and word_char bits should be already initialized by
  4514. peek_token. */
  4515. return elem;
  4516. }
  4517. if (BE (end != -1 && start > end, 0))
  4518. {
  4519. /* First number greater than second. */
  4520. *err = REG_BADBR;
  4521. return NULL;
  4522. }
  4523. }
  4524. else
  4525. {
  4526. start = (token->type == OP_DUP_PLUS) ? 1 : 0;
  4527. end = (token->type == OP_DUP_QUESTION) ? 1 : -1;
  4528. }
  4529. fetch_token (token, regexp, syntax);
  4530. if (BE (elem == NULL, 0))
  4531. return NULL;
  4532. if (BE (start == 0 && end == 0, 0))
  4533. {
  4534. postorder (elem, free_tree, NULL);
  4535. return NULL;
  4536. }
  4537. /* Extract "<re>{n,m}" to "<re><re>...<re><re>{0,<m-n>}". */
  4538. if (BE (start > 0, 0))
  4539. {
  4540. tree = elem;
  4541. for (i = 2; i <= start; ++i)
  4542. {
  4543. elem = duplicate_tree (elem, dfa);
  4544. tree = create_tree (dfa, tree, elem, CONCAT);
  4545. if (BE (elem == NULL || tree == NULL, 0))
  4546. goto parse_dup_op_espace;
  4547. }
  4548. if (start == end)
  4549. return tree;
  4550. /* Duplicate ELEM before it is marked optional. */
  4551. elem = duplicate_tree (elem, dfa);
  4552. old_tree = tree;
  4553. }
  4554. else
  4555. old_tree = NULL;
  4556. if (elem->token.type == SUBEXP)
  4557. postorder (elem, mark_opt_subexp, (void *) (long) elem->token.opr.idx);
  4558. tree = create_tree (dfa, elem, NULL, (end == -1 ? OP_DUP_ASTERISK : OP_ALT));
  4559. if (BE (tree == NULL, 0))
  4560. goto parse_dup_op_espace;
  4561. /* This loop is actually executed only when end != -1,
  4562. to rewrite <re>{0,n} as (<re>(<re>...<re>?)?)?... We have
  4563. already created the start+1-th copy. */
  4564. for (i = start + 2; i <= end; ++i)
  4565. {
  4566. elem = duplicate_tree (elem, dfa);
  4567. tree = create_tree (dfa, tree, elem, CONCAT);
  4568. if (BE (elem == NULL || tree == NULL, 0))
  4569. goto parse_dup_op_espace;
  4570. tree = create_tree (dfa, tree, NULL, OP_ALT);
  4571. if (BE (tree == NULL, 0))
  4572. goto parse_dup_op_espace;
  4573. }
  4574. if (old_tree)
  4575. tree = create_tree (dfa, old_tree, tree, CONCAT);
  4576. return tree;
  4577. parse_dup_op_espace:
  4578. *err = REG_ESPACE;
  4579. return NULL;
  4580. }
  4581. /* Size of the names for collating symbol/equivalence_class/character_class.
  4582. I'm not sure, but maybe enough. */
  4583. #define BRACKET_NAME_BUF_SIZE 32
  4584. #ifndef _LIBC
  4585. /* Local function for parse_bracket_exp only used in case of NOT _LIBC.
  4586. Build the range expression which starts from START_ELEM, and ends
  4587. at END_ELEM. The result are written to MBCSET and SBCSET.
  4588. RANGE_ALLOC is the allocated size of mbcset->range_starts, and
  4589. mbcset->range_ends, is a pointer argument sinse we may
  4590. update it. */
  4591. static reg_errcode_t
  4592. internal_function
  4593. # ifdef RE_ENABLE_I18N
  4594. build_range_exp (bitset_t sbcset, re_charset_t *mbcset, int *range_alloc,
  4595. bracket_elem_t *start_elem, bracket_elem_t *end_elem)
  4596. # else /* not RE_ENABLE_I18N */
  4597. build_range_exp (bitset_t sbcset, bracket_elem_t *start_elem,
  4598. bracket_elem_t *end_elem)
  4599. # endif /* not RE_ENABLE_I18N */
  4600. {
  4601. unsigned int start_ch, end_ch;
  4602. /* Equivalence Classes and Character Classes can't be a range start/end. */
  4603. if (BE (start_elem->type == EQUIV_CLASS || start_elem->type == CHAR_CLASS
  4604. || end_elem->type == EQUIV_CLASS || end_elem->type == CHAR_CLASS,
  4605. 0))
  4606. return REG_ERANGE;
  4607. /* We can handle no multi character collating elements without libc
  4608. support. */
  4609. if (BE ((start_elem->type == COLL_SYM
  4610. && strlen ((char *) start_elem->opr.name) > 1)
  4611. || (end_elem->type == COLL_SYM
  4612. && strlen ((char *) end_elem->opr.name) > 1), 0))
  4613. return REG_ECOLLATE;
  4614. # ifdef RE_ENABLE_I18N
  4615. {
  4616. wchar_t wc;
  4617. wint_t start_wc;
  4618. wint_t end_wc;
  4619. wchar_t cmp_buf[6] = {L'\0', L'\0', L'\0', L'\0', L'\0', L'\0'};
  4620. start_ch = ((start_elem->type == SB_CHAR) ? start_elem->opr.ch
  4621. : ((start_elem->type == COLL_SYM) ? start_elem->opr.name[0]
  4622. : 0));
  4623. end_ch = ((end_elem->type == SB_CHAR) ? end_elem->opr.ch
  4624. : ((end_elem->type == COLL_SYM) ? end_elem->opr.name[0]
  4625. : 0));
  4626. start_wc = ((start_elem->type == SB_CHAR || start_elem->type == COLL_SYM)
  4627. ? __btowc (start_ch) : start_elem->opr.wch);
  4628. end_wc = ((end_elem->type == SB_CHAR || end_elem->type == COLL_SYM)
  4629. ? __btowc (end_ch) : end_elem->opr.wch);
  4630. if (start_wc == WEOF || end_wc == WEOF)
  4631. return REG_ECOLLATE;
  4632. cmp_buf[0] = start_wc;
  4633. cmp_buf[4] = end_wc;
  4634. if (wcscoll (cmp_buf, cmp_buf + 4) > 0)
  4635. return REG_ERANGE;
  4636. /* Got valid collation sequence values, add them as a new entry.
  4637. However, for !_LIBC we have no collation elements: if the
  4638. character set is single byte, the single byte character set
  4639. that we build below suffices. parse_bracket_exp passes
  4640. no MBCSET if dfa->mb_cur_max == 1. */
  4641. if (mbcset)
  4642. {
  4643. /* Check the space of the arrays. */
  4644. if (BE (*range_alloc == mbcset->nranges, 0))
  4645. {
  4646. /* There is not enough space, need realloc. */
  4647. wchar_t *new_array_start, *new_array_end;
  4648. int new_nranges;
  4649. /* +1 in case of mbcset->nranges is 0. */
  4650. new_nranges = 2 * mbcset->nranges + 1;
  4651. /* Use realloc since mbcset->range_starts and mbcset->range_ends
  4652. are NULL if *range_alloc == 0. */
  4653. new_array_start = re_realloc (mbcset->range_starts, wchar_t,
  4654. new_nranges);
  4655. new_array_end = re_realloc (mbcset->range_ends, wchar_t,
  4656. new_nranges);
  4657. if (BE (new_array_start == NULL || new_array_end == NULL, 0))
  4658. return REG_ESPACE;
  4659. mbcset->range_starts = new_array_start;
  4660. mbcset->range_ends = new_array_end;
  4661. *range_alloc = new_nranges;
  4662. }
  4663. mbcset->range_starts[mbcset->nranges] = start_wc;
  4664. mbcset->range_ends[mbcset->nranges++] = end_wc;
  4665. }
  4666. /* Build the table for single byte characters. */
  4667. for (wc = 0; wc < SBC_MAX; ++wc)
  4668. {
  4669. cmp_buf[2] = wc;
  4670. if (wcscoll (cmp_buf, cmp_buf + 2) <= 0
  4671. && wcscoll (cmp_buf + 2, cmp_buf + 4) <= 0)
  4672. bitset_set (sbcset, wc);
  4673. }
  4674. }
  4675. # else /* not RE_ENABLE_I18N */
  4676. {
  4677. unsigned int ch;
  4678. start_ch = ((start_elem->type == SB_CHAR ) ? start_elem->opr.ch
  4679. : ((start_elem->type == COLL_SYM) ? start_elem->opr.name[0]
  4680. : 0));
  4681. end_ch = ((end_elem->type == SB_CHAR ) ? end_elem->opr.ch
  4682. : ((end_elem->type == COLL_SYM) ? end_elem->opr.name[0]
  4683. : 0));
  4684. if (start_ch > end_ch)
  4685. return REG_ERANGE;
  4686. /* Build the table for single byte characters. */
  4687. for (ch = 0; ch < SBC_MAX; ++ch)
  4688. if (start_ch <= ch && ch <= end_ch)
  4689. bitset_set (sbcset, ch);
  4690. }
  4691. # endif /* not RE_ENABLE_I18N */
  4692. return REG_NOERROR;
  4693. }
  4694. #endif /* not _LIBC */
  4695. #ifndef _LIBC
  4696. /* Helper function for parse_bracket_exp only used in case of NOT _LIBC..
  4697. Build the collating element which is represented by NAME.
  4698. The result are written to MBCSET and SBCSET.
  4699. COLL_SYM_ALLOC is the allocated size of mbcset->coll_sym, is a
  4700. pointer argument since we may update it. */
  4701. static reg_errcode_t
  4702. internal_function
  4703. # ifdef RE_ENABLE_I18N
  4704. build_collating_symbol (bitset_t sbcset, re_charset_t *mbcset,
  4705. int *coll_sym_alloc, const unsigned char *name)
  4706. # else /* not RE_ENABLE_I18N */
  4707. build_collating_symbol (bitset_t sbcset, const unsigned char *name)
  4708. # endif /* not RE_ENABLE_I18N */
  4709. {
  4710. size_t name_len = strlen ((const char *) name);
  4711. if (BE (name_len != 1, 0))
  4712. return REG_ECOLLATE;
  4713. else
  4714. {
  4715. bitset_set (sbcset, name[0]);
  4716. return REG_NOERROR;
  4717. }
  4718. }
  4719. #endif /* not _LIBC */
  4720. /* This function parse bracket expression like "[abc]", "[a-c]",
  4721. "[[.a-a.]]" etc. */
  4722. static bin_tree_t *
  4723. parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa, re_token_t *token,
  4724. reg_syntax_t syntax, reg_errcode_t *err)
  4725. {
  4726. #ifdef _LIBC
  4727. const unsigned char *collseqmb;
  4728. const char *collseqwc;
  4729. uint32_t nrules;
  4730. int32_t table_size;
  4731. const int32_t *symb_table;
  4732. const unsigned char *extra;
  4733. /* Local function for parse_bracket_exp used in _LIBC environement.
  4734. Seek the collating symbol entry correspondings to NAME.
  4735. Return the index of the symbol in the SYMB_TABLE. */
  4736. auto inline int32_t
  4737. __attribute ((always_inline))
  4738. seek_collating_symbol_entry (name, name_len)
  4739. const unsigned char *name;
  4740. size_t name_len;
  4741. {
  4742. int32_t hash = elem_hash ((const char *) name, name_len);
  4743. int32_t elem = hash % table_size;
  4744. if (symb_table[2 * elem] != 0)
  4745. {
  4746. int32_t second = hash % (table_size - 2) + 1;
  4747. do
  4748. {
  4749. /* First compare the hashing value. */
  4750. if (symb_table[2 * elem] == hash
  4751. /* Compare the length of the name. */
  4752. && name_len == extra[symb_table[2 * elem + 1]]
  4753. /* Compare the name. */
  4754. && memcmp (name, &extra[symb_table[2 * elem + 1] + 1],
  4755. name_len) == 0)
  4756. {
  4757. /* Yep, this is the entry. */
  4758. break;
  4759. }
  4760. /* Next entry. */
  4761. elem += second;
  4762. }
  4763. while (symb_table[2 * elem] != 0);
  4764. }
  4765. return elem;
  4766. }
  4767. /* Local function for parse_bracket_exp used in _LIBC environment.
  4768. Look up the collation sequence value of BR_ELEM.
  4769. Return the value if succeeded, UINT_MAX otherwise. */
  4770. auto inline unsigned int
  4771. __attribute ((always_inline))
  4772. lookup_collation_sequence_value (br_elem)
  4773. bracket_elem_t *br_elem;
  4774. {
  4775. if (br_elem->type == SB_CHAR)
  4776. {
  4777. /*
  4778. if (MB_CUR_MAX == 1)
  4779. */
  4780. if (nrules == 0)
  4781. return collseqmb[br_elem->opr.ch];
  4782. else
  4783. {
  4784. wint_t wc = __btowc (br_elem->opr.ch);
  4785. return __collseq_table_lookup (collseqwc, wc);
  4786. }
  4787. }
  4788. else if (br_elem->type == MB_CHAR)
  4789. {
  4790. if (nrules != 0)
  4791. return __collseq_table_lookup (collseqwc, br_elem->opr.wch);
  4792. }
  4793. else if (br_elem->type == COLL_SYM)
  4794. {
  4795. size_t sym_name_len = strlen ((char *) br_elem->opr.name);
  4796. if (nrules != 0)
  4797. {
  4798. int32_t elem, idx;
  4799. elem = seek_collating_symbol_entry (br_elem->opr.name,
  4800. sym_name_len);
  4801. if (symb_table[2 * elem] != 0)
  4802. {
  4803. /* We found the entry. */
  4804. idx = symb_table[2 * elem + 1];
  4805. /* Skip the name of collating element name. */
  4806. idx += 1 + extra[idx];
  4807. /* Skip the byte sequence of the collating element. */
  4808. idx += 1 + extra[idx];
  4809. /* Adjust for the alignment. */
  4810. idx = (idx + 3) & ~3;
  4811. /* Skip the multibyte collation sequence value. */
  4812. idx += sizeof (unsigned int);
  4813. /* Skip the wide char sequence of the collating element. */
  4814. idx += sizeof (unsigned int) *
  4815. (1 + *(unsigned int *) (extra + idx));
  4816. /* Return the collation sequence value. */
  4817. return *(unsigned int *) (extra + idx);
  4818. }
  4819. else if (symb_table[2 * elem] == 0 && sym_name_len == 1)
  4820. {
  4821. /* No valid character. Match it as a single byte
  4822. character. */
  4823. return collseqmb[br_elem->opr.name[0]];
  4824. }
  4825. }
  4826. else if (sym_name_len == 1)
  4827. return collseqmb[br_elem->opr.name[0]];
  4828. }
  4829. return UINT_MAX;
  4830. }
  4831. /* Local function for parse_bracket_exp used in _LIBC environement.
  4832. Build the range expression which starts from START_ELEM, and ends
  4833. at END_ELEM. The result are written to MBCSET and SBCSET.
  4834. RANGE_ALLOC is the allocated size of mbcset->range_starts, and
  4835. mbcset->range_ends, is a pointer argument sinse we may
  4836. update it. */
  4837. auto inline reg_errcode_t
  4838. __attribute ((always_inline))
  4839. build_range_exp (sbcset, mbcset, range_alloc, start_elem, end_elem)
  4840. re_charset_t *mbcset;
  4841. int *range_alloc;
  4842. bitset_t sbcset;
  4843. bracket_elem_t *start_elem, *end_elem;
  4844. {
  4845. unsigned int ch;
  4846. uint32_t start_collseq;
  4847. uint32_t end_collseq;
  4848. /* Equivalence Classes and Character Classes can't be a range
  4849. start/end. */
  4850. if (BE (start_elem->type == EQUIV_CLASS || start_elem->type == CHAR_CLASS
  4851. || end_elem->type == EQUIV_CLASS || end_elem->type == CHAR_CLASS,
  4852. 0))
  4853. return REG_ERANGE;
  4854. start_collseq = lookup_collation_sequence_value (start_elem);
  4855. end_collseq = lookup_collation_sequence_value (end_elem);
  4856. /* Check start/end collation sequence values. */
  4857. if (BE (start_collseq == UINT_MAX || end_collseq == UINT_MAX, 0))
  4858. return REG_ECOLLATE;
  4859. if (BE ((syntax & RE_NO_EMPTY_RANGES) && start_collseq > end_collseq, 0))
  4860. return REG_ERANGE;
  4861. /* Got valid collation sequence values, add them as a new entry.
  4862. However, if we have no collation elements, and the character set
  4863. is single byte, the single byte character set that we
  4864. build below suffices. */
  4865. if (nrules > 0 || dfa->mb_cur_max > 1)
  4866. {
  4867. /* Check the space of the arrays. */
  4868. if (BE (*range_alloc == mbcset->nranges, 0))
  4869. {
  4870. /* There is not enough space, need realloc. */
  4871. uint32_t *new_array_start;
  4872. uint32_t *new_array_end;
  4873. int new_nranges;
  4874. /* +1 in case of mbcset->nranges is 0. */
  4875. new_nranges = 2 * mbcset->nranges + 1;
  4876. new_array_start = re_realloc (mbcset->range_starts, uint32_t,
  4877. new_nranges);
  4878. new_array_end = re_realloc (mbcset->range_ends, uint32_t,
  4879. new_nranges);
  4880. if (BE (new_array_start == NULL || new_array_end == NULL, 0))
  4881. return REG_ESPACE;
  4882. mbcset->range_starts = new_array_start;
  4883. mbcset->range_ends = new_array_end;
  4884. *range_alloc = new_nranges;
  4885. }
  4886. mbcset->range_starts[mbcset->nranges] = start_collseq;
  4887. mbcset->range_ends[mbcset->nranges++] = end_collseq;
  4888. }
  4889. /* Build the table for single byte characters. */
  4890. for (ch = 0; ch < SBC_MAX; ch++)
  4891. {
  4892. uint32_t ch_collseq;
  4893. /*
  4894. if (MB_CUR_MAX == 1)
  4895. */
  4896. if (nrules == 0)
  4897. ch_collseq = collseqmb[ch];
  4898. else
  4899. ch_collseq = __collseq_table_lookup (collseqwc, __btowc (ch));
  4900. if (start_collseq <= ch_collseq && ch_collseq <= end_collseq)
  4901. bitset_set (sbcset, ch);
  4902. }
  4903. return REG_NOERROR;
  4904. }
  4905. /* Local function for parse_bracket_exp used in _LIBC environement.
  4906. Build the collating element which is represented by NAME.
  4907. The result are written to MBCSET and SBCSET.
  4908. COLL_SYM_ALLOC is the allocated size of mbcset->coll_sym, is a
  4909. pointer argument sinse we may update it. */
  4910. auto inline reg_errcode_t
  4911. __attribute ((always_inline))
  4912. build_collating_symbol (sbcset, mbcset, coll_sym_alloc, name)
  4913. re_charset_t *mbcset;
  4914. int *coll_sym_alloc;
  4915. bitset_t sbcset;
  4916. const unsigned char *name;
  4917. {
  4918. int32_t elem, idx;
  4919. size_t name_len = strlen ((const char *) name);
  4920. if (nrules != 0)
  4921. {
  4922. elem = seek_collating_symbol_entry (name, name_len);
  4923. if (symb_table[2 * elem] != 0)
  4924. {
  4925. /* We found the entry. */
  4926. idx = symb_table[2 * elem + 1];
  4927. /* Skip the name of collating element name. */
  4928. idx += 1 + extra[idx];
  4929. }
  4930. else if (symb_table[2 * elem] == 0 && name_len == 1)
  4931. {
  4932. /* No valid character, treat it as a normal
  4933. character. */
  4934. bitset_set (sbcset, name[0]);
  4935. return REG_NOERROR;
  4936. }
  4937. else
  4938. return REG_ECOLLATE;
  4939. /* Got valid collation sequence, add it as a new entry. */
  4940. /* Check the space of the arrays. */
  4941. if (BE (*coll_sym_alloc == mbcset->ncoll_syms, 0))
  4942. {
  4943. /* Not enough, realloc it. */
  4944. /* +1 in case of mbcset->ncoll_syms is 0. */
  4945. int new_coll_sym_alloc = 2 * mbcset->ncoll_syms + 1;
  4946. /* Use realloc since mbcset->coll_syms is NULL
  4947. if *alloc == 0. */
  4948. int32_t *new_coll_syms = re_realloc (mbcset->coll_syms, int32_t,
  4949. new_coll_sym_alloc);
  4950. if (BE (new_coll_syms == NULL, 0))
  4951. return REG_ESPACE;
  4952. mbcset->coll_syms = new_coll_syms;
  4953. *coll_sym_alloc = new_coll_sym_alloc;
  4954. }
  4955. mbcset->coll_syms[mbcset->ncoll_syms++] = idx;
  4956. return REG_NOERROR;
  4957. }
  4958. else
  4959. {
  4960. if (BE (name_len != 1, 0))
  4961. return REG_ECOLLATE;
  4962. else
  4963. {
  4964. bitset_set (sbcset, name[0]);
  4965. return REG_NOERROR;
  4966. }
  4967. }
  4968. }
  4969. #endif
  4970. re_token_t br_token;
  4971. re_bitset_ptr_t sbcset;
  4972. #ifdef RE_ENABLE_I18N
  4973. re_charset_t *mbcset;
  4974. int coll_sym_alloc = 0, range_alloc = 0, mbchar_alloc = 0;
  4975. int equiv_class_alloc = 0, char_class_alloc = 0;
  4976. #endif /* not RE_ENABLE_I18N */
  4977. int non_match = 0;
  4978. bin_tree_t *work_tree;
  4979. int token_len;
  4980. int first_round = 1;
  4981. #ifdef _LIBC
  4982. collseqmb = (const unsigned char *)
  4983. _NL_CURRENT (LC_COLLATE, _NL_COLLATE_COLLSEQMB);
  4984. nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
  4985. if (nrules)
  4986. {
  4987. /*
  4988. if (MB_CUR_MAX > 1)
  4989. */
  4990. collseqwc = _NL_CURRENT (LC_COLLATE, _NL_COLLATE_COLLSEQWC);
  4991. table_size = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_SYMB_HASH_SIZEMB);
  4992. symb_table = (const int32_t *) _NL_CURRENT (LC_COLLATE,
  4993. _NL_COLLATE_SYMB_TABLEMB);
  4994. extra = (const unsigned char *) _NL_CURRENT (LC_COLLATE,
  4995. _NL_COLLATE_SYMB_EXTRAMB);
  4996. }
  4997. #endif
  4998. sbcset = (re_bitset_ptr_t) calloc (sizeof (bitset_t), 1);
  4999. #ifdef RE_ENABLE_I18N
  5000. mbcset = (re_charset_t *) calloc (sizeof (re_charset_t), 1);
  5001. #endif /* RE_ENABLE_I18N */
  5002. #ifdef RE_ENABLE_I18N
  5003. if (BE (sbcset == NULL || mbcset == NULL, 0))
  5004. #else
  5005. if (BE (sbcset == NULL, 0))
  5006. #endif /* RE_ENABLE_I18N */
  5007. {
  5008. *err = REG_ESPACE;
  5009. return NULL;
  5010. }
  5011. token_len = peek_token_bracket (token, regexp, syntax);
  5012. if (BE (token->type == END_OF_RE, 0))
  5013. {
  5014. *err = REG_BADPAT;
  5015. goto parse_bracket_exp_free_return;
  5016. }
  5017. if (token->type == OP_NON_MATCH_LIST)
  5018. {
  5019. #ifdef RE_ENABLE_I18N
  5020. mbcset->non_match = 1;
  5021. #endif /* not RE_ENABLE_I18N */
  5022. non_match = 1;
  5023. if (syntax & RE_HAT_LISTS_NOT_NEWLINE)
  5024. bitset_set (sbcset, '\n');
  5025. re_string_skip_bytes (regexp, token_len); /* Skip a token. */
  5026. token_len = peek_token_bracket (token, regexp, syntax);
  5027. if (BE (token->type == END_OF_RE, 0))
  5028. {
  5029. *err = REG_BADPAT;
  5030. goto parse_bracket_exp_free_return;
  5031. }
  5032. }
  5033. /* We treat the first ']' as a normal character. */
  5034. if (token->type == OP_CLOSE_BRACKET)
  5035. token->type = CHARACTER;
  5036. while (1)
  5037. {
  5038. bracket_elem_t start_elem, end_elem;
  5039. unsigned char start_name_buf[BRACKET_NAME_BUF_SIZE];
  5040. unsigned char end_name_buf[BRACKET_NAME_BUF_SIZE];
  5041. reg_errcode_t ret;
  5042. int token_len2 = 0, is_range_exp = 0;
  5043. re_token_t token2;
  5044. start_elem.opr.name = start_name_buf;
  5045. ret = parse_bracket_element (&start_elem, regexp, token, token_len, dfa,
  5046. syntax, first_round);
  5047. if (BE (ret != REG_NOERROR, 0))
  5048. {
  5049. *err = ret;
  5050. goto parse_bracket_exp_free_return;
  5051. }
  5052. first_round = 0;
  5053. /* Get information about the next token. We need it in any case. */
  5054. token_len = peek_token_bracket (token, regexp, syntax);
  5055. /* Do not check for ranges if we know they are not allowed. */
  5056. if (start_elem.type != CHAR_CLASS && start_elem.type != EQUIV_CLASS)
  5057. {
  5058. if (BE (token->type == END_OF_RE, 0))
  5059. {
  5060. *err = REG_EBRACK;
  5061. goto parse_bracket_exp_free_return;
  5062. }
  5063. if (token->type == OP_CHARSET_RANGE)
  5064. {
  5065. re_string_skip_bytes (regexp, token_len); /* Skip '-'. */
  5066. token_len2 = peek_token_bracket (&token2, regexp, syntax);
  5067. if (BE (token2.type == END_OF_RE, 0))
  5068. {
  5069. *err = REG_EBRACK;
  5070. goto parse_bracket_exp_free_return;
  5071. }
  5072. if (token2.type == OP_CLOSE_BRACKET)
  5073. {
  5074. /* We treat the last '-' as a normal character. */
  5075. re_string_skip_bytes (regexp, -token_len);
  5076. token->type = CHARACTER;
  5077. }
  5078. else
  5079. is_range_exp = 1;
  5080. }
  5081. }
  5082. if (is_range_exp == 1)
  5083. {
  5084. end_elem.opr.name = end_name_buf;
  5085. ret = parse_bracket_element (&end_elem, regexp, &token2, token_len2,
  5086. dfa, syntax, 1);
  5087. if (BE (ret != REG_NOERROR, 0))
  5088. {
  5089. *err = ret;
  5090. goto parse_bracket_exp_free_return;
  5091. }
  5092. token_len = peek_token_bracket (token, regexp, syntax);
  5093. #ifdef _LIBC
  5094. *err = build_range_exp (sbcset, mbcset, &range_alloc,
  5095. &start_elem, &end_elem);
  5096. #else
  5097. # ifdef RE_ENABLE_I18N
  5098. *err = build_range_exp (sbcset,
  5099. dfa->mb_cur_max > 1 ? mbcset : NULL,
  5100. &range_alloc, &start_elem, &end_elem);
  5101. # else
  5102. *err = build_range_exp (sbcset, &start_elem, &end_elem);
  5103. # endif
  5104. #endif /* RE_ENABLE_I18N */
  5105. if (BE (*err != REG_NOERROR, 0))
  5106. goto parse_bracket_exp_free_return;
  5107. }
  5108. else
  5109. {
  5110. switch (start_elem.type)
  5111. {
  5112. case SB_CHAR:
  5113. bitset_set (sbcset, start_elem.opr.ch);
  5114. break;
  5115. #ifdef RE_ENABLE_I18N
  5116. case MB_CHAR:
  5117. /* Check whether the array has enough space. */
  5118. if (BE (mbchar_alloc == mbcset->nmbchars, 0))
  5119. {
  5120. wchar_t *new_mbchars;
  5121. /* Not enough, realloc it. */
  5122. /* +1 in case of mbcset->nmbchars is 0. */
  5123. mbchar_alloc = 2 * mbcset->nmbchars + 1;
  5124. /* Use realloc since array is NULL if *alloc == 0. */
  5125. new_mbchars = re_realloc (mbcset->mbchars, wchar_t,
  5126. mbchar_alloc);
  5127. if (BE (new_mbchars == NULL, 0))
  5128. goto parse_bracket_exp_espace;
  5129. mbcset->mbchars = new_mbchars;
  5130. }
  5131. mbcset->mbchars[mbcset->nmbchars++] = start_elem.opr.wch;
  5132. break;
  5133. #endif /* RE_ENABLE_I18N */
  5134. case EQUIV_CLASS:
  5135. *err = build_equiv_class (sbcset,
  5136. #ifdef RE_ENABLE_I18N
  5137. mbcset, &equiv_class_alloc,
  5138. #endif /* RE_ENABLE_I18N */
  5139. start_elem.opr.name);
  5140. if (BE (*err != REG_NOERROR, 0))
  5141. goto parse_bracket_exp_free_return;
  5142. break;
  5143. case COLL_SYM:
  5144. *err = build_collating_symbol (sbcset,
  5145. #ifdef RE_ENABLE_I18N
  5146. mbcset, &coll_sym_alloc,
  5147. #endif /* RE_ENABLE_I18N */
  5148. start_elem.opr.name);
  5149. if (BE (*err != REG_NOERROR, 0))
  5150. goto parse_bracket_exp_free_return;
  5151. break;
  5152. case CHAR_CLASS:
  5153. *err = build_charclass (regexp->trans, sbcset,
  5154. #ifdef RE_ENABLE_I18N
  5155. mbcset, &char_class_alloc,
  5156. #endif /* RE_ENABLE_I18N */
  5157. start_elem.opr.name, syntax);
  5158. if (BE (*err != REG_NOERROR, 0))
  5159. goto parse_bracket_exp_free_return;
  5160. break;
  5161. default:
  5162. assert (0);
  5163. break;
  5164. }
  5165. }
  5166. if (BE (token->type == END_OF_RE, 0))
  5167. {
  5168. *err = REG_EBRACK;
  5169. goto parse_bracket_exp_free_return;
  5170. }
  5171. if (token->type == OP_CLOSE_BRACKET)
  5172. break;
  5173. }
  5174. re_string_skip_bytes (regexp, token_len); /* Skip a token. */
  5175. /* If it is non-matching list. */
  5176. if (non_match)
  5177. bitset_not (sbcset);
  5178. #ifdef RE_ENABLE_I18N
  5179. /* Ensure only single byte characters are set. */
  5180. if (dfa->mb_cur_max > 1)
  5181. bitset_mask (sbcset, dfa->sb_char);
  5182. if (mbcset->nmbchars || mbcset->ncoll_syms || mbcset->nequiv_classes
  5183. || mbcset->nranges || (dfa->mb_cur_max > 1 && (mbcset->nchar_classes
  5184. || mbcset->non_match)))
  5185. {
  5186. bin_tree_t *mbc_tree;
  5187. int sbc_idx;
  5188. /* Build a tree for complex bracket. */
  5189. dfa->has_mb_node = 1;
  5190. br_token.type = COMPLEX_BRACKET;
  5191. br_token.opr.mbcset = mbcset;
  5192. mbc_tree = create_token_tree (dfa, NULL, NULL, &br_token);
  5193. if (BE (mbc_tree == NULL, 0))
  5194. goto parse_bracket_exp_espace;
  5195. for (sbc_idx = 0; sbc_idx < BITSET_WORDS; ++sbc_idx)
  5196. if (sbcset[sbc_idx])
  5197. break;
  5198. /* If there are no bits set in sbcset, there is no point
  5199. of having both SIMPLE_BRACKET and COMPLEX_BRACKET. */
  5200. if (sbc_idx < BITSET_WORDS)
  5201. {
  5202. /* Build a tree for simple bracket. */
  5203. br_token.type = SIMPLE_BRACKET;
  5204. br_token.opr.sbcset = sbcset;
  5205. work_tree = create_token_tree (dfa, NULL, NULL, &br_token);
  5206. if (BE (work_tree == NULL, 0))
  5207. goto parse_bracket_exp_espace;
  5208. /* Then join them by ALT node. */
  5209. work_tree = create_tree (dfa, work_tree, mbc_tree, OP_ALT);
  5210. if (BE (work_tree == NULL, 0))
  5211. goto parse_bracket_exp_espace;
  5212. }
  5213. else
  5214. {
  5215. re_free (sbcset);
  5216. work_tree = mbc_tree;
  5217. }
  5218. }
  5219. else
  5220. #endif /* not RE_ENABLE_I18N */
  5221. {
  5222. #ifdef RE_ENABLE_I18N
  5223. free_charset (mbcset);
  5224. #endif
  5225. /* Build a tree for simple bracket. */
  5226. br_token.type = SIMPLE_BRACKET;
  5227. br_token.opr.sbcset = sbcset;
  5228. work_tree = create_token_tree (dfa, NULL, NULL, &br_token);
  5229. if (BE (work_tree == NULL, 0))
  5230. goto parse_bracket_exp_espace;
  5231. }
  5232. return work_tree;
  5233. parse_bracket_exp_espace:
  5234. *err = REG_ESPACE;
  5235. parse_bracket_exp_free_return:
  5236. re_free (sbcset);
  5237. #ifdef RE_ENABLE_I18N
  5238. free_charset (mbcset);
  5239. #endif /* RE_ENABLE_I18N */
  5240. return NULL;
  5241. }
  5242. /* Parse an element in the bracket expression. */
  5243. static reg_errcode_t
  5244. parse_bracket_element (bracket_elem_t *elem, re_string_t *regexp,
  5245. re_token_t *token, int token_len, re_dfa_t *dfa,
  5246. reg_syntax_t syntax, int accept_hyphen)
  5247. {
  5248. #ifdef RE_ENABLE_I18N
  5249. int cur_char_size;
  5250. cur_char_size = re_string_char_size_at (regexp, re_string_cur_idx (regexp));
  5251. if (cur_char_size > 1)
  5252. {
  5253. elem->type = MB_CHAR;
  5254. elem->opr.wch = re_string_wchar_at (regexp, re_string_cur_idx (regexp));
  5255. re_string_skip_bytes (regexp, cur_char_size);
  5256. return REG_NOERROR;
  5257. }
  5258. #endif /* RE_ENABLE_I18N */
  5259. re_string_skip_bytes (regexp, token_len); /* Skip a token. */
  5260. if (token->type == OP_OPEN_COLL_ELEM || token->type == OP_OPEN_CHAR_CLASS
  5261. || token->type == OP_OPEN_EQUIV_CLASS)
  5262. return parse_bracket_symbol (elem, regexp, token);
  5263. if (BE (token->type == OP_CHARSET_RANGE, 0) && !accept_hyphen)
  5264. {
  5265. /* A '-' must only appear as anything but a range indicator before
  5266. the closing bracket. Everything else is an error. */
  5267. re_token_t token2;
  5268. (void) peek_token_bracket (&token2, regexp, syntax);
  5269. if (token2.type != OP_CLOSE_BRACKET)
  5270. /* The actual error value is not standardized since this whole
  5271. case is undefined. But ERANGE makes good sense. */
  5272. return REG_ERANGE;
  5273. }
  5274. elem->type = SB_CHAR;
  5275. elem->opr.ch = token->opr.c;
  5276. return REG_NOERROR;
  5277. }
  5278. /* Parse a bracket symbol in the bracket expression. Bracket symbols are
  5279. such as [:<character_class>:], [.<collating_element>.], and
  5280. [=<equivalent_class>=]. */
  5281. static reg_errcode_t
  5282. parse_bracket_symbol (bracket_elem_t *elem, re_string_t *regexp,
  5283. re_token_t *token)
  5284. {
  5285. unsigned char ch, delim = token->opr.c;
  5286. int i = 0;
  5287. if (re_string_eoi(regexp))
  5288. return REG_EBRACK;
  5289. for (;; ++i)
  5290. {
  5291. if (i >= BRACKET_NAME_BUF_SIZE)
  5292. return REG_EBRACK;
  5293. if (token->type == OP_OPEN_CHAR_CLASS)
  5294. ch = re_string_fetch_byte_case (regexp);
  5295. else
  5296. ch = re_string_fetch_byte (regexp);
  5297. if (re_string_eoi(regexp))
  5298. return REG_EBRACK;
  5299. if (ch == delim && re_string_peek_byte (regexp, 0) == ']')
  5300. break;
  5301. elem->opr.name[i] = ch;
  5302. }
  5303. re_string_skip_bytes (regexp, 1);
  5304. elem->opr.name[i] = '\0';
  5305. switch (token->type)
  5306. {
  5307. case OP_OPEN_COLL_ELEM:
  5308. elem->type = COLL_SYM;
  5309. break;
  5310. case OP_OPEN_EQUIV_CLASS:
  5311. elem->type = EQUIV_CLASS;
  5312. break;
  5313. case OP_OPEN_CHAR_CLASS:
  5314. elem->type = CHAR_CLASS;
  5315. break;
  5316. default:
  5317. break;
  5318. }
  5319. return REG_NOERROR;
  5320. }
  5321. /* Helper function for parse_bracket_exp.
  5322. Build the equivalence class which is represented by NAME.
  5323. The result are written to MBCSET and SBCSET.
  5324. EQUIV_CLASS_ALLOC is the allocated size of mbcset->equiv_classes,
  5325. is a pointer argument sinse we may update it. */
  5326. static reg_errcode_t
  5327. #ifdef RE_ENABLE_I18N
  5328. build_equiv_class (bitset_t sbcset, re_charset_t *mbcset,
  5329. int *equiv_class_alloc, const unsigned char *name)
  5330. #else /* not RE_ENABLE_I18N */
  5331. build_equiv_class (bitset_t sbcset, const unsigned char *name)
  5332. #endif /* not RE_ENABLE_I18N */
  5333. {
  5334. #ifdef _LIBC
  5335. uint32_t nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
  5336. if (nrules != 0)
  5337. {
  5338. const int32_t *table, *indirect;
  5339. const unsigned char *weights, *extra, *cp;
  5340. unsigned char char_buf[2];
  5341. int32_t idx1, idx2;
  5342. unsigned int ch;
  5343. size_t len;
  5344. /* This #include defines a local function! */
  5345. # include <locale/weight.h>
  5346. /* Calculate the index for equivalence class. */
  5347. cp = name;
  5348. table = (const int32_t *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
  5349. weights = (const unsigned char *) _NL_CURRENT (LC_COLLATE,
  5350. _NL_COLLATE_WEIGHTMB);
  5351. extra = (const unsigned char *) _NL_CURRENT (LC_COLLATE,
  5352. _NL_COLLATE_EXTRAMB);
  5353. indirect = (const int32_t *) _NL_CURRENT (LC_COLLATE,
  5354. _NL_COLLATE_INDIRECTMB);
  5355. idx1 = findidx (&cp);
  5356. if (BE (idx1 == 0 || cp < name + strlen ((const char *) name), 0))
  5357. /* This isn't a valid character. */
  5358. return REG_ECOLLATE;
  5359. /* Build single byte matcing table for this equivalence class. */
  5360. char_buf[1] = (unsigned char) '\0';
  5361. len = weights[idx1 & 0xffffff];
  5362. for (ch = 0; ch < SBC_MAX; ++ch)
  5363. {
  5364. char_buf[0] = ch;
  5365. cp = char_buf;
  5366. idx2 = findidx (&cp);
  5367. /*
  5368. idx2 = table[ch];
  5369. */
  5370. if (idx2 == 0)
  5371. /* This isn't a valid character. */
  5372. continue;
  5373. /* Compare only if the length matches and the collation rule
  5374. index is the same. */
  5375. if (len == weights[idx2 & 0xffffff] && (idx1 >> 24) == (idx2 >> 24))
  5376. {
  5377. int cnt = 0;
  5378. while (cnt <= len &&
  5379. weights[(idx1 & 0xffffff) + 1 + cnt]
  5380. == weights[(idx2 & 0xffffff) + 1 + cnt])
  5381. ++cnt;
  5382. if (cnt > len)
  5383. bitset_set (sbcset, ch);
  5384. }
  5385. }
  5386. /* Check whether the array has enough space. */
  5387. if (BE (*equiv_class_alloc == mbcset->nequiv_classes, 0))
  5388. {
  5389. /* Not enough, realloc it. */
  5390. /* +1 in case of mbcset->nequiv_classes is 0. */
  5391. int new_equiv_class_alloc = 2 * mbcset->nequiv_classes + 1;
  5392. /* Use realloc since the array is NULL if *alloc == 0. */
  5393. int32_t *new_equiv_classes = re_realloc (mbcset->equiv_classes,
  5394. int32_t,
  5395. new_equiv_class_alloc);
  5396. if (BE (new_equiv_classes == NULL, 0))
  5397. return REG_ESPACE;
  5398. mbcset->equiv_classes = new_equiv_classes;
  5399. *equiv_class_alloc = new_equiv_class_alloc;
  5400. }
  5401. mbcset->equiv_classes[mbcset->nequiv_classes++] = idx1;
  5402. }
  5403. else
  5404. #endif /* _LIBC */
  5405. {
  5406. if (BE (strlen ((const char *) name) != 1, 0))
  5407. return REG_ECOLLATE;
  5408. bitset_set (sbcset, *name);
  5409. }
  5410. return REG_NOERROR;
  5411. }
  5412. /* Helper function for parse_bracket_exp.
  5413. Build the character class which is represented by NAME.
  5414. The result are written to MBCSET and SBCSET.
  5415. CHAR_CLASS_ALLOC is the allocated size of mbcset->char_classes,
  5416. is a pointer argument sinse we may update it. */
  5417. static reg_errcode_t
  5418. #ifdef RE_ENABLE_I18N
  5419. build_charclass (RE_TRANSLATE_TYPE trans, bitset_t sbcset,
  5420. re_charset_t *mbcset, int *char_class_alloc,
  5421. const unsigned char *class_name, reg_syntax_t syntax)
  5422. #else /* not RE_ENABLE_I18N */
  5423. build_charclass (RE_TRANSLATE_TYPE trans, bitset_t sbcset,
  5424. const unsigned char *class_name, reg_syntax_t syntax)
  5425. #endif /* not RE_ENABLE_I18N */
  5426. {
  5427. int i;
  5428. const char *name = (const char *) class_name;
  5429. /* In case of REG_ICASE "upper" and "lower" match the both of
  5430. upper and lower cases. */
  5431. if ((syntax & RE_ICASE)
  5432. && (strcmp (name, "upper") == 0 || strcmp (name, "lower") == 0))
  5433. name = "alpha";
  5434. #ifdef RE_ENABLE_I18N
  5435. /* Check the space of the arrays. */
  5436. if (BE (*char_class_alloc == mbcset->nchar_classes, 0))
  5437. {
  5438. /* Not enough, realloc it. */
  5439. /* +1 in case of mbcset->nchar_classes is 0. */
  5440. int new_char_class_alloc = 2 * mbcset->nchar_classes + 1;
  5441. /* Use realloc since array is NULL if *alloc == 0. */
  5442. wctype_t *new_char_classes = re_realloc (mbcset->char_classes, wctype_t,
  5443. new_char_class_alloc);
  5444. if (BE (new_char_classes == NULL, 0))
  5445. return REG_ESPACE;
  5446. mbcset->char_classes = new_char_classes;
  5447. *char_class_alloc = new_char_class_alloc;
  5448. }
  5449. mbcset->char_classes[mbcset->nchar_classes++] = __wctype (name);
  5450. #endif /* RE_ENABLE_I18N */
  5451. #define BUILD_CHARCLASS_LOOP(ctype_func) \
  5452. do { \
  5453. if (BE (trans != NULL, 0)) \
  5454. { \
  5455. for (i = 0; i < SBC_MAX; ++i) \
  5456. if (ctype_func (i)) \
  5457. bitset_set (sbcset, trans[i]); \
  5458. } \
  5459. else \
  5460. { \
  5461. for (i = 0; i < SBC_MAX; ++i) \
  5462. if (ctype_func (i)) \
  5463. bitset_set (sbcset, i); \
  5464. } \
  5465. } while (0)
  5466. if (strcmp (name, "alnum") == 0)
  5467. BUILD_CHARCLASS_LOOP (isalnum);
  5468. else if (strcmp (name, "cntrl") == 0)
  5469. BUILD_CHARCLASS_LOOP (iscntrl);
  5470. else if (strcmp (name, "lower") == 0)
  5471. BUILD_CHARCLASS_LOOP (islower);
  5472. else if (strcmp (name, "space") == 0)
  5473. BUILD_CHARCLASS_LOOP (isspace);
  5474. else if (strcmp (name, "alpha") == 0)
  5475. BUILD_CHARCLASS_LOOP (isalpha);
  5476. else if (strcmp (name, "digit") == 0)
  5477. BUILD_CHARCLASS_LOOP (isdigit);
  5478. else if (strcmp (name, "print") == 0)
  5479. BUILD_CHARCLASS_LOOP (isprint);
  5480. else if (strcmp (name, "upper") == 0)
  5481. BUILD_CHARCLASS_LOOP (isupper);
  5482. else if (strcmp (name, "blank") == 0)
  5483. BUILD_CHARCLASS_LOOP (isblank);
  5484. else if (strcmp (name, "graph") == 0)
  5485. BUILD_CHARCLASS_LOOP (isgraph);
  5486. else if (strcmp (name, "punct") == 0)
  5487. BUILD_CHARCLASS_LOOP (ispunct);
  5488. else if (strcmp (name, "xdigit") == 0)
  5489. BUILD_CHARCLASS_LOOP (isxdigit);
  5490. else
  5491. return REG_ECTYPE;
  5492. return REG_NOERROR;
  5493. }
  5494. static bin_tree_t *
  5495. build_charclass_op (re_dfa_t *dfa, RE_TRANSLATE_TYPE trans,
  5496. const unsigned char *class_name,
  5497. const unsigned char *extra, int non_match,
  5498. reg_errcode_t *err)
  5499. {
  5500. re_bitset_ptr_t sbcset;
  5501. #ifdef RE_ENABLE_I18N
  5502. re_charset_t *mbcset;
  5503. int alloc = 0;
  5504. #endif /* not RE_ENABLE_I18N */
  5505. reg_errcode_t ret;
  5506. re_token_t br_token;
  5507. bin_tree_t *tree;
  5508. sbcset = (re_bitset_ptr_t) calloc (sizeof (bitset_t), 1);
  5509. #ifdef RE_ENABLE_I18N
  5510. mbcset = (re_charset_t *) calloc (sizeof (re_charset_t), 1);
  5511. #endif /* RE_ENABLE_I18N */
  5512. #ifdef RE_ENABLE_I18N
  5513. if (BE (sbcset == NULL || mbcset == NULL, 0))
  5514. #else /* not RE_ENABLE_I18N */
  5515. if (BE (sbcset == NULL, 0))
  5516. #endif /* not RE_ENABLE_I18N */
  5517. {
  5518. *err = REG_ESPACE;
  5519. return NULL;
  5520. }
  5521. if (non_match)
  5522. {
  5523. #ifdef RE_ENABLE_I18N
  5524. mbcset->non_match = 1;
  5525. #endif /* not RE_ENABLE_I18N */
  5526. }
  5527. /* We don't care the syntax in this case. */
  5528. ret = build_charclass (trans, sbcset,
  5529. #ifdef RE_ENABLE_I18N
  5530. mbcset, &alloc,
  5531. #endif /* RE_ENABLE_I18N */
  5532. class_name, 0);
  5533. if (BE (ret != REG_NOERROR, 0))
  5534. {
  5535. re_free (sbcset);
  5536. #ifdef RE_ENABLE_I18N
  5537. free_charset (mbcset);
  5538. #endif /* RE_ENABLE_I18N */
  5539. *err = ret;
  5540. return NULL;
  5541. }
  5542. /* \w match '_' also. */
  5543. for (; *extra; extra++)
  5544. bitset_set (sbcset, *extra);
  5545. /* If it is non-matching list. */
  5546. if (non_match)
  5547. bitset_not (sbcset);
  5548. #ifdef RE_ENABLE_I18N
  5549. /* Ensure only single byte characters are set. */
  5550. if (dfa->mb_cur_max > 1)
  5551. bitset_mask (sbcset, dfa->sb_char);
  5552. #endif
  5553. /* Build a tree for simple bracket. */
  5554. br_token.type = SIMPLE_BRACKET;
  5555. br_token.opr.sbcset = sbcset;
  5556. tree = create_token_tree (dfa, NULL, NULL, &br_token);
  5557. if (BE (tree == NULL, 0))
  5558. goto build_word_op_espace;
  5559. #ifdef RE_ENABLE_I18N
  5560. if (dfa->mb_cur_max > 1)
  5561. {
  5562. bin_tree_t *mbc_tree;
  5563. /* Build a tree for complex bracket. */
  5564. br_token.type = COMPLEX_BRACKET;
  5565. br_token.opr.mbcset = mbcset;
  5566. dfa->has_mb_node = 1;
  5567. mbc_tree = create_token_tree (dfa, NULL, NULL, &br_token);
  5568. if (BE (mbc_tree == NULL, 0))
  5569. goto build_word_op_espace;
  5570. /* Then join them by ALT node. */
  5571. tree = create_tree (dfa, tree, mbc_tree, OP_ALT);
  5572. if (BE (mbc_tree != NULL, 1))
  5573. return tree;
  5574. }
  5575. else
  5576. {
  5577. free_charset (mbcset);
  5578. return tree;
  5579. }
  5580. #else /* not RE_ENABLE_I18N */
  5581. return tree;
  5582. #endif /* not RE_ENABLE_I18N */
  5583. build_word_op_espace:
  5584. re_free (sbcset);
  5585. #ifdef RE_ENABLE_I18N
  5586. free_charset (mbcset);
  5587. #endif /* RE_ENABLE_I18N */
  5588. *err = REG_ESPACE;
  5589. return NULL;
  5590. }
  5591. /* This is intended for the expressions like "a{1,3}".
  5592. Fetch a number from `input', and return the number.
  5593. Return -1, if the number field is empty like "{,1}".
  5594. Return -2, If an error is occured. */
  5595. static int
  5596. fetch_number (re_string_t *input, re_token_t *token, reg_syntax_t syntax)
  5597. {
  5598. int num = -1;
  5599. unsigned char c;
  5600. while (1)
  5601. {
  5602. fetch_token (token, input, syntax);
  5603. c = token->opr.c;
  5604. if (BE (token->type == END_OF_RE, 0))
  5605. return -2;
  5606. if (token->type == OP_CLOSE_DUP_NUM || c == ',')
  5607. break;
  5608. num = ((token->type != CHARACTER || c < '0' || '9' < c || num == -2)
  5609. ? -2 : ((num == -1) ? c - '0' : num * 10 + c - '0'));
  5610. num = (num > RE_DUP_MAX) ? -2 : num;
  5611. }
  5612. return num;
  5613. }
  5614. #ifdef RE_ENABLE_I18N
  5615. static void
  5616. free_charset (re_charset_t *cset)
  5617. {
  5618. re_free (cset->mbchars);
  5619. # ifdef _LIBC
  5620. re_free (cset->coll_syms);
  5621. re_free (cset->equiv_classes);
  5622. re_free (cset->range_starts);
  5623. re_free (cset->range_ends);
  5624. # endif
  5625. re_free (cset->char_classes);
  5626. re_free (cset);
  5627. }
  5628. #endif /* RE_ENABLE_I18N */
  5629. /* Functions for binary tree operation. */
  5630. /* Create a tree node. */
  5631. static bin_tree_t *
  5632. create_tree (re_dfa_t *dfa, bin_tree_t *left, bin_tree_t *right,
  5633. re_token_type_t type)
  5634. {
  5635. re_token_t t;
  5636. t.type = type;
  5637. return create_token_tree (dfa, left, right, &t);
  5638. }
  5639. static bin_tree_t *
  5640. create_token_tree (re_dfa_t *dfa, bin_tree_t *left, bin_tree_t *right,
  5641. const re_token_t *token)
  5642. {
  5643. bin_tree_t *tree;
  5644. if (BE (dfa->str_tree_storage_idx == BIN_TREE_STORAGE_SIZE, 0))
  5645. {
  5646. bin_tree_storage_t *storage = re_malloc (bin_tree_storage_t, 1);
  5647. if (storage == NULL)
  5648. return NULL;
  5649. storage->next = dfa->str_tree_storage;
  5650. dfa->str_tree_storage = storage;
  5651. dfa->str_tree_storage_idx = 0;
  5652. }
  5653. tree = &dfa->str_tree_storage->data[dfa->str_tree_storage_idx++];
  5654. tree->parent = NULL;
  5655. tree->left = left;
  5656. tree->right = right;
  5657. tree->token = *token;
  5658. tree->token.duplicated = 0;
  5659. tree->token.opt_subexp = 0;
  5660. tree->first = NULL;
  5661. tree->next = NULL;
  5662. tree->node_idx = -1;
  5663. if (left != NULL)
  5664. left->parent = tree;
  5665. if (right != NULL)
  5666. right->parent = tree;
  5667. return tree;
  5668. }
  5669. /* Mark the tree SRC as an optional subexpression.
  5670. To be called from preorder or postorder. */
  5671. static reg_errcode_t
  5672. mark_opt_subexp (void *extra, bin_tree_t *node)
  5673. {
  5674. int idx = (int) (long) extra;
  5675. if (node->token.type == SUBEXP && node->token.opr.idx == idx)
  5676. node->token.opt_subexp = 1;
  5677. return REG_NOERROR;
  5678. }
  5679. /* Free the allocated memory inside NODE. */
  5680. static void
  5681. free_token (re_token_t *node)
  5682. {
  5683. #ifdef RE_ENABLE_I18N
  5684. if (node->type == COMPLEX_BRACKET && node->duplicated == 0)
  5685. free_charset (node->opr.mbcset);
  5686. else
  5687. #endif /* RE_ENABLE_I18N */
  5688. if (node->type == SIMPLE_BRACKET && node->duplicated == 0)
  5689. re_free (node->opr.sbcset);
  5690. }
  5691. /* Worker function for tree walking. Free the allocated memory inside NODE
  5692. and its children. */
  5693. static reg_errcode_t
  5694. free_tree (void *extra, bin_tree_t *node)
  5695. {
  5696. free_token (&node->token);
  5697. return REG_NOERROR;
  5698. }
  5699. /* Duplicate the node SRC, and return new node. This is a preorder
  5700. visit similar to the one implemented by the generic visitor, but
  5701. we need more infrastructure to maintain two parallel trees --- so,
  5702. it's easier to duplicate. */
  5703. static bin_tree_t *
  5704. duplicate_tree (const bin_tree_t *root, re_dfa_t *dfa)
  5705. {
  5706. const bin_tree_t *node;
  5707. bin_tree_t *dup_root;
  5708. bin_tree_t **p_new = &dup_root, *dup_node = root->parent;
  5709. for (node = root; ; )
  5710. {
  5711. /* Create a new tree and link it back to the current parent. */
  5712. *p_new = create_token_tree (dfa, NULL, NULL, &node->token);
  5713. if (*p_new == NULL)
  5714. return NULL;
  5715. (*p_new)->parent = dup_node;
  5716. (*p_new)->token.duplicated = 1;
  5717. dup_node = *p_new;
  5718. /* Go to the left node, or up and to the right. */
  5719. if (node->left)
  5720. {
  5721. node = node->left;
  5722. p_new = &dup_node->left;
  5723. }
  5724. else
  5725. {
  5726. const bin_tree_t *prev = NULL;
  5727. while (node->right == prev || node->right == NULL)
  5728. {
  5729. prev = node;
  5730. node = node->parent;
  5731. dup_node = dup_node->parent;
  5732. if (!node)
  5733. return dup_root;
  5734. }
  5735. node = node->right;
  5736. p_new = &dup_node->right;
  5737. }
  5738. }
  5739. }
  5740. /* Extended regular expression matching and search library.
  5741. Copyright (C) 2002, 2003, 2004, 2005, 2007 Free Software Foundation, Inc.
  5742. This file is part of the GNU C Library.
  5743. Contributed by Isamu Hasegawa <isamu@yamato.ibm.com>.
  5744. The GNU C Library is free software; you can redistribute it and/or
  5745. modify it under the terms of the GNU Lesser General Public
  5746. License as published by the Free Software Foundation; either
  5747. version 2.1 of the License, or (at your option) any later version.
  5748. The GNU C Library is distributed in the hope that it will be useful,
  5749. but WITHOUT ANY WARRANTY; without even the implied warranty of
  5750. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  5751. Lesser General Public License for more details.
  5752. You should have received a copy of the GNU Lesser General Public
  5753. License along with the GNU C Library; if not, write to the Free
  5754. Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  5755. 02111-1307 USA. */
  5756. static reg_errcode_t match_ctx_init (re_match_context_t *cache, int eflags,
  5757. int n) internal_function;
  5758. static void match_ctx_clean (re_match_context_t *mctx) internal_function;
  5759. static void match_ctx_free (re_match_context_t *cache) internal_function;
  5760. static reg_errcode_t match_ctx_add_entry (re_match_context_t *cache, int node,
  5761. int str_idx, int from, int to)
  5762. internal_function;
  5763. static int search_cur_bkref_entry (const re_match_context_t *mctx, int str_idx)
  5764. internal_function;
  5765. static reg_errcode_t match_ctx_add_subtop (re_match_context_t *mctx, int node,
  5766. int str_idx) internal_function;
  5767. static re_sub_match_last_t * match_ctx_add_sublast (re_sub_match_top_t *subtop,
  5768. int node, int str_idx)
  5769. internal_function;
  5770. static void sift_ctx_init (re_sift_context_t *sctx, re_dfastate_t **sifted_sts,
  5771. re_dfastate_t **limited_sts, int last_node,
  5772. int last_str_idx)
  5773. internal_function;
  5774. static reg_errcode_t re_search_internal (const regex_t *preg,
  5775. const char *string, int length,
  5776. int start, int range, int stop,
  5777. size_t nmatch, regmatch_t pmatch[],
  5778. int eflags) internal_function;
  5779. static int re_search_2_stub (struct re_pattern_buffer *bufp,
  5780. const char *string1, int length1,
  5781. const char *string2, int length2,
  5782. int start, int range, struct re_registers *regs,
  5783. int stop, int ret_len) internal_function;
  5784. static int re_search_stub (struct re_pattern_buffer *bufp,
  5785. const char *string, int length, int start,
  5786. int range, int stop, struct re_registers *regs,
  5787. int ret_len) internal_function;
  5788. static unsigned re_copy_regs (struct re_registers *regs, regmatch_t *pmatch,
  5789. int nregs, int regs_allocated) internal_function;
  5790. static reg_errcode_t prune_impossible_nodes (re_match_context_t *mctx)
  5791. internal_function;
  5792. static int check_matching (re_match_context_t *mctx, int fl_longest_match,
  5793. int *p_match_first) internal_function;
  5794. static int check_halt_state_context (const re_match_context_t *mctx,
  5795. const re_dfastate_t *state, int idx)
  5796. internal_function;
  5797. static void update_regs (const re_dfa_t *dfa, regmatch_t *pmatch,
  5798. regmatch_t *prev_idx_match, int cur_node,
  5799. int cur_idx, int nmatch) internal_function;
  5800. static reg_errcode_t push_fail_stack (struct re_fail_stack_t *fs,
  5801. int str_idx, int dest_node, int nregs,
  5802. regmatch_t *regs,
  5803. re_node_set *eps_via_nodes)
  5804. internal_function;
  5805. static reg_errcode_t set_regs (const regex_t *preg,
  5806. const re_match_context_t *mctx,
  5807. size_t nmatch, regmatch_t *pmatch,
  5808. int fl_backtrack) internal_function;
  5809. static reg_errcode_t free_fail_stack_return (struct re_fail_stack_t *fs)
  5810. internal_function;
  5811. #ifdef RE_ENABLE_I18N
  5812. static int sift_states_iter_mb (const re_match_context_t *mctx,
  5813. re_sift_context_t *sctx,
  5814. int node_idx, int str_idx, int max_str_idx)
  5815. internal_function;
  5816. #endif /* RE_ENABLE_I18N */
  5817. static reg_errcode_t sift_states_backward (const re_match_context_t *mctx,
  5818. re_sift_context_t *sctx)
  5819. internal_function;
  5820. static reg_errcode_t build_sifted_states (const re_match_context_t *mctx,
  5821. re_sift_context_t *sctx, int str_idx,
  5822. re_node_set *cur_dest)
  5823. internal_function;
  5824. static reg_errcode_t update_cur_sifted_state (const re_match_context_t *mctx,
  5825. re_sift_context_t *sctx,
  5826. int str_idx,
  5827. re_node_set *dest_nodes)
  5828. internal_function;
  5829. static reg_errcode_t add_epsilon_src_nodes (const re_dfa_t *dfa,
  5830. re_node_set *dest_nodes,
  5831. const re_node_set *candidates)
  5832. internal_function;
  5833. static int check_dst_limits (const re_match_context_t *mctx,
  5834. re_node_set *limits,
  5835. int dst_node, int dst_idx, int src_node,
  5836. int src_idx) internal_function;
  5837. static int check_dst_limits_calc_pos_1 (const re_match_context_t *mctx,
  5838. int boundaries, int subexp_idx,
  5839. int from_node, int bkref_idx)
  5840. internal_function;
  5841. static int check_dst_limits_calc_pos (const re_match_context_t *mctx,
  5842. int limit, int subexp_idx,
  5843. int node, int str_idx,
  5844. int bkref_idx) internal_function;
  5845. static reg_errcode_t check_subexp_limits (const re_dfa_t *dfa,
  5846. re_node_set *dest_nodes,
  5847. const re_node_set *candidates,
  5848. re_node_set *limits,
  5849. struct re_backref_cache_entry *bkref_ents,
  5850. int str_idx) internal_function;
  5851. static reg_errcode_t sift_states_bkref (const re_match_context_t *mctx,
  5852. re_sift_context_t *sctx,
  5853. int str_idx, const re_node_set *candidates)
  5854. internal_function;
  5855. static reg_errcode_t merge_state_array (const re_dfa_t *dfa,
  5856. re_dfastate_t **dst,
  5857. re_dfastate_t **src, int num)
  5858. internal_function;
  5859. static re_dfastate_t *find_recover_state (reg_errcode_t *err,
  5860. re_match_context_t *mctx) internal_function;
  5861. static re_dfastate_t *transit_state (reg_errcode_t *err,
  5862. re_match_context_t *mctx,
  5863. re_dfastate_t *state) internal_function;
  5864. static re_dfastate_t *merge_state_with_log (reg_errcode_t *err,
  5865. re_match_context_t *mctx,
  5866. re_dfastate_t *next_state)
  5867. internal_function;
  5868. static reg_errcode_t check_subexp_matching_top (re_match_context_t *mctx,
  5869. re_node_set *cur_nodes,
  5870. int str_idx) internal_function;
  5871. #if 0
  5872. static re_dfastate_t *transit_state_sb (reg_errcode_t *err,
  5873. re_match_context_t *mctx,
  5874. re_dfastate_t *pstate)
  5875. internal_function;
  5876. #endif
  5877. #ifdef RE_ENABLE_I18N
  5878. static reg_errcode_t transit_state_mb (re_match_context_t *mctx,
  5879. re_dfastate_t *pstate)
  5880. internal_function;
  5881. #endif /* RE_ENABLE_I18N */
  5882. static reg_errcode_t transit_state_bkref (re_match_context_t *mctx,
  5883. const re_node_set *nodes)
  5884. internal_function;
  5885. static reg_errcode_t get_subexp (re_match_context_t *mctx,
  5886. int bkref_node, int bkref_str_idx)
  5887. internal_function;
  5888. static reg_errcode_t get_subexp_sub (re_match_context_t *mctx,
  5889. const re_sub_match_top_t *sub_top,
  5890. re_sub_match_last_t *sub_last,
  5891. int bkref_node, int bkref_str)
  5892. internal_function;
  5893. static int find_subexp_node (const re_dfa_t *dfa, const re_node_set *nodes,
  5894. int subexp_idx, int type) internal_function;
  5895. static reg_errcode_t check_arrival (re_match_context_t *mctx,
  5896. state_array_t *path, int top_node,
  5897. int top_str, int last_node, int last_str,
  5898. int type) internal_function;
  5899. static reg_errcode_t check_arrival_add_next_nodes (re_match_context_t *mctx,
  5900. int str_idx,
  5901. re_node_set *cur_nodes,
  5902. re_node_set *next_nodes)
  5903. internal_function;
  5904. static reg_errcode_t check_arrival_expand_ecl (const re_dfa_t *dfa,
  5905. re_node_set *cur_nodes,
  5906. int ex_subexp, int type)
  5907. internal_function;
  5908. static reg_errcode_t check_arrival_expand_ecl_sub (const re_dfa_t *dfa,
  5909. re_node_set *dst_nodes,
  5910. int target, int ex_subexp,
  5911. int type) internal_function;
  5912. static reg_errcode_t expand_bkref_cache (re_match_context_t *mctx,
  5913. re_node_set *cur_nodes, int cur_str,
  5914. int subexp_num, int type)
  5915. internal_function;
  5916. static int build_trtable (const re_dfa_t *dfa,
  5917. re_dfastate_t *state) internal_function;
  5918. #ifdef RE_ENABLE_I18N
  5919. static int check_node_accept_bytes (const re_dfa_t *dfa, int node_idx,
  5920. const re_string_t *input, int idx)
  5921. internal_function;
  5922. # ifdef _LIBC
  5923. static unsigned int find_collation_sequence_value (const unsigned char *mbs,
  5924. size_t name_len)
  5925. internal_function;
  5926. # endif /* _LIBC */
  5927. #endif /* RE_ENABLE_I18N */
  5928. static int group_nodes_into_DFAstates (const re_dfa_t *dfa,
  5929. const re_dfastate_t *state,
  5930. re_node_set *states_node,
  5931. bitset_t *states_ch) internal_function;
  5932. static int check_node_accept (const re_match_context_t *mctx,
  5933. const re_token_t *node, int idx)
  5934. internal_function;
  5935. static reg_errcode_t extend_buffers (re_match_context_t *mctx)
  5936. internal_function;
  5937. /* Entry point for POSIX code. */
  5938. /* regexec searches for a given pattern, specified by PREG, in the
  5939. string STRING.
  5940. If NMATCH is zero or REG_NOSUB was set in the cflags argument to
  5941. `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
  5942. least NMATCH elements, and we set them to the offsets of the
  5943. corresponding matched substrings.
  5944. EFLAGS specifies `execution flags' which affect matching: if
  5945. REG_NOTBOL is set, then ^ does not match at the beginning of the
  5946. string; if REG_NOTEOL is set, then $ does not match at the end.
  5947. We return 0 if we find a match and REG_NOMATCH if not. */
  5948. int
  5949. regexec (preg, string, nmatch, pmatch, eflags)
  5950. const regex_t *__restrict preg;
  5951. const char *__restrict string;
  5952. size_t nmatch;
  5953. regmatch_t pmatch[];
  5954. int eflags;
  5955. {
  5956. reg_errcode_t err;
  5957. int start, length;
  5958. re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
  5959. if (eflags & ~(REG_NOTBOL | REG_NOTEOL | REG_STARTEND))
  5960. return REG_BADPAT;
  5961. if (eflags & REG_STARTEND)
  5962. {
  5963. start = pmatch[0].rm_so;
  5964. length = pmatch[0].rm_eo;
  5965. }
  5966. else
  5967. {
  5968. start = 0;
  5969. length = strlen (string);
  5970. }
  5971. __libc_lock_lock (dfa->lock);
  5972. if (preg->no_sub)
  5973. err = re_search_internal (preg, string, length, start, length - start,
  5974. length, 0, NULL, eflags);
  5975. else
  5976. err = re_search_internal (preg, string, length, start, length - start,
  5977. length, nmatch, pmatch, eflags);
  5978. __libc_lock_unlock (dfa->lock);
  5979. return err != REG_NOERROR;
  5980. }
  5981. #ifdef _LIBC
  5982. # include <shlib-compat.h>
  5983. versioned_symbol (libc, __regexec, regexec, GLIBC_2_3_4);
  5984. # if SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_3_4)
  5985. __typeof__ (__regexec) __compat_regexec;
  5986. int
  5987. attribute_compat_text_section
  5988. __compat_regexec (const regex_t *__restrict preg,
  5989. const char *__restrict string, size_t nmatch,
  5990. regmatch_t pmatch[], int eflags)
  5991. {
  5992. return regexec (preg, string, nmatch, pmatch,
  5993. eflags & (REG_NOTBOL | REG_NOTEOL));
  5994. }
  5995. compat_symbol (libc, __compat_regexec, regexec, GLIBC_2_0);
  5996. # endif
  5997. #endif
  5998. /* Entry points for GNU code. */
  5999. /* re_match, re_search, re_match_2, re_search_2
  6000. The former two functions operate on STRING with length LENGTH,
  6001. while the later two operate on concatenation of STRING1 and STRING2
  6002. with lengths LENGTH1 and LENGTH2, respectively.
  6003. re_match() matches the compiled pattern in BUFP against the string,
  6004. starting at index START.
  6005. re_search() first tries matching at index START, then it tries to match
  6006. starting from index START + 1, and so on. The last start position tried
  6007. is START + RANGE. (Thus RANGE = 0 forces re_search to operate the same
  6008. way as re_match().)
  6009. The parameter STOP of re_{match,search}_2 specifies that no match exceeding
  6010. the first STOP characters of the concatenation of the strings should be
  6011. concerned.
  6012. If REGS is not NULL, and BUFP->no_sub is not set, the offsets of the match
  6013. and all groups is stroed in REGS. (For the "_2" variants, the offsets are
  6014. computed relative to the concatenation, not relative to the individual
  6015. strings.)
  6016. On success, re_match* functions return the length of the match, re_search*
  6017. return the position of the start of the match. Return value -1 means no
  6018. match was found and -2 indicates an internal error. */
  6019. int
  6020. re_match (bufp, string, length, start, regs)
  6021. struct re_pattern_buffer *bufp;
  6022. const char *string;
  6023. int length, start;
  6024. struct re_registers *regs;
  6025. {
  6026. return re_search_stub (bufp, string, length, start, 0, length, regs, 1);
  6027. }
  6028. #ifdef _LIBC
  6029. weak_alias (__re_match, re_match)
  6030. #endif
  6031. int
  6032. re_search (bufp, string, length, start, range, regs)
  6033. struct re_pattern_buffer *bufp;
  6034. const char *string;
  6035. int length, start, range;
  6036. struct re_registers *regs;
  6037. {
  6038. return re_search_stub (bufp, string, length, start, range, length, regs, 0);
  6039. }
  6040. #ifdef _LIBC
  6041. weak_alias (__re_search, re_search)
  6042. #endif
  6043. int
  6044. re_match_2 (bufp, string1, length1, string2, length2, start, regs, stop)
  6045. struct re_pattern_buffer *bufp;
  6046. const char *string1, *string2;
  6047. int length1, length2, start, stop;
  6048. struct re_registers *regs;
  6049. {
  6050. return re_search_2_stub (bufp, string1, length1, string2, length2,
  6051. start, 0, regs, stop, 1);
  6052. }
  6053. #ifdef _LIBC
  6054. weak_alias (__re_match_2, re_match_2)
  6055. #endif
  6056. int
  6057. re_search_2 (bufp, string1, length1, string2, length2, start, range, regs, stop)
  6058. struct re_pattern_buffer *bufp;
  6059. const char *string1, *string2;
  6060. int length1, length2, start, range, stop;
  6061. struct re_registers *regs;
  6062. {
  6063. return re_search_2_stub (bufp, string1, length1, string2, length2,
  6064. start, range, regs, stop, 0);
  6065. }
  6066. #ifdef _LIBC
  6067. weak_alias (__re_search_2, re_search_2)
  6068. #endif
  6069. static int
  6070. re_search_2_stub (bufp, string1, length1, string2, length2, start, range, regs,
  6071. stop, ret_len)
  6072. struct re_pattern_buffer *bufp;
  6073. const char *string1, *string2;
  6074. int length1, length2, start, range, stop, ret_len;
  6075. struct re_registers *regs;
  6076. {
  6077. const char *str;
  6078. int rval;
  6079. int len = length1 + length2;
  6080. int free_str = 0;
  6081. if (BE (length1 < 0 || length2 < 0 || stop < 0, 0))
  6082. return -2;
  6083. /* Concatenate the strings. */
  6084. if (length2 > 0)
  6085. if (length1 > 0)
  6086. {
  6087. char *s = re_malloc (char, len);
  6088. if (BE (s == NULL, 0))
  6089. return -2;
  6090. #ifdef _LIBC
  6091. memcpy (__mempcpy (s, string1, length1), string2, length2);
  6092. #else
  6093. memcpy (s, string1, length1);
  6094. memcpy (s + length1, string2, length2);
  6095. #endif
  6096. str = s;
  6097. free_str = 1;
  6098. }
  6099. else
  6100. str = string2;
  6101. else
  6102. str = string1;
  6103. rval = re_search_stub (bufp, str, len, start, range, stop, regs,
  6104. ret_len);
  6105. if (free_str)
  6106. re_free ((char *) str);
  6107. return rval;
  6108. }
  6109. /* The parameters have the same meaning as those of re_search.
  6110. Additional parameters:
  6111. If RET_LEN is nonzero the length of the match is returned (re_match style);
  6112. otherwise the position of the match is returned. */
  6113. static int
  6114. re_search_stub (bufp, string, length, start, range, stop, regs, ret_len)
  6115. struct re_pattern_buffer *bufp;
  6116. const char *string;
  6117. int length, start, range, stop, ret_len;
  6118. struct re_registers *regs;
  6119. {
  6120. reg_errcode_t result;
  6121. regmatch_t *pmatch;
  6122. int nregs, rval;
  6123. int eflags = 0;
  6124. re_dfa_t *dfa = (re_dfa_t *) bufp->buffer;
  6125. /* Check for out-of-range. */
  6126. if (BE (start < 0 || start > length, 0))
  6127. return -1;
  6128. if (BE (start + range > length, 0))
  6129. range = length - start;
  6130. else if (BE (start + range < 0, 0))
  6131. range = -start;
  6132. __libc_lock_lock (dfa->lock);
  6133. eflags |= (bufp->not_bol) ? REG_NOTBOL : 0;
  6134. eflags |= (bufp->not_eol) ? REG_NOTEOL : 0;
  6135. /* Compile fastmap if we haven't yet. */
  6136. if (range > 0 && bufp->fastmap != NULL && !bufp->fastmap_accurate)
  6137. re_compile_fastmap (bufp);
  6138. if (BE (bufp->no_sub, 0))
  6139. regs = NULL;
  6140. /* We need at least 1 register. */
  6141. if (regs == NULL)
  6142. nregs = 1;
  6143. else if (BE (bufp->regs_allocated == REGS_FIXED &&
  6144. regs->num_regs < bufp->re_nsub + 1, 0))
  6145. {
  6146. nregs = regs->num_regs;
  6147. if (BE (nregs < 1, 0))
  6148. {
  6149. /* Nothing can be copied to regs. */
  6150. regs = NULL;
  6151. nregs = 1;
  6152. }
  6153. }
  6154. else
  6155. nregs = bufp->re_nsub + 1;
  6156. pmatch = re_malloc (regmatch_t, nregs);
  6157. if (BE (pmatch == NULL, 0))
  6158. {
  6159. rval = -2;
  6160. goto out;
  6161. }
  6162. result = re_search_internal (bufp, string, length, start, range, stop,
  6163. nregs, pmatch, eflags);
  6164. rval = 0;
  6165. /* I hope we needn't fill ther regs with -1's when no match was found. */
  6166. if (result != REG_NOERROR)
  6167. rval = -1;
  6168. else if (regs != NULL)
  6169. {
  6170. /* If caller wants register contents data back, copy them. */
  6171. bufp->regs_allocated = re_copy_regs (regs, pmatch, nregs,
  6172. bufp->regs_allocated);
  6173. if (BE (bufp->regs_allocated == REGS_UNALLOCATED, 0))
  6174. rval = -2;
  6175. }
  6176. if (BE (rval == 0, 1))
  6177. {
  6178. if (ret_len)
  6179. {
  6180. assert (pmatch[0].rm_so == start);
  6181. rval = pmatch[0].rm_eo - start;
  6182. }
  6183. else
  6184. rval = pmatch[0].rm_so;
  6185. }
  6186. re_free (pmatch);
  6187. out:
  6188. __libc_lock_unlock (dfa->lock);
  6189. return rval;
  6190. }
  6191. static unsigned
  6192. re_copy_regs (regs, pmatch, nregs, regs_allocated)
  6193. struct re_registers *regs;
  6194. regmatch_t *pmatch;
  6195. int nregs, regs_allocated;
  6196. {
  6197. int rval = REGS_REALLOCATE;
  6198. int i;
  6199. int need_regs = nregs + 1;
  6200. /* We need one extra element beyond `num_regs' for the `-1' marker GNU code
  6201. uses. */
  6202. /* Have the register data arrays been allocated? */
  6203. if (regs_allocated == REGS_UNALLOCATED)
  6204. { /* No. So allocate them with malloc. */
  6205. regs->start = re_malloc (regoff_t, need_regs);
  6206. regs->end = re_malloc (regoff_t, need_regs);
  6207. if (BE (regs->start == NULL, 0) || BE (regs->end == NULL, 0))
  6208. return REGS_UNALLOCATED;
  6209. regs->num_regs = need_regs;
  6210. }
  6211. else if (regs_allocated == REGS_REALLOCATE)
  6212. { /* Yes. If we need more elements than were already
  6213. allocated, reallocate them. If we need fewer, just
  6214. leave it alone. */
  6215. if (BE (need_regs > regs->num_regs, 0))
  6216. {
  6217. regoff_t *new_start = re_realloc (regs->start, regoff_t, need_regs);
  6218. regoff_t *new_end = re_realloc (regs->end, regoff_t, need_regs);
  6219. if (BE (new_start == NULL, 0) || BE (new_end == NULL, 0))
  6220. return REGS_UNALLOCATED;
  6221. regs->start = new_start;
  6222. regs->end = new_end;
  6223. regs->num_regs = need_regs;
  6224. }
  6225. }
  6226. else
  6227. {
  6228. assert (regs_allocated == REGS_FIXED);
  6229. /* This function may not be called with REGS_FIXED and nregs too big. */
  6230. assert (regs->num_regs >= nregs);
  6231. rval = REGS_FIXED;
  6232. }
  6233. /* Copy the regs. */
  6234. for (i = 0; i < nregs; ++i)
  6235. {
  6236. regs->start[i] = pmatch[i].rm_so;
  6237. regs->end[i] = pmatch[i].rm_eo;
  6238. }
  6239. for ( ; i < regs->num_regs; ++i)
  6240. regs->start[i] = regs->end[i] = -1;
  6241. return rval;
  6242. }
  6243. /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
  6244. ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
  6245. this memory for recording register information. STARTS and ENDS
  6246. must be allocated using the malloc library routine, and must each
  6247. be at least NUM_REGS * sizeof (regoff_t) bytes long.
  6248. If NUM_REGS == 0, then subsequent matches should allocate their own
  6249. register data.
  6250. Unless this function is called, the first search or match using
  6251. PATTERN_BUFFER will allocate its own register data, without
  6252. freeing the old data. */
  6253. void
  6254. re_set_registers (bufp, regs, num_regs, starts, ends)
  6255. struct re_pattern_buffer *bufp;
  6256. struct re_registers *regs;
  6257. unsigned num_regs;
  6258. regoff_t *starts, *ends;
  6259. {
  6260. if (num_regs)
  6261. {
  6262. bufp->regs_allocated = REGS_REALLOCATE;
  6263. regs->num_regs = num_regs;
  6264. regs->start = starts;
  6265. regs->end = ends;
  6266. }
  6267. else
  6268. {
  6269. bufp->regs_allocated = REGS_UNALLOCATED;
  6270. regs->num_regs = 0;
  6271. regs->start = regs->end = (regoff_t *) 0;
  6272. }
  6273. }
  6274. #ifdef _LIBC
  6275. weak_alias (__re_set_registers, re_set_registers)
  6276. #endif
  6277. /* Entry points compatible with 4.2 BSD regex library. We don't define
  6278. them unless specifically requested. */
  6279. #if defined _REGEX_RE_COMP || defined _LIBC
  6280. int
  6281. # ifdef _LIBC
  6282. weak_function
  6283. # endif
  6284. re_exec (s)
  6285. const char *s;
  6286. {
  6287. return 0 == regexec (&re_comp_buf, s, 0, NULL, 0);
  6288. }
  6289. #endif /* _REGEX_RE_COMP */
  6290. /* Internal entry point. */
  6291. /* Searches for a compiled pattern PREG in the string STRING, whose
  6292. length is LENGTH. NMATCH, PMATCH, and EFLAGS have the same
  6293. mingings with regexec. START, and RANGE have the same meanings
  6294. with re_search.
  6295. Return REG_NOERROR if we find a match, and REG_NOMATCH if not,
  6296. otherwise return the error code.
  6297. Note: We assume front end functions already check ranges.
  6298. (START + RANGE >= 0 && START + RANGE <= LENGTH) */
  6299. static reg_errcode_t
  6300. re_search_internal (preg, string, length, start, range, stop, nmatch, pmatch,
  6301. eflags)
  6302. const regex_t *preg;
  6303. const char *string;
  6304. int length, start, range, stop, eflags;
  6305. size_t nmatch;
  6306. regmatch_t pmatch[];
  6307. {
  6308. reg_errcode_t err;
  6309. const re_dfa_t *dfa = (const re_dfa_t *) preg->buffer;
  6310. int left_lim, right_lim, incr;
  6311. int fl_longest_match, match_first, match_kind, match_last = -1;
  6312. int extra_nmatch;
  6313. int sb, ch;
  6314. #if defined _LIBC || (defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L)
  6315. re_match_context_t mctx = { .dfa = dfa };
  6316. #else
  6317. re_match_context_t mctx;
  6318. #endif
  6319. char *fastmap = (preg->fastmap != NULL && preg->fastmap_accurate
  6320. && range && !preg->can_be_null) ? preg->fastmap : NULL;
  6321. RE_TRANSLATE_TYPE t = preg->translate;
  6322. #if !(defined _LIBC || (defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L))
  6323. memset (&mctx, '\0', sizeof (re_match_context_t));
  6324. mctx.dfa = dfa;
  6325. #endif
  6326. extra_nmatch = (nmatch > preg->re_nsub) ? nmatch - (preg->re_nsub + 1) : 0;
  6327. nmatch -= extra_nmatch;
  6328. /* Check if the DFA haven't been compiled. */
  6329. if (BE (preg->used == 0 || dfa->init_state == NULL
  6330. || dfa->init_state_word == NULL || dfa->init_state_nl == NULL
  6331. || dfa->init_state_begbuf == NULL, 0))
  6332. return REG_NOMATCH;
  6333. #ifdef DEBUG
  6334. /* We assume front-end functions already check them. */
  6335. assert (start + range >= 0 && start + range <= length);
  6336. #endif
  6337. /* If initial states with non-begbuf contexts have no elements,
  6338. the regex must be anchored. If preg->newline_anchor is set,
  6339. we'll never use init_state_nl, so do not check it. */
  6340. if (dfa->init_state->nodes.nelem == 0
  6341. && dfa->init_state_word->nodes.nelem == 0
  6342. && (dfa->init_state_nl->nodes.nelem == 0
  6343. || !preg->newline_anchor))
  6344. {
  6345. if (start != 0 && start + range != 0)
  6346. return REG_NOMATCH;
  6347. start = range = 0;
  6348. }
  6349. /* We must check the longest matching, if nmatch > 0. */
  6350. fl_longest_match = (nmatch != 0 || dfa->nbackref);
  6351. err = re_string_allocate (&mctx.input, string, length, dfa->nodes_len + 1,
  6352. preg->translate, preg->syntax & RE_ICASE, dfa);
  6353. if (BE (err != REG_NOERROR, 0))
  6354. goto free_return;
  6355. mctx.input.stop = stop;
  6356. mctx.input.raw_stop = stop;
  6357. mctx.input.newline_anchor = preg->newline_anchor;
  6358. err = match_ctx_init (&mctx, eflags, dfa->nbackref * 2);
  6359. if (BE (err != REG_NOERROR, 0))
  6360. goto free_return;
  6361. /* We will log all the DFA states through which the dfa pass,
  6362. if nmatch > 1, or this dfa has "multibyte node", which is a
  6363. back-reference or a node which can accept multibyte character or
  6364. multi character collating element. */
  6365. if (nmatch > 1 || dfa->has_mb_node)
  6366. {
  6367. mctx.state_log = re_malloc (re_dfastate_t *, mctx.input.bufs_len + 1);
  6368. if (BE (mctx.state_log == NULL, 0))
  6369. {
  6370. err = REG_ESPACE;
  6371. goto free_return;
  6372. }
  6373. }
  6374. else
  6375. mctx.state_log = NULL;
  6376. match_first = start;
  6377. mctx.input.tip_context = (eflags & REG_NOTBOL) ? CONTEXT_BEGBUF
  6378. : CONTEXT_NEWLINE | CONTEXT_BEGBUF;
  6379. /* Check incrementally whether of not the input string match. */
  6380. incr = (range < 0) ? -1 : 1;
  6381. left_lim = (range < 0) ? start + range : start;
  6382. right_lim = (range < 0) ? start : start + range;
  6383. sb = dfa->mb_cur_max == 1;
  6384. match_kind =
  6385. (fastmap
  6386. ? ((sb || !(preg->syntax & RE_ICASE || t) ? 4 : 0)
  6387. | (range >= 0 ? 2 : 0)
  6388. | (t != NULL ? 1 : 0))
  6389. : 8);
  6390. for (;; match_first += incr)
  6391. {
  6392. err = REG_NOMATCH;
  6393. if (match_first < left_lim || right_lim < match_first)
  6394. goto free_return;
  6395. /* Advance as rapidly as possible through the string, until we
  6396. find a plausible place to start matching. This may be done
  6397. with varying efficiency, so there are various possibilities:
  6398. only the most common of them are specialized, in order to
  6399. save on code size. We use a switch statement for speed. */
  6400. switch (match_kind)
  6401. {
  6402. case 8:
  6403. /* No fastmap. */
  6404. break;
  6405. case 7:
  6406. /* Fastmap with single-byte translation, match forward. */
  6407. while (BE (match_first < right_lim, 1)
  6408. && !fastmap[t[(unsigned char) string[match_first]]])
  6409. ++match_first;
  6410. goto forward_match_found_start_or_reached_end;
  6411. case 6:
  6412. /* Fastmap without translation, match forward. */
  6413. while (BE (match_first < right_lim, 1)
  6414. && !fastmap[(unsigned char) string[match_first]])
  6415. ++match_first;
  6416. forward_match_found_start_or_reached_end:
  6417. if (BE (match_first == right_lim, 0))
  6418. {
  6419. ch = match_first >= length
  6420. ? 0 : (unsigned char) string[match_first];
  6421. if (!fastmap[t ? t[ch] : ch])
  6422. goto free_return;
  6423. }
  6424. break;
  6425. case 4:
  6426. case 5:
  6427. /* Fastmap without multi-byte translation, match backwards. */
  6428. while (match_first >= left_lim)
  6429. {
  6430. ch = match_first >= length
  6431. ? 0 : (unsigned char) string[match_first];
  6432. if (fastmap[t ? t[ch] : ch])
  6433. break;
  6434. --match_first;
  6435. }
  6436. if (match_first < left_lim)
  6437. goto free_return;
  6438. break;
  6439. default:
  6440. /* In this case, we can't determine easily the current byte,
  6441. since it might be a component byte of a multibyte
  6442. character. Then we use the constructed buffer instead. */
  6443. for (;;)
  6444. {
  6445. /* If MATCH_FIRST is out of the valid range, reconstruct the
  6446. buffers. */
  6447. unsigned int offset = match_first - mctx.input.raw_mbs_idx;
  6448. if (BE (offset >= (unsigned int) mctx.input.valid_raw_len, 0))
  6449. {
  6450. err = re_string_reconstruct (&mctx.input, match_first,
  6451. eflags);
  6452. if (BE (err != REG_NOERROR, 0))
  6453. goto free_return;
  6454. offset = match_first - mctx.input.raw_mbs_idx;
  6455. }
  6456. /* If MATCH_FIRST is out of the buffer, leave it as '\0'.
  6457. Note that MATCH_FIRST must not be smaller than 0. */
  6458. ch = (match_first >= length
  6459. ? 0 : re_string_byte_at (&mctx.input, offset));
  6460. if (fastmap[ch])
  6461. break;
  6462. match_first += incr;
  6463. if (match_first < left_lim || match_first > right_lim)
  6464. {
  6465. err = REG_NOMATCH;
  6466. goto free_return;
  6467. }
  6468. }
  6469. break;
  6470. }
  6471. /* Reconstruct the buffers so that the matcher can assume that
  6472. the matching starts from the beginning of the buffer. */
  6473. err = re_string_reconstruct (&mctx.input, match_first, eflags);
  6474. if (BE (err != REG_NOERROR, 0))
  6475. goto free_return;
  6476. #ifdef RE_ENABLE_I18N
  6477. /* Don't consider this char as a possible match start if it part,
  6478. yet isn't the head, of a multibyte character. */
  6479. if (!sb && !re_string_first_byte (&mctx.input, 0))
  6480. continue;
  6481. #endif
  6482. /* It seems to be appropriate one, then use the matcher. */
  6483. /* We assume that the matching starts from 0. */
  6484. mctx.state_log_top = mctx.nbkref_ents = mctx.max_mb_elem_len = 0;
  6485. match_last = check_matching (&mctx, fl_longest_match,
  6486. range >= 0 ? &match_first : NULL);
  6487. if (match_last != -1)
  6488. {
  6489. if (BE (match_last == -2, 0))
  6490. {
  6491. err = REG_ESPACE;
  6492. goto free_return;
  6493. }
  6494. else
  6495. {
  6496. mctx.match_last = match_last;
  6497. if ((!preg->no_sub && nmatch > 1) || dfa->nbackref)
  6498. {
  6499. re_dfastate_t *pstate = mctx.state_log[match_last];
  6500. mctx.last_node = check_halt_state_context (&mctx, pstate,
  6501. match_last);
  6502. }
  6503. if ((!preg->no_sub && nmatch > 1 && dfa->has_plural_match)
  6504. || dfa->nbackref)
  6505. {
  6506. err = prune_impossible_nodes (&mctx);
  6507. if (err == REG_NOERROR)
  6508. break;
  6509. if (BE (err != REG_NOMATCH, 0))
  6510. goto free_return;
  6511. match_last = -1;
  6512. }
  6513. else
  6514. break; /* We found a match. */
  6515. }
  6516. }
  6517. match_ctx_clean (&mctx);
  6518. }
  6519. #ifdef DEBUG
  6520. assert (match_last != -1);
  6521. assert (err == REG_NOERROR);
  6522. #endif
  6523. /* Set pmatch[] if we need. */
  6524. if (nmatch > 0)
  6525. {
  6526. int reg_idx;
  6527. /* Initialize registers. */
  6528. for (reg_idx = 1; reg_idx < nmatch; ++reg_idx)
  6529. pmatch[reg_idx].rm_so = pmatch[reg_idx].rm_eo = -1;
  6530. /* Set the points where matching start/end. */
  6531. pmatch[0].rm_so = 0;
  6532. pmatch[0].rm_eo = mctx.match_last;
  6533. if (!preg->no_sub && nmatch > 1)
  6534. {
  6535. err = set_regs (preg, &mctx, nmatch, pmatch,
  6536. dfa->has_plural_match && dfa->nbackref > 0);
  6537. if (BE (err != REG_NOERROR, 0))
  6538. goto free_return;
  6539. }
  6540. /* At last, add the offset to the each registers, since we slided
  6541. the buffers so that we could assume that the matching starts
  6542. from 0. */
  6543. for (reg_idx = 0; reg_idx < nmatch; ++reg_idx)
  6544. if (pmatch[reg_idx].rm_so != -1)
  6545. {
  6546. #ifdef RE_ENABLE_I18N
  6547. if (BE (mctx.input.offsets_needed != 0, 0))
  6548. {
  6549. pmatch[reg_idx].rm_so =
  6550. (pmatch[reg_idx].rm_so == mctx.input.valid_len
  6551. ? mctx.input.valid_raw_len
  6552. : mctx.input.offsets[pmatch[reg_idx].rm_so]);
  6553. pmatch[reg_idx].rm_eo =
  6554. (pmatch[reg_idx].rm_eo == mctx.input.valid_len
  6555. ? mctx.input.valid_raw_len
  6556. : mctx.input.offsets[pmatch[reg_idx].rm_eo]);
  6557. }
  6558. #else
  6559. assert (mctx.input.offsets_needed == 0);
  6560. #endif
  6561. pmatch[reg_idx].rm_so += match_first;
  6562. pmatch[reg_idx].rm_eo += match_first;
  6563. }
  6564. for (reg_idx = 0; reg_idx < extra_nmatch; ++reg_idx)
  6565. {
  6566. pmatch[nmatch + reg_idx].rm_so = -1;
  6567. pmatch[nmatch + reg_idx].rm_eo = -1;
  6568. }
  6569. if (dfa->subexp_map)
  6570. for (reg_idx = 0; reg_idx + 1 < nmatch; reg_idx++)
  6571. if (dfa->subexp_map[reg_idx] != reg_idx)
  6572. {
  6573. pmatch[reg_idx + 1].rm_so
  6574. = pmatch[dfa->subexp_map[reg_idx] + 1].rm_so;
  6575. pmatch[reg_idx + 1].rm_eo
  6576. = pmatch[dfa->subexp_map[reg_idx] + 1].rm_eo;
  6577. }
  6578. }
  6579. free_return:
  6580. re_free (mctx.state_log);
  6581. if (dfa->nbackref)
  6582. match_ctx_free (&mctx);
  6583. re_string_destruct (&mctx.input);
  6584. return err;
  6585. }
  6586. static reg_errcode_t
  6587. prune_impossible_nodes (mctx)
  6588. re_match_context_t *mctx;
  6589. {
  6590. const re_dfa_t *const dfa = mctx->dfa;
  6591. int halt_node, match_last;
  6592. reg_errcode_t ret;
  6593. re_dfastate_t **sifted_states;
  6594. re_dfastate_t **lim_states = NULL;
  6595. re_sift_context_t sctx;
  6596. #ifdef DEBUG
  6597. assert (mctx->state_log != NULL);
  6598. #endif
  6599. match_last = mctx->match_last;
  6600. halt_node = mctx->last_node;
  6601. sifted_states = re_malloc (re_dfastate_t *, match_last + 1);
  6602. if (BE (sifted_states == NULL, 0))
  6603. {
  6604. ret = REG_ESPACE;
  6605. goto free_return;
  6606. }
  6607. if (dfa->nbackref)
  6608. {
  6609. lim_states = re_malloc (re_dfastate_t *, match_last + 1);
  6610. if (BE (lim_states == NULL, 0))
  6611. {
  6612. ret = REG_ESPACE;
  6613. goto free_return;
  6614. }
  6615. while (1)
  6616. {
  6617. memset (lim_states, '\0',
  6618. sizeof (re_dfastate_t *) * (match_last + 1));
  6619. sift_ctx_init (&sctx, sifted_states, lim_states, halt_node,
  6620. match_last);
  6621. ret = sift_states_backward (mctx, &sctx);
  6622. re_node_set_free (&sctx.limits);
  6623. if (BE (ret != REG_NOERROR, 0))
  6624. goto free_return;
  6625. if (sifted_states[0] != NULL || lim_states[0] != NULL)
  6626. break;
  6627. do
  6628. {
  6629. --match_last;
  6630. if (match_last < 0)
  6631. {
  6632. ret = REG_NOMATCH;
  6633. goto free_return;
  6634. }
  6635. } while (mctx->state_log[match_last] == NULL
  6636. || !mctx->state_log[match_last]->halt);
  6637. halt_node = check_halt_state_context (mctx,
  6638. mctx->state_log[match_last],
  6639. match_last);
  6640. }
  6641. ret = merge_state_array (dfa, sifted_states, lim_states,
  6642. match_last + 1);
  6643. re_free (lim_states);
  6644. lim_states = NULL;
  6645. if (BE (ret != REG_NOERROR, 0))
  6646. goto free_return;
  6647. }
  6648. else
  6649. {
  6650. sift_ctx_init (&sctx, sifted_states, lim_states, halt_node, match_last);
  6651. ret = sift_states_backward (mctx, &sctx);
  6652. re_node_set_free (&sctx.limits);
  6653. if (BE (ret != REG_NOERROR, 0))
  6654. goto free_return;
  6655. }
  6656. re_free (mctx->state_log);
  6657. mctx->state_log = sifted_states;
  6658. sifted_states = NULL;
  6659. mctx->last_node = halt_node;
  6660. mctx->match_last = match_last;
  6661. ret = REG_NOERROR;
  6662. free_return:
  6663. re_free (sifted_states);
  6664. re_free (lim_states);
  6665. return ret;
  6666. }
  6667. /* Acquire an initial state and return it.
  6668. We must select appropriate initial state depending on the context,
  6669. since initial states may have constraints like "\<", "^", etc.. */
  6670. static inline re_dfastate_t *
  6671. __attribute ((always_inline)) internal_function
  6672. acquire_init_state_context (reg_errcode_t *err, const re_match_context_t *mctx,
  6673. int idx)
  6674. {
  6675. const re_dfa_t *const dfa = mctx->dfa;
  6676. if (dfa->init_state->has_constraint)
  6677. {
  6678. unsigned int context;
  6679. context = re_string_context_at (&mctx->input, idx - 1, mctx->eflags);
  6680. if (IS_WORD_CONTEXT (context))
  6681. return dfa->init_state_word;
  6682. else if (IS_ORDINARY_CONTEXT (context))
  6683. return dfa->init_state;
  6684. else if (IS_BEGBUF_CONTEXT (context) && IS_NEWLINE_CONTEXT (context))
  6685. return dfa->init_state_begbuf;
  6686. else if (IS_NEWLINE_CONTEXT (context))
  6687. return dfa->init_state_nl;
  6688. else if (IS_BEGBUF_CONTEXT (context))
  6689. {
  6690. /* It is relatively rare case, then calculate on demand. */
  6691. return re_acquire_state_context (err, dfa,
  6692. dfa->init_state->entrance_nodes,
  6693. context);
  6694. }
  6695. else
  6696. /* Must not happen? */
  6697. return dfa->init_state;
  6698. }
  6699. else
  6700. return dfa->init_state;
  6701. }
  6702. /* Check whether the regular expression match input string INPUT or not,
  6703. and return the index where the matching end, return -1 if not match,
  6704. or return -2 in case of an error.
  6705. FL_LONGEST_MATCH means we want the POSIX longest matching.
  6706. If P_MATCH_FIRST is not NULL, and the match fails, it is set to the
  6707. next place where we may want to try matching.
  6708. Note that the matcher assume that the maching starts from the current
  6709. index of the buffer. */
  6710. static int
  6711. internal_function
  6712. check_matching (re_match_context_t *mctx, int fl_longest_match,
  6713. int *p_match_first)
  6714. {
  6715. const re_dfa_t *const dfa = mctx->dfa;
  6716. reg_errcode_t err;
  6717. int match = 0;
  6718. int match_last = -1;
  6719. int cur_str_idx = re_string_cur_idx (&mctx->input);
  6720. re_dfastate_t *cur_state;
  6721. int at_init_state = p_match_first != NULL;
  6722. int next_start_idx = cur_str_idx;
  6723. err = REG_NOERROR;
  6724. cur_state = acquire_init_state_context (&err, mctx, cur_str_idx);
  6725. /* An initial state must not be NULL (invalid). */
  6726. if (BE (cur_state == NULL, 0))
  6727. {
  6728. assert (err == REG_ESPACE);
  6729. return -2;
  6730. }
  6731. if (mctx->state_log != NULL)
  6732. {
  6733. mctx->state_log[cur_str_idx] = cur_state;
  6734. /* Check OP_OPEN_SUBEXP in the initial state in case that we use them
  6735. later. E.g. Processing back references. */
  6736. if (BE (dfa->nbackref, 0))
  6737. {
  6738. at_init_state = 0;
  6739. err = check_subexp_matching_top (mctx, &cur_state->nodes, 0);
  6740. if (BE (err != REG_NOERROR, 0))
  6741. return err;
  6742. if (cur_state->has_backref)
  6743. {
  6744. err = transit_state_bkref (mctx, &cur_state->nodes);
  6745. if (BE (err != REG_NOERROR, 0))
  6746. return err;
  6747. }
  6748. }
  6749. }
  6750. /* If the RE accepts NULL string. */
  6751. if (BE (cur_state->halt, 0))
  6752. {
  6753. if (!cur_state->has_constraint
  6754. || check_halt_state_context (mctx, cur_state, cur_str_idx))
  6755. {
  6756. if (!fl_longest_match)
  6757. return cur_str_idx;
  6758. else
  6759. {
  6760. match_last = cur_str_idx;
  6761. match = 1;
  6762. }
  6763. }
  6764. }
  6765. while (!re_string_eoi (&mctx->input))
  6766. {
  6767. re_dfastate_t *old_state = cur_state;
  6768. int next_char_idx = re_string_cur_idx (&mctx->input) + 1;
  6769. if (BE (next_char_idx >= mctx->input.bufs_len, 0)
  6770. || (BE (next_char_idx >= mctx->input.valid_len, 0)
  6771. && mctx->input.valid_len < mctx->input.len))
  6772. {
  6773. err = extend_buffers (mctx);
  6774. if (BE (err != REG_NOERROR, 0))
  6775. {
  6776. assert (err == REG_ESPACE);
  6777. return -2;
  6778. }
  6779. }
  6780. cur_state = transit_state (&err, mctx, cur_state);
  6781. if (mctx->state_log != NULL)
  6782. cur_state = merge_state_with_log (&err, mctx, cur_state);
  6783. if (cur_state == NULL)
  6784. {
  6785. /* Reached the invalid state or an error. Try to recover a valid
  6786. state using the state log, if available and if we have not
  6787. already found a valid (even if not the longest) match. */
  6788. if (BE (err != REG_NOERROR, 0))
  6789. return -2;
  6790. if (mctx->state_log == NULL
  6791. || (match && !fl_longest_match)
  6792. || (cur_state = find_recover_state (&err, mctx)) == NULL)
  6793. break;
  6794. }
  6795. if (BE (at_init_state, 0))
  6796. {
  6797. if (old_state == cur_state)
  6798. next_start_idx = next_char_idx;
  6799. else
  6800. at_init_state = 0;
  6801. }
  6802. if (cur_state->halt)
  6803. {
  6804. /* Reached a halt state.
  6805. Check the halt state can satisfy the current context. */
  6806. if (!cur_state->has_constraint
  6807. || check_halt_state_context (mctx, cur_state,
  6808. re_string_cur_idx (&mctx->input)))
  6809. {
  6810. /* We found an appropriate halt state. */
  6811. match_last = re_string_cur_idx (&mctx->input);
  6812. match = 1;
  6813. /* We found a match, do not modify match_first below. */
  6814. p_match_first = NULL;
  6815. if (!fl_longest_match)
  6816. break;
  6817. }
  6818. }
  6819. }
  6820. if (p_match_first)
  6821. *p_match_first += next_start_idx;
  6822. return match_last;
  6823. }
  6824. /* Check NODE match the current context. */
  6825. static int
  6826. internal_function
  6827. check_halt_node_context (const re_dfa_t *dfa, int node, unsigned int context)
  6828. {
  6829. re_token_type_t type = dfa->nodes[node].type;
  6830. unsigned int constraint = dfa->nodes[node].constraint;
  6831. if (type != END_OF_RE)
  6832. return 0;
  6833. if (!constraint)
  6834. return 1;
  6835. if (NOT_SATISFY_NEXT_CONSTRAINT (constraint, context))
  6836. return 0;
  6837. return 1;
  6838. }
  6839. /* Check the halt state STATE match the current context.
  6840. Return 0 if not match, if the node, STATE has, is a halt node and
  6841. match the context, return the node. */
  6842. static int
  6843. internal_function
  6844. check_halt_state_context (const re_match_context_t *mctx,
  6845. const re_dfastate_t *state, int idx)
  6846. {
  6847. int i;
  6848. unsigned int context;
  6849. #ifdef DEBUG
  6850. assert (state->halt);
  6851. #endif
  6852. context = re_string_context_at (&mctx->input, idx, mctx->eflags);
  6853. for (i = 0; i < state->nodes.nelem; ++i)
  6854. if (check_halt_node_context (mctx->dfa, state->nodes.elems[i], context))
  6855. return state->nodes.elems[i];
  6856. return 0;
  6857. }
  6858. /* Compute the next node to which "NFA" transit from NODE("NFA" is a NFA
  6859. corresponding to the DFA).
  6860. Return the destination node, and update EPS_VIA_NODES, return -1 in case
  6861. of errors. */
  6862. static int
  6863. internal_function
  6864. proceed_next_node (const re_match_context_t *mctx, int nregs, regmatch_t *regs,
  6865. int *pidx, int node, re_node_set *eps_via_nodes,
  6866. struct re_fail_stack_t *fs)
  6867. {
  6868. const re_dfa_t *const dfa = mctx->dfa;
  6869. int i, err;
  6870. if (IS_EPSILON_NODE (dfa->nodes[node].type))
  6871. {
  6872. re_node_set *cur_nodes = &mctx->state_log[*pidx]->nodes;
  6873. re_node_set *edests = &dfa->edests[node];
  6874. int dest_node;
  6875. err = re_node_set_insert (eps_via_nodes, node);
  6876. if (BE (err < 0, 0))
  6877. return -2;
  6878. /* Pick up a valid destination, or return -1 if none is found. */
  6879. for (dest_node = -1, i = 0; i < edests->nelem; ++i)
  6880. {
  6881. int candidate = edests->elems[i];
  6882. if (!re_node_set_contains (cur_nodes, candidate))
  6883. continue;
  6884. if (dest_node == -1)
  6885. dest_node = candidate;
  6886. else
  6887. {
  6888. /* In order to avoid infinite loop like "(a*)*", return the second
  6889. epsilon-transition if the first was already considered. */
  6890. if (re_node_set_contains (eps_via_nodes, dest_node))
  6891. return candidate;
  6892. /* Otherwise, push the second epsilon-transition on the fail stack. */
  6893. else if (fs != NULL
  6894. && push_fail_stack (fs, *pidx, candidate, nregs, regs,
  6895. eps_via_nodes))
  6896. return -2;
  6897. /* We know we are going to exit. */
  6898. break;
  6899. }
  6900. }
  6901. return dest_node;
  6902. }
  6903. else
  6904. {
  6905. int naccepted = 0;
  6906. re_token_type_t type = dfa->nodes[node].type;
  6907. #ifdef RE_ENABLE_I18N
  6908. if (dfa->nodes[node].accept_mb)
  6909. naccepted = check_node_accept_bytes (dfa, node, &mctx->input, *pidx);
  6910. else
  6911. #endif /* RE_ENABLE_I18N */
  6912. if (type == OP_BACK_REF)
  6913. {
  6914. int subexp_idx = dfa->nodes[node].opr.idx + 1;
  6915. naccepted = regs[subexp_idx].rm_eo - regs[subexp_idx].rm_so;
  6916. if (fs != NULL)
  6917. {
  6918. if (regs[subexp_idx].rm_so == -1 || regs[subexp_idx].rm_eo == -1)
  6919. return -1;
  6920. else if (naccepted)
  6921. {
  6922. char *buf = (char *) re_string_get_buffer (&mctx->input);
  6923. if (memcmp (buf + regs[subexp_idx].rm_so, buf + *pidx,
  6924. naccepted) != 0)
  6925. return -1;
  6926. }
  6927. }
  6928. if (naccepted == 0)
  6929. {
  6930. int dest_node;
  6931. err = re_node_set_insert (eps_via_nodes, node);
  6932. if (BE (err < 0, 0))
  6933. return -2;
  6934. dest_node = dfa->edests[node].elems[0];
  6935. if (re_node_set_contains (&mctx->state_log[*pidx]->nodes,
  6936. dest_node))
  6937. return dest_node;
  6938. }
  6939. }
  6940. if (naccepted != 0
  6941. || check_node_accept (mctx, dfa->nodes + node, *pidx))
  6942. {
  6943. int dest_node = dfa->nexts[node];
  6944. *pidx = (naccepted == 0) ? *pidx + 1 : *pidx + naccepted;
  6945. if (fs && (*pidx > mctx->match_last || mctx->state_log[*pidx] == NULL
  6946. || !re_node_set_contains (&mctx->state_log[*pidx]->nodes,
  6947. dest_node)))
  6948. return -1;
  6949. re_node_set_empty (eps_via_nodes);
  6950. return dest_node;
  6951. }
  6952. }
  6953. return -1;
  6954. }
  6955. static reg_errcode_t
  6956. internal_function
  6957. push_fail_stack (struct re_fail_stack_t *fs, int str_idx, int dest_node,
  6958. int nregs, regmatch_t *regs, re_node_set *eps_via_nodes)
  6959. {
  6960. reg_errcode_t err;
  6961. int num = fs->num++;
  6962. if (fs->num == fs->alloc)
  6963. {
  6964. struct re_fail_stack_ent_t *new_array;
  6965. new_array = realloc (fs->stack, (sizeof (struct re_fail_stack_ent_t)
  6966. * fs->alloc * 2));
  6967. if (new_array == NULL)
  6968. return REG_ESPACE;
  6969. fs->alloc *= 2;
  6970. fs->stack = new_array;
  6971. }
  6972. fs->stack[num].idx = str_idx;
  6973. fs->stack[num].node = dest_node;
  6974. fs->stack[num].regs = re_malloc (regmatch_t, nregs);
  6975. if (fs->stack[num].regs == NULL)
  6976. return REG_ESPACE;
  6977. memcpy (fs->stack[num].regs, regs, sizeof (regmatch_t) * nregs);
  6978. err = re_node_set_init_copy (&fs->stack[num].eps_via_nodes, eps_via_nodes);
  6979. return err;
  6980. }
  6981. static int
  6982. internal_function
  6983. pop_fail_stack (struct re_fail_stack_t *fs, int *pidx, int nregs,
  6984. regmatch_t *regs, re_node_set *eps_via_nodes)
  6985. {
  6986. int num = --fs->num;
  6987. assert (num >= 0);
  6988. *pidx = fs->stack[num].idx;
  6989. memcpy (regs, fs->stack[num].regs, sizeof (regmatch_t) * nregs);
  6990. re_node_set_free (eps_via_nodes);
  6991. re_free (fs->stack[num].regs);
  6992. *eps_via_nodes = fs->stack[num].eps_via_nodes;
  6993. return fs->stack[num].node;
  6994. }
  6995. /* Set the positions where the subexpressions are starts/ends to registers
  6996. PMATCH.
  6997. Note: We assume that pmatch[0] is already set, and
  6998. pmatch[i].rm_so == pmatch[i].rm_eo == -1 for 0 < i < nmatch. */
  6999. static reg_errcode_t
  7000. internal_function
  7001. set_regs (const regex_t *preg, const re_match_context_t *mctx, size_t nmatch,
  7002. regmatch_t *pmatch, int fl_backtrack)
  7003. {
  7004. const re_dfa_t *dfa = (const re_dfa_t *) preg->buffer;
  7005. int idx, cur_node;
  7006. re_node_set eps_via_nodes;
  7007. struct re_fail_stack_t *fs;
  7008. struct re_fail_stack_t fs_body = { 0, 2, NULL };
  7009. regmatch_t *prev_idx_match;
  7010. int prev_idx_match_malloced = 0;
  7011. #ifdef DEBUG
  7012. assert (nmatch > 1);
  7013. assert (mctx->state_log != NULL);
  7014. #endif
  7015. if (fl_backtrack)
  7016. {
  7017. fs = &fs_body;
  7018. fs->stack = re_malloc (struct re_fail_stack_ent_t, fs->alloc);
  7019. if (fs->stack == NULL)
  7020. return REG_ESPACE;
  7021. }
  7022. else
  7023. fs = NULL;
  7024. cur_node = dfa->init_node;
  7025. re_node_set_init_empty (&eps_via_nodes);
  7026. if (__libc_use_alloca (nmatch * sizeof (regmatch_t)))
  7027. prev_idx_match = (regmatch_t *) alloca (nmatch * sizeof (regmatch_t));
  7028. else
  7029. {
  7030. prev_idx_match = re_malloc (regmatch_t, nmatch);
  7031. if (prev_idx_match == NULL)
  7032. {
  7033. free_fail_stack_return (fs);
  7034. return REG_ESPACE;
  7035. }
  7036. prev_idx_match_malloced = 1;
  7037. }
  7038. memcpy (prev_idx_match, pmatch, sizeof (regmatch_t) * nmatch);
  7039. for (idx = pmatch[0].rm_so; idx <= pmatch[0].rm_eo ;)
  7040. {
  7041. update_regs (dfa, pmatch, prev_idx_match, cur_node, idx, nmatch);
  7042. if (idx == pmatch[0].rm_eo && cur_node == mctx->last_node)
  7043. {
  7044. int reg_idx;
  7045. if (fs)
  7046. {
  7047. for (reg_idx = 0; reg_idx < nmatch; ++reg_idx)
  7048. if (pmatch[reg_idx].rm_so > -1 && pmatch[reg_idx].rm_eo == -1)
  7049. break;
  7050. if (reg_idx == nmatch)
  7051. {
  7052. re_node_set_free (&eps_via_nodes);
  7053. if (prev_idx_match_malloced)
  7054. re_free (prev_idx_match);
  7055. return free_fail_stack_return (fs);
  7056. }
  7057. cur_node = pop_fail_stack (fs, &idx, nmatch, pmatch,
  7058. &eps_via_nodes);
  7059. }
  7060. else
  7061. {
  7062. re_node_set_free (&eps_via_nodes);
  7063. if (prev_idx_match_malloced)
  7064. re_free (prev_idx_match);
  7065. return REG_NOERROR;
  7066. }
  7067. }
  7068. /* Proceed to next node. */
  7069. cur_node = proceed_next_node (mctx, nmatch, pmatch, &idx, cur_node,
  7070. &eps_via_nodes, fs);
  7071. if (BE (cur_node < 0, 0))
  7072. {
  7073. if (BE (cur_node == -2, 0))
  7074. {
  7075. re_node_set_free (&eps_via_nodes);
  7076. if (prev_idx_match_malloced)
  7077. re_free (prev_idx_match);
  7078. free_fail_stack_return (fs);
  7079. return REG_ESPACE;
  7080. }
  7081. if (fs)
  7082. cur_node = pop_fail_stack (fs, &idx, nmatch, pmatch,
  7083. &eps_via_nodes);
  7084. else
  7085. {
  7086. re_node_set_free (&eps_via_nodes);
  7087. if (prev_idx_match_malloced)
  7088. re_free (prev_idx_match);
  7089. return REG_NOMATCH;
  7090. }
  7091. }
  7092. }
  7093. re_node_set_free (&eps_via_nodes);
  7094. if (prev_idx_match_malloced)
  7095. re_free (prev_idx_match);
  7096. return free_fail_stack_return (fs);
  7097. }
  7098. static reg_errcode_t
  7099. internal_function
  7100. free_fail_stack_return (struct re_fail_stack_t *fs)
  7101. {
  7102. if (fs)
  7103. {
  7104. int fs_idx;
  7105. for (fs_idx = 0; fs_idx < fs->num; ++fs_idx)
  7106. {
  7107. re_node_set_free (&fs->stack[fs_idx].eps_via_nodes);
  7108. re_free (fs->stack[fs_idx].regs);
  7109. }
  7110. re_free (fs->stack);
  7111. }
  7112. return REG_NOERROR;
  7113. }
  7114. static void
  7115. internal_function
  7116. update_regs (const re_dfa_t *dfa, regmatch_t *pmatch,
  7117. regmatch_t *prev_idx_match, int cur_node, int cur_idx, int nmatch)
  7118. {
  7119. int type = dfa->nodes[cur_node].type;
  7120. if (type == OP_OPEN_SUBEXP)
  7121. {
  7122. int reg_num = dfa->nodes[cur_node].opr.idx + 1;
  7123. /* We are at the first node of this sub expression. */
  7124. if (reg_num < nmatch)
  7125. {
  7126. pmatch[reg_num].rm_so = cur_idx;
  7127. pmatch[reg_num].rm_eo = -1;
  7128. }
  7129. }
  7130. else if (type == OP_CLOSE_SUBEXP)
  7131. {
  7132. int reg_num = dfa->nodes[cur_node].opr.idx + 1;
  7133. if (reg_num < nmatch)
  7134. {
  7135. /* We are at the last node of this sub expression. */
  7136. if (pmatch[reg_num].rm_so < cur_idx)
  7137. {
  7138. pmatch[reg_num].rm_eo = cur_idx;
  7139. /* This is a non-empty match or we are not inside an optional
  7140. subexpression. Accept this right away. */
  7141. memcpy (prev_idx_match, pmatch, sizeof (regmatch_t) * nmatch);
  7142. }
  7143. else
  7144. {
  7145. if (dfa->nodes[cur_node].opt_subexp
  7146. && prev_idx_match[reg_num].rm_so != -1)
  7147. /* We transited through an empty match for an optional
  7148. subexpression, like (a?)*, and this is not the subexp's
  7149. first match. Copy back the old content of the registers
  7150. so that matches of an inner subexpression are undone as
  7151. well, like in ((a?))*. */
  7152. memcpy (pmatch, prev_idx_match, sizeof (regmatch_t) * nmatch);
  7153. else
  7154. /* We completed a subexpression, but it may be part of
  7155. an optional one, so do not update PREV_IDX_MATCH. */
  7156. pmatch[reg_num].rm_eo = cur_idx;
  7157. }
  7158. }
  7159. }
  7160. }
  7161. /* This function checks the STATE_LOG from the SCTX->last_str_idx to 0
  7162. and sift the nodes in each states according to the following rules.
  7163. Updated state_log will be wrote to STATE_LOG.
  7164. Rules: We throw away the Node `a' in the STATE_LOG[STR_IDX] if...
  7165. 1. When STR_IDX == MATCH_LAST(the last index in the state_log):
  7166. If `a' isn't the LAST_NODE and `a' can't epsilon transit to
  7167. the LAST_NODE, we throw away the node `a'.
  7168. 2. When 0 <= STR_IDX < MATCH_LAST and `a' accepts
  7169. string `s' and transit to `b':
  7170. i. If 'b' isn't in the STATE_LOG[STR_IDX+strlen('s')], we throw
  7171. away the node `a'.
  7172. ii. If 'b' is in the STATE_LOG[STR_IDX+strlen('s')] but 'b' is
  7173. thrown away, we throw away the node `a'.
  7174. 3. When 0 <= STR_IDX < MATCH_LAST and 'a' epsilon transit to 'b':
  7175. i. If 'b' isn't in the STATE_LOG[STR_IDX], we throw away the
  7176. node `a'.
  7177. ii. If 'b' is in the STATE_LOG[STR_IDX] but 'b' is thrown away,
  7178. we throw away the node `a'. */
  7179. #define STATE_NODE_CONTAINS(state,node) \
  7180. ((state) != NULL && re_node_set_contains (&(state)->nodes, node))
  7181. static reg_errcode_t
  7182. internal_function
  7183. sift_states_backward (const re_match_context_t *mctx, re_sift_context_t *sctx)
  7184. {
  7185. reg_errcode_t err;
  7186. int null_cnt = 0;
  7187. int str_idx = sctx->last_str_idx;
  7188. re_node_set cur_dest;
  7189. #ifdef DEBUG
  7190. assert (mctx->state_log != NULL && mctx->state_log[str_idx] != NULL);
  7191. #endif
  7192. /* Build sifted state_log[str_idx]. It has the nodes which can epsilon
  7193. transit to the last_node and the last_node itself. */
  7194. err = re_node_set_init_1 (&cur_dest, sctx->last_node);
  7195. if (BE (err != REG_NOERROR, 0))
  7196. return err;
  7197. err = update_cur_sifted_state (mctx, sctx, str_idx, &cur_dest);
  7198. if (BE (err != REG_NOERROR, 0))
  7199. goto free_return;
  7200. /* Then check each states in the state_log. */
  7201. while (str_idx > 0)
  7202. {
  7203. /* Update counters. */
  7204. null_cnt = (sctx->sifted_states[str_idx] == NULL) ? null_cnt + 1 : 0;
  7205. if (null_cnt > mctx->max_mb_elem_len)
  7206. {
  7207. memset (sctx->sifted_states, '\0',
  7208. sizeof (re_dfastate_t *) * str_idx);
  7209. re_node_set_free (&cur_dest);
  7210. return REG_NOERROR;
  7211. }
  7212. re_node_set_empty (&cur_dest);
  7213. --str_idx;
  7214. if (mctx->state_log[str_idx])
  7215. {
  7216. err = build_sifted_states (mctx, sctx, str_idx, &cur_dest);
  7217. if (BE (err != REG_NOERROR, 0))
  7218. goto free_return;
  7219. }
  7220. /* Add all the nodes which satisfy the following conditions:
  7221. - It can epsilon transit to a node in CUR_DEST.
  7222. - It is in CUR_SRC.
  7223. And update state_log. */
  7224. err = update_cur_sifted_state (mctx, sctx, str_idx, &cur_dest);
  7225. if (BE (err != REG_NOERROR, 0))
  7226. goto free_return;
  7227. }
  7228. err = REG_NOERROR;
  7229. free_return:
  7230. re_node_set_free (&cur_dest);
  7231. return err;
  7232. }
  7233. static reg_errcode_t
  7234. internal_function
  7235. build_sifted_states (const re_match_context_t *mctx, re_sift_context_t *sctx,
  7236. int str_idx, re_node_set *cur_dest)
  7237. {
  7238. const re_dfa_t *const dfa = mctx->dfa;
  7239. const re_node_set *cur_src = &mctx->state_log[str_idx]->non_eps_nodes;
  7240. int i;
  7241. /* Then build the next sifted state.
  7242. We build the next sifted state on `cur_dest', and update
  7243. `sifted_states[str_idx]' with `cur_dest'.
  7244. Note:
  7245. `cur_dest' is the sifted state from `state_log[str_idx + 1]'.
  7246. `cur_src' points the node_set of the old `state_log[str_idx]'
  7247. (with the epsilon nodes pre-filtered out). */
  7248. for (i = 0; i < cur_src->nelem; i++)
  7249. {
  7250. int prev_node = cur_src->elems[i];
  7251. int naccepted = 0;
  7252. int ret;
  7253. #ifdef DEBUG
  7254. re_token_type_t type = dfa->nodes[prev_node].type;
  7255. assert (!IS_EPSILON_NODE (type));
  7256. #endif
  7257. #ifdef RE_ENABLE_I18N
  7258. /* If the node may accept `multi byte'. */
  7259. if (dfa->nodes[prev_node].accept_mb)
  7260. naccepted = sift_states_iter_mb (mctx, sctx, prev_node,
  7261. str_idx, sctx->last_str_idx);
  7262. #endif /* RE_ENABLE_I18N */
  7263. /* We don't check backreferences here.
  7264. See update_cur_sifted_state(). */
  7265. if (!naccepted
  7266. && check_node_accept (mctx, dfa->nodes + prev_node, str_idx)
  7267. && STATE_NODE_CONTAINS (sctx->sifted_states[str_idx + 1],
  7268. dfa->nexts[prev_node]))
  7269. naccepted = 1;
  7270. if (naccepted == 0)
  7271. continue;
  7272. if (sctx->limits.nelem)
  7273. {
  7274. int to_idx = str_idx + naccepted;
  7275. if (check_dst_limits (mctx, &sctx->limits,
  7276. dfa->nexts[prev_node], to_idx,
  7277. prev_node, str_idx))
  7278. continue;
  7279. }
  7280. ret = re_node_set_insert (cur_dest, prev_node);
  7281. if (BE (ret == -1, 0))
  7282. return REG_ESPACE;
  7283. }
  7284. return REG_NOERROR;
  7285. }
  7286. /* Helper functions. */
  7287. static reg_errcode_t
  7288. internal_function
  7289. clean_state_log_if_needed (re_match_context_t *mctx, int next_state_log_idx)
  7290. {
  7291. int top = mctx->state_log_top;
  7292. if (next_state_log_idx >= mctx->input.bufs_len
  7293. || (next_state_log_idx >= mctx->input.valid_len
  7294. && mctx->input.valid_len < mctx->input.len))
  7295. {
  7296. reg_errcode_t err;
  7297. err = extend_buffers (mctx);
  7298. if (BE (err != REG_NOERROR, 0))
  7299. return err;
  7300. }
  7301. if (top < next_state_log_idx)
  7302. {
  7303. memset (mctx->state_log + top + 1, '\0',
  7304. sizeof (re_dfastate_t *) * (next_state_log_idx - top));
  7305. mctx->state_log_top = next_state_log_idx;
  7306. }
  7307. return REG_NOERROR;
  7308. }
  7309. static reg_errcode_t
  7310. internal_function
  7311. merge_state_array (const re_dfa_t *dfa, re_dfastate_t **dst,
  7312. re_dfastate_t **src, int num)
  7313. {
  7314. int st_idx;
  7315. reg_errcode_t err;
  7316. for (st_idx = 0; st_idx < num; ++st_idx)
  7317. {
  7318. if (dst[st_idx] == NULL)
  7319. dst[st_idx] = src[st_idx];
  7320. else if (src[st_idx] != NULL)
  7321. {
  7322. re_node_set merged_set;
  7323. err = re_node_set_init_union (&merged_set, &dst[st_idx]->nodes,
  7324. &src[st_idx]->nodes);
  7325. if (BE (err != REG_NOERROR, 0))
  7326. return err;
  7327. dst[st_idx] = re_acquire_state (&err, dfa, &merged_set);
  7328. re_node_set_free (&merged_set);
  7329. if (BE (err != REG_NOERROR, 0))
  7330. return err;
  7331. }
  7332. }
  7333. return REG_NOERROR;
  7334. }
  7335. static reg_errcode_t
  7336. internal_function
  7337. update_cur_sifted_state (const re_match_context_t *mctx,
  7338. re_sift_context_t *sctx, int str_idx,
  7339. re_node_set *dest_nodes)
  7340. {
  7341. const re_dfa_t *const dfa = mctx->dfa;
  7342. reg_errcode_t err = REG_NOERROR;
  7343. const re_node_set *candidates;
  7344. candidates = ((mctx->state_log[str_idx] == NULL) ? NULL
  7345. : &mctx->state_log[str_idx]->nodes);
  7346. if (dest_nodes->nelem == 0)
  7347. sctx->sifted_states[str_idx] = NULL;
  7348. else
  7349. {
  7350. if (candidates)
  7351. {
  7352. /* At first, add the nodes which can epsilon transit to a node in
  7353. DEST_NODE. */
  7354. err = add_epsilon_src_nodes (dfa, dest_nodes, candidates);
  7355. if (BE (err != REG_NOERROR, 0))
  7356. return err;
  7357. /* Then, check the limitations in the current sift_context. */
  7358. if (sctx->limits.nelem)
  7359. {
  7360. err = check_subexp_limits (dfa, dest_nodes, candidates, &sctx->limits,
  7361. mctx->bkref_ents, str_idx);
  7362. if (BE (err != REG_NOERROR, 0))
  7363. return err;
  7364. }
  7365. }
  7366. sctx->sifted_states[str_idx] = re_acquire_state (&err, dfa, dest_nodes);
  7367. if (BE (err != REG_NOERROR, 0))
  7368. return err;
  7369. }
  7370. if (candidates && mctx->state_log[str_idx]->has_backref)
  7371. {
  7372. err = sift_states_bkref (mctx, sctx, str_idx, candidates);
  7373. if (BE (err != REG_NOERROR, 0))
  7374. return err;
  7375. }
  7376. return REG_NOERROR;
  7377. }
  7378. static reg_errcode_t
  7379. internal_function
  7380. add_epsilon_src_nodes (const re_dfa_t *dfa, re_node_set *dest_nodes,
  7381. const re_node_set *candidates)
  7382. {
  7383. reg_errcode_t err = REG_NOERROR;
  7384. int i;
  7385. re_dfastate_t *state = re_acquire_state (&err, dfa, dest_nodes);
  7386. if (BE (err != REG_NOERROR, 0))
  7387. return err;
  7388. if (!state->inveclosure.alloc)
  7389. {
  7390. err = re_node_set_alloc (&state->inveclosure, dest_nodes->nelem);
  7391. if (BE (err != REG_NOERROR, 0))
  7392. return REG_ESPACE;
  7393. for (i = 0; i < dest_nodes->nelem; i++)
  7394. re_node_set_merge (&state->inveclosure,
  7395. dfa->inveclosures + dest_nodes->elems[i]);
  7396. }
  7397. return re_node_set_add_intersect (dest_nodes, candidates,
  7398. &state->inveclosure);
  7399. }
  7400. static reg_errcode_t
  7401. internal_function
  7402. sub_epsilon_src_nodes (const re_dfa_t *dfa, int node, re_node_set *dest_nodes,
  7403. const re_node_set *candidates)
  7404. {
  7405. int ecl_idx;
  7406. reg_errcode_t err;
  7407. re_node_set *inv_eclosure = dfa->inveclosures + node;
  7408. re_node_set except_nodes;
  7409. re_node_set_init_empty (&except_nodes);
  7410. for (ecl_idx = 0; ecl_idx < inv_eclosure->nelem; ++ecl_idx)
  7411. {
  7412. int cur_node = inv_eclosure->elems[ecl_idx];
  7413. if (cur_node == node)
  7414. continue;
  7415. if (IS_EPSILON_NODE (dfa->nodes[cur_node].type))
  7416. {
  7417. int edst1 = dfa->edests[cur_node].elems[0];
  7418. int edst2 = ((dfa->edests[cur_node].nelem > 1)
  7419. ? dfa->edests[cur_node].elems[1] : -1);
  7420. if ((!re_node_set_contains (inv_eclosure, edst1)
  7421. && re_node_set_contains (dest_nodes, edst1))
  7422. || (edst2 > 0
  7423. && !re_node_set_contains (inv_eclosure, edst2)
  7424. && re_node_set_contains (dest_nodes, edst2)))
  7425. {
  7426. err = re_node_set_add_intersect (&except_nodes, candidates,
  7427. dfa->inveclosures + cur_node);
  7428. if (BE (err != REG_NOERROR, 0))
  7429. {
  7430. re_node_set_free (&except_nodes);
  7431. return err;
  7432. }
  7433. }
  7434. }
  7435. }
  7436. for (ecl_idx = 0; ecl_idx < inv_eclosure->nelem; ++ecl_idx)
  7437. {
  7438. int cur_node = inv_eclosure->elems[ecl_idx];
  7439. if (!re_node_set_contains (&except_nodes, cur_node))
  7440. {
  7441. int idx = re_node_set_contains (dest_nodes, cur_node) - 1;
  7442. re_node_set_remove_at (dest_nodes, idx);
  7443. }
  7444. }
  7445. re_node_set_free (&except_nodes);
  7446. return REG_NOERROR;
  7447. }
  7448. static int
  7449. internal_function
  7450. check_dst_limits (const re_match_context_t *mctx, re_node_set *limits,
  7451. int dst_node, int dst_idx, int src_node, int src_idx)
  7452. {
  7453. const re_dfa_t *const dfa = mctx->dfa;
  7454. int lim_idx, src_pos, dst_pos;
  7455. int dst_bkref_idx = search_cur_bkref_entry (mctx, dst_idx);
  7456. int src_bkref_idx = search_cur_bkref_entry (mctx, src_idx);
  7457. for (lim_idx = 0; lim_idx < limits->nelem; ++lim_idx)
  7458. {
  7459. int subexp_idx;
  7460. struct re_backref_cache_entry *ent;
  7461. ent = mctx->bkref_ents + limits->elems[lim_idx];
  7462. subexp_idx = dfa->nodes[ent->node].opr.idx;
  7463. dst_pos = check_dst_limits_calc_pos (mctx, limits->elems[lim_idx],
  7464. subexp_idx, dst_node, dst_idx,
  7465. dst_bkref_idx);
  7466. src_pos = check_dst_limits_calc_pos (mctx, limits->elems[lim_idx],
  7467. subexp_idx, src_node, src_idx,
  7468. src_bkref_idx);
  7469. /* In case of:
  7470. <src> <dst> ( <subexp> )
  7471. ( <subexp> ) <src> <dst>
  7472. ( <subexp1> <src> <subexp2> <dst> <subexp3> ) */
  7473. if (src_pos == dst_pos)
  7474. continue; /* This is unrelated limitation. */
  7475. else
  7476. return 1;
  7477. }
  7478. return 0;
  7479. }
  7480. static int
  7481. internal_function
  7482. check_dst_limits_calc_pos_1 (const re_match_context_t *mctx, int boundaries,
  7483. int subexp_idx, int from_node, int bkref_idx)
  7484. {
  7485. const re_dfa_t *const dfa = mctx->dfa;
  7486. const re_node_set *eclosures = dfa->eclosures + from_node;
  7487. int node_idx;
  7488. /* Else, we are on the boundary: examine the nodes on the epsilon
  7489. closure. */
  7490. for (node_idx = 0; node_idx < eclosures->nelem; ++node_idx)
  7491. {
  7492. int node = eclosures->elems[node_idx];
  7493. switch (dfa->nodes[node].type)
  7494. {
  7495. case OP_BACK_REF:
  7496. if (bkref_idx != -1)
  7497. {
  7498. struct re_backref_cache_entry *ent = mctx->bkref_ents + bkref_idx;
  7499. do
  7500. {
  7501. int dst, cpos;
  7502. if (ent->node != node)
  7503. continue;
  7504. if (subexp_idx < BITSET_WORD_BITS
  7505. && !(ent->eps_reachable_subexps_map
  7506. & ((bitset_word_t) 1 << subexp_idx)))
  7507. continue;
  7508. /* Recurse trying to reach the OP_OPEN_SUBEXP and
  7509. OP_CLOSE_SUBEXP cases below. But, if the
  7510. destination node is the same node as the source
  7511. node, don't recurse because it would cause an
  7512. infinite loop: a regex that exhibits this behavior
  7513. is ()\1*\1* */
  7514. dst = dfa->edests[node].elems[0];
  7515. if (dst == from_node)
  7516. {
  7517. if (boundaries & 1)
  7518. return -1;
  7519. else /* if (boundaries & 2) */
  7520. return 0;
  7521. }
  7522. cpos =
  7523. check_dst_limits_calc_pos_1 (mctx, boundaries, subexp_idx,
  7524. dst, bkref_idx);
  7525. if (cpos == -1 /* && (boundaries & 1) */)
  7526. return -1;
  7527. if (cpos == 0 && (boundaries & 2))
  7528. return 0;
  7529. if (subexp_idx < BITSET_WORD_BITS)
  7530. ent->eps_reachable_subexps_map
  7531. &= ~((bitset_word_t) 1 << subexp_idx);
  7532. }
  7533. while (ent++->more);
  7534. }
  7535. break;
  7536. case OP_OPEN_SUBEXP:
  7537. if ((boundaries & 1) && subexp_idx == dfa->nodes[node].opr.idx)
  7538. return -1;
  7539. break;
  7540. case OP_CLOSE_SUBEXP:
  7541. if ((boundaries & 2) && subexp_idx == dfa->nodes[node].opr.idx)
  7542. return 0;
  7543. break;
  7544. default:
  7545. break;
  7546. }
  7547. }
  7548. return (boundaries & 2) ? 1 : 0;
  7549. }
  7550. static int
  7551. internal_function
  7552. check_dst_limits_calc_pos (const re_match_context_t *mctx, int limit,
  7553. int subexp_idx, int from_node, int str_idx,
  7554. int bkref_idx)
  7555. {
  7556. struct re_backref_cache_entry *lim = mctx->bkref_ents + limit;
  7557. int boundaries;
  7558. /* If we are outside the range of the subexpression, return -1 or 1. */
  7559. if (str_idx < lim->subexp_from)
  7560. return -1;
  7561. if (lim->subexp_to < str_idx)
  7562. return 1;
  7563. /* If we are within the subexpression, return 0. */
  7564. boundaries = (str_idx == lim->subexp_from);
  7565. boundaries |= (str_idx == lim->subexp_to) << 1;
  7566. if (boundaries == 0)
  7567. return 0;
  7568. /* Else, examine epsilon closure. */
  7569. return check_dst_limits_calc_pos_1 (mctx, boundaries, subexp_idx,
  7570. from_node, bkref_idx);
  7571. }
  7572. /* Check the limitations of sub expressions LIMITS, and remove the nodes
  7573. which are against limitations from DEST_NODES. */
  7574. static reg_errcode_t
  7575. internal_function
  7576. check_subexp_limits (const re_dfa_t *dfa, re_node_set *dest_nodes,
  7577. const re_node_set *candidates, re_node_set *limits,
  7578. struct re_backref_cache_entry *bkref_ents, int str_idx)
  7579. {
  7580. reg_errcode_t err;
  7581. int node_idx, lim_idx;
  7582. for (lim_idx = 0; lim_idx < limits->nelem; ++lim_idx)
  7583. {
  7584. int subexp_idx;
  7585. struct re_backref_cache_entry *ent;
  7586. ent = bkref_ents + limits->elems[lim_idx];
  7587. if (str_idx <= ent->subexp_from || ent->str_idx < str_idx)
  7588. continue; /* This is unrelated limitation. */
  7589. subexp_idx = dfa->nodes[ent->node].opr.idx;
  7590. if (ent->subexp_to == str_idx)
  7591. {
  7592. int ops_node = -1;
  7593. int cls_node = -1;
  7594. for (node_idx = 0; node_idx < dest_nodes->nelem; ++node_idx)
  7595. {
  7596. int node = dest_nodes->elems[node_idx];
  7597. re_token_type_t type = dfa->nodes[node].type;
  7598. if (type == OP_OPEN_SUBEXP
  7599. && subexp_idx == dfa->nodes[node].opr.idx)
  7600. ops_node = node;
  7601. else if (type == OP_CLOSE_SUBEXP
  7602. && subexp_idx == dfa->nodes[node].opr.idx)
  7603. cls_node = node;
  7604. }
  7605. /* Check the limitation of the open subexpression. */
  7606. /* Note that (ent->subexp_to = str_idx != ent->subexp_from). */
  7607. if (ops_node >= 0)
  7608. {
  7609. err = sub_epsilon_src_nodes (dfa, ops_node, dest_nodes,
  7610. candidates);
  7611. if (BE (err != REG_NOERROR, 0))
  7612. return err;
  7613. }
  7614. /* Check the limitation of the close subexpression. */
  7615. if (cls_node >= 0)
  7616. for (node_idx = 0; node_idx < dest_nodes->nelem; ++node_idx)
  7617. {
  7618. int node = dest_nodes->elems[node_idx];
  7619. if (!re_node_set_contains (dfa->inveclosures + node,
  7620. cls_node)
  7621. && !re_node_set_contains (dfa->eclosures + node,
  7622. cls_node))
  7623. {
  7624. /* It is against this limitation.
  7625. Remove it form the current sifted state. */
  7626. err = sub_epsilon_src_nodes (dfa, node, dest_nodes,
  7627. candidates);
  7628. if (BE (err != REG_NOERROR, 0))
  7629. return err;
  7630. --node_idx;
  7631. }
  7632. }
  7633. }
  7634. else /* (ent->subexp_to != str_idx) */
  7635. {
  7636. for (node_idx = 0; node_idx < dest_nodes->nelem; ++node_idx)
  7637. {
  7638. int node = dest_nodes->elems[node_idx];
  7639. re_token_type_t type = dfa->nodes[node].type;
  7640. if (type == OP_CLOSE_SUBEXP || type == OP_OPEN_SUBEXP)
  7641. {
  7642. if (subexp_idx != dfa->nodes[node].opr.idx)
  7643. continue;
  7644. /* It is against this limitation.
  7645. Remove it form the current sifted state. */
  7646. err = sub_epsilon_src_nodes (dfa, node, dest_nodes,
  7647. candidates);
  7648. if (BE (err != REG_NOERROR, 0))
  7649. return err;
  7650. }
  7651. }
  7652. }
  7653. }
  7654. return REG_NOERROR;
  7655. }
  7656. static reg_errcode_t
  7657. internal_function
  7658. sift_states_bkref (const re_match_context_t *mctx, re_sift_context_t *sctx,
  7659. int str_idx, const re_node_set *candidates)
  7660. {
  7661. const re_dfa_t *const dfa = mctx->dfa;
  7662. reg_errcode_t err;
  7663. int node_idx, node;
  7664. re_sift_context_t local_sctx;
  7665. int first_idx = search_cur_bkref_entry (mctx, str_idx);
  7666. if (first_idx == -1)
  7667. return REG_NOERROR;
  7668. local_sctx.sifted_states = NULL; /* Mark that it hasn't been initialized. */
  7669. for (node_idx = 0; node_idx < candidates->nelem; ++node_idx)
  7670. {
  7671. int enabled_idx;
  7672. re_token_type_t type;
  7673. struct re_backref_cache_entry *entry;
  7674. node = candidates->elems[node_idx];
  7675. type = dfa->nodes[node].type;
  7676. /* Avoid infinite loop for the REs like "()\1+". */
  7677. if (node == sctx->last_node && str_idx == sctx->last_str_idx)
  7678. continue;
  7679. if (type != OP_BACK_REF)
  7680. continue;
  7681. entry = mctx->bkref_ents + first_idx;
  7682. enabled_idx = first_idx;
  7683. do
  7684. {
  7685. int subexp_len;
  7686. int to_idx;
  7687. int dst_node;
  7688. int ret;
  7689. re_dfastate_t *cur_state;
  7690. if (entry->node != node)
  7691. continue;
  7692. subexp_len = entry->subexp_to - entry->subexp_from;
  7693. to_idx = str_idx + subexp_len;
  7694. dst_node = (subexp_len ? dfa->nexts[node]
  7695. : dfa->edests[node].elems[0]);
  7696. if (to_idx > sctx->last_str_idx
  7697. || sctx->sifted_states[to_idx] == NULL
  7698. || !STATE_NODE_CONTAINS (sctx->sifted_states[to_idx], dst_node)
  7699. || check_dst_limits (mctx, &sctx->limits, node,
  7700. str_idx, dst_node, to_idx))
  7701. continue;
  7702. if (local_sctx.sifted_states == NULL)
  7703. {
  7704. local_sctx = *sctx;
  7705. err = re_node_set_init_copy (&local_sctx.limits, &sctx->limits);
  7706. if (BE (err != REG_NOERROR, 0))
  7707. goto free_return;
  7708. }
  7709. local_sctx.last_node = node;
  7710. local_sctx.last_str_idx = str_idx;
  7711. ret = re_node_set_insert (&local_sctx.limits, enabled_idx);
  7712. if (BE (ret < 0, 0))
  7713. {
  7714. err = REG_ESPACE;
  7715. goto free_return;
  7716. }
  7717. cur_state = local_sctx.sifted_states[str_idx];
  7718. err = sift_states_backward (mctx, &local_sctx);
  7719. if (BE (err != REG_NOERROR, 0))
  7720. goto free_return;
  7721. if (sctx->limited_states != NULL)
  7722. {
  7723. err = merge_state_array (dfa, sctx->limited_states,
  7724. local_sctx.sifted_states,
  7725. str_idx + 1);
  7726. if (BE (err != REG_NOERROR, 0))
  7727. goto free_return;
  7728. }
  7729. local_sctx.sifted_states[str_idx] = cur_state;
  7730. re_node_set_remove (&local_sctx.limits, enabled_idx);
  7731. /* mctx->bkref_ents may have changed, reload the pointer. */
  7732. entry = mctx->bkref_ents + enabled_idx;
  7733. }
  7734. while (enabled_idx++, entry++->more);
  7735. }
  7736. err = REG_NOERROR;
  7737. free_return:
  7738. if (local_sctx.sifted_states != NULL)
  7739. {
  7740. re_node_set_free (&local_sctx.limits);
  7741. }
  7742. return err;
  7743. }
  7744. #ifdef RE_ENABLE_I18N
  7745. static int
  7746. internal_function
  7747. sift_states_iter_mb (const re_match_context_t *mctx, re_sift_context_t *sctx,
  7748. int node_idx, int str_idx, int max_str_idx)
  7749. {
  7750. const re_dfa_t *const dfa = mctx->dfa;
  7751. int naccepted;
  7752. /* Check the node can accept `multi byte'. */
  7753. naccepted = check_node_accept_bytes (dfa, node_idx, &mctx->input, str_idx);
  7754. if (naccepted > 0 && str_idx + naccepted <= max_str_idx &&
  7755. !STATE_NODE_CONTAINS (sctx->sifted_states[str_idx + naccepted],
  7756. dfa->nexts[node_idx]))
  7757. /* The node can't accept the `multi byte', or the
  7758. destination was already thrown away, then the node
  7759. could't accept the current input `multi byte'. */
  7760. naccepted = 0;
  7761. /* Otherwise, it is sure that the node could accept
  7762. `naccepted' bytes input. */
  7763. return naccepted;
  7764. }
  7765. #endif /* RE_ENABLE_I18N */
  7766. /* Functions for state transition. */
  7767. /* Return the next state to which the current state STATE will transit by
  7768. accepting the current input byte, and update STATE_LOG if necessary.
  7769. If STATE can accept a multibyte char/collating element/back reference
  7770. update the destination of STATE_LOG. */
  7771. static re_dfastate_t *
  7772. internal_function
  7773. transit_state (reg_errcode_t *err, re_match_context_t *mctx,
  7774. re_dfastate_t *state)
  7775. {
  7776. re_dfastate_t **trtable;
  7777. unsigned char ch;
  7778. #ifdef RE_ENABLE_I18N
  7779. /* If the current state can accept multibyte. */
  7780. if (BE (state->accept_mb, 0))
  7781. {
  7782. *err = transit_state_mb (mctx, state);
  7783. if (BE (*err != REG_NOERROR, 0))
  7784. return NULL;
  7785. }
  7786. #endif /* RE_ENABLE_I18N */
  7787. /* Then decide the next state with the single byte. */
  7788. #if 0
  7789. if (0)
  7790. /* don't use transition table */
  7791. return transit_state_sb (err, mctx, state);
  7792. #endif
  7793. /* Use transition table */
  7794. ch = re_string_fetch_byte (&mctx->input);
  7795. for (;;)
  7796. {
  7797. trtable = state->trtable;
  7798. if (BE (trtable != NULL, 1))
  7799. return trtable[ch];
  7800. trtable = state->word_trtable;
  7801. if (BE (trtable != NULL, 1))
  7802. {
  7803. unsigned int context;
  7804. context
  7805. = re_string_context_at (&mctx->input,
  7806. re_string_cur_idx (&mctx->input) - 1,
  7807. mctx->eflags);
  7808. if (IS_WORD_CONTEXT (context))
  7809. return trtable[ch + SBC_MAX];
  7810. else
  7811. return trtable[ch];
  7812. }
  7813. if (!build_trtable (mctx->dfa, state))
  7814. {
  7815. *err = REG_ESPACE;
  7816. return NULL;
  7817. }
  7818. /* Retry, we now have a transition table. */
  7819. }
  7820. }
  7821. /* Update the state_log if we need */
  7822. re_dfastate_t *
  7823. internal_function
  7824. merge_state_with_log (reg_errcode_t *err, re_match_context_t *mctx,
  7825. re_dfastate_t *next_state)
  7826. {
  7827. const re_dfa_t *const dfa = mctx->dfa;
  7828. int cur_idx = re_string_cur_idx (&mctx->input);
  7829. if (cur_idx > mctx->state_log_top)
  7830. {
  7831. mctx->state_log[cur_idx] = next_state;
  7832. mctx->state_log_top = cur_idx;
  7833. }
  7834. else if (mctx->state_log[cur_idx] == 0)
  7835. {
  7836. mctx->state_log[cur_idx] = next_state;
  7837. }
  7838. else
  7839. {
  7840. re_dfastate_t *pstate;
  7841. unsigned int context;
  7842. re_node_set next_nodes, *log_nodes, *table_nodes = NULL;
  7843. /* If (state_log[cur_idx] != 0), it implies that cur_idx is
  7844. the destination of a multibyte char/collating element/
  7845. back reference. Then the next state is the union set of
  7846. these destinations and the results of the transition table. */
  7847. pstate = mctx->state_log[cur_idx];
  7848. log_nodes = pstate->entrance_nodes;
  7849. if (next_state != NULL)
  7850. {
  7851. table_nodes = next_state->entrance_nodes;
  7852. *err = re_node_set_init_union (&next_nodes, table_nodes,
  7853. log_nodes);
  7854. if (BE (*err != REG_NOERROR, 0))
  7855. return NULL;
  7856. }
  7857. else
  7858. next_nodes = *log_nodes;
  7859. /* Note: We already add the nodes of the initial state,
  7860. then we don't need to add them here. */
  7861. context = re_string_context_at (&mctx->input,
  7862. re_string_cur_idx (&mctx->input) - 1,
  7863. mctx->eflags);
  7864. next_state = mctx->state_log[cur_idx]
  7865. = re_acquire_state_context (err, dfa, &next_nodes, context);
  7866. /* We don't need to check errors here, since the return value of
  7867. this function is next_state and ERR is already set. */
  7868. if (table_nodes != NULL)
  7869. re_node_set_free (&next_nodes);
  7870. }
  7871. if (BE (dfa->nbackref, 0) && next_state != NULL)
  7872. {
  7873. /* Check OP_OPEN_SUBEXP in the current state in case that we use them
  7874. later. We must check them here, since the back references in the
  7875. next state might use them. */
  7876. *err = check_subexp_matching_top (mctx, &next_state->nodes,
  7877. cur_idx);
  7878. if (BE (*err != REG_NOERROR, 0))
  7879. return NULL;
  7880. /* If the next state has back references. */
  7881. if (next_state->has_backref)
  7882. {
  7883. *err = transit_state_bkref (mctx, &next_state->nodes);
  7884. if (BE (*err != REG_NOERROR, 0))
  7885. return NULL;
  7886. next_state = mctx->state_log[cur_idx];
  7887. }
  7888. }
  7889. return next_state;
  7890. }
  7891. /* Skip bytes in the input that correspond to part of a
  7892. multi-byte match, then look in the log for a state
  7893. from which to restart matching. */
  7894. re_dfastate_t *
  7895. internal_function
  7896. find_recover_state (reg_errcode_t *err, re_match_context_t *mctx)
  7897. {
  7898. re_dfastate_t *cur_state;
  7899. do
  7900. {
  7901. int max = mctx->state_log_top;
  7902. int cur_str_idx = re_string_cur_idx (&mctx->input);
  7903. do
  7904. {
  7905. if (++cur_str_idx > max)
  7906. return NULL;
  7907. re_string_skip_bytes (&mctx->input, 1);
  7908. }
  7909. while (mctx->state_log[cur_str_idx] == NULL);
  7910. cur_state = merge_state_with_log (err, mctx, NULL);
  7911. }
  7912. while (*err == REG_NOERROR && cur_state == NULL);
  7913. return cur_state;
  7914. }
  7915. /* Helper functions for transit_state. */
  7916. /* From the node set CUR_NODES, pick up the nodes whose types are
  7917. OP_OPEN_SUBEXP and which have corresponding back references in the regular
  7918. expression. And register them to use them later for evaluating the
  7919. correspoding back references. */
  7920. static reg_errcode_t
  7921. internal_function
  7922. check_subexp_matching_top (re_match_context_t *mctx, re_node_set *cur_nodes,
  7923. int str_idx)
  7924. {
  7925. const re_dfa_t *const dfa = mctx->dfa;
  7926. int node_idx;
  7927. reg_errcode_t err;
  7928. /* TODO: This isn't efficient.
  7929. Because there might be more than one nodes whose types are
  7930. OP_OPEN_SUBEXP and whose index is SUBEXP_IDX, we must check all
  7931. nodes.
  7932. E.g. RE: (a){2} */
  7933. for (node_idx = 0; node_idx < cur_nodes->nelem; ++node_idx)
  7934. {
  7935. int node = cur_nodes->elems[node_idx];
  7936. if (dfa->nodes[node].type == OP_OPEN_SUBEXP
  7937. && dfa->nodes[node].opr.idx < BITSET_WORD_BITS
  7938. && (dfa->used_bkref_map
  7939. & ((bitset_word_t) 1 << dfa->nodes[node].opr.idx)))
  7940. {
  7941. err = match_ctx_add_subtop (mctx, node, str_idx);
  7942. if (BE (err != REG_NOERROR, 0))
  7943. return err;
  7944. }
  7945. }
  7946. return REG_NOERROR;
  7947. }
  7948. #if 0
  7949. /* Return the next state to which the current state STATE will transit by
  7950. accepting the current input byte. */
  7951. static re_dfastate_t *
  7952. transit_state_sb (reg_errcode_t *err, re_match_context_t *mctx,
  7953. re_dfastate_t *state)
  7954. {
  7955. const re_dfa_t *const dfa = mctx->dfa;
  7956. re_node_set next_nodes;
  7957. re_dfastate_t *next_state;
  7958. int node_cnt, cur_str_idx = re_string_cur_idx (&mctx->input);
  7959. unsigned int context;
  7960. *err = re_node_set_alloc (&next_nodes, state->nodes.nelem + 1);
  7961. if (BE (*err != REG_NOERROR, 0))
  7962. return NULL;
  7963. for (node_cnt = 0; node_cnt < state->nodes.nelem; ++node_cnt)
  7964. {
  7965. int cur_node = state->nodes.elems[node_cnt];
  7966. if (check_node_accept (mctx, dfa->nodes + cur_node, cur_str_idx))
  7967. {
  7968. *err = re_node_set_merge (&next_nodes,
  7969. dfa->eclosures + dfa->nexts[cur_node]);
  7970. if (BE (*err != REG_NOERROR, 0))
  7971. {
  7972. re_node_set_free (&next_nodes);
  7973. return NULL;
  7974. }
  7975. }
  7976. }
  7977. context = re_string_context_at (&mctx->input, cur_str_idx, mctx->eflags);
  7978. next_state = re_acquire_state_context (err, dfa, &next_nodes, context);
  7979. /* We don't need to check errors here, since the return value of
  7980. this function is next_state and ERR is already set. */
  7981. re_node_set_free (&next_nodes);
  7982. re_string_skip_bytes (&mctx->input, 1);
  7983. return next_state;
  7984. }
  7985. #endif
  7986. #ifdef RE_ENABLE_I18N
  7987. static reg_errcode_t
  7988. internal_function
  7989. transit_state_mb (re_match_context_t *mctx, re_dfastate_t *pstate)
  7990. {
  7991. const re_dfa_t *const dfa = mctx->dfa;
  7992. reg_errcode_t err;
  7993. int i;
  7994. for (i = 0; i < pstate->nodes.nelem; ++i)
  7995. {
  7996. re_node_set dest_nodes, *new_nodes;
  7997. int cur_node_idx = pstate->nodes.elems[i];
  7998. int naccepted, dest_idx;
  7999. unsigned int context;
  8000. re_dfastate_t *dest_state;
  8001. if (!dfa->nodes[cur_node_idx].accept_mb)
  8002. continue;
  8003. if (dfa->nodes[cur_node_idx].constraint)
  8004. {
  8005. context = re_string_context_at (&mctx->input,
  8006. re_string_cur_idx (&mctx->input),
  8007. mctx->eflags);
  8008. if (NOT_SATISFY_NEXT_CONSTRAINT (dfa->nodes[cur_node_idx].constraint,
  8009. context))
  8010. continue;
  8011. }
  8012. /* How many bytes the node can accept? */
  8013. naccepted = check_node_accept_bytes (dfa, cur_node_idx, &mctx->input,
  8014. re_string_cur_idx (&mctx->input));
  8015. if (naccepted == 0)
  8016. continue;
  8017. /* The node can accepts `naccepted' bytes. */
  8018. dest_idx = re_string_cur_idx (&mctx->input) + naccepted;
  8019. mctx->max_mb_elem_len = ((mctx->max_mb_elem_len < naccepted) ? naccepted
  8020. : mctx->max_mb_elem_len);
  8021. err = clean_state_log_if_needed (mctx, dest_idx);
  8022. if (BE (err != REG_NOERROR, 0))
  8023. return err;
  8024. #ifdef DEBUG
  8025. assert (dfa->nexts[cur_node_idx] != -1);
  8026. #endif
  8027. new_nodes = dfa->eclosures + dfa->nexts[cur_node_idx];
  8028. dest_state = mctx->state_log[dest_idx];
  8029. if (dest_state == NULL)
  8030. dest_nodes = *new_nodes;
  8031. else
  8032. {
  8033. err = re_node_set_init_union (&dest_nodes,
  8034. dest_state->entrance_nodes, new_nodes);
  8035. if (BE (err != REG_NOERROR, 0))
  8036. return err;
  8037. }
  8038. context = re_string_context_at (&mctx->input, dest_idx - 1,
  8039. mctx->eflags);
  8040. mctx->state_log[dest_idx]
  8041. = re_acquire_state_context (&err, dfa, &dest_nodes, context);
  8042. if (dest_state != NULL)
  8043. re_node_set_free (&dest_nodes);
  8044. if (BE (mctx->state_log[dest_idx] == NULL && err != REG_NOERROR, 0))
  8045. return err;
  8046. }
  8047. return REG_NOERROR;
  8048. }
  8049. #endif /* RE_ENABLE_I18N */
  8050. static reg_errcode_t
  8051. internal_function
  8052. transit_state_bkref (re_match_context_t *mctx, const re_node_set *nodes)
  8053. {
  8054. const re_dfa_t *const dfa = mctx->dfa;
  8055. reg_errcode_t err;
  8056. int i;
  8057. int cur_str_idx = re_string_cur_idx (&mctx->input);
  8058. for (i = 0; i < nodes->nelem; ++i)
  8059. {
  8060. int dest_str_idx, prev_nelem, bkc_idx;
  8061. int node_idx = nodes->elems[i];
  8062. unsigned int context;
  8063. const re_token_t *node = dfa->nodes + node_idx;
  8064. re_node_set *new_dest_nodes;
  8065. /* Check whether `node' is a backreference or not. */
  8066. if (node->type != OP_BACK_REF)
  8067. continue;
  8068. if (node->constraint)
  8069. {
  8070. context = re_string_context_at (&mctx->input, cur_str_idx,
  8071. mctx->eflags);
  8072. if (NOT_SATISFY_NEXT_CONSTRAINT (node->constraint, context))
  8073. continue;
  8074. }
  8075. /* `node' is a backreference.
  8076. Check the substring which the substring matched. */
  8077. bkc_idx = mctx->nbkref_ents;
  8078. err = get_subexp (mctx, node_idx, cur_str_idx);
  8079. if (BE (err != REG_NOERROR, 0))
  8080. goto free_return;
  8081. /* And add the epsilon closures (which is `new_dest_nodes') of
  8082. the backreference to appropriate state_log. */
  8083. #ifdef DEBUG
  8084. assert (dfa->nexts[node_idx] != -1);
  8085. #endif
  8086. for (; bkc_idx < mctx->nbkref_ents; ++bkc_idx)
  8087. {
  8088. int subexp_len;
  8089. re_dfastate_t *dest_state;
  8090. struct re_backref_cache_entry *bkref_ent;
  8091. bkref_ent = mctx->bkref_ents + bkc_idx;
  8092. if (bkref_ent->node != node_idx || bkref_ent->str_idx != cur_str_idx)
  8093. continue;
  8094. subexp_len = bkref_ent->subexp_to - bkref_ent->subexp_from;
  8095. new_dest_nodes = (subexp_len == 0
  8096. ? dfa->eclosures + dfa->edests[node_idx].elems[0]
  8097. : dfa->eclosures + dfa->nexts[node_idx]);
  8098. dest_str_idx = (cur_str_idx + bkref_ent->subexp_to
  8099. - bkref_ent->subexp_from);
  8100. context = re_string_context_at (&mctx->input, dest_str_idx - 1,
  8101. mctx->eflags);
  8102. dest_state = mctx->state_log[dest_str_idx];
  8103. prev_nelem = ((mctx->state_log[cur_str_idx] == NULL) ? 0
  8104. : mctx->state_log[cur_str_idx]->nodes.nelem);
  8105. /* Add `new_dest_node' to state_log. */
  8106. if (dest_state == NULL)
  8107. {
  8108. mctx->state_log[dest_str_idx]
  8109. = re_acquire_state_context (&err, dfa, new_dest_nodes,
  8110. context);
  8111. if (BE (mctx->state_log[dest_str_idx] == NULL
  8112. && err != REG_NOERROR, 0))
  8113. goto free_return;
  8114. }
  8115. else
  8116. {
  8117. re_node_set dest_nodes;
  8118. err = re_node_set_init_union (&dest_nodes,
  8119. dest_state->entrance_nodes,
  8120. new_dest_nodes);
  8121. if (BE (err != REG_NOERROR, 0))
  8122. {
  8123. re_node_set_free (&dest_nodes);
  8124. goto free_return;
  8125. }
  8126. mctx->state_log[dest_str_idx]
  8127. = re_acquire_state_context (&err, dfa, &dest_nodes, context);
  8128. re_node_set_free (&dest_nodes);
  8129. if (BE (mctx->state_log[dest_str_idx] == NULL
  8130. && err != REG_NOERROR, 0))
  8131. goto free_return;
  8132. }
  8133. /* We need to check recursively if the backreference can epsilon
  8134. transit. */
  8135. if (subexp_len == 0
  8136. && mctx->state_log[cur_str_idx]->nodes.nelem > prev_nelem)
  8137. {
  8138. err = check_subexp_matching_top (mctx, new_dest_nodes,
  8139. cur_str_idx);
  8140. if (BE (err != REG_NOERROR, 0))
  8141. goto free_return;
  8142. err = transit_state_bkref (mctx, new_dest_nodes);
  8143. if (BE (err != REG_NOERROR, 0))
  8144. goto free_return;
  8145. }
  8146. }
  8147. }
  8148. err = REG_NOERROR;
  8149. free_return:
  8150. return err;
  8151. }
  8152. /* Enumerate all the candidates which the backreference BKREF_NODE can match
  8153. at BKREF_STR_IDX, and register them by match_ctx_add_entry().
  8154. Note that we might collect inappropriate candidates here.
  8155. However, the cost of checking them strictly here is too high, then we
  8156. delay these checking for prune_impossible_nodes(). */
  8157. static reg_errcode_t
  8158. internal_function
  8159. get_subexp (re_match_context_t *mctx, int bkref_node, int bkref_str_idx)
  8160. {
  8161. const re_dfa_t *const dfa = mctx->dfa;
  8162. int subexp_num, sub_top_idx;
  8163. const char *buf = (const char *) re_string_get_buffer (&mctx->input);
  8164. /* Return if we have already checked BKREF_NODE at BKREF_STR_IDX. */
  8165. int cache_idx = search_cur_bkref_entry (mctx, bkref_str_idx);
  8166. if (cache_idx != -1)
  8167. {
  8168. const struct re_backref_cache_entry *entry
  8169. = mctx->bkref_ents + cache_idx;
  8170. do
  8171. if (entry->node == bkref_node)
  8172. return REG_NOERROR; /* We already checked it. */
  8173. while (entry++->more);
  8174. }
  8175. subexp_num = dfa->nodes[bkref_node].opr.idx;
  8176. /* For each sub expression */
  8177. for (sub_top_idx = 0; sub_top_idx < mctx->nsub_tops; ++sub_top_idx)
  8178. {
  8179. reg_errcode_t err;
  8180. re_sub_match_top_t *sub_top = mctx->sub_tops[sub_top_idx];
  8181. re_sub_match_last_t *sub_last;
  8182. int sub_last_idx, sl_str, bkref_str_off;
  8183. if (dfa->nodes[sub_top->node].opr.idx != subexp_num)
  8184. continue; /* It isn't related. */
  8185. sl_str = sub_top->str_idx;
  8186. bkref_str_off = bkref_str_idx;
  8187. /* At first, check the last node of sub expressions we already
  8188. evaluated. */
  8189. for (sub_last_idx = 0; sub_last_idx < sub_top->nlasts; ++sub_last_idx)
  8190. {
  8191. int sl_str_diff;
  8192. sub_last = sub_top->lasts[sub_last_idx];
  8193. sl_str_diff = sub_last->str_idx - sl_str;
  8194. /* The matched string by the sub expression match with the substring
  8195. at the back reference? */
  8196. if (sl_str_diff > 0)
  8197. {
  8198. if (BE (bkref_str_off + sl_str_diff > mctx->input.valid_len, 0))
  8199. {
  8200. /* Not enough chars for a successful match. */
  8201. if (bkref_str_off + sl_str_diff > mctx->input.len)
  8202. break;
  8203. err = clean_state_log_if_needed (mctx,
  8204. bkref_str_off
  8205. + sl_str_diff);
  8206. if (BE (err != REG_NOERROR, 0))
  8207. return err;
  8208. buf = (const char *) re_string_get_buffer (&mctx->input);
  8209. }
  8210. if (memcmp (buf + bkref_str_off, buf + sl_str, sl_str_diff) != 0)
  8211. /* We don't need to search this sub expression any more. */
  8212. break;
  8213. }
  8214. bkref_str_off += sl_str_diff;
  8215. sl_str += sl_str_diff;
  8216. err = get_subexp_sub (mctx, sub_top, sub_last, bkref_node,
  8217. bkref_str_idx);
  8218. /* Reload buf, since the preceding call might have reallocated
  8219. the buffer. */
  8220. buf = (const char *) re_string_get_buffer (&mctx->input);
  8221. if (err == REG_NOMATCH)
  8222. continue;
  8223. if (BE (err != REG_NOERROR, 0))
  8224. return err;
  8225. }
  8226. if (sub_last_idx < sub_top->nlasts)
  8227. continue;
  8228. if (sub_last_idx > 0)
  8229. ++sl_str;
  8230. /* Then, search for the other last nodes of the sub expression. */
  8231. for (; sl_str <= bkref_str_idx; ++sl_str)
  8232. {
  8233. int cls_node, sl_str_off;
  8234. const re_node_set *nodes;
  8235. sl_str_off = sl_str - sub_top->str_idx;
  8236. /* The matched string by the sub expression match with the substring
  8237. at the back reference? */
  8238. if (sl_str_off > 0)
  8239. {
  8240. if (BE (bkref_str_off >= mctx->input.valid_len, 0))
  8241. {
  8242. /* If we are at the end of the input, we cannot match. */
  8243. if (bkref_str_off >= mctx->input.len)
  8244. break;
  8245. err = extend_buffers (mctx);
  8246. if (BE (err != REG_NOERROR, 0))
  8247. return err;
  8248. buf = (const char *) re_string_get_buffer (&mctx->input);
  8249. }
  8250. if (buf [bkref_str_off++] != buf[sl_str - 1])
  8251. break; /* We don't need to search this sub expression
  8252. any more. */
  8253. }
  8254. if (mctx->state_log[sl_str] == NULL)
  8255. continue;
  8256. /* Does this state have a ')' of the sub expression? */
  8257. nodes = &mctx->state_log[sl_str]->nodes;
  8258. cls_node = find_subexp_node (dfa, nodes, subexp_num,
  8259. OP_CLOSE_SUBEXP);
  8260. if (cls_node == -1)
  8261. continue; /* No. */
  8262. if (sub_top->path == NULL)
  8263. {
  8264. sub_top->path = calloc (sizeof (state_array_t),
  8265. sl_str - sub_top->str_idx + 1);
  8266. if (sub_top->path == NULL)
  8267. return REG_ESPACE;
  8268. }
  8269. /* Can the OP_OPEN_SUBEXP node arrive the OP_CLOSE_SUBEXP node
  8270. in the current context? */
  8271. err = check_arrival (mctx, sub_top->path, sub_top->node,
  8272. sub_top->str_idx, cls_node, sl_str,
  8273. OP_CLOSE_SUBEXP);
  8274. if (err == REG_NOMATCH)
  8275. continue;
  8276. if (BE (err != REG_NOERROR, 0))
  8277. return err;
  8278. sub_last = match_ctx_add_sublast (sub_top, cls_node, sl_str);
  8279. if (BE (sub_last == NULL, 0))
  8280. return REG_ESPACE;
  8281. err = get_subexp_sub (mctx, sub_top, sub_last, bkref_node,
  8282. bkref_str_idx);
  8283. if (err == REG_NOMATCH)
  8284. continue;
  8285. }
  8286. }
  8287. return REG_NOERROR;
  8288. }
  8289. /* Helper functions for get_subexp(). */
  8290. /* Check SUB_LAST can arrive to the back reference BKREF_NODE at BKREF_STR.
  8291. If it can arrive, register the sub expression expressed with SUB_TOP
  8292. and SUB_LAST. */
  8293. static reg_errcode_t
  8294. internal_function
  8295. get_subexp_sub (re_match_context_t *mctx, const re_sub_match_top_t *sub_top,
  8296. re_sub_match_last_t *sub_last, int bkref_node, int bkref_str)
  8297. {
  8298. reg_errcode_t err;
  8299. int to_idx;
  8300. /* Can the subexpression arrive the back reference? */
  8301. err = check_arrival (mctx, &sub_last->path, sub_last->node,
  8302. sub_last->str_idx, bkref_node, bkref_str,
  8303. OP_OPEN_SUBEXP);
  8304. if (err != REG_NOERROR)
  8305. return err;
  8306. err = match_ctx_add_entry (mctx, bkref_node, bkref_str, sub_top->str_idx,
  8307. sub_last->str_idx);
  8308. if (BE (err != REG_NOERROR, 0))
  8309. return err;
  8310. to_idx = bkref_str + sub_last->str_idx - sub_top->str_idx;
  8311. return clean_state_log_if_needed (mctx, to_idx);
  8312. }
  8313. /* Find the first node which is '(' or ')' and whose index is SUBEXP_IDX.
  8314. Search '(' if FL_OPEN, or search ')' otherwise.
  8315. TODO: This function isn't efficient...
  8316. Because there might be more than one nodes whose types are
  8317. OP_OPEN_SUBEXP and whose index is SUBEXP_IDX, we must check all
  8318. nodes.
  8319. E.g. RE: (a){2} */
  8320. static int
  8321. internal_function
  8322. find_subexp_node (const re_dfa_t *dfa, const re_node_set *nodes,
  8323. int subexp_idx, int type)
  8324. {
  8325. int cls_idx;
  8326. for (cls_idx = 0; cls_idx < nodes->nelem; ++cls_idx)
  8327. {
  8328. int cls_node = nodes->elems[cls_idx];
  8329. const re_token_t *node = dfa->nodes + cls_node;
  8330. if (node->type == type
  8331. && node->opr.idx == subexp_idx)
  8332. return cls_node;
  8333. }
  8334. return -1;
  8335. }
  8336. /* Check whether the node TOP_NODE at TOP_STR can arrive to the node
  8337. LAST_NODE at LAST_STR. We record the path onto PATH since it will be
  8338. heavily reused.
  8339. Return REG_NOERROR if it can arrive, or REG_NOMATCH otherwise. */
  8340. static reg_errcode_t
  8341. internal_function
  8342. check_arrival (re_match_context_t *mctx, state_array_t *path, int top_node,
  8343. int top_str, int last_node, int last_str, int type)
  8344. {
  8345. const re_dfa_t *const dfa = mctx->dfa;
  8346. reg_errcode_t err = REG_NOERROR;
  8347. int subexp_num, backup_cur_idx, str_idx, null_cnt;
  8348. re_dfastate_t *cur_state = NULL;
  8349. re_node_set *cur_nodes, next_nodes;
  8350. re_dfastate_t **backup_state_log;
  8351. unsigned int context;
  8352. subexp_num = dfa->nodes[top_node].opr.idx;
  8353. /* Extend the buffer if we need. */
  8354. if (BE (path->alloc < last_str + mctx->max_mb_elem_len + 1, 0))
  8355. {
  8356. re_dfastate_t **new_array;
  8357. int old_alloc = path->alloc;
  8358. path->alloc += last_str + mctx->max_mb_elem_len + 1;
  8359. new_array = re_realloc (path->array, re_dfastate_t *, path->alloc);
  8360. if (BE (new_array == NULL, 0))
  8361. {
  8362. path->alloc = old_alloc;
  8363. return REG_ESPACE;
  8364. }
  8365. path->array = new_array;
  8366. memset (new_array + old_alloc, '\0',
  8367. sizeof (re_dfastate_t *) * (path->alloc - old_alloc));
  8368. }
  8369. str_idx = path->next_idx ?: top_str;
  8370. /* Temporary modify MCTX. */
  8371. backup_state_log = mctx->state_log;
  8372. backup_cur_idx = mctx->input.cur_idx;
  8373. mctx->state_log = path->array;
  8374. mctx->input.cur_idx = str_idx;
  8375. /* Setup initial node set. */
  8376. context = re_string_context_at (&mctx->input, str_idx - 1, mctx->eflags);
  8377. if (str_idx == top_str)
  8378. {
  8379. err = re_node_set_init_1 (&next_nodes, top_node);
  8380. if (BE (err != REG_NOERROR, 0))
  8381. return err;
  8382. err = check_arrival_expand_ecl (dfa, &next_nodes, subexp_num, type);
  8383. if (BE (err != REG_NOERROR, 0))
  8384. {
  8385. re_node_set_free (&next_nodes);
  8386. return err;
  8387. }
  8388. }
  8389. else
  8390. {
  8391. cur_state = mctx->state_log[str_idx];
  8392. if (cur_state && cur_state->has_backref)
  8393. {
  8394. err = re_node_set_init_copy (&next_nodes, &cur_state->nodes);
  8395. if (BE (err != REG_NOERROR, 0))
  8396. return err;
  8397. }
  8398. else
  8399. re_node_set_init_empty (&next_nodes);
  8400. }
  8401. if (str_idx == top_str || (cur_state && cur_state->has_backref))
  8402. {
  8403. if (next_nodes.nelem)
  8404. {
  8405. err = expand_bkref_cache (mctx, &next_nodes, str_idx,
  8406. subexp_num, type);
  8407. if (BE (err != REG_NOERROR, 0))
  8408. {
  8409. re_node_set_free (&next_nodes);
  8410. return err;
  8411. }
  8412. }
  8413. cur_state = re_acquire_state_context (&err, dfa, &next_nodes, context);
  8414. if (BE (cur_state == NULL && err != REG_NOERROR, 0))
  8415. {
  8416. re_node_set_free (&next_nodes);
  8417. return err;
  8418. }
  8419. mctx->state_log[str_idx] = cur_state;
  8420. }
  8421. for (null_cnt = 0; str_idx < last_str && null_cnt <= mctx->max_mb_elem_len;)
  8422. {
  8423. re_node_set_empty (&next_nodes);
  8424. if (mctx->state_log[str_idx + 1])
  8425. {
  8426. err = re_node_set_merge (&next_nodes,
  8427. &mctx->state_log[str_idx + 1]->nodes);
  8428. if (BE (err != REG_NOERROR, 0))
  8429. {
  8430. re_node_set_free (&next_nodes);
  8431. return err;
  8432. }
  8433. }
  8434. if (cur_state)
  8435. {
  8436. err = check_arrival_add_next_nodes (mctx, str_idx,
  8437. &cur_state->non_eps_nodes,
  8438. &next_nodes);
  8439. if (BE (err != REG_NOERROR, 0))
  8440. {
  8441. re_node_set_free (&next_nodes);
  8442. return err;
  8443. }
  8444. }
  8445. ++str_idx;
  8446. if (next_nodes.nelem)
  8447. {
  8448. err = check_arrival_expand_ecl (dfa, &next_nodes, subexp_num, type);
  8449. if (BE (err != REG_NOERROR, 0))
  8450. {
  8451. re_node_set_free (&next_nodes);
  8452. return err;
  8453. }
  8454. err = expand_bkref_cache (mctx, &next_nodes, str_idx,
  8455. subexp_num, type);
  8456. if (BE (err != REG_NOERROR, 0))
  8457. {
  8458. re_node_set_free (&next_nodes);
  8459. return err;
  8460. }
  8461. }
  8462. context = re_string_context_at (&mctx->input, str_idx - 1, mctx->eflags);
  8463. cur_state = re_acquire_state_context (&err, dfa, &next_nodes, context);
  8464. if (BE (cur_state == NULL && err != REG_NOERROR, 0))
  8465. {
  8466. re_node_set_free (&next_nodes);
  8467. return err;
  8468. }
  8469. mctx->state_log[str_idx] = cur_state;
  8470. null_cnt = cur_state == NULL ? null_cnt + 1 : 0;
  8471. }
  8472. re_node_set_free (&next_nodes);
  8473. cur_nodes = (mctx->state_log[last_str] == NULL ? NULL
  8474. : &mctx->state_log[last_str]->nodes);
  8475. path->next_idx = str_idx;
  8476. /* Fix MCTX. */
  8477. mctx->state_log = backup_state_log;
  8478. mctx->input.cur_idx = backup_cur_idx;
  8479. /* Then check the current node set has the node LAST_NODE. */
  8480. if (cur_nodes != NULL && re_node_set_contains (cur_nodes, last_node))
  8481. return REG_NOERROR;
  8482. return REG_NOMATCH;
  8483. }
  8484. /* Helper functions for check_arrival. */
  8485. /* Calculate the destination nodes of CUR_NODES at STR_IDX, and append them
  8486. to NEXT_NODES.
  8487. TODO: This function is similar to the functions transit_state*(),
  8488. however this function has many additional works.
  8489. Can't we unify them? */
  8490. static reg_errcode_t
  8491. internal_function
  8492. check_arrival_add_next_nodes (re_match_context_t *mctx, int str_idx,
  8493. re_node_set *cur_nodes, re_node_set *next_nodes)
  8494. {
  8495. const re_dfa_t *const dfa = mctx->dfa;
  8496. int result;
  8497. int cur_idx;
  8498. reg_errcode_t err = REG_NOERROR;
  8499. re_node_set union_set;
  8500. re_node_set_init_empty (&union_set);
  8501. for (cur_idx = 0; cur_idx < cur_nodes->nelem; ++cur_idx)
  8502. {
  8503. int naccepted = 0;
  8504. int cur_node = cur_nodes->elems[cur_idx];
  8505. #ifdef DEBUG
  8506. re_token_type_t type = dfa->nodes[cur_node].type;
  8507. assert (!IS_EPSILON_NODE (type));
  8508. #endif
  8509. #ifdef RE_ENABLE_I18N
  8510. /* If the node may accept `multi byte'. */
  8511. if (dfa->nodes[cur_node].accept_mb)
  8512. {
  8513. naccepted = check_node_accept_bytes (dfa, cur_node, &mctx->input,
  8514. str_idx);
  8515. if (naccepted > 1)
  8516. {
  8517. re_dfastate_t *dest_state;
  8518. int next_node = dfa->nexts[cur_node];
  8519. int next_idx = str_idx + naccepted;
  8520. dest_state = mctx->state_log[next_idx];
  8521. re_node_set_empty (&union_set);
  8522. if (dest_state)
  8523. {
  8524. err = re_node_set_merge (&union_set, &dest_state->nodes);
  8525. if (BE (err != REG_NOERROR, 0))
  8526. {
  8527. re_node_set_free (&union_set);
  8528. return err;
  8529. }
  8530. }
  8531. result = re_node_set_insert (&union_set, next_node);
  8532. if (BE (result < 0, 0))
  8533. {
  8534. re_node_set_free (&union_set);
  8535. return REG_ESPACE;
  8536. }
  8537. mctx->state_log[next_idx] = re_acquire_state (&err, dfa,
  8538. &union_set);
  8539. if (BE (mctx->state_log[next_idx] == NULL
  8540. && err != REG_NOERROR, 0))
  8541. {
  8542. re_node_set_free (&union_set);
  8543. return err;
  8544. }
  8545. }
  8546. }
  8547. #endif /* RE_ENABLE_I18N */
  8548. if (naccepted
  8549. || check_node_accept (mctx, dfa->nodes + cur_node, str_idx))
  8550. {
  8551. result = re_node_set_insert (next_nodes, dfa->nexts[cur_node]);
  8552. if (BE (result < 0, 0))
  8553. {
  8554. re_node_set_free (&union_set);
  8555. return REG_ESPACE;
  8556. }
  8557. }
  8558. }
  8559. re_node_set_free (&union_set);
  8560. return REG_NOERROR;
  8561. }
  8562. /* For all the nodes in CUR_NODES, add the epsilon closures of them to
  8563. CUR_NODES, however exclude the nodes which are:
  8564. - inside the sub expression whose number is EX_SUBEXP, if FL_OPEN.
  8565. - out of the sub expression whose number is EX_SUBEXP, if !FL_OPEN.
  8566. */
  8567. static reg_errcode_t
  8568. internal_function
  8569. check_arrival_expand_ecl (const re_dfa_t *dfa, re_node_set *cur_nodes,
  8570. int ex_subexp, int type)
  8571. {
  8572. reg_errcode_t err;
  8573. int idx, outside_node;
  8574. re_node_set new_nodes;
  8575. #ifdef DEBUG
  8576. assert (cur_nodes->nelem);
  8577. #endif
  8578. err = re_node_set_alloc (&new_nodes, cur_nodes->nelem);
  8579. if (BE (err != REG_NOERROR, 0))
  8580. return err;
  8581. /* Create a new node set NEW_NODES with the nodes which are epsilon
  8582. closures of the node in CUR_NODES. */
  8583. for (idx = 0; idx < cur_nodes->nelem; ++idx)
  8584. {
  8585. int cur_node = cur_nodes->elems[idx];
  8586. const re_node_set *eclosure = dfa->eclosures + cur_node;
  8587. outside_node = find_subexp_node (dfa, eclosure, ex_subexp, type);
  8588. if (outside_node == -1)
  8589. {
  8590. /* There are no problematic nodes, just merge them. */
  8591. err = re_node_set_merge (&new_nodes, eclosure);
  8592. if (BE (err != REG_NOERROR, 0))
  8593. {
  8594. re_node_set_free (&new_nodes);
  8595. return err;
  8596. }
  8597. }
  8598. else
  8599. {
  8600. /* There are problematic nodes, re-calculate incrementally. */
  8601. err = check_arrival_expand_ecl_sub (dfa, &new_nodes, cur_node,
  8602. ex_subexp, type);
  8603. if (BE (err != REG_NOERROR, 0))
  8604. {
  8605. re_node_set_free (&new_nodes);
  8606. return err;
  8607. }
  8608. }
  8609. }
  8610. re_node_set_free (cur_nodes);
  8611. *cur_nodes = new_nodes;
  8612. return REG_NOERROR;
  8613. }
  8614. /* Helper function for check_arrival_expand_ecl.
  8615. Check incrementally the epsilon closure of TARGET, and if it isn't
  8616. problematic append it to DST_NODES. */
  8617. static reg_errcode_t
  8618. internal_function
  8619. check_arrival_expand_ecl_sub (const re_dfa_t *dfa, re_node_set *dst_nodes,
  8620. int target, int ex_subexp, int type)
  8621. {
  8622. int cur_node;
  8623. for (cur_node = target; !re_node_set_contains (dst_nodes, cur_node);)
  8624. {
  8625. int err;
  8626. if (dfa->nodes[cur_node].type == type
  8627. && dfa->nodes[cur_node].opr.idx == ex_subexp)
  8628. {
  8629. if (type == OP_CLOSE_SUBEXP)
  8630. {
  8631. err = re_node_set_insert (dst_nodes, cur_node);
  8632. if (BE (err == -1, 0))
  8633. return REG_ESPACE;
  8634. }
  8635. break;
  8636. }
  8637. err = re_node_set_insert (dst_nodes, cur_node);
  8638. if (BE (err == -1, 0))
  8639. return REG_ESPACE;
  8640. if (dfa->edests[cur_node].nelem == 0)
  8641. break;
  8642. if (dfa->edests[cur_node].nelem == 2)
  8643. {
  8644. err = check_arrival_expand_ecl_sub (dfa, dst_nodes,
  8645. dfa->edests[cur_node].elems[1],
  8646. ex_subexp, type);
  8647. if (BE (err != REG_NOERROR, 0))
  8648. return err;
  8649. }
  8650. cur_node = dfa->edests[cur_node].elems[0];
  8651. }
  8652. return REG_NOERROR;
  8653. }
  8654. /* For all the back references in the current state, calculate the
  8655. destination of the back references by the appropriate entry
  8656. in MCTX->BKREF_ENTS. */
  8657. static reg_errcode_t
  8658. internal_function
  8659. expand_bkref_cache (re_match_context_t *mctx, re_node_set *cur_nodes,
  8660. int cur_str, int subexp_num, int type)
  8661. {
  8662. const re_dfa_t *const dfa = mctx->dfa;
  8663. reg_errcode_t err;
  8664. int cache_idx_start = search_cur_bkref_entry (mctx, cur_str);
  8665. struct re_backref_cache_entry *ent;
  8666. if (cache_idx_start == -1)
  8667. return REG_NOERROR;
  8668. restart:
  8669. ent = mctx->bkref_ents + cache_idx_start;
  8670. do
  8671. {
  8672. int to_idx, next_node;
  8673. /* Is this entry ENT is appropriate? */
  8674. if (!re_node_set_contains (cur_nodes, ent->node))
  8675. continue; /* No. */
  8676. to_idx = cur_str + ent->subexp_to - ent->subexp_from;
  8677. /* Calculate the destination of the back reference, and append it
  8678. to MCTX->STATE_LOG. */
  8679. if (to_idx == cur_str)
  8680. {
  8681. /* The backreference did epsilon transit, we must re-check all the
  8682. node in the current state. */
  8683. re_node_set new_dests;
  8684. reg_errcode_t err2, err3;
  8685. next_node = dfa->edests[ent->node].elems[0];
  8686. if (re_node_set_contains (cur_nodes, next_node))
  8687. continue;
  8688. err = re_node_set_init_1 (&new_dests, next_node);
  8689. err2 = check_arrival_expand_ecl (dfa, &new_dests, subexp_num, type);
  8690. err3 = re_node_set_merge (cur_nodes, &new_dests);
  8691. re_node_set_free (&new_dests);
  8692. if (BE (err != REG_NOERROR || err2 != REG_NOERROR
  8693. || err3 != REG_NOERROR, 0))
  8694. {
  8695. err = (err != REG_NOERROR ? err
  8696. : (err2 != REG_NOERROR ? err2 : err3));
  8697. return err;
  8698. }
  8699. /* TODO: It is still inefficient... */
  8700. goto restart;
  8701. }
  8702. else
  8703. {
  8704. re_node_set union_set;
  8705. next_node = dfa->nexts[ent->node];
  8706. if (mctx->state_log[to_idx])
  8707. {
  8708. int ret;
  8709. if (re_node_set_contains (&mctx->state_log[to_idx]->nodes,
  8710. next_node))
  8711. continue;
  8712. err = re_node_set_init_copy (&union_set,
  8713. &mctx->state_log[to_idx]->nodes);
  8714. ret = re_node_set_insert (&union_set, next_node);
  8715. if (BE (err != REG_NOERROR || ret < 0, 0))
  8716. {
  8717. re_node_set_free (&union_set);
  8718. err = err != REG_NOERROR ? err : REG_ESPACE;
  8719. return err;
  8720. }
  8721. }
  8722. else
  8723. {
  8724. err = re_node_set_init_1 (&union_set, next_node);
  8725. if (BE (err != REG_NOERROR, 0))
  8726. return err;
  8727. }
  8728. mctx->state_log[to_idx] = re_acquire_state (&err, dfa, &union_set);
  8729. re_node_set_free (&union_set);
  8730. if (BE (mctx->state_log[to_idx] == NULL
  8731. && err != REG_NOERROR, 0))
  8732. return err;
  8733. }
  8734. }
  8735. while (ent++->more);
  8736. return REG_NOERROR;
  8737. }
  8738. /* Build transition table for the state.
  8739. Return 1 if succeeded, otherwise return NULL. */
  8740. static int
  8741. internal_function
  8742. build_trtable (const re_dfa_t *dfa, re_dfastate_t *state)
  8743. {
  8744. reg_errcode_t err;
  8745. int i, j, ch, need_word_trtable = 0;
  8746. bitset_word_t elem, mask;
  8747. bool dests_node_malloced = false;
  8748. bool dest_states_malloced = false;
  8749. int ndests; /* Number of the destination states from `state'. */
  8750. re_dfastate_t **trtable;
  8751. re_dfastate_t **dest_states = NULL, **dest_states_word, **dest_states_nl;
  8752. re_node_set follows, *dests_node;
  8753. bitset_t *dests_ch;
  8754. bitset_t acceptable;
  8755. struct dests_alloc
  8756. {
  8757. re_node_set dests_node[SBC_MAX];
  8758. bitset_t dests_ch[SBC_MAX];
  8759. } *dests_alloc;
  8760. /* We build DFA states which corresponds to the destination nodes
  8761. from `state'. `dests_node[i]' represents the nodes which i-th
  8762. destination state contains, and `dests_ch[i]' represents the
  8763. characters which i-th destination state accepts. */
  8764. if (__libc_use_alloca (sizeof (struct dests_alloc)))
  8765. dests_alloc = (struct dests_alloc *) alloca (sizeof (struct dests_alloc));
  8766. else
  8767. {
  8768. dests_alloc = re_malloc (struct dests_alloc, 1);
  8769. if (BE (dests_alloc == NULL, 0))
  8770. return 0;
  8771. dests_node_malloced = true;
  8772. }
  8773. dests_node = dests_alloc->dests_node;
  8774. dests_ch = dests_alloc->dests_ch;
  8775. /* Initialize transiton table. */
  8776. state->word_trtable = state->trtable = NULL;
  8777. /* At first, group all nodes belonging to `state' into several
  8778. destinations. */
  8779. ndests = group_nodes_into_DFAstates (dfa, state, dests_node, dests_ch);
  8780. if (BE (ndests <= 0, 0))
  8781. {
  8782. if (dests_node_malloced)
  8783. free (dests_alloc);
  8784. /* Return 0 in case of an error, 1 otherwise. */
  8785. if (ndests == 0)
  8786. {
  8787. state->trtable = (re_dfastate_t **)
  8788. calloc (sizeof (re_dfastate_t *), SBC_MAX);
  8789. return 1;
  8790. }
  8791. return 0;
  8792. }
  8793. err = re_node_set_alloc (&follows, ndests + 1);
  8794. if (BE (err != REG_NOERROR, 0))
  8795. goto out_free;
  8796. if (__libc_use_alloca ((sizeof (re_node_set) + sizeof (bitset_t)) * SBC_MAX
  8797. + ndests * 3 * sizeof (re_dfastate_t *)))
  8798. dest_states = (re_dfastate_t **)
  8799. alloca (ndests * 3 * sizeof (re_dfastate_t *));
  8800. else
  8801. {
  8802. dest_states = (re_dfastate_t **)
  8803. malloc (ndests * 3 * sizeof (re_dfastate_t *));
  8804. if (BE (dest_states == NULL, 0))
  8805. {
  8806. out_free:
  8807. if (dest_states_malloced)
  8808. free (dest_states);
  8809. re_node_set_free (&follows);
  8810. for (i = 0; i < ndests; ++i)
  8811. re_node_set_free (dests_node + i);
  8812. if (dests_node_malloced)
  8813. free (dests_alloc);
  8814. return 0;
  8815. }
  8816. dest_states_malloced = true;
  8817. }
  8818. dest_states_word = dest_states + ndests;
  8819. dest_states_nl = dest_states_word + ndests;
  8820. bitset_empty (acceptable);
  8821. /* Then build the states for all destinations. */
  8822. for (i = 0; i < ndests; ++i)
  8823. {
  8824. int next_node;
  8825. re_node_set_empty (&follows);
  8826. /* Merge the follows of this destination states. */
  8827. for (j = 0; j < dests_node[i].nelem; ++j)
  8828. {
  8829. next_node = dfa->nexts[dests_node[i].elems[j]];
  8830. if (next_node != -1)
  8831. {
  8832. err = re_node_set_merge (&follows, dfa->eclosures + next_node);
  8833. if (BE (err != REG_NOERROR, 0))
  8834. goto out_free;
  8835. }
  8836. }
  8837. dest_states[i] = re_acquire_state_context (&err, dfa, &follows, 0);
  8838. if (BE (dest_states[i] == NULL && err != REG_NOERROR, 0))
  8839. goto out_free;
  8840. /* If the new state has context constraint,
  8841. build appropriate states for these contexts. */
  8842. if (dest_states[i]->has_constraint)
  8843. {
  8844. dest_states_word[i] = re_acquire_state_context (&err, dfa, &follows,
  8845. CONTEXT_WORD);
  8846. if (BE (dest_states_word[i] == NULL && err != REG_NOERROR, 0))
  8847. goto out_free;
  8848. if (dest_states[i] != dest_states_word[i] && dfa->mb_cur_max > 1)
  8849. need_word_trtable = 1;
  8850. dest_states_nl[i] = re_acquire_state_context (&err, dfa, &follows,
  8851. CONTEXT_NEWLINE);
  8852. if (BE (dest_states_nl[i] == NULL && err != REG_NOERROR, 0))
  8853. goto out_free;
  8854. }
  8855. else
  8856. {
  8857. dest_states_word[i] = dest_states[i];
  8858. dest_states_nl[i] = dest_states[i];
  8859. }
  8860. bitset_merge (acceptable, dests_ch[i]);
  8861. }
  8862. if (!BE (need_word_trtable, 0))
  8863. {
  8864. /* We don't care about whether the following character is a word
  8865. character, or we are in a single-byte character set so we can
  8866. discern by looking at the character code: allocate a
  8867. 256-entry transition table. */
  8868. trtable = state->trtable =
  8869. (re_dfastate_t **) calloc (sizeof (re_dfastate_t *), SBC_MAX);
  8870. if (BE (trtable == NULL, 0))
  8871. goto out_free;
  8872. /* For all characters ch...: */
  8873. for (i = 0; i < BITSET_WORDS; ++i)
  8874. for (ch = i * BITSET_WORD_BITS, elem = acceptable[i], mask = 1;
  8875. elem;
  8876. mask <<= 1, elem >>= 1, ++ch)
  8877. if (BE (elem & 1, 0))
  8878. {
  8879. /* There must be exactly one destination which accepts
  8880. character ch. See group_nodes_into_DFAstates. */
  8881. for (j = 0; (dests_ch[j][i] & mask) == 0; ++j)
  8882. ;
  8883. /* j-th destination accepts the word character ch. */
  8884. if (dfa->word_char[i] & mask)
  8885. trtable[ch] = dest_states_word[j];
  8886. else
  8887. trtable[ch] = dest_states[j];
  8888. }
  8889. }
  8890. else
  8891. {
  8892. /* We care about whether the following character is a word
  8893. character, and we are in a multi-byte character set: discern
  8894. by looking at the character code: build two 256-entry
  8895. transition tables, one starting at trtable[0] and one
  8896. starting at trtable[SBC_MAX]. */
  8897. trtable = state->word_trtable =
  8898. (re_dfastate_t **) calloc (sizeof (re_dfastate_t *), 2 * SBC_MAX);
  8899. if (BE (trtable == NULL, 0))
  8900. goto out_free;
  8901. /* For all characters ch...: */
  8902. for (i = 0; i < BITSET_WORDS; ++i)
  8903. for (ch = i * BITSET_WORD_BITS, elem = acceptable[i], mask = 1;
  8904. elem;
  8905. mask <<= 1, elem >>= 1, ++ch)
  8906. if (BE (elem & 1, 0))
  8907. {
  8908. /* There must be exactly one destination which accepts
  8909. character ch. See group_nodes_into_DFAstates. */
  8910. for (j = 0; (dests_ch[j][i] & mask) == 0; ++j)
  8911. ;
  8912. /* j-th destination accepts the word character ch. */
  8913. trtable[ch] = dest_states[j];
  8914. trtable[ch + SBC_MAX] = dest_states_word[j];
  8915. }
  8916. }
  8917. /* new line */
  8918. if (bitset_contain (acceptable, NEWLINE_CHAR))
  8919. {
  8920. /* The current state accepts newline character. */
  8921. for (j = 0; j < ndests; ++j)
  8922. if (bitset_contain (dests_ch[j], NEWLINE_CHAR))
  8923. {
  8924. /* k-th destination accepts newline character. */
  8925. trtable[NEWLINE_CHAR] = dest_states_nl[j];
  8926. if (need_word_trtable)
  8927. trtable[NEWLINE_CHAR + SBC_MAX] = dest_states_nl[j];
  8928. /* There must be only one destination which accepts
  8929. newline. See group_nodes_into_DFAstates. */
  8930. break;
  8931. }
  8932. }
  8933. if (dest_states_malloced)
  8934. free (dest_states);
  8935. re_node_set_free (&follows);
  8936. for (i = 0; i < ndests; ++i)
  8937. re_node_set_free (dests_node + i);
  8938. if (dests_node_malloced)
  8939. free (dests_alloc);
  8940. return 1;
  8941. }
  8942. /* Group all nodes belonging to STATE into several destinations.
  8943. Then for all destinations, set the nodes belonging to the destination
  8944. to DESTS_NODE[i] and set the characters accepted by the destination
  8945. to DEST_CH[i]. This function return the number of destinations. */
  8946. static int
  8947. internal_function
  8948. group_nodes_into_DFAstates (const re_dfa_t *dfa, const re_dfastate_t *state,
  8949. re_node_set *dests_node, bitset_t *dests_ch)
  8950. {
  8951. reg_errcode_t err;
  8952. int result;
  8953. int i, j, k;
  8954. int ndests; /* Number of the destinations from `state'. */
  8955. bitset_t accepts; /* Characters a node can accept. */
  8956. const re_node_set *cur_nodes = &state->nodes;
  8957. bitset_empty (accepts);
  8958. ndests = 0;
  8959. /* For all the nodes belonging to `state', */
  8960. for (i = 0; i < cur_nodes->nelem; ++i)
  8961. {
  8962. re_token_t *node = &dfa->nodes[cur_nodes->elems[i]];
  8963. re_token_type_t type = node->type;
  8964. unsigned int constraint = node->constraint;
  8965. /* Enumerate all single byte character this node can accept. */
  8966. if (type == CHARACTER)
  8967. bitset_set (accepts, node->opr.c);
  8968. else if (type == SIMPLE_BRACKET)
  8969. {
  8970. bitset_merge (accepts, node->opr.sbcset);
  8971. }
  8972. else if (type == OP_PERIOD)
  8973. {
  8974. #ifdef RE_ENABLE_I18N
  8975. if (dfa->mb_cur_max > 1)
  8976. bitset_merge (accepts, dfa->sb_char);
  8977. else
  8978. #endif
  8979. bitset_set_all (accepts);
  8980. if (!(dfa->syntax & RE_DOT_NEWLINE))
  8981. bitset_clear (accepts, '\n');
  8982. if (dfa->syntax & RE_DOT_NOT_NULL)
  8983. bitset_clear (accepts, '\0');
  8984. }
  8985. #ifdef RE_ENABLE_I18N
  8986. else if (type == OP_UTF8_PERIOD)
  8987. {
  8988. memset (accepts, '\xff', sizeof (bitset_t) / 2);
  8989. if (!(dfa->syntax & RE_DOT_NEWLINE))
  8990. bitset_clear (accepts, '\n');
  8991. if (dfa->syntax & RE_DOT_NOT_NULL)
  8992. bitset_clear (accepts, '\0');
  8993. }
  8994. #endif
  8995. else
  8996. continue;
  8997. /* Check the `accepts' and sift the characters which are not
  8998. match it the context. */
  8999. if (constraint)
  9000. {
  9001. if (constraint & NEXT_NEWLINE_CONSTRAINT)
  9002. {
  9003. bool accepts_newline = bitset_contain (accepts, NEWLINE_CHAR);
  9004. bitset_empty (accepts);
  9005. if (accepts_newline)
  9006. bitset_set (accepts, NEWLINE_CHAR);
  9007. else
  9008. continue;
  9009. }
  9010. if (constraint & NEXT_ENDBUF_CONSTRAINT)
  9011. {
  9012. bitset_empty (accepts);
  9013. continue;
  9014. }
  9015. if (constraint & NEXT_WORD_CONSTRAINT)
  9016. {
  9017. bitset_word_t any_set = 0;
  9018. if (type == CHARACTER && !node->word_char)
  9019. {
  9020. bitset_empty (accepts);
  9021. continue;
  9022. }
  9023. #ifdef RE_ENABLE_I18N
  9024. if (dfa->mb_cur_max > 1)
  9025. for (j = 0; j < BITSET_WORDS; ++j)
  9026. any_set |= (accepts[j] &= (dfa->word_char[j] | ~dfa->sb_char[j]));
  9027. else
  9028. #endif
  9029. for (j = 0; j < BITSET_WORDS; ++j)
  9030. any_set |= (accepts[j] &= dfa->word_char[j]);
  9031. if (!any_set)
  9032. continue;
  9033. }
  9034. if (constraint & NEXT_NOTWORD_CONSTRAINT)
  9035. {
  9036. bitset_word_t any_set = 0;
  9037. if (type == CHARACTER && node->word_char)
  9038. {
  9039. bitset_empty (accepts);
  9040. continue;
  9041. }
  9042. #ifdef RE_ENABLE_I18N
  9043. if (dfa->mb_cur_max > 1)
  9044. for (j = 0; j < BITSET_WORDS; ++j)
  9045. any_set |= (accepts[j] &= ~(dfa->word_char[j] & dfa->sb_char[j]));
  9046. else
  9047. #endif
  9048. for (j = 0; j < BITSET_WORDS; ++j)
  9049. any_set |= (accepts[j] &= ~dfa->word_char[j]);
  9050. if (!any_set)
  9051. continue;
  9052. }
  9053. }
  9054. /* Then divide `accepts' into DFA states, or create a new
  9055. state. Above, we make sure that accepts is not empty. */
  9056. for (j = 0; j < ndests; ++j)
  9057. {
  9058. bitset_t intersec; /* Intersection sets, see below. */
  9059. bitset_t remains;
  9060. /* Flags, see below. */
  9061. bitset_word_t has_intersec, not_subset, not_consumed;
  9062. /* Optimization, skip if this state doesn't accept the character. */
  9063. if (type == CHARACTER && !bitset_contain (dests_ch[j], node->opr.c))
  9064. continue;
  9065. /* Enumerate the intersection set of this state and `accepts'. */
  9066. has_intersec = 0;
  9067. for (k = 0; k < BITSET_WORDS; ++k)
  9068. has_intersec |= intersec[k] = accepts[k] & dests_ch[j][k];
  9069. /* And skip if the intersection set is empty. */
  9070. if (!has_intersec)
  9071. continue;
  9072. /* Then check if this state is a subset of `accepts'. */
  9073. not_subset = not_consumed = 0;
  9074. for (k = 0; k < BITSET_WORDS; ++k)
  9075. {
  9076. not_subset |= remains[k] = ~accepts[k] & dests_ch[j][k];
  9077. not_consumed |= accepts[k] = accepts[k] & ~dests_ch[j][k];
  9078. }
  9079. /* If this state isn't a subset of `accepts', create a
  9080. new group state, which has the `remains'. */
  9081. if (not_subset)
  9082. {
  9083. bitset_copy (dests_ch[ndests], remains);
  9084. bitset_copy (dests_ch[j], intersec);
  9085. err = re_node_set_init_copy (dests_node + ndests, &dests_node[j]);
  9086. if (BE (err != REG_NOERROR, 0))
  9087. goto error_return;
  9088. ++ndests;
  9089. }
  9090. /* Put the position in the current group. */
  9091. result = re_node_set_insert (&dests_node[j], cur_nodes->elems[i]);
  9092. if (BE (result < 0, 0))
  9093. goto error_return;
  9094. /* If all characters are consumed, go to next node. */
  9095. if (!not_consumed)
  9096. break;
  9097. }
  9098. /* Some characters remain, create a new group. */
  9099. if (j == ndests)
  9100. {
  9101. bitset_copy (dests_ch[ndests], accepts);
  9102. err = re_node_set_init_1 (dests_node + ndests, cur_nodes->elems[i]);
  9103. if (BE (err != REG_NOERROR, 0))
  9104. goto error_return;
  9105. ++ndests;
  9106. bitset_empty (accepts);
  9107. }
  9108. }
  9109. return ndests;
  9110. error_return:
  9111. for (j = 0; j < ndests; ++j)
  9112. re_node_set_free (dests_node + j);
  9113. return -1;
  9114. }
  9115. #ifdef RE_ENABLE_I18N
  9116. /* Check how many bytes the node `dfa->nodes[node_idx]' accepts.
  9117. Return the number of the bytes the node accepts.
  9118. STR_IDX is the current index of the input string.
  9119. This function handles the nodes which can accept one character, or
  9120. one collating element like '.', '[a-z]', opposite to the other nodes
  9121. can only accept one byte. */
  9122. static int
  9123. internal_function
  9124. check_node_accept_bytes (const re_dfa_t *dfa, int node_idx,
  9125. const re_string_t *input, int str_idx)
  9126. {
  9127. const re_token_t *node = dfa->nodes + node_idx;
  9128. int char_len, elem_len;
  9129. int i;
  9130. if (BE (node->type == OP_UTF8_PERIOD, 0))
  9131. {
  9132. unsigned char c = re_string_byte_at (input, str_idx), d;
  9133. if (BE (c < 0xc2, 1))
  9134. return 0;
  9135. if (str_idx + 2 > input->len)
  9136. return 0;
  9137. d = re_string_byte_at (input, str_idx + 1);
  9138. if (c < 0xe0)
  9139. return (d < 0x80 || d > 0xbf) ? 0 : 2;
  9140. else if (c < 0xf0)
  9141. {
  9142. char_len = 3;
  9143. if (c == 0xe0 && d < 0xa0)
  9144. return 0;
  9145. }
  9146. else if (c < 0xf8)
  9147. {
  9148. char_len = 4;
  9149. if (c == 0xf0 && d < 0x90)
  9150. return 0;
  9151. }
  9152. else if (c < 0xfc)
  9153. {
  9154. char_len = 5;
  9155. if (c == 0xf8 && d < 0x88)
  9156. return 0;
  9157. }
  9158. else if (c < 0xfe)
  9159. {
  9160. char_len = 6;
  9161. if (c == 0xfc && d < 0x84)
  9162. return 0;
  9163. }
  9164. else
  9165. return 0;
  9166. if (str_idx + char_len > input->len)
  9167. return 0;
  9168. for (i = 1; i < char_len; ++i)
  9169. {
  9170. d = re_string_byte_at (input, str_idx + i);
  9171. if (d < 0x80 || d > 0xbf)
  9172. return 0;
  9173. }
  9174. return char_len;
  9175. }
  9176. char_len = re_string_char_size_at (input, str_idx);
  9177. if (node->type == OP_PERIOD)
  9178. {
  9179. if (char_len <= 1)
  9180. return 0;
  9181. /* FIXME: I don't think this if is needed, as both '\n'
  9182. and '\0' are char_len == 1. */
  9183. /* '.' accepts any one character except the following two cases. */
  9184. if ((!(dfa->syntax & RE_DOT_NEWLINE) &&
  9185. re_string_byte_at (input, str_idx) == '\n') ||
  9186. ((dfa->syntax & RE_DOT_NOT_NULL) &&
  9187. re_string_byte_at (input, str_idx) == '\0'))
  9188. return 0;
  9189. return char_len;
  9190. }
  9191. elem_len = re_string_elem_size_at (input, str_idx);
  9192. if ((elem_len <= 1 && char_len <= 1) || char_len == 0)
  9193. return 0;
  9194. if (node->type == COMPLEX_BRACKET)
  9195. {
  9196. const re_charset_t *cset = node->opr.mbcset;
  9197. # ifdef _LIBC
  9198. const unsigned char *pin
  9199. = ((const unsigned char *) re_string_get_buffer (input) + str_idx);
  9200. int j;
  9201. uint32_t nrules;
  9202. # endif /* _LIBC */
  9203. int match_len = 0;
  9204. wchar_t wc = ((cset->nranges || cset->nchar_classes || cset->nmbchars)
  9205. ? re_string_wchar_at (input, str_idx) : 0);
  9206. /* match with multibyte character? */
  9207. for (i = 0; i < cset->nmbchars; ++i)
  9208. if (wc == cset->mbchars[i])
  9209. {
  9210. match_len = char_len;
  9211. goto check_node_accept_bytes_match;
  9212. }
  9213. /* match with character_class? */
  9214. for (i = 0; i < cset->nchar_classes; ++i)
  9215. {
  9216. wctype_t wt = cset->char_classes[i];
  9217. if (__iswctype (wc, wt))
  9218. {
  9219. match_len = char_len;
  9220. goto check_node_accept_bytes_match;
  9221. }
  9222. }
  9223. # ifdef _LIBC
  9224. nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
  9225. if (nrules != 0)
  9226. {
  9227. unsigned int in_collseq = 0;
  9228. const int32_t *table, *indirect;
  9229. const unsigned char *weights, *extra;
  9230. const char *collseqwc;
  9231. /* This #include defines a local function! */
  9232. # include <locale/weight.h>
  9233. /* match with collating_symbol? */
  9234. if (cset->ncoll_syms)
  9235. extra = (const unsigned char *)
  9236. _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
  9237. for (i = 0; i < cset->ncoll_syms; ++i)
  9238. {
  9239. const unsigned char *coll_sym = extra + cset->coll_syms[i];
  9240. /* Compare the length of input collating element and
  9241. the length of current collating element. */
  9242. if (*coll_sym != elem_len)
  9243. continue;
  9244. /* Compare each bytes. */
  9245. for (j = 0; j < *coll_sym; j++)
  9246. if (pin[j] != coll_sym[1 + j])
  9247. break;
  9248. if (j == *coll_sym)
  9249. {
  9250. /* Match if every bytes is equal. */
  9251. match_len = j;
  9252. goto check_node_accept_bytes_match;
  9253. }
  9254. }
  9255. if (cset->nranges)
  9256. {
  9257. if (elem_len <= char_len)
  9258. {
  9259. collseqwc = _NL_CURRENT (LC_COLLATE, _NL_COLLATE_COLLSEQWC);
  9260. in_collseq = __collseq_table_lookup (collseqwc, wc);
  9261. }
  9262. else
  9263. in_collseq = find_collation_sequence_value (pin, elem_len);
  9264. }
  9265. /* match with range expression? */
  9266. for (i = 0; i < cset->nranges; ++i)
  9267. if (cset->range_starts[i] <= in_collseq
  9268. && in_collseq <= cset->range_ends[i])
  9269. {
  9270. match_len = elem_len;
  9271. goto check_node_accept_bytes_match;
  9272. }
  9273. /* match with equivalence_class? */
  9274. if (cset->nequiv_classes)
  9275. {
  9276. const unsigned char *cp = pin;
  9277. table = (const int32_t *)
  9278. _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
  9279. weights = (const unsigned char *)
  9280. _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB);
  9281. extra = (const unsigned char *)
  9282. _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
  9283. indirect = (const int32_t *)
  9284. _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB);
  9285. int32_t idx = findidx (&cp);
  9286. if (idx > 0)
  9287. for (i = 0; i < cset->nequiv_classes; ++i)
  9288. {
  9289. int32_t equiv_class_idx = cset->equiv_classes[i];
  9290. size_t weight_len = weights[idx & 0xffffff];
  9291. if (weight_len == weights[equiv_class_idx & 0xffffff]
  9292. && (idx >> 24) == (equiv_class_idx >> 24))
  9293. {
  9294. int cnt = 0;
  9295. idx &= 0xffffff;
  9296. equiv_class_idx &= 0xffffff;
  9297. while (cnt <= weight_len
  9298. && (weights[equiv_class_idx + 1 + cnt]
  9299. == weights[idx + 1 + cnt]))
  9300. ++cnt;
  9301. if (cnt > weight_len)
  9302. {
  9303. match_len = elem_len;
  9304. goto check_node_accept_bytes_match;
  9305. }
  9306. }
  9307. }
  9308. }
  9309. }
  9310. else
  9311. # endif /* _LIBC */
  9312. {
  9313. /* match with range expression? */
  9314. #if __GNUC__ >= 2
  9315. wchar_t cmp_buf[] = {L'\0', L'\0', wc, L'\0', L'\0', L'\0'};
  9316. #else
  9317. wchar_t cmp_buf[] = {L'\0', L'\0', L'\0', L'\0', L'\0', L'\0'};
  9318. cmp_buf[2] = wc;
  9319. #endif
  9320. for (i = 0; i < cset->nranges; ++i)
  9321. {
  9322. cmp_buf[0] = cset->range_starts[i];
  9323. cmp_buf[4] = cset->range_ends[i];
  9324. if (wcscoll (cmp_buf, cmp_buf + 2) <= 0
  9325. && wcscoll (cmp_buf + 2, cmp_buf + 4) <= 0)
  9326. {
  9327. match_len = char_len;
  9328. goto check_node_accept_bytes_match;
  9329. }
  9330. }
  9331. }
  9332. check_node_accept_bytes_match:
  9333. if (!cset->non_match)
  9334. return match_len;
  9335. else
  9336. {
  9337. if (match_len > 0)
  9338. return 0;
  9339. else
  9340. return (elem_len > char_len) ? elem_len : char_len;
  9341. }
  9342. }
  9343. return 0;
  9344. }
  9345. # ifdef _LIBC
  9346. static unsigned int
  9347. internal_function
  9348. find_collation_sequence_value (const unsigned char *mbs, size_t mbs_len)
  9349. {
  9350. uint32_t nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
  9351. if (nrules == 0)
  9352. {
  9353. if (mbs_len == 1)
  9354. {
  9355. /* No valid character. Match it as a single byte character. */
  9356. const unsigned char *collseq = (const unsigned char *)
  9357. _NL_CURRENT (LC_COLLATE, _NL_COLLATE_COLLSEQMB);
  9358. return collseq[mbs[0]];
  9359. }
  9360. return UINT_MAX;
  9361. }
  9362. else
  9363. {
  9364. int32_t idx;
  9365. const unsigned char *extra = (const unsigned char *)
  9366. _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
  9367. int32_t extrasize = (const unsigned char *)
  9368. _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB + 1) - extra;
  9369. for (idx = 0; idx < extrasize;)
  9370. {
  9371. int mbs_cnt, found = 0;
  9372. int32_t elem_mbs_len;
  9373. /* Skip the name of collating element name. */
  9374. idx = idx + extra[idx] + 1;
  9375. elem_mbs_len = extra[idx++];
  9376. if (mbs_len == elem_mbs_len)
  9377. {
  9378. for (mbs_cnt = 0; mbs_cnt < elem_mbs_len; ++mbs_cnt)
  9379. if (extra[idx + mbs_cnt] != mbs[mbs_cnt])
  9380. break;
  9381. if (mbs_cnt == elem_mbs_len)
  9382. /* Found the entry. */
  9383. found = 1;
  9384. }
  9385. /* Skip the byte sequence of the collating element. */
  9386. idx += elem_mbs_len;
  9387. /* Adjust for the alignment. */
  9388. idx = (idx + 3) & ~3;
  9389. /* Skip the collation sequence value. */
  9390. idx += sizeof (uint32_t);
  9391. /* Skip the wide char sequence of the collating element. */
  9392. idx = idx + sizeof (uint32_t) * (extra[idx] + 1);
  9393. /* If we found the entry, return the sequence value. */
  9394. if (found)
  9395. return *(uint32_t *) (extra + idx);
  9396. /* Skip the collation sequence value. */
  9397. idx += sizeof (uint32_t);
  9398. }
  9399. return UINT_MAX;
  9400. }
  9401. }
  9402. # endif /* _LIBC */
  9403. #endif /* RE_ENABLE_I18N */
  9404. /* Check whether the node accepts the byte which is IDX-th
  9405. byte of the INPUT. */
  9406. static int
  9407. internal_function
  9408. check_node_accept (const re_match_context_t *mctx, const re_token_t *node,
  9409. int idx)
  9410. {
  9411. unsigned char ch;
  9412. ch = re_string_byte_at (&mctx->input, idx);
  9413. switch (node->type)
  9414. {
  9415. case CHARACTER:
  9416. if (node->opr.c != ch)
  9417. return 0;
  9418. break;
  9419. case SIMPLE_BRACKET:
  9420. if (!bitset_contain (node->opr.sbcset, ch))
  9421. return 0;
  9422. break;
  9423. #ifdef RE_ENABLE_I18N
  9424. case OP_UTF8_PERIOD:
  9425. if (ch >= 0x80)
  9426. return 0;
  9427. /* FALLTHROUGH */
  9428. #endif
  9429. case OP_PERIOD:
  9430. if ((ch == '\n' && !(mctx->dfa->syntax & RE_DOT_NEWLINE))
  9431. || (ch == '\0' && (mctx->dfa->syntax & RE_DOT_NOT_NULL)))
  9432. return 0;
  9433. break;
  9434. default:
  9435. return 0;
  9436. }
  9437. if (node->constraint)
  9438. {
  9439. /* The node has constraints. Check whether the current context
  9440. satisfies the constraints. */
  9441. unsigned int context = re_string_context_at (&mctx->input, idx,
  9442. mctx->eflags);
  9443. if (NOT_SATISFY_NEXT_CONSTRAINT (node->constraint, context))
  9444. return 0;
  9445. }
  9446. return 1;
  9447. }
  9448. /* Extend the buffers, if the buffers have run out. */
  9449. static reg_errcode_t
  9450. internal_function
  9451. extend_buffers (re_match_context_t *mctx)
  9452. {
  9453. reg_errcode_t ret;
  9454. re_string_t *pstr = &mctx->input;
  9455. /* Double the lengthes of the buffers. */
  9456. ret = re_string_realloc_buffers (pstr, pstr->bufs_len * 2);
  9457. if (BE (ret != REG_NOERROR, 0))
  9458. return ret;
  9459. if (mctx->state_log != NULL)
  9460. {
  9461. /* And double the length of state_log. */
  9462. /* XXX We have no indication of the size of this buffer. If this
  9463. allocation fail we have no indication that the state_log array
  9464. does not have the right size. */
  9465. re_dfastate_t **new_array = re_realloc (mctx->state_log, re_dfastate_t *,
  9466. pstr->bufs_len + 1);
  9467. if (BE (new_array == NULL, 0))
  9468. return REG_ESPACE;
  9469. mctx->state_log = new_array;
  9470. }
  9471. /* Then reconstruct the buffers. */
  9472. if (pstr->icase)
  9473. {
  9474. #ifdef RE_ENABLE_I18N
  9475. if (pstr->mb_cur_max > 1)
  9476. {
  9477. ret = build_wcs_upper_buffer (pstr);
  9478. if (BE (ret != REG_NOERROR, 0))
  9479. return ret;
  9480. }
  9481. else
  9482. #endif /* RE_ENABLE_I18N */
  9483. build_upper_buffer (pstr);
  9484. }
  9485. else
  9486. {
  9487. #ifdef RE_ENABLE_I18N
  9488. if (pstr->mb_cur_max > 1)
  9489. build_wcs_buffer (pstr);
  9490. else
  9491. #endif /* RE_ENABLE_I18N */
  9492. {
  9493. if (pstr->trans != NULL)
  9494. re_string_translate_buffer (pstr);
  9495. }
  9496. }
  9497. return REG_NOERROR;
  9498. }
  9499. /* Functions for matching context. */
  9500. /* Initialize MCTX. */
  9501. static reg_errcode_t
  9502. internal_function
  9503. match_ctx_init (re_match_context_t *mctx, int eflags, int n)
  9504. {
  9505. mctx->eflags = eflags;
  9506. mctx->match_last = -1;
  9507. if (n > 0)
  9508. {
  9509. mctx->bkref_ents = re_malloc (struct re_backref_cache_entry, n);
  9510. mctx->sub_tops = re_malloc (re_sub_match_top_t *, n);
  9511. if (BE (mctx->bkref_ents == NULL || mctx->sub_tops == NULL, 0))
  9512. return REG_ESPACE;
  9513. }
  9514. /* Already zero-ed by the caller.
  9515. else
  9516. mctx->bkref_ents = NULL;
  9517. mctx->nbkref_ents = 0;
  9518. mctx->nsub_tops = 0; */
  9519. mctx->abkref_ents = n;
  9520. mctx->max_mb_elem_len = 1;
  9521. mctx->asub_tops = n;
  9522. return REG_NOERROR;
  9523. }
  9524. /* Clean the entries which depend on the current input in MCTX.
  9525. This function must be invoked when the matcher changes the start index
  9526. of the input, or changes the input string. */
  9527. static void
  9528. internal_function
  9529. match_ctx_clean (re_match_context_t *mctx)
  9530. {
  9531. int st_idx;
  9532. for (st_idx = 0; st_idx < mctx->nsub_tops; ++st_idx)
  9533. {
  9534. int sl_idx;
  9535. re_sub_match_top_t *top = mctx->sub_tops[st_idx];
  9536. for (sl_idx = 0; sl_idx < top->nlasts; ++sl_idx)
  9537. {
  9538. re_sub_match_last_t *last = top->lasts[sl_idx];
  9539. re_free (last->path.array);
  9540. re_free (last);
  9541. }
  9542. re_free (top->lasts);
  9543. if (top->path)
  9544. {
  9545. re_free (top->path->array);
  9546. re_free (top->path);
  9547. }
  9548. free (top);
  9549. }
  9550. mctx->nsub_tops = 0;
  9551. mctx->nbkref_ents = 0;
  9552. }
  9553. /* Free all the memory associated with MCTX. */
  9554. static void
  9555. internal_function
  9556. match_ctx_free (re_match_context_t *mctx)
  9557. {
  9558. /* First, free all the memory associated with MCTX->SUB_TOPS. */
  9559. match_ctx_clean (mctx);
  9560. re_free (mctx->sub_tops);
  9561. re_free (mctx->bkref_ents);
  9562. }
  9563. /* Add a new backreference entry to MCTX.
  9564. Note that we assume that caller never call this function with duplicate
  9565. entry, and call with STR_IDX which isn't smaller than any existing entry.
  9566. */
  9567. static reg_errcode_t
  9568. internal_function
  9569. match_ctx_add_entry (re_match_context_t *mctx, int node, int str_idx, int from,
  9570. int to)
  9571. {
  9572. if (mctx->nbkref_ents >= mctx->abkref_ents)
  9573. {
  9574. struct re_backref_cache_entry* new_entry;
  9575. new_entry = re_realloc (mctx->bkref_ents, struct re_backref_cache_entry,
  9576. mctx->abkref_ents * 2);
  9577. if (BE (new_entry == NULL, 0))
  9578. {
  9579. re_free (mctx->bkref_ents);
  9580. return REG_ESPACE;
  9581. }
  9582. mctx->bkref_ents = new_entry;
  9583. memset (mctx->bkref_ents + mctx->nbkref_ents, '\0',
  9584. sizeof (struct re_backref_cache_entry) * mctx->abkref_ents);
  9585. mctx->abkref_ents *= 2;
  9586. }
  9587. if (mctx->nbkref_ents > 0
  9588. && mctx->bkref_ents[mctx->nbkref_ents - 1].str_idx == str_idx)
  9589. mctx->bkref_ents[mctx->nbkref_ents - 1].more = 1;
  9590. mctx->bkref_ents[mctx->nbkref_ents].node = node;
  9591. mctx->bkref_ents[mctx->nbkref_ents].str_idx = str_idx;
  9592. mctx->bkref_ents[mctx->nbkref_ents].subexp_from = from;
  9593. mctx->bkref_ents[mctx->nbkref_ents].subexp_to = to;
  9594. /* This is a cache that saves negative results of check_dst_limits_calc_pos.
  9595. If bit N is clear, means that this entry won't epsilon-transition to
  9596. an OP_OPEN_SUBEXP or OP_CLOSE_SUBEXP for the N+1-th subexpression. If
  9597. it is set, check_dst_limits_calc_pos_1 will recurse and try to find one
  9598. such node.
  9599. A backreference does not epsilon-transition unless it is empty, so set
  9600. to all zeros if FROM != TO. */
  9601. mctx->bkref_ents[mctx->nbkref_ents].eps_reachable_subexps_map
  9602. = (from == to ? ~0 : 0);
  9603. mctx->bkref_ents[mctx->nbkref_ents++].more = 0;
  9604. if (mctx->max_mb_elem_len < to - from)
  9605. mctx->max_mb_elem_len = to - from;
  9606. return REG_NOERROR;
  9607. }
  9608. /* Search for the first entry which has the same str_idx, or -1 if none is
  9609. found. Note that MCTX->BKREF_ENTS is already sorted by MCTX->STR_IDX. */
  9610. static int
  9611. internal_function
  9612. search_cur_bkref_entry (const re_match_context_t *mctx, int str_idx)
  9613. {
  9614. int left, right, mid, last;
  9615. last = right = mctx->nbkref_ents;
  9616. for (left = 0; left < right;)
  9617. {
  9618. mid = (left + right) / 2;
  9619. if (mctx->bkref_ents[mid].str_idx < str_idx)
  9620. left = mid + 1;
  9621. else
  9622. right = mid;
  9623. }
  9624. if (left < last && mctx->bkref_ents[left].str_idx == str_idx)
  9625. return left;
  9626. else
  9627. return -1;
  9628. }
  9629. /* Register the node NODE, whose type is OP_OPEN_SUBEXP, and which matches
  9630. at STR_IDX. */
  9631. static reg_errcode_t
  9632. internal_function
  9633. match_ctx_add_subtop (re_match_context_t *mctx, int node, int str_idx)
  9634. {
  9635. #ifdef DEBUG
  9636. assert (mctx->sub_tops != NULL);
  9637. assert (mctx->asub_tops > 0);
  9638. #endif
  9639. if (BE (mctx->nsub_tops == mctx->asub_tops, 0))
  9640. {
  9641. int new_asub_tops = mctx->asub_tops * 2;
  9642. re_sub_match_top_t **new_array = re_realloc (mctx->sub_tops,
  9643. re_sub_match_top_t *,
  9644. new_asub_tops);
  9645. if (BE (new_array == NULL, 0))
  9646. return REG_ESPACE;
  9647. mctx->sub_tops = new_array;
  9648. mctx->asub_tops = new_asub_tops;
  9649. }
  9650. mctx->sub_tops[mctx->nsub_tops] = calloc (1, sizeof (re_sub_match_top_t));
  9651. if (BE (mctx->sub_tops[mctx->nsub_tops] == NULL, 0))
  9652. return REG_ESPACE;
  9653. mctx->sub_tops[mctx->nsub_tops]->node = node;
  9654. mctx->sub_tops[mctx->nsub_tops++]->str_idx = str_idx;
  9655. return REG_NOERROR;
  9656. }
  9657. /* Register the node NODE, whose type is OP_CLOSE_SUBEXP, and which matches
  9658. at STR_IDX, whose corresponding OP_OPEN_SUBEXP is SUB_TOP. */
  9659. static re_sub_match_last_t *
  9660. internal_function
  9661. match_ctx_add_sublast (re_sub_match_top_t *subtop, int node, int str_idx)
  9662. {
  9663. re_sub_match_last_t *new_entry;
  9664. if (BE (subtop->nlasts == subtop->alasts, 0))
  9665. {
  9666. int new_alasts = 2 * subtop->alasts + 1;
  9667. re_sub_match_last_t **new_array = re_realloc (subtop->lasts,
  9668. re_sub_match_last_t *,
  9669. new_alasts);
  9670. if (BE (new_array == NULL, 0))
  9671. return NULL;
  9672. subtop->lasts = new_array;
  9673. subtop->alasts = new_alasts;
  9674. }
  9675. new_entry = calloc (1, sizeof (re_sub_match_last_t));
  9676. if (BE (new_entry != NULL, 1))
  9677. {
  9678. subtop->lasts[subtop->nlasts] = new_entry;
  9679. new_entry->node = node;
  9680. new_entry->str_idx = str_idx;
  9681. ++subtop->nlasts;
  9682. }
  9683. return new_entry;
  9684. }
  9685. static void
  9686. internal_function
  9687. sift_ctx_init (re_sift_context_t *sctx, re_dfastate_t **sifted_sts,
  9688. re_dfastate_t **limited_sts, int last_node, int last_str_idx)
  9689. {
  9690. sctx->sifted_states = sifted_sts;
  9691. sctx->limited_states = limited_sts;
  9692. sctx->last_node = last_node;
  9693. sctx->last_str_idx = last_str_idx;
  9694. re_node_set_init_empty (&sctx->limits);
  9695. }
  9696. /* Binary backward compatibility. */
  9697. #if _LIBC
  9698. # include <shlib-compat.h>
  9699. # if SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_3)
  9700. link_warning (re_max_failures, "the 're_max_failures' variable is obsolete and will go away.")
  9701. int re_max_failures = 2000;
  9702. # endif
  9703. #endif