1 /* Extended regular expression matching and search library.
2 Copyright (C) 2002-2012 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Isamu Hasegawa <isamu@yamato.ibm.com>.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License along
17 with this program; if not, see <http://www.gnu.org/licenses/>. */
21 static reg_errcode_t match_ctx_init (re_match_context_t *cache, int eflags,
22 Idx n) internal_function;
23 static void match_ctx_clean (re_match_context_t *mctx) internal_function;
24 static void match_ctx_free (re_match_context_t *cache) internal_function;
25 static reg_errcode_t match_ctx_add_entry (re_match_context_t *cache, Idx node,
26 Idx str_idx, Idx from, Idx to)
28 static Idx search_cur_bkref_entry (const re_match_context_t *mctx, Idx str_idx)
30 static reg_errcode_t match_ctx_add_subtop (re_match_context_t *mctx, Idx node,
31 Idx str_idx) internal_function;
32 static re_sub_match_last_t * match_ctx_add_sublast (re_sub_match_top_t *subtop,
33 Idx node, Idx str_idx)
35 static void sift_ctx_init (re_sift_context_t *sctx, re_dfastate_t **sifted_sts,
36 re_dfastate_t **limited_sts, Idx last_node,
39 static reg_errcode_t re_search_internal (const regex_t *preg,
40 const char *string, Idx length,
41 Idx start, Idx last_start, Idx stop,
42 size_t nmatch, regmatch_t pmatch[],
43 int eflags) internal_function;
44 static regoff_t re_search_2_stub (struct re_pattern_buffer *bufp,
45 const char *string1, Idx length1,
46 const char *string2, Idx length2,
47 Idx start, regoff_t range,
48 struct re_registers *regs,
49 Idx stop, bool ret_len) internal_function;
50 static regoff_t re_search_stub (struct re_pattern_buffer *bufp,
51 const char *string, Idx length, Idx start,
52 regoff_t range, Idx stop,
53 struct re_registers *regs,
54 bool ret_len) internal_function;
55 static unsigned re_copy_regs (struct re_registers *regs, regmatch_t *pmatch,
56 Idx nregs, int regs_allocated) internal_function;
57 static reg_errcode_t prune_impossible_nodes (re_match_context_t *mctx)
59 static Idx check_matching (re_match_context_t *mctx, bool fl_longest_match,
60 Idx *p_match_first) internal_function;
61 static Idx check_halt_state_context (const re_match_context_t *mctx,
62 const re_dfastate_t *state, Idx idx)
64 static void update_regs (const re_dfa_t *dfa, regmatch_t *pmatch,
65 regmatch_t *prev_idx_match, Idx cur_node,
66 Idx cur_idx, Idx nmatch) internal_function;
67 static reg_errcode_t push_fail_stack (struct re_fail_stack_t *fs,
68 Idx str_idx, Idx dest_node, Idx nregs,
70 re_node_set *eps_via_nodes)
72 static reg_errcode_t set_regs (const regex_t *preg,
73 const re_match_context_t *mctx,
74 size_t nmatch, regmatch_t *pmatch,
75 bool fl_backtrack) internal_function;
76 static reg_errcode_t free_fail_stack_return (struct re_fail_stack_t *fs)
80 static int sift_states_iter_mb (const re_match_context_t *mctx,
81 re_sift_context_t *sctx,
82 Idx node_idx, Idx str_idx, Idx max_str_idx)
84 #endif /* RE_ENABLE_I18N */
85 static reg_errcode_t sift_states_backward (const re_match_context_t *mctx,
86 re_sift_context_t *sctx)
88 static reg_errcode_t build_sifted_states (const re_match_context_t *mctx,
89 re_sift_context_t *sctx, Idx str_idx,
90 re_node_set *cur_dest)
92 static reg_errcode_t update_cur_sifted_state (const re_match_context_t *mctx,
93 re_sift_context_t *sctx,
95 re_node_set *dest_nodes)
97 static reg_errcode_t add_epsilon_src_nodes (const re_dfa_t *dfa,
98 re_node_set *dest_nodes,
99 const re_node_set *candidates)
101 static bool check_dst_limits (const re_match_context_t *mctx,
102 const re_node_set *limits,
103 Idx dst_node, Idx dst_idx, Idx src_node,
104 Idx src_idx) internal_function;
105 static int check_dst_limits_calc_pos_1 (const re_match_context_t *mctx,
106 int boundaries, Idx subexp_idx,
107 Idx from_node, Idx bkref_idx)
109 static int check_dst_limits_calc_pos (const re_match_context_t *mctx,
110 Idx limit, Idx subexp_idx,
111 Idx node, Idx str_idx,
112 Idx bkref_idx) internal_function;
113 static reg_errcode_t check_subexp_limits (const re_dfa_t *dfa,
114 re_node_set *dest_nodes,
115 const re_node_set *candidates,
117 struct re_backref_cache_entry *bkref_ents,
118 Idx str_idx) internal_function;
119 static reg_errcode_t sift_states_bkref (const re_match_context_t *mctx,
120 re_sift_context_t *sctx,
121 Idx str_idx, const re_node_set *candidates)
123 static reg_errcode_t merge_state_array (const re_dfa_t *dfa,
125 re_dfastate_t **src, Idx num)
127 static re_dfastate_t *find_recover_state (reg_errcode_t *err,
128 re_match_context_t *mctx) internal_function;
129 static re_dfastate_t *transit_state (reg_errcode_t *err,
130 re_match_context_t *mctx,
131 re_dfastate_t *state) internal_function;
132 static re_dfastate_t *merge_state_with_log (reg_errcode_t *err,
133 re_match_context_t *mctx,
134 re_dfastate_t *next_state)
136 static reg_errcode_t check_subexp_matching_top (re_match_context_t *mctx,
137 re_node_set *cur_nodes,
138 Idx str_idx) internal_function;
140 static re_dfastate_t *transit_state_sb (reg_errcode_t *err,
141 re_match_context_t *mctx,
142 re_dfastate_t *pstate)
145 #ifdef RE_ENABLE_I18N
146 static reg_errcode_t transit_state_mb (re_match_context_t *mctx,
147 re_dfastate_t *pstate)
149 #endif /* RE_ENABLE_I18N */
150 static reg_errcode_t transit_state_bkref (re_match_context_t *mctx,
151 const re_node_set *nodes)
153 static reg_errcode_t get_subexp (re_match_context_t *mctx,
154 Idx bkref_node, Idx bkref_str_idx)
156 static reg_errcode_t get_subexp_sub (re_match_context_t *mctx,
157 const re_sub_match_top_t *sub_top,
158 re_sub_match_last_t *sub_last,
159 Idx bkref_node, Idx bkref_str)
161 static Idx find_subexp_node (const re_dfa_t *dfa, const re_node_set *nodes,
162 Idx subexp_idx, int type) internal_function;
163 static reg_errcode_t check_arrival (re_match_context_t *mctx,
164 state_array_t *path, Idx top_node,
165 Idx top_str, Idx last_node, Idx last_str,
166 int type) internal_function;
167 static reg_errcode_t check_arrival_add_next_nodes (re_match_context_t *mctx,
169 re_node_set *cur_nodes,
170 re_node_set *next_nodes)
172 static reg_errcode_t check_arrival_expand_ecl (const re_dfa_t *dfa,
173 re_node_set *cur_nodes,
174 Idx ex_subexp, int type)
176 static reg_errcode_t check_arrival_expand_ecl_sub (const re_dfa_t *dfa,
177 re_node_set *dst_nodes,
178 Idx target, Idx ex_subexp,
179 int type) internal_function;
180 static reg_errcode_t expand_bkref_cache (re_match_context_t *mctx,
181 re_node_set *cur_nodes, Idx cur_str,
182 Idx subexp_num, int type)
184 static bool build_trtable (const re_dfa_t *dfa,
185 re_dfastate_t *state) internal_function;
186 #ifdef RE_ENABLE_I18N
187 static int check_node_accept_bytes (const re_dfa_t *dfa, Idx node_idx,
188 const re_string_t *input, Idx idx)
191 static unsigned int find_collation_sequence_value (const unsigned char *mbs,
195 #endif /* RE_ENABLE_I18N */
196 static Idx group_nodes_into_DFAstates (const re_dfa_t *dfa,
197 const re_dfastate_t *state,
198 re_node_set *states_node,
199 bitset_t *states_ch) internal_function;
200 static bool check_node_accept (const re_match_context_t *mctx,
201 const re_token_t *node, Idx idx)
203 static reg_errcode_t extend_buffers (re_match_context_t *mctx)
206 /* Entry point for POSIX code. */
208 /* regexec searches for a given pattern, specified by PREG, in the
211 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
212 'regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
213 least NMATCH elements, and we set them to the offsets of the
214 corresponding matched substrings.
216 EFLAGS specifies "execution flags" which affect matching: if
217 REG_NOTBOL is set, then ^ does not match at the beginning of the
218 string; if REG_NOTEOL is set, then $ does not match at the end.
220 We return 0 if we find a match and REG_NOMATCH if not. */
223 regexec (preg, string, nmatch, pmatch, eflags)
224 const regex_t *_Restrict_ preg;
225 const char *_Restrict_ string;
227 regmatch_t pmatch[_Restrict_arr_];
233 re_dfa_t *dfa = preg->buffer;
236 if (eflags & ~(REG_NOTBOL | REG_NOTEOL | REG_STARTEND))
239 if (eflags & REG_STARTEND)
241 start = pmatch[0].rm_so;
242 length = pmatch[0].rm_eo;
247 length = strlen (string);
250 __libc_lock_lock (dfa->lock);
252 err = re_search_internal (preg, string, length, start, length,
253 length, 0, NULL, eflags);
255 err = re_search_internal (preg, string, length, start, length,
256 length, nmatch, pmatch, eflags);
257 __libc_lock_unlock (dfa->lock);
258 return err != REG_NOERROR;
262 # include <shlib-compat.h>
263 versioned_symbol (libc, __regexec, regexec, GLIBC_2_3_4);
265 # if SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_3_4)
266 __typeof__ (__regexec) __compat_regexec;
269 attribute_compat_text_section
270 __compat_regexec (const regex_t *_Restrict_ preg,
271 const char *_Restrict_ string, size_t nmatch,
272 regmatch_t pmatch[], int eflags)
274 return regexec (preg, string, nmatch, pmatch,
275 eflags & (REG_NOTBOL | REG_NOTEOL));
277 compat_symbol (libc, __compat_regexec, regexec, GLIBC_2_0);
281 /* Entry points for GNU code. */
283 /* re_match, re_search, re_match_2, re_search_2
285 The former two functions operate on STRING with length LENGTH,
286 while the later two operate on concatenation of STRING1 and STRING2
287 with lengths LENGTH1 and LENGTH2, respectively.
289 re_match() matches the compiled pattern in BUFP against the string,
290 starting at index START.
292 re_search() first tries matching at index START, then it tries to match
293 starting from index START + 1, and so on. The last start position tried
294 is START + RANGE. (Thus RANGE = 0 forces re_search to operate the same
297 The parameter STOP of re_{match,search}_2 specifies that no match exceeding
298 the first STOP characters of the concatenation of the strings should be
301 If REGS is not NULL, and BUFP->no_sub is not set, the offsets of the match
302 and all groups is stored in REGS. (For the "_2" variants, the offsets are
303 computed relative to the concatenation, not relative to the individual
306 On success, re_match* functions return the length of the match, re_search*
307 return the position of the start of the match. Return value -1 means no
308 match was found and -2 indicates an internal error. */
311 re_match (bufp, string, length, start, regs)
312 struct re_pattern_buffer *bufp;
315 struct re_registers *regs;
317 return re_search_stub (bufp, string, length, start, 0, length, regs, true);
320 weak_alias (__re_match, re_match)
324 re_search (bufp, string, length, start, range, regs)
325 struct re_pattern_buffer *bufp;
329 struct re_registers *regs;
331 return re_search_stub (bufp, string, length, start, range, length, regs,
335 weak_alias (__re_search, re_search)
339 re_match_2 (bufp, string1, length1, string2, length2, start, regs, stop)
340 struct re_pattern_buffer *bufp;
341 const char *string1, *string2;
342 Idx length1, length2, start, stop;
343 struct re_registers *regs;
345 return re_search_2_stub (bufp, string1, length1, string2, length2,
346 start, 0, regs, stop, true);
349 weak_alias (__re_match_2, re_match_2)
353 re_search_2 (bufp, string1, length1, string2, length2, start, range, regs, stop)
354 struct re_pattern_buffer *bufp;
355 const char *string1, *string2;
356 Idx length1, length2, start, stop;
358 struct re_registers *regs;
360 return re_search_2_stub (bufp, string1, length1, string2, length2,
361 start, range, regs, stop, false);
364 weak_alias (__re_search_2, re_search_2)
368 re_search_2_stub (struct re_pattern_buffer *bufp,
369 const char *string1, Idx length1,
370 const char *string2, Idx length2,
371 Idx start, regoff_t range, struct re_registers *regs,
372 Idx stop, bool ret_len)
376 Idx len = length1 + length2;
379 verify (! TYPE_SIGNED (Idx));
380 if (BE (len < length1, 0))
382 /* if (BE (length1 < 0 || length2 < 0 || stop < 0, 0))
385 /* Concatenate the strings. */
389 s = re_malloc (char, len);
391 if (BE (s == NULL, 0))
394 memcpy (__mempcpy (s, string1, length1), string2, length2);
396 memcpy (s, string1, length1);
397 memcpy (s + length1, string2, length2);
406 rval = re_search_stub (bufp, str, len, start, range, stop, regs,
412 /* The parameters have the same meaning as those of re_search.
413 Additional parameters:
414 If RET_LEN is true the length of the match is returned (re_match style);
415 otherwise the position of the match is returned. */
418 re_search_stub (struct re_pattern_buffer *bufp,
419 const char *string, Idx length,
420 Idx start, regoff_t range, Idx stop, struct re_registers *regs,
423 reg_errcode_t result;
429 re_dfa_t *dfa = bufp->buffer;
431 Idx last_start = start + range;
433 /* Check for out-of-range. */
434 verify (! TYPE_SIGNED (Idx));
435 /* if (BE (start < 0, 0))
437 if (BE (start > length, 0))
439 if (BE (length < last_start || (0 <= range && last_start < start), 0))
441 else if (BE (/* last_start < 0 || */ (range < 0 && start <= last_start), 0))
444 __libc_lock_lock (dfa->lock);
446 eflags |= (bufp->not_bol) ? REG_NOTBOL : 0;
447 eflags |= (bufp->not_eol) ? REG_NOTEOL : 0;
449 /* Compile fastmap if we haven't yet. */
450 if (start < last_start && bufp->fastmap != NULL && !bufp->fastmap_accurate)
451 re_compile_fastmap (bufp);
453 if (BE (bufp->no_sub, 0))
456 /* We need at least 1 register. */
459 else if (BE (bufp->regs_allocated == REGS_FIXED
460 && regs->num_regs <= bufp->re_nsub, 0))
462 nregs = regs->num_regs;
463 if (BE (nregs < 1, 0))
465 /* Nothing can be copied to regs. */
471 nregs = bufp->re_nsub + 1;
472 pmatch = re_malloc (regmatch_t, nregs);
473 if (BE (pmatch == NULL, 0))
479 result = re_search_internal (bufp, string, length, start, last_start, stop,
480 nregs, pmatch, eflags);
484 /* I hope we needn't fill ther regs with -1's when no match was found. */
485 if (result != REG_NOERROR)
486 rval = result == REG_NOMATCH ? -1 : -2;
487 else if (regs != NULL)
489 /* If caller wants register contents data back, copy them. */
490 bufp->regs_allocated = re_copy_regs (regs, pmatch, nregs,
491 bufp->regs_allocated);
492 if (BE (bufp->regs_allocated == REGS_UNALLOCATED, 0))
496 if (BE (rval == 0, 1))
500 assert (pmatch[0].rm_so == start);
501 rval = pmatch[0].rm_eo - start;
504 rval = pmatch[0].rm_so;
508 __libc_lock_unlock (dfa->lock);
513 re_copy_regs (struct re_registers *regs, regmatch_t *pmatch, Idx nregs,
516 int rval = REGS_REALLOCATE;
518 Idx need_regs = nregs + 1;
519 /* We need one extra element beyond 'num_regs' for the '-1' marker GNU code
522 /* Have the register data arrays been allocated? */
523 if (regs_allocated == REGS_UNALLOCATED)
524 { /* No. So allocate them with malloc. */
525 regs->start = re_malloc (regoff_t, need_regs);
526 if (BE (regs->start == NULL, 0))
527 return REGS_UNALLOCATED;
528 regs->end = re_malloc (regoff_t, need_regs);
529 if (BE (regs->end == NULL, 0))
531 re_free (regs->start);
532 return REGS_UNALLOCATED;
534 regs->num_regs = need_regs;
536 else if (regs_allocated == REGS_REALLOCATE)
537 { /* Yes. If we need more elements than were already
538 allocated, reallocate them. If we need fewer, just
540 if (BE (need_regs > regs->num_regs, 0))
542 regoff_t *new_start = re_realloc (regs->start, regoff_t, need_regs);
544 if (BE (new_start == NULL, 0))
545 return REGS_UNALLOCATED;
546 new_end = re_realloc (regs->end, regoff_t, need_regs);
547 if (BE (new_end == NULL, 0))
550 return REGS_UNALLOCATED;
552 regs->start = new_start;
554 regs->num_regs = need_regs;
559 assert (regs_allocated == REGS_FIXED);
560 /* This function may not be called with REGS_FIXED and nregs too big. */
561 assert (regs->num_regs >= nregs);
566 for (i = 0; i < nregs; ++i)
568 regs->start[i] = pmatch[i].rm_so;
569 regs->end[i] = pmatch[i].rm_eo;
571 for ( ; i < regs->num_regs; ++i)
572 regs->start[i] = regs->end[i] = -1;
577 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
578 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
579 this memory for recording register information. STARTS and ENDS
580 must be allocated using the malloc library routine, and must each
581 be at least NUM_REGS * sizeof (regoff_t) bytes long.
583 If NUM_REGS == 0, then subsequent matches should allocate their own
586 Unless this function is called, the first search or match using
587 PATTERN_BUFFER will allocate its own register data, without
588 freeing the old data. */
591 re_set_registers (bufp, regs, num_regs, starts, ends)
592 struct re_pattern_buffer *bufp;
593 struct re_registers *regs;
594 __re_size_t num_regs;
595 regoff_t *starts, *ends;
599 bufp->regs_allocated = REGS_REALLOCATE;
600 regs->num_regs = num_regs;
601 regs->start = starts;
606 bufp->regs_allocated = REGS_UNALLOCATED;
608 regs->start = regs->end = NULL;
612 weak_alias (__re_set_registers, re_set_registers)
615 /* Entry points compatible with 4.2 BSD regex library. We don't define
616 them unless specifically requested. */
618 #if defined _REGEX_RE_COMP || defined _LIBC
626 return 0 == regexec (&re_comp_buf, s, 0, NULL, 0);
628 #endif /* _REGEX_RE_COMP */
630 /* Internal entry point. */
632 /* Searches for a compiled pattern PREG in the string STRING, whose
633 length is LENGTH. NMATCH, PMATCH, and EFLAGS have the same
634 meaning as with regexec. LAST_START is START + RANGE, where
635 START and RANGE have the same meaning as with re_search.
636 Return REG_NOERROR if we find a match, and REG_NOMATCH if not,
637 otherwise return the error code.
638 Note: We assume front end functions already check ranges.
639 (0 <= LAST_START && LAST_START <= LENGTH) */
642 __attribute_warn_unused_result__
643 re_search_internal (const regex_t *preg,
644 const char *string, Idx length,
645 Idx start, Idx last_start, Idx stop,
646 size_t nmatch, regmatch_t pmatch[],
650 const re_dfa_t *dfa = preg->buffer;
651 Idx left_lim, right_lim;
653 bool fl_longest_match;
656 Idx match_last = REG_MISSING;
660 #if defined _LIBC || (defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L)
661 re_match_context_t mctx = { .dfa = dfa };
663 re_match_context_t mctx;
665 char *fastmap = ((preg->fastmap != NULL && preg->fastmap_accurate
666 && start != last_start && !preg->can_be_null)
667 ? preg->fastmap : NULL);
668 RE_TRANSLATE_TYPE t = preg->translate;
670 #if !(defined _LIBC || (defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L))
671 memset (&mctx, '\0', sizeof (re_match_context_t));
675 extra_nmatch = (nmatch > preg->re_nsub) ? nmatch - (preg->re_nsub + 1) : 0;
676 nmatch -= extra_nmatch;
678 /* Check if the DFA haven't been compiled. */
679 if (BE (preg->used == 0 || dfa->init_state == NULL
680 || dfa->init_state_word == NULL || dfa->init_state_nl == NULL
681 || dfa->init_state_begbuf == NULL, 0))
685 /* We assume front-end functions already check them. */
686 assert (0 <= last_start && last_start <= length);
689 /* If initial states with non-begbuf contexts have no elements,
690 the regex must be anchored. If preg->newline_anchor is set,
691 we'll never use init_state_nl, so do not check it. */
692 if (dfa->init_state->nodes.nelem == 0
693 && dfa->init_state_word->nodes.nelem == 0
694 && (dfa->init_state_nl->nodes.nelem == 0
695 || !preg->newline_anchor))
697 if (start != 0 && last_start != 0)
699 start = last_start = 0;
702 /* We must check the longest matching, if nmatch > 0. */
703 fl_longest_match = (nmatch != 0 || dfa->nbackref);
705 err = re_string_allocate (&mctx.input, string, length, dfa->nodes_len + 1,
706 preg->translate, (preg->syntax & RE_ICASE) != 0,
708 if (BE (err != REG_NOERROR, 0))
710 mctx.input.stop = stop;
711 mctx.input.raw_stop = stop;
712 mctx.input.newline_anchor = preg->newline_anchor;
714 err = match_ctx_init (&mctx, eflags, dfa->nbackref * 2);
715 if (BE (err != REG_NOERROR, 0))
718 /* We will log all the DFA states through which the dfa pass,
719 if nmatch > 1, or this dfa has "multibyte node", which is a
720 back-reference or a node which can accept multibyte character or
721 multi character collating element. */
722 if (nmatch > 1 || dfa->has_mb_node)
724 /* Avoid overflow. */
725 if (BE ((MIN (IDX_MAX, SIZE_MAX / sizeof (re_dfastate_t *))
726 <= mctx.input.bufs_len), 0))
732 mctx.state_log = re_malloc (re_dfastate_t *, mctx.input.bufs_len + 1);
733 if (BE (mctx.state_log == NULL, 0))
740 mctx.state_log = NULL;
743 mctx.input.tip_context = (eflags & REG_NOTBOL) ? CONTEXT_BEGBUF
744 : CONTEXT_NEWLINE | CONTEXT_BEGBUF;
746 /* Check incrementally whether of not the input string match. */
747 incr = (last_start < start) ? -1 : 1;
748 left_lim = (last_start < start) ? last_start : start;
749 right_lim = (last_start < start) ? start : last_start;
750 sb = dfa->mb_cur_max == 1;
753 ? ((sb || !(preg->syntax & RE_ICASE || t) ? 4 : 0)
754 | (start <= last_start ? 2 : 0)
755 | (t != NULL ? 1 : 0))
758 for (;; match_first += incr)
761 if (match_first < left_lim || right_lim < match_first)
764 /* Advance as rapidly as possible through the string, until we
765 find a plausible place to start matching. This may be done
766 with varying efficiency, so there are various possibilities:
767 only the most common of them are specialized, in order to
768 save on code size. We use a switch statement for speed. */
776 /* Fastmap with single-byte translation, match forward. */
777 while (BE (match_first < right_lim, 1)
778 && !fastmap[t[(unsigned char) string[match_first]]])
780 goto forward_match_found_start_or_reached_end;
783 /* Fastmap without translation, match forward. */
784 while (BE (match_first < right_lim, 1)
785 && !fastmap[(unsigned char) string[match_first]])
788 forward_match_found_start_or_reached_end:
789 if (BE (match_first == right_lim, 0))
791 ch = match_first >= length
792 ? 0 : (unsigned char) string[match_first];
793 if (!fastmap[t ? t[ch] : ch])
800 /* Fastmap without multi-byte translation, match backwards. */
801 while (match_first >= left_lim)
803 ch = match_first >= length
804 ? 0 : (unsigned char) string[match_first];
805 if (fastmap[t ? t[ch] : ch])
809 if (match_first < left_lim)
814 /* In this case, we can't determine easily the current byte,
815 since it might be a component byte of a multibyte
816 character. Then we use the constructed buffer instead. */
819 /* If MATCH_FIRST is out of the valid range, reconstruct the
821 __re_size_t offset = match_first - mctx.input.raw_mbs_idx;
822 if (BE (offset >= (__re_size_t) mctx.input.valid_raw_len, 0))
824 err = re_string_reconstruct (&mctx.input, match_first,
826 if (BE (err != REG_NOERROR, 0))
829 offset = match_first - mctx.input.raw_mbs_idx;
831 /* If MATCH_FIRST is out of the buffer, leave it as '\0'.
832 Note that MATCH_FIRST must not be smaller than 0. */
833 ch = (match_first >= length
834 ? 0 : re_string_byte_at (&mctx.input, offset));
838 if (match_first < left_lim || match_first > right_lim)
847 /* Reconstruct the buffers so that the matcher can assume that
848 the matching starts from the beginning of the buffer. */
849 err = re_string_reconstruct (&mctx.input, match_first, eflags);
850 if (BE (err != REG_NOERROR, 0))
853 #ifdef RE_ENABLE_I18N
854 /* Don't consider this char as a possible match start if it part,
855 yet isn't the head, of a multibyte character. */
856 if (!sb && !re_string_first_byte (&mctx.input, 0))
860 /* It seems to be appropriate one, then use the matcher. */
861 /* We assume that the matching starts from 0. */
862 mctx.state_log_top = mctx.nbkref_ents = mctx.max_mb_elem_len = 0;
863 match_last = check_matching (&mctx, fl_longest_match,
864 start <= last_start ? &match_first : NULL);
865 if (match_last != REG_MISSING)
867 if (BE (match_last == REG_ERROR, 0))
874 mctx.match_last = match_last;
875 if ((!preg->no_sub && nmatch > 1) || dfa->nbackref)
877 re_dfastate_t *pstate = mctx.state_log[match_last];
878 mctx.last_node = check_halt_state_context (&mctx, pstate,
881 if ((!preg->no_sub && nmatch > 1 && dfa->has_plural_match)
884 err = prune_impossible_nodes (&mctx);
885 if (err == REG_NOERROR)
887 if (BE (err != REG_NOMATCH, 0))
889 match_last = REG_MISSING;
892 break; /* We found a match. */
896 match_ctx_clean (&mctx);
900 assert (match_last != REG_MISSING);
901 assert (err == REG_NOERROR);
904 /* Set pmatch[] if we need. */
909 /* Initialize registers. */
910 for (reg_idx = 1; reg_idx < nmatch; ++reg_idx)
911 pmatch[reg_idx].rm_so = pmatch[reg_idx].rm_eo = -1;
913 /* Set the points where matching start/end. */
915 pmatch[0].rm_eo = mctx.match_last;
916 /* FIXME: This function should fail if mctx.match_last exceeds
917 the maximum possible regoff_t value. We need a new error
918 code REG_OVERFLOW. */
920 if (!preg->no_sub && nmatch > 1)
922 err = set_regs (preg, &mctx, nmatch, pmatch,
923 dfa->has_plural_match && dfa->nbackref > 0);
924 if (BE (err != REG_NOERROR, 0))
928 /* At last, add the offset to each register, since we slid
929 the buffers so that we could assume that the matching starts
931 for (reg_idx = 0; reg_idx < nmatch; ++reg_idx)
932 if (pmatch[reg_idx].rm_so != -1)
934 #ifdef RE_ENABLE_I18N
935 if (BE (mctx.input.offsets_needed != 0, 0))
937 pmatch[reg_idx].rm_so =
938 (pmatch[reg_idx].rm_so == mctx.input.valid_len
939 ? mctx.input.valid_raw_len
940 : mctx.input.offsets[pmatch[reg_idx].rm_so]);
941 pmatch[reg_idx].rm_eo =
942 (pmatch[reg_idx].rm_eo == mctx.input.valid_len
943 ? mctx.input.valid_raw_len
944 : mctx.input.offsets[pmatch[reg_idx].rm_eo]);
947 assert (mctx.input.offsets_needed == 0);
949 pmatch[reg_idx].rm_so += match_first;
950 pmatch[reg_idx].rm_eo += match_first;
952 for (reg_idx = 0; reg_idx < extra_nmatch; ++reg_idx)
954 pmatch[nmatch + reg_idx].rm_so = -1;
955 pmatch[nmatch + reg_idx].rm_eo = -1;
959 for (reg_idx = 0; reg_idx + 1 < nmatch; reg_idx++)
960 if (dfa->subexp_map[reg_idx] != reg_idx)
962 pmatch[reg_idx + 1].rm_so
963 = pmatch[dfa->subexp_map[reg_idx] + 1].rm_so;
964 pmatch[reg_idx + 1].rm_eo
965 = pmatch[dfa->subexp_map[reg_idx] + 1].rm_eo;
970 re_free (mctx.state_log);
972 match_ctx_free (&mctx);
973 re_string_destruct (&mctx.input);
978 __attribute_warn_unused_result__
979 prune_impossible_nodes (re_match_context_t *mctx)
981 const re_dfa_t *const dfa = mctx->dfa;
982 Idx halt_node, match_last;
984 re_dfastate_t **sifted_states;
985 re_dfastate_t **lim_states = NULL;
986 re_sift_context_t sctx;
988 assert (mctx->state_log != NULL);
990 match_last = mctx->match_last;
991 halt_node = mctx->last_node;
993 /* Avoid overflow. */
994 if (BE (MIN (IDX_MAX, SIZE_MAX / sizeof (re_dfastate_t *)) <= match_last, 0))
997 sifted_states = re_malloc (re_dfastate_t *, match_last + 1);
998 if (BE (sifted_states == NULL, 0))
1005 lim_states = re_malloc (re_dfastate_t *, match_last + 1);
1006 if (BE (lim_states == NULL, 0))
1013 memset (lim_states, '\0',
1014 sizeof (re_dfastate_t *) * (match_last + 1));
1015 sift_ctx_init (&sctx, sifted_states, lim_states, halt_node,
1017 ret = sift_states_backward (mctx, &sctx);
1018 re_node_set_free (&sctx.limits);
1019 if (BE (ret != REG_NOERROR, 0))
1021 if (sifted_states[0] != NULL || lim_states[0] != NULL)
1026 if (! REG_VALID_INDEX (match_last))
1031 } while (mctx->state_log[match_last] == NULL
1032 || !mctx->state_log[match_last]->halt);
1033 halt_node = check_halt_state_context (mctx,
1034 mctx->state_log[match_last],
1037 ret = merge_state_array (dfa, sifted_states, lim_states,
1039 re_free (lim_states);
1041 if (BE (ret != REG_NOERROR, 0))
1046 sift_ctx_init (&sctx, sifted_states, lim_states, halt_node, match_last);
1047 ret = sift_states_backward (mctx, &sctx);
1048 re_node_set_free (&sctx.limits);
1049 if (BE (ret != REG_NOERROR, 0))
1051 if (sifted_states[0] == NULL)
1057 re_free (mctx->state_log);
1058 mctx->state_log = sifted_states;
1059 sifted_states = NULL;
1060 mctx->last_node = halt_node;
1061 mctx->match_last = match_last;
1064 re_free (sifted_states);
1065 re_free (lim_states);
1069 /* Acquire an initial state and return it.
1070 We must select appropriate initial state depending on the context,
1071 since initial states may have constraints like "\<", "^", etc.. */
1073 static inline re_dfastate_t *
1074 __attribute ((always_inline)) internal_function
1075 acquire_init_state_context (reg_errcode_t *err, const re_match_context_t *mctx,
1078 const re_dfa_t *const dfa = mctx->dfa;
1079 if (dfa->init_state->has_constraint)
1081 unsigned int context;
1082 context = re_string_context_at (&mctx->input, idx - 1, mctx->eflags);
1083 if (IS_WORD_CONTEXT (context))
1084 return dfa->init_state_word;
1085 else if (IS_ORDINARY_CONTEXT (context))
1086 return dfa->init_state;
1087 else if (IS_BEGBUF_CONTEXT (context) && IS_NEWLINE_CONTEXT (context))
1088 return dfa->init_state_begbuf;
1089 else if (IS_NEWLINE_CONTEXT (context))
1090 return dfa->init_state_nl;
1091 else if (IS_BEGBUF_CONTEXT (context))
1093 /* It is relatively rare case, then calculate on demand. */
1094 return re_acquire_state_context (err, dfa,
1095 dfa->init_state->entrance_nodes,
1099 /* Must not happen? */
1100 return dfa->init_state;
1103 return dfa->init_state;
1106 /* Check whether the regular expression match input string INPUT or not,
1107 and return the index where the matching end. Return REG_MISSING if
1108 there is no match, and return REG_ERROR in case of an error.
1109 FL_LONGEST_MATCH means we want the POSIX longest matching.
1110 If P_MATCH_FIRST is not NULL, and the match fails, it is set to the
1111 next place where we may want to try matching.
1112 Note that the matcher assumes that the matching starts from the current
1113 index of the buffer. */
1116 internal_function __attribute_warn_unused_result__
1117 check_matching (re_match_context_t *mctx, bool fl_longest_match,
1120 const re_dfa_t *const dfa = mctx->dfa;
1123 Idx match_last = REG_MISSING;
1124 Idx cur_str_idx = re_string_cur_idx (&mctx->input);
1125 re_dfastate_t *cur_state;
1126 bool at_init_state = p_match_first != NULL;
1127 Idx next_start_idx = cur_str_idx;
1130 cur_state = acquire_init_state_context (&err, mctx, cur_str_idx);
1131 /* An initial state must not be NULL (invalid). */
1132 if (BE (cur_state == NULL, 0))
1134 assert (err == REG_ESPACE);
1138 if (mctx->state_log != NULL)
1140 mctx->state_log[cur_str_idx] = cur_state;
1142 /* Check OP_OPEN_SUBEXP in the initial state in case that we use them
1143 later. E.g. Processing back references. */
1144 if (BE (dfa->nbackref, 0))
1146 at_init_state = false;
1147 err = check_subexp_matching_top (mctx, &cur_state->nodes, 0);
1148 if (BE (err != REG_NOERROR, 0))
1151 if (cur_state->has_backref)
1153 err = transit_state_bkref (mctx, &cur_state->nodes);
1154 if (BE (err != REG_NOERROR, 0))
1160 /* If the RE accepts NULL string. */
1161 if (BE (cur_state->halt, 0))
1163 if (!cur_state->has_constraint
1164 || check_halt_state_context (mctx, cur_state, cur_str_idx))
1166 if (!fl_longest_match)
1170 match_last = cur_str_idx;
1176 while (!re_string_eoi (&mctx->input))
1178 re_dfastate_t *old_state = cur_state;
1179 Idx next_char_idx = re_string_cur_idx (&mctx->input) + 1;
1181 if ((BE (next_char_idx >= mctx->input.bufs_len, 0)
1182 && mctx->input.bufs_len < mctx->input.len)
1183 || (BE (next_char_idx >= mctx->input.valid_len, 0)
1184 && mctx->input.valid_len < mctx->input.len))
1186 err = extend_buffers (mctx);
1187 if (BE (err != REG_NOERROR, 0))
1189 assert (err == REG_ESPACE);
1194 cur_state = transit_state (&err, mctx, cur_state);
1195 if (mctx->state_log != NULL)
1196 cur_state = merge_state_with_log (&err, mctx, cur_state);
1198 if (cur_state == NULL)
1200 /* Reached the invalid state or an error. Try to recover a valid
1201 state using the state log, if available and if we have not
1202 already found a valid (even if not the longest) match. */
1203 if (BE (err != REG_NOERROR, 0))
1206 if (mctx->state_log == NULL
1207 || (match && !fl_longest_match)
1208 || (cur_state = find_recover_state (&err, mctx)) == NULL)
1212 if (BE (at_init_state, 0))
1214 if (old_state == cur_state)
1215 next_start_idx = next_char_idx;
1217 at_init_state = false;
1220 if (cur_state->halt)
1222 /* Reached a halt state.
1223 Check the halt state can satisfy the current context. */
1224 if (!cur_state->has_constraint
1225 || check_halt_state_context (mctx, cur_state,
1226 re_string_cur_idx (&mctx->input)))
1228 /* We found an appropriate halt state. */
1229 match_last = re_string_cur_idx (&mctx->input);
1232 /* We found a match, do not modify match_first below. */
1233 p_match_first = NULL;
1234 if (!fl_longest_match)
1241 *p_match_first += next_start_idx;
1246 /* Check NODE match the current context. */
1250 check_halt_node_context (const re_dfa_t *dfa, Idx node, unsigned int context)
1252 re_token_type_t type = dfa->nodes[node].type;
1253 unsigned int constraint = dfa->nodes[node].constraint;
1254 if (type != END_OF_RE)
1258 if (NOT_SATISFY_NEXT_CONSTRAINT (constraint, context))
1263 /* Check the halt state STATE match the current context.
1264 Return 0 if not match, if the node, STATE has, is a halt node and
1265 match the context, return the node. */
1269 check_halt_state_context (const re_match_context_t *mctx,
1270 const re_dfastate_t *state, Idx idx)
1273 unsigned int context;
1275 assert (state->halt);
1277 context = re_string_context_at (&mctx->input, idx, mctx->eflags);
1278 for (i = 0; i < state->nodes.nelem; ++i)
1279 if (check_halt_node_context (mctx->dfa, state->nodes.elems[i], context))
1280 return state->nodes.elems[i];
1284 /* Compute the next node to which "NFA" transit from NODE("NFA" is a NFA
1285 corresponding to the DFA).
1286 Return the destination node, and update EPS_VIA_NODES;
1287 return REG_MISSING in case of errors. */
1291 proceed_next_node (const re_match_context_t *mctx, Idx nregs, regmatch_t *regs,
1292 Idx *pidx, Idx node, re_node_set *eps_via_nodes,
1293 struct re_fail_stack_t *fs)
1295 const re_dfa_t *const dfa = mctx->dfa;
1298 if (IS_EPSILON_NODE (dfa->nodes[node].type))
1300 re_node_set *cur_nodes = &mctx->state_log[*pidx]->nodes;
1301 re_node_set *edests = &dfa->edests[node];
1303 ok = re_node_set_insert (eps_via_nodes, node);
1306 /* Pick up a valid destination, or return REG_MISSING if none
1308 for (dest_node = REG_MISSING, i = 0; i < edests->nelem; ++i)
1310 Idx candidate = edests->elems[i];
1311 if (!re_node_set_contains (cur_nodes, candidate))
1313 if (dest_node == REG_MISSING)
1314 dest_node = candidate;
1318 /* In order to avoid infinite loop like "(a*)*", return the second
1319 epsilon-transition if the first was already considered. */
1320 if (re_node_set_contains (eps_via_nodes, dest_node))
1323 /* Otherwise, push the second epsilon-transition on the fail stack. */
1325 && push_fail_stack (fs, *pidx, candidate, nregs, regs,
1329 /* We know we are going to exit. */
1338 re_token_type_t type = dfa->nodes[node].type;
1340 #ifdef RE_ENABLE_I18N
1341 if (dfa->nodes[node].accept_mb)
1342 naccepted = check_node_accept_bytes (dfa, node, &mctx->input, *pidx);
1344 #endif /* RE_ENABLE_I18N */
1345 if (type == OP_BACK_REF)
1347 Idx subexp_idx = dfa->nodes[node].opr.idx + 1;
1348 naccepted = regs[subexp_idx].rm_eo - regs[subexp_idx].rm_so;
1351 if (regs[subexp_idx].rm_so == -1 || regs[subexp_idx].rm_eo == -1)
1355 char *buf = (char *) re_string_get_buffer (&mctx->input);
1356 if (memcmp (buf + regs[subexp_idx].rm_so, buf + *pidx,
1365 ok = re_node_set_insert (eps_via_nodes, node);
1368 dest_node = dfa->edests[node].elems[0];
1369 if (re_node_set_contains (&mctx->state_log[*pidx]->nodes,
1376 || check_node_accept (mctx, dfa->nodes + node, *pidx))
1378 Idx dest_node = dfa->nexts[node];
1379 *pidx = (naccepted == 0) ? *pidx + 1 : *pidx + naccepted;
1380 if (fs && (*pidx > mctx->match_last || mctx->state_log[*pidx] == NULL
1381 || !re_node_set_contains (&mctx->state_log[*pidx]->nodes,
1384 re_node_set_empty (eps_via_nodes);
1391 static reg_errcode_t
1392 internal_function __attribute_warn_unused_result__
1393 push_fail_stack (struct re_fail_stack_t *fs, Idx str_idx, Idx dest_node,
1394 Idx nregs, regmatch_t *regs, re_node_set *eps_via_nodes)
1397 Idx num = fs->num++;
1398 if (fs->num == fs->alloc)
1400 struct re_fail_stack_ent_t *new_array;
1401 new_array = realloc (fs->stack, (sizeof (struct re_fail_stack_ent_t)
1403 if (new_array == NULL)
1406 fs->stack = new_array;
1408 fs->stack[num].idx = str_idx;
1409 fs->stack[num].node = dest_node;
1410 fs->stack[num].regs = re_malloc (regmatch_t, nregs);
1411 if (fs->stack[num].regs == NULL)
1413 memcpy (fs->stack[num].regs, regs, sizeof (regmatch_t) * nregs);
1414 err = re_node_set_init_copy (&fs->stack[num].eps_via_nodes, eps_via_nodes);
1420 pop_fail_stack (struct re_fail_stack_t *fs, Idx *pidx, Idx nregs,
1421 regmatch_t *regs, re_node_set *eps_via_nodes)
1423 Idx num = --fs->num;
1424 assert (REG_VALID_INDEX (num));
1425 *pidx = fs->stack[num].idx;
1426 memcpy (regs, fs->stack[num].regs, sizeof (regmatch_t) * nregs);
1427 re_node_set_free (eps_via_nodes);
1428 re_free (fs->stack[num].regs);
1429 *eps_via_nodes = fs->stack[num].eps_via_nodes;
1430 return fs->stack[num].node;
1433 /* Set the positions where the subexpressions are starts/ends to registers
1435 Note: We assume that pmatch[0] is already set, and
1436 pmatch[i].rm_so == pmatch[i].rm_eo == -1 for 0 < i < nmatch. */
1438 static reg_errcode_t
1439 internal_function __attribute_warn_unused_result__
1440 set_regs (const regex_t *preg, const re_match_context_t *mctx, size_t nmatch,
1441 regmatch_t *pmatch, bool fl_backtrack)
1443 const re_dfa_t *dfa = preg->buffer;
1445 re_node_set eps_via_nodes;
1446 struct re_fail_stack_t *fs;
1447 struct re_fail_stack_t fs_body = { 0, 2, NULL };
1448 regmatch_t *prev_idx_match;
1449 bool prev_idx_match_malloced = false;
1452 assert (nmatch > 1);
1453 assert (mctx->state_log != NULL);
1458 fs->stack = re_malloc (struct re_fail_stack_ent_t, fs->alloc);
1459 if (fs->stack == NULL)
1465 cur_node = dfa->init_node;
1466 re_node_set_init_empty (&eps_via_nodes);
1468 if (__libc_use_alloca (nmatch * sizeof (regmatch_t)))
1469 prev_idx_match = (regmatch_t *) alloca (nmatch * sizeof (regmatch_t));
1472 prev_idx_match = re_malloc (regmatch_t, nmatch);
1473 if (prev_idx_match == NULL)
1475 free_fail_stack_return (fs);
1478 prev_idx_match_malloced = true;
1480 memcpy (prev_idx_match, pmatch, sizeof (regmatch_t) * nmatch);
1482 for (idx = pmatch[0].rm_so; idx <= pmatch[0].rm_eo ;)
1484 update_regs (dfa, pmatch, prev_idx_match, cur_node, idx, nmatch);
1486 if (idx == pmatch[0].rm_eo && cur_node == mctx->last_node)
1491 for (reg_idx = 0; reg_idx < nmatch; ++reg_idx)
1492 if (pmatch[reg_idx].rm_so > -1 && pmatch[reg_idx].rm_eo == -1)
1494 if (reg_idx == nmatch)
1496 re_node_set_free (&eps_via_nodes);
1497 if (prev_idx_match_malloced)
1498 re_free (prev_idx_match);
1499 return free_fail_stack_return (fs);
1501 cur_node = pop_fail_stack (fs, &idx, nmatch, pmatch,
1506 re_node_set_free (&eps_via_nodes);
1507 if (prev_idx_match_malloced)
1508 re_free (prev_idx_match);
1513 /* Proceed to next node. */
1514 cur_node = proceed_next_node (mctx, nmatch, pmatch, &idx, cur_node,
1515 &eps_via_nodes, fs);
1517 if (BE (! REG_VALID_INDEX (cur_node), 0))
1519 if (BE (cur_node == REG_ERROR, 0))
1521 re_node_set_free (&eps_via_nodes);
1522 if (prev_idx_match_malloced)
1523 re_free (prev_idx_match);
1524 free_fail_stack_return (fs);
1528 cur_node = pop_fail_stack (fs, &idx, nmatch, pmatch,
1532 re_node_set_free (&eps_via_nodes);
1533 if (prev_idx_match_malloced)
1534 re_free (prev_idx_match);
1539 re_node_set_free (&eps_via_nodes);
1540 if (prev_idx_match_malloced)
1541 re_free (prev_idx_match);
1542 return free_fail_stack_return (fs);
1545 static reg_errcode_t
1547 free_fail_stack_return (struct re_fail_stack_t *fs)
1552 for (fs_idx = 0; fs_idx < fs->num; ++fs_idx)
1554 re_node_set_free (&fs->stack[fs_idx].eps_via_nodes);
1555 re_free (fs->stack[fs_idx].regs);
1557 re_free (fs->stack);
1564 update_regs (const re_dfa_t *dfa, regmatch_t *pmatch,
1565 regmatch_t *prev_idx_match, Idx cur_node, Idx cur_idx, Idx nmatch)
1567 int type = dfa->nodes[cur_node].type;
1568 if (type == OP_OPEN_SUBEXP)
1570 Idx reg_num = dfa->nodes[cur_node].opr.idx + 1;
1572 /* We are at the first node of this sub expression. */
1573 if (reg_num < nmatch)
1575 pmatch[reg_num].rm_so = cur_idx;
1576 pmatch[reg_num].rm_eo = -1;
1579 else if (type == OP_CLOSE_SUBEXP)
1581 Idx reg_num = dfa->nodes[cur_node].opr.idx + 1;
1582 if (reg_num < nmatch)
1584 /* We are at the last node of this sub expression. */
1585 if (pmatch[reg_num].rm_so < cur_idx)
1587 pmatch[reg_num].rm_eo = cur_idx;
1588 /* This is a non-empty match or we are not inside an optional
1589 subexpression. Accept this right away. */
1590 memcpy (prev_idx_match, pmatch, sizeof (regmatch_t) * nmatch);
1594 if (dfa->nodes[cur_node].opt_subexp
1595 && prev_idx_match[reg_num].rm_so != -1)
1596 /* We transited through an empty match for an optional
1597 subexpression, like (a?)*, and this is not the subexp's
1598 first match. Copy back the old content of the registers
1599 so that matches of an inner subexpression are undone as
1600 well, like in ((a?))*. */
1601 memcpy (pmatch, prev_idx_match, sizeof (regmatch_t) * nmatch);
1603 /* We completed a subexpression, but it may be part of
1604 an optional one, so do not update PREV_IDX_MATCH. */
1605 pmatch[reg_num].rm_eo = cur_idx;
1611 /* This function checks the STATE_LOG from the SCTX->last_str_idx to 0
1612 and sift the nodes in each states according to the following rules.
1613 Updated state_log will be wrote to STATE_LOG.
1615 Rules: We throw away the Node 'a' in the STATE_LOG[STR_IDX] if...
1616 1. When STR_IDX == MATCH_LAST(the last index in the state_log):
1617 If 'a' isn't the LAST_NODE and 'a' can't epsilon transit to
1618 the LAST_NODE, we throw away the node 'a'.
1619 2. When 0 <= STR_IDX < MATCH_LAST and 'a' accepts
1620 string 's' and transit to 'b':
1621 i. If 'b' isn't in the STATE_LOG[STR_IDX+strlen('s')], we throw
1623 ii. If 'b' is in the STATE_LOG[STR_IDX+strlen('s')] but 'b' is
1624 thrown away, we throw away the node 'a'.
1625 3. When 0 <= STR_IDX < MATCH_LAST and 'a' epsilon transit to 'b':
1626 i. If 'b' isn't in the STATE_LOG[STR_IDX], we throw away the
1628 ii. If 'b' is in the STATE_LOG[STR_IDX] but 'b' is thrown away,
1629 we throw away the node 'a'. */
1631 #define STATE_NODE_CONTAINS(state,node) \
1632 ((state) != NULL && re_node_set_contains (&(state)->nodes, node))
1634 static reg_errcode_t
1636 sift_states_backward (const re_match_context_t *mctx, re_sift_context_t *sctx)
1640 Idx str_idx = sctx->last_str_idx;
1641 re_node_set cur_dest;
1644 assert (mctx->state_log != NULL && mctx->state_log[str_idx] != NULL);
1647 /* Build sifted state_log[str_idx]. It has the nodes which can epsilon
1648 transit to the last_node and the last_node itself. */
1649 err = re_node_set_init_1 (&cur_dest, sctx->last_node);
1650 if (BE (err != REG_NOERROR, 0))
1652 err = update_cur_sifted_state (mctx, sctx, str_idx, &cur_dest);
1653 if (BE (err != REG_NOERROR, 0))
1656 /* Then check each states in the state_log. */
1659 /* Update counters. */
1660 null_cnt = (sctx->sifted_states[str_idx] == NULL) ? null_cnt + 1 : 0;
1661 if (null_cnt > mctx->max_mb_elem_len)
1663 memset (sctx->sifted_states, '\0',
1664 sizeof (re_dfastate_t *) * str_idx);
1665 re_node_set_free (&cur_dest);
1668 re_node_set_empty (&cur_dest);
1671 if (mctx->state_log[str_idx])
1673 err = build_sifted_states (mctx, sctx, str_idx, &cur_dest);
1674 if (BE (err != REG_NOERROR, 0))
1678 /* Add all the nodes which satisfy the following conditions:
1679 - It can epsilon transit to a node in CUR_DEST.
1681 And update state_log. */
1682 err = update_cur_sifted_state (mctx, sctx, str_idx, &cur_dest);
1683 if (BE (err != REG_NOERROR, 0))
1688 re_node_set_free (&cur_dest);
1692 static reg_errcode_t
1693 internal_function __attribute_warn_unused_result__
1694 build_sifted_states (const re_match_context_t *mctx, re_sift_context_t *sctx,
1695 Idx str_idx, re_node_set *cur_dest)
1697 const re_dfa_t *const dfa = mctx->dfa;
1698 const re_node_set *cur_src = &mctx->state_log[str_idx]->non_eps_nodes;
1701 /* Then build the next sifted state.
1702 We build the next sifted state on 'cur_dest', and update
1703 'sifted_states[str_idx]' with 'cur_dest'.
1705 'cur_dest' is the sifted state from 'state_log[str_idx + 1]'.
1706 'cur_src' points the node_set of the old 'state_log[str_idx]'
1707 (with the epsilon nodes pre-filtered out). */
1708 for (i = 0; i < cur_src->nelem; i++)
1710 Idx prev_node = cur_src->elems[i];
1715 re_token_type_t type = dfa->nodes[prev_node].type;
1716 assert (!IS_EPSILON_NODE (type));
1718 #ifdef RE_ENABLE_I18N
1719 /* If the node may accept "multi byte". */
1720 if (dfa->nodes[prev_node].accept_mb)
1721 naccepted = sift_states_iter_mb (mctx, sctx, prev_node,
1722 str_idx, sctx->last_str_idx);
1723 #endif /* RE_ENABLE_I18N */
1725 /* We don't check backreferences here.
1726 See update_cur_sifted_state(). */
1728 && check_node_accept (mctx, dfa->nodes + prev_node, str_idx)
1729 && STATE_NODE_CONTAINS (sctx->sifted_states[str_idx + 1],
1730 dfa->nexts[prev_node]))
1736 if (sctx->limits.nelem)
1738 Idx to_idx = str_idx + naccepted;
1739 if (check_dst_limits (mctx, &sctx->limits,
1740 dfa->nexts[prev_node], to_idx,
1741 prev_node, str_idx))
1744 ok = re_node_set_insert (cur_dest, prev_node);
1752 /* Helper functions. */
1754 static reg_errcode_t
1756 clean_state_log_if_needed (re_match_context_t *mctx, Idx next_state_log_idx)
1758 Idx top = mctx->state_log_top;
1760 if ((next_state_log_idx >= mctx->input.bufs_len
1761 && mctx->input.bufs_len < mctx->input.len)
1762 || (next_state_log_idx >= mctx->input.valid_len
1763 && mctx->input.valid_len < mctx->input.len))
1766 err = extend_buffers (mctx);
1767 if (BE (err != REG_NOERROR, 0))
1771 if (top < next_state_log_idx)
1773 memset (mctx->state_log + top + 1, '\0',
1774 sizeof (re_dfastate_t *) * (next_state_log_idx - top));
1775 mctx->state_log_top = next_state_log_idx;
1780 static reg_errcode_t
1782 merge_state_array (const re_dfa_t *dfa, re_dfastate_t **dst,
1783 re_dfastate_t **src, Idx num)
1787 for (st_idx = 0; st_idx < num; ++st_idx)
1789 if (dst[st_idx] == NULL)
1790 dst[st_idx] = src[st_idx];
1791 else if (src[st_idx] != NULL)
1793 re_node_set merged_set;
1794 err = re_node_set_init_union (&merged_set, &dst[st_idx]->nodes,
1795 &src[st_idx]->nodes);
1796 if (BE (err != REG_NOERROR, 0))
1798 dst[st_idx] = re_acquire_state (&err, dfa, &merged_set);
1799 re_node_set_free (&merged_set);
1800 if (BE (err != REG_NOERROR, 0))
1807 static reg_errcode_t
1809 update_cur_sifted_state (const re_match_context_t *mctx,
1810 re_sift_context_t *sctx, Idx str_idx,
1811 re_node_set *dest_nodes)
1813 const re_dfa_t *const dfa = mctx->dfa;
1814 reg_errcode_t err = REG_NOERROR;
1815 const re_node_set *candidates;
1816 candidates = ((mctx->state_log[str_idx] == NULL) ? NULL
1817 : &mctx->state_log[str_idx]->nodes);
1819 if (dest_nodes->nelem == 0)
1820 sctx->sifted_states[str_idx] = NULL;
1825 /* At first, add the nodes which can epsilon transit to a node in
1827 err = add_epsilon_src_nodes (dfa, dest_nodes, candidates);
1828 if (BE (err != REG_NOERROR, 0))
1831 /* Then, check the limitations in the current sift_context. */
1832 if (sctx->limits.nelem)
1834 err = check_subexp_limits (dfa, dest_nodes, candidates, &sctx->limits,
1835 mctx->bkref_ents, str_idx);
1836 if (BE (err != REG_NOERROR, 0))
1841 sctx->sifted_states[str_idx] = re_acquire_state (&err, dfa, dest_nodes);
1842 if (BE (err != REG_NOERROR, 0))
1846 if (candidates && mctx->state_log[str_idx]->has_backref)
1848 err = sift_states_bkref (mctx, sctx, str_idx, candidates);
1849 if (BE (err != REG_NOERROR, 0))
1855 static reg_errcode_t
1856 internal_function __attribute_warn_unused_result__
1857 add_epsilon_src_nodes (const re_dfa_t *dfa, re_node_set *dest_nodes,
1858 const re_node_set *candidates)
1860 reg_errcode_t err = REG_NOERROR;
1863 re_dfastate_t *state = re_acquire_state (&err, dfa, dest_nodes);
1864 if (BE (err != REG_NOERROR, 0))
1867 if (!state->inveclosure.alloc)
1869 err = re_node_set_alloc (&state->inveclosure, dest_nodes->nelem);
1870 if (BE (err != REG_NOERROR, 0))
1872 for (i = 0; i < dest_nodes->nelem; i++)
1874 err = re_node_set_merge (&state->inveclosure,
1875 dfa->inveclosures + dest_nodes->elems[i]);
1876 if (BE (err != REG_NOERROR, 0))
1880 return re_node_set_add_intersect (dest_nodes, candidates,
1881 &state->inveclosure);
1884 static reg_errcode_t
1886 sub_epsilon_src_nodes (const re_dfa_t *dfa, Idx node, re_node_set *dest_nodes,
1887 const re_node_set *candidates)
1891 re_node_set *inv_eclosure = dfa->inveclosures + node;
1892 re_node_set except_nodes;
1893 re_node_set_init_empty (&except_nodes);
1894 for (ecl_idx = 0; ecl_idx < inv_eclosure->nelem; ++ecl_idx)
1896 Idx cur_node = inv_eclosure->elems[ecl_idx];
1897 if (cur_node == node)
1899 if (IS_EPSILON_NODE (dfa->nodes[cur_node].type))
1901 Idx edst1 = dfa->edests[cur_node].elems[0];
1902 Idx edst2 = ((dfa->edests[cur_node].nelem > 1)
1903 ? dfa->edests[cur_node].elems[1] : REG_MISSING);
1904 if ((!re_node_set_contains (inv_eclosure, edst1)
1905 && re_node_set_contains (dest_nodes, edst1))
1906 || (REG_VALID_NONZERO_INDEX (edst2)
1907 && !re_node_set_contains (inv_eclosure, edst2)
1908 && re_node_set_contains (dest_nodes, edst2)))
1910 err = re_node_set_add_intersect (&except_nodes, candidates,
1911 dfa->inveclosures + cur_node);
1912 if (BE (err != REG_NOERROR, 0))
1914 re_node_set_free (&except_nodes);
1920 for (ecl_idx = 0; ecl_idx < inv_eclosure->nelem; ++ecl_idx)
1922 Idx cur_node = inv_eclosure->elems[ecl_idx];
1923 if (!re_node_set_contains (&except_nodes, cur_node))
1925 Idx idx = re_node_set_contains (dest_nodes, cur_node) - 1;
1926 re_node_set_remove_at (dest_nodes, idx);
1929 re_node_set_free (&except_nodes);
1935 check_dst_limits (const re_match_context_t *mctx, const re_node_set *limits,
1936 Idx dst_node, Idx dst_idx, Idx src_node, Idx src_idx)
1938 const re_dfa_t *const dfa = mctx->dfa;
1939 Idx lim_idx, src_pos, dst_pos;
1941 Idx dst_bkref_idx = search_cur_bkref_entry (mctx, dst_idx);
1942 Idx src_bkref_idx = search_cur_bkref_entry (mctx, src_idx);
1943 for (lim_idx = 0; lim_idx < limits->nelem; ++lim_idx)
1946 struct re_backref_cache_entry *ent;
1947 ent = mctx->bkref_ents + limits->elems[lim_idx];
1948 subexp_idx = dfa->nodes[ent->node].opr.idx;
1950 dst_pos = check_dst_limits_calc_pos (mctx, limits->elems[lim_idx],
1951 subexp_idx, dst_node, dst_idx,
1953 src_pos = check_dst_limits_calc_pos (mctx, limits->elems[lim_idx],
1954 subexp_idx, src_node, src_idx,
1958 <src> <dst> ( <subexp> )
1959 ( <subexp> ) <src> <dst>
1960 ( <subexp1> <src> <subexp2> <dst> <subexp3> ) */
1961 if (src_pos == dst_pos)
1962 continue; /* This is unrelated limitation. */
1971 check_dst_limits_calc_pos_1 (const re_match_context_t *mctx, int boundaries,
1972 Idx subexp_idx, Idx from_node, Idx bkref_idx)
1974 const re_dfa_t *const dfa = mctx->dfa;
1975 const re_node_set *eclosures = dfa->eclosures + from_node;
1978 /* Else, we are on the boundary: examine the nodes on the epsilon
1980 for (node_idx = 0; node_idx < eclosures->nelem; ++node_idx)
1982 Idx node = eclosures->elems[node_idx];
1983 switch (dfa->nodes[node].type)
1986 if (bkref_idx != REG_MISSING)
1988 struct re_backref_cache_entry *ent = mctx->bkref_ents + bkref_idx;
1994 if (ent->node != node)
1997 if (subexp_idx < BITSET_WORD_BITS
1998 && !(ent->eps_reachable_subexps_map
1999 & ((bitset_word_t) 1 << subexp_idx)))
2002 /* Recurse trying to reach the OP_OPEN_SUBEXP and
2003 OP_CLOSE_SUBEXP cases below. But, if the
2004 destination node is the same node as the source
2005 node, don't recurse because it would cause an
2006 infinite loop: a regex that exhibits this behavior
2008 dst = dfa->edests[node].elems[0];
2009 if (dst == from_node)
2013 else /* if (boundaries & 2) */
2018 check_dst_limits_calc_pos_1 (mctx, boundaries, subexp_idx,
2020 if (cpos == -1 /* && (boundaries & 1) */)
2022 if (cpos == 0 && (boundaries & 2))
2025 if (subexp_idx < BITSET_WORD_BITS)
2026 ent->eps_reachable_subexps_map
2027 &= ~((bitset_word_t) 1 << subexp_idx);
2029 while (ent++->more);
2033 case OP_OPEN_SUBEXP:
2034 if ((boundaries & 1) && subexp_idx == dfa->nodes[node].opr.idx)
2038 case OP_CLOSE_SUBEXP:
2039 if ((boundaries & 2) && subexp_idx == dfa->nodes[node].opr.idx)
2048 return (boundaries & 2) ? 1 : 0;
2053 check_dst_limits_calc_pos (const re_match_context_t *mctx, Idx limit,
2054 Idx subexp_idx, Idx from_node, Idx str_idx,
2057 struct re_backref_cache_entry *lim = mctx->bkref_ents + limit;
2060 /* If we are outside the range of the subexpression, return -1 or 1. */
2061 if (str_idx < lim->subexp_from)
2064 if (lim->subexp_to < str_idx)
2067 /* If we are within the subexpression, return 0. */
2068 boundaries = (str_idx == lim->subexp_from);
2069 boundaries |= (str_idx == lim->subexp_to) << 1;
2070 if (boundaries == 0)
2073 /* Else, examine epsilon closure. */
2074 return check_dst_limits_calc_pos_1 (mctx, boundaries, subexp_idx,
2075 from_node, bkref_idx);
2078 /* Check the limitations of sub expressions LIMITS, and remove the nodes
2079 which are against limitations from DEST_NODES. */
2081 static reg_errcode_t
2083 check_subexp_limits (const re_dfa_t *dfa, re_node_set *dest_nodes,
2084 const re_node_set *candidates, re_node_set *limits,
2085 struct re_backref_cache_entry *bkref_ents, Idx str_idx)
2088 Idx node_idx, lim_idx;
2090 for (lim_idx = 0; lim_idx < limits->nelem; ++lim_idx)
2093 struct re_backref_cache_entry *ent;
2094 ent = bkref_ents + limits->elems[lim_idx];
2096 if (str_idx <= ent->subexp_from || ent->str_idx < str_idx)
2097 continue; /* This is unrelated limitation. */
2099 subexp_idx = dfa->nodes[ent->node].opr.idx;
2100 if (ent->subexp_to == str_idx)
2102 Idx ops_node = REG_MISSING;
2103 Idx cls_node = REG_MISSING;
2104 for (node_idx = 0; node_idx < dest_nodes->nelem; ++node_idx)
2106 Idx node = dest_nodes->elems[node_idx];
2107 re_token_type_t type = dfa->nodes[node].type;
2108 if (type == OP_OPEN_SUBEXP
2109 && subexp_idx == dfa->nodes[node].opr.idx)
2111 else if (type == OP_CLOSE_SUBEXP
2112 && subexp_idx == dfa->nodes[node].opr.idx)
2116 /* Check the limitation of the open subexpression. */
2117 /* Note that (ent->subexp_to = str_idx != ent->subexp_from). */
2118 if (REG_VALID_INDEX (ops_node))
2120 err = sub_epsilon_src_nodes (dfa, ops_node, dest_nodes,
2122 if (BE (err != REG_NOERROR, 0))
2126 /* Check the limitation of the close subexpression. */
2127 if (REG_VALID_INDEX (cls_node))
2128 for (node_idx = 0; node_idx < dest_nodes->nelem; ++node_idx)
2130 Idx node = dest_nodes->elems[node_idx];
2131 if (!re_node_set_contains (dfa->inveclosures + node,
2133 && !re_node_set_contains (dfa->eclosures + node,
2136 /* It is against this limitation.
2137 Remove it form the current sifted state. */
2138 err = sub_epsilon_src_nodes (dfa, node, dest_nodes,
2140 if (BE (err != REG_NOERROR, 0))
2146 else /* (ent->subexp_to != str_idx) */
2148 for (node_idx = 0; node_idx < dest_nodes->nelem; ++node_idx)
2150 Idx node = dest_nodes->elems[node_idx];
2151 re_token_type_t type = dfa->nodes[node].type;
2152 if (type == OP_CLOSE_SUBEXP || type == OP_OPEN_SUBEXP)
2154 if (subexp_idx != dfa->nodes[node].opr.idx)
2156 /* It is against this limitation.
2157 Remove it form the current sifted state. */
2158 err = sub_epsilon_src_nodes (dfa, node, dest_nodes,
2160 if (BE (err != REG_NOERROR, 0))
2169 static reg_errcode_t
2170 internal_function __attribute_warn_unused_result__
2171 sift_states_bkref (const re_match_context_t *mctx, re_sift_context_t *sctx,
2172 Idx str_idx, const re_node_set *candidates)
2174 const re_dfa_t *const dfa = mctx->dfa;
2177 re_sift_context_t local_sctx;
2178 Idx first_idx = search_cur_bkref_entry (mctx, str_idx);
2180 if (first_idx == REG_MISSING)
2183 local_sctx.sifted_states = NULL; /* Mark that it hasn't been initialized. */
2185 for (node_idx = 0; node_idx < candidates->nelem; ++node_idx)
2188 re_token_type_t type;
2189 struct re_backref_cache_entry *entry;
2190 node = candidates->elems[node_idx];
2191 type = dfa->nodes[node].type;
2192 /* Avoid infinite loop for the REs like "()\1+". */
2193 if (node == sctx->last_node && str_idx == sctx->last_str_idx)
2195 if (type != OP_BACK_REF)
2198 entry = mctx->bkref_ents + first_idx;
2199 enabled_idx = first_idx;
2206 re_dfastate_t *cur_state;
2208 if (entry->node != node)
2210 subexp_len = entry->subexp_to - entry->subexp_from;
2211 to_idx = str_idx + subexp_len;
2212 dst_node = (subexp_len ? dfa->nexts[node]
2213 : dfa->edests[node].elems[0]);
2215 if (to_idx > sctx->last_str_idx
2216 || sctx->sifted_states[to_idx] == NULL
2217 || !STATE_NODE_CONTAINS (sctx->sifted_states[to_idx], dst_node)
2218 || check_dst_limits (mctx, &sctx->limits, node,
2219 str_idx, dst_node, to_idx))
2222 if (local_sctx.sifted_states == NULL)
2225 err = re_node_set_init_copy (&local_sctx.limits, &sctx->limits);
2226 if (BE (err != REG_NOERROR, 0))
2229 local_sctx.last_node = node;
2230 local_sctx.last_str_idx = str_idx;
2231 ok = re_node_set_insert (&local_sctx.limits, enabled_idx);
2237 cur_state = local_sctx.sifted_states[str_idx];
2238 err = sift_states_backward (mctx, &local_sctx);
2239 if (BE (err != REG_NOERROR, 0))
2241 if (sctx->limited_states != NULL)
2243 err = merge_state_array (dfa, sctx->limited_states,
2244 local_sctx.sifted_states,
2246 if (BE (err != REG_NOERROR, 0))
2249 local_sctx.sifted_states[str_idx] = cur_state;
2250 re_node_set_remove (&local_sctx.limits, enabled_idx);
2252 /* mctx->bkref_ents may have changed, reload the pointer. */
2253 entry = mctx->bkref_ents + enabled_idx;
2255 while (enabled_idx++, entry++->more);
2259 if (local_sctx.sifted_states != NULL)
2261 re_node_set_free (&local_sctx.limits);
2268 #ifdef RE_ENABLE_I18N
2271 sift_states_iter_mb (const re_match_context_t *mctx, re_sift_context_t *sctx,
2272 Idx node_idx, Idx str_idx, Idx max_str_idx)
2274 const re_dfa_t *const dfa = mctx->dfa;
2276 /* Check the node can accept "multi byte". */
2277 naccepted = check_node_accept_bytes (dfa, node_idx, &mctx->input, str_idx);
2278 if (naccepted > 0 && str_idx + naccepted <= max_str_idx &&
2279 !STATE_NODE_CONTAINS (sctx->sifted_states[str_idx + naccepted],
2280 dfa->nexts[node_idx]))
2281 /* The node can't accept the "multi byte", or the
2282 destination was already thrown away, then the node
2283 could't accept the current input "multi byte". */
2285 /* Otherwise, it is sure that the node could accept
2286 'naccepted' bytes input. */
2289 #endif /* RE_ENABLE_I18N */
2292 /* Functions for state transition. */
2294 /* Return the next state to which the current state STATE will transit by
2295 accepting the current input byte, and update STATE_LOG if necessary.
2296 If STATE can accept a multibyte char/collating element/back reference
2297 update the destination of STATE_LOG. */
2299 static re_dfastate_t *
2300 internal_function __attribute_warn_unused_result__
2301 transit_state (reg_errcode_t *err, re_match_context_t *mctx,
2302 re_dfastate_t *state)
2304 re_dfastate_t **trtable;
2307 #ifdef RE_ENABLE_I18N
2308 /* If the current state can accept multibyte. */
2309 if (BE (state->accept_mb, 0))
2311 *err = transit_state_mb (mctx, state);
2312 if (BE (*err != REG_NOERROR, 0))
2315 #endif /* RE_ENABLE_I18N */
2317 /* Then decide the next state with the single byte. */
2320 /* don't use transition table */
2321 return transit_state_sb (err, mctx, state);
2324 /* Use transition table */
2325 ch = re_string_fetch_byte (&mctx->input);
2328 trtable = state->trtable;
2329 if (BE (trtable != NULL, 1))
2332 trtable = state->word_trtable;
2333 if (BE (trtable != NULL, 1))
2335 unsigned int context;
2337 = re_string_context_at (&mctx->input,
2338 re_string_cur_idx (&mctx->input) - 1,
2340 if (IS_WORD_CONTEXT (context))
2341 return trtable[ch + SBC_MAX];
2346 if (!build_trtable (mctx->dfa, state))
2352 /* Retry, we now have a transition table. */
2356 /* Update the state_log if we need */
2357 static re_dfastate_t *
2359 merge_state_with_log (reg_errcode_t *err, re_match_context_t *mctx,
2360 re_dfastate_t *next_state)
2362 const re_dfa_t *const dfa = mctx->dfa;
2363 Idx cur_idx = re_string_cur_idx (&mctx->input);
2365 if (cur_idx > mctx->state_log_top)
2367 mctx->state_log[cur_idx] = next_state;
2368 mctx->state_log_top = cur_idx;
2370 else if (mctx->state_log[cur_idx] == 0)
2372 mctx->state_log[cur_idx] = next_state;
2376 re_dfastate_t *pstate;
2377 unsigned int context;
2378 re_node_set next_nodes, *log_nodes, *table_nodes = NULL;
2379 /* If (state_log[cur_idx] != 0), it implies that cur_idx is
2380 the destination of a multibyte char/collating element/
2381 back reference. Then the next state is the union set of
2382 these destinations and the results of the transition table. */
2383 pstate = mctx->state_log[cur_idx];
2384 log_nodes = pstate->entrance_nodes;
2385 if (next_state != NULL)
2387 table_nodes = next_state->entrance_nodes;
2388 *err = re_node_set_init_union (&next_nodes, table_nodes,
2390 if (BE (*err != REG_NOERROR, 0))
2394 next_nodes = *log_nodes;
2395 /* Note: We already add the nodes of the initial state,
2396 then we don't need to add them here. */
2398 context = re_string_context_at (&mctx->input,
2399 re_string_cur_idx (&mctx->input) - 1,
2401 next_state = mctx->state_log[cur_idx]
2402 = re_acquire_state_context (err, dfa, &next_nodes, context);
2403 /* We don't need to check errors here, since the return value of
2404 this function is next_state and ERR is already set. */
2406 if (table_nodes != NULL)
2407 re_node_set_free (&next_nodes);
2410 if (BE (dfa->nbackref, 0) && next_state != NULL)
2412 /* Check OP_OPEN_SUBEXP in the current state in case that we use them
2413 later. We must check them here, since the back references in the
2414 next state might use them. */
2415 *err = check_subexp_matching_top (mctx, &next_state->nodes,
2417 if (BE (*err != REG_NOERROR, 0))
2420 /* If the next state has back references. */
2421 if (next_state->has_backref)
2423 *err = transit_state_bkref (mctx, &next_state->nodes);
2424 if (BE (*err != REG_NOERROR, 0))
2426 next_state = mctx->state_log[cur_idx];
2433 /* Skip bytes in the input that correspond to part of a
2434 multi-byte match, then look in the log for a state
2435 from which to restart matching. */
2436 static re_dfastate_t *
2438 find_recover_state (reg_errcode_t *err, re_match_context_t *mctx)
2440 re_dfastate_t *cur_state;
2443 Idx max = mctx->state_log_top;
2444 Idx cur_str_idx = re_string_cur_idx (&mctx->input);
2448 if (++cur_str_idx > max)
2450 re_string_skip_bytes (&mctx->input, 1);
2452 while (mctx->state_log[cur_str_idx] == NULL);
2454 cur_state = merge_state_with_log (err, mctx, NULL);
2456 while (*err == REG_NOERROR && cur_state == NULL);
2460 /* Helper functions for transit_state. */
2462 /* From the node set CUR_NODES, pick up the nodes whose types are
2463 OP_OPEN_SUBEXP and which have corresponding back references in the regular
2464 expression. And register them to use them later for evaluating the
2465 corresponding back references. */
2467 static reg_errcode_t
2469 check_subexp_matching_top (re_match_context_t *mctx, re_node_set *cur_nodes,
2472 const re_dfa_t *const dfa = mctx->dfa;
2476 /* TODO: This isn't efficient.
2477 Because there might be more than one nodes whose types are
2478 OP_OPEN_SUBEXP and whose index is SUBEXP_IDX, we must check all
2481 for (node_idx = 0; node_idx < cur_nodes->nelem; ++node_idx)
2483 Idx node = cur_nodes->elems[node_idx];
2484 if (dfa->nodes[node].type == OP_OPEN_SUBEXP
2485 && dfa->nodes[node].opr.idx < BITSET_WORD_BITS
2486 && (dfa->used_bkref_map
2487 & ((bitset_word_t) 1 << dfa->nodes[node].opr.idx)))
2489 err = match_ctx_add_subtop (mctx, node, str_idx);
2490 if (BE (err != REG_NOERROR, 0))
2498 /* Return the next state to which the current state STATE will transit by
2499 accepting the current input byte. */
2501 static re_dfastate_t *
2502 transit_state_sb (reg_errcode_t *err, re_match_context_t *mctx,
2503 re_dfastate_t *state)
2505 const re_dfa_t *const dfa = mctx->dfa;
2506 re_node_set next_nodes;
2507 re_dfastate_t *next_state;
2508 Idx node_cnt, cur_str_idx = re_string_cur_idx (&mctx->input);
2509 unsigned int context;
2511 *err = re_node_set_alloc (&next_nodes, state->nodes.nelem + 1);
2512 if (BE (*err != REG_NOERROR, 0))
2514 for (node_cnt = 0; node_cnt < state->nodes.nelem; ++node_cnt)
2516 Idx cur_node = state->nodes.elems[node_cnt];
2517 if (check_node_accept (mctx, dfa->nodes + cur_node, cur_str_idx))
2519 *err = re_node_set_merge (&next_nodes,
2520 dfa->eclosures + dfa->nexts[cur_node]);
2521 if (BE (*err != REG_NOERROR, 0))
2523 re_node_set_free (&next_nodes);
2528 context = re_string_context_at (&mctx->input, cur_str_idx, mctx->eflags);
2529 next_state = re_acquire_state_context (err, dfa, &next_nodes, context);
2530 /* We don't need to check errors here, since the return value of
2531 this function is next_state and ERR is already set. */
2533 re_node_set_free (&next_nodes);
2534 re_string_skip_bytes (&mctx->input, 1);
2539 #ifdef RE_ENABLE_I18N
2540 static reg_errcode_t
2542 transit_state_mb (re_match_context_t *mctx, re_dfastate_t *pstate)
2544 const re_dfa_t *const dfa = mctx->dfa;
2548 for (i = 0; i < pstate->nodes.nelem; ++i)
2550 re_node_set dest_nodes, *new_nodes;
2551 Idx cur_node_idx = pstate->nodes.elems[i];
2554 unsigned int context;
2555 re_dfastate_t *dest_state;
2557 if (!dfa->nodes[cur_node_idx].accept_mb)
2560 if (dfa->nodes[cur_node_idx].constraint)
2562 context = re_string_context_at (&mctx->input,
2563 re_string_cur_idx (&mctx->input),
2565 if (NOT_SATISFY_NEXT_CONSTRAINT (dfa->nodes[cur_node_idx].constraint,
2570 /* How many bytes the node can accept? */
2571 naccepted = check_node_accept_bytes (dfa, cur_node_idx, &mctx->input,
2572 re_string_cur_idx (&mctx->input));
2576 /* The node can accepts 'naccepted' bytes. */
2577 dest_idx = re_string_cur_idx (&mctx->input) + naccepted;
2578 mctx->max_mb_elem_len = ((mctx->max_mb_elem_len < naccepted) ? naccepted
2579 : mctx->max_mb_elem_len);
2580 err = clean_state_log_if_needed (mctx, dest_idx);
2581 if (BE (err != REG_NOERROR, 0))
2584 assert (dfa->nexts[cur_node_idx] != REG_MISSING);
2586 new_nodes = dfa->eclosures + dfa->nexts[cur_node_idx];
2588 dest_state = mctx->state_log[dest_idx];
2589 if (dest_state == NULL)
2590 dest_nodes = *new_nodes;
2593 err = re_node_set_init_union (&dest_nodes,
2594 dest_state->entrance_nodes, new_nodes);
2595 if (BE (err != REG_NOERROR, 0))
2598 context = re_string_context_at (&mctx->input, dest_idx - 1,
2600 mctx->state_log[dest_idx]
2601 = re_acquire_state_context (&err, dfa, &dest_nodes, context);
2602 if (dest_state != NULL)
2603 re_node_set_free (&dest_nodes);
2604 if (BE (mctx->state_log[dest_idx] == NULL && err != REG_NOERROR, 0))
2609 #endif /* RE_ENABLE_I18N */
2611 static reg_errcode_t
2613 transit_state_bkref (re_match_context_t *mctx, const re_node_set *nodes)
2615 const re_dfa_t *const dfa = mctx->dfa;
2618 Idx cur_str_idx = re_string_cur_idx (&mctx->input);
2620 for (i = 0; i < nodes->nelem; ++i)
2622 Idx dest_str_idx, prev_nelem, bkc_idx;
2623 Idx node_idx = nodes->elems[i];
2624 unsigned int context;
2625 const re_token_t *node = dfa->nodes + node_idx;
2626 re_node_set *new_dest_nodes;
2628 /* Check whether 'node' is a backreference or not. */
2629 if (node->type != OP_BACK_REF)
2632 if (node->constraint)
2634 context = re_string_context_at (&mctx->input, cur_str_idx,
2636 if (NOT_SATISFY_NEXT_CONSTRAINT (node->constraint, context))
2640 /* 'node' is a backreference.
2641 Check the substring which the substring matched. */
2642 bkc_idx = mctx->nbkref_ents;
2643 err = get_subexp (mctx, node_idx, cur_str_idx);
2644 if (BE (err != REG_NOERROR, 0))
2647 /* And add the epsilon closures (which is 'new_dest_nodes') of
2648 the backreference to appropriate state_log. */
2650 assert (dfa->nexts[node_idx] != REG_MISSING);
2652 for (; bkc_idx < mctx->nbkref_ents; ++bkc_idx)
2655 re_dfastate_t *dest_state;
2656 struct re_backref_cache_entry *bkref_ent;
2657 bkref_ent = mctx->bkref_ents + bkc_idx;
2658 if (bkref_ent->node != node_idx || bkref_ent->str_idx != cur_str_idx)
2660 subexp_len = bkref_ent->subexp_to - bkref_ent->subexp_from;
2661 new_dest_nodes = (subexp_len == 0
2662 ? dfa->eclosures + dfa->edests[node_idx].elems[0]
2663 : dfa->eclosures + dfa->nexts[node_idx]);
2664 dest_str_idx = (cur_str_idx + bkref_ent->subexp_to
2665 - bkref_ent->subexp_from);
2666 context = re_string_context_at (&mctx->input, dest_str_idx - 1,
2668 dest_state = mctx->state_log[dest_str_idx];
2669 prev_nelem = ((mctx->state_log[cur_str_idx] == NULL) ? 0
2670 : mctx->state_log[cur_str_idx]->nodes.nelem);
2671 /* Add 'new_dest_node' to state_log. */
2672 if (dest_state == NULL)
2674 mctx->state_log[dest_str_idx]
2675 = re_acquire_state_context (&err, dfa, new_dest_nodes,
2677 if (BE (mctx->state_log[dest_str_idx] == NULL
2678 && err != REG_NOERROR, 0))
2683 re_node_set dest_nodes;
2684 err = re_node_set_init_union (&dest_nodes,
2685 dest_state->entrance_nodes,
2687 if (BE (err != REG_NOERROR, 0))
2689 re_node_set_free (&dest_nodes);
2692 mctx->state_log[dest_str_idx]
2693 = re_acquire_state_context (&err, dfa, &dest_nodes, context);
2694 re_node_set_free (&dest_nodes);
2695 if (BE (mctx->state_log[dest_str_idx] == NULL
2696 && err != REG_NOERROR, 0))
2699 /* We need to check recursively if the backreference can epsilon
2702 && mctx->state_log[cur_str_idx]->nodes.nelem > prev_nelem)
2704 err = check_subexp_matching_top (mctx, new_dest_nodes,
2706 if (BE (err != REG_NOERROR, 0))
2708 err = transit_state_bkref (mctx, new_dest_nodes);
2709 if (BE (err != REG_NOERROR, 0))
2719 /* Enumerate all the candidates which the backreference BKREF_NODE can match
2720 at BKREF_STR_IDX, and register them by match_ctx_add_entry().
2721 Note that we might collect inappropriate candidates here.
2722 However, the cost of checking them strictly here is too high, then we
2723 delay these checking for prune_impossible_nodes(). */
2725 static reg_errcode_t
2726 internal_function __attribute_warn_unused_result__
2727 get_subexp (re_match_context_t *mctx, Idx bkref_node, Idx bkref_str_idx)
2729 const re_dfa_t *const dfa = mctx->dfa;
2730 Idx subexp_num, sub_top_idx;
2731 const char *buf = (const char *) re_string_get_buffer (&mctx->input);
2732 /* Return if we have already checked BKREF_NODE at BKREF_STR_IDX. */
2733 Idx cache_idx = search_cur_bkref_entry (mctx, bkref_str_idx);
2734 if (cache_idx != REG_MISSING)
2736 const struct re_backref_cache_entry *entry
2737 = mctx->bkref_ents + cache_idx;
2739 if (entry->node == bkref_node)
2740 return REG_NOERROR; /* We already checked it. */
2741 while (entry++->more);
2744 subexp_num = dfa->nodes[bkref_node].opr.idx;
2746 /* For each sub expression */
2747 for (sub_top_idx = 0; sub_top_idx < mctx->nsub_tops; ++sub_top_idx)
2750 re_sub_match_top_t *sub_top = mctx->sub_tops[sub_top_idx];
2751 re_sub_match_last_t *sub_last;
2752 Idx sub_last_idx, sl_str, bkref_str_off;
2754 if (dfa->nodes[sub_top->node].opr.idx != subexp_num)
2755 continue; /* It isn't related. */
2757 sl_str = sub_top->str_idx;
2758 bkref_str_off = bkref_str_idx;
2759 /* At first, check the last node of sub expressions we already
2761 for (sub_last_idx = 0; sub_last_idx < sub_top->nlasts; ++sub_last_idx)
2763 regoff_t sl_str_diff;
2764 sub_last = sub_top->lasts[sub_last_idx];
2765 sl_str_diff = sub_last->str_idx - sl_str;
2766 /* The matched string by the sub expression match with the substring
2767 at the back reference? */
2768 if (sl_str_diff > 0)
2770 if (BE (bkref_str_off + sl_str_diff > mctx->input.valid_len, 0))
2772 /* Not enough chars for a successful match. */
2773 if (bkref_str_off + sl_str_diff > mctx->input.len)
2776 err = clean_state_log_if_needed (mctx,
2779 if (BE (err != REG_NOERROR, 0))
2781 buf = (const char *) re_string_get_buffer (&mctx->input);
2783 if (memcmp (buf + bkref_str_off, buf + sl_str, sl_str_diff) != 0)
2784 /* We don't need to search this sub expression any more. */
2787 bkref_str_off += sl_str_diff;
2788 sl_str += sl_str_diff;
2789 err = get_subexp_sub (mctx, sub_top, sub_last, bkref_node,
2792 /* Reload buf, since the preceding call might have reallocated
2794 buf = (const char *) re_string_get_buffer (&mctx->input);
2796 if (err == REG_NOMATCH)
2798 if (BE (err != REG_NOERROR, 0))
2802 if (sub_last_idx < sub_top->nlasts)
2804 if (sub_last_idx > 0)
2806 /* Then, search for the other last nodes of the sub expression. */
2807 for (; sl_str <= bkref_str_idx; ++sl_str)
2810 regoff_t sl_str_off;
2811 const re_node_set *nodes;
2812 sl_str_off = sl_str - sub_top->str_idx;
2813 /* The matched string by the sub expression match with the substring
2814 at the back reference? */
2817 if (BE (bkref_str_off >= mctx->input.valid_len, 0))
2819 /* If we are at the end of the input, we cannot match. */
2820 if (bkref_str_off >= mctx->input.len)
2823 err = extend_buffers (mctx);
2824 if (BE (err != REG_NOERROR, 0))
2827 buf = (const char *) re_string_get_buffer (&mctx->input);
2829 if (buf [bkref_str_off++] != buf[sl_str - 1])
2830 break; /* We don't need to search this sub expression
2833 if (mctx->state_log[sl_str] == NULL)
2835 /* Does this state have a ')' of the sub expression? */
2836 nodes = &mctx->state_log[sl_str]->nodes;
2837 cls_node = find_subexp_node (dfa, nodes, subexp_num,
2839 if (cls_node == REG_MISSING)
2841 if (sub_top->path == NULL)
2843 sub_top->path = calloc (sizeof (state_array_t),
2844 sl_str - sub_top->str_idx + 1);
2845 if (sub_top->path == NULL)
2848 /* Can the OP_OPEN_SUBEXP node arrive the OP_CLOSE_SUBEXP node
2849 in the current context? */
2850 err = check_arrival (mctx, sub_top->path, sub_top->node,
2851 sub_top->str_idx, cls_node, sl_str,
2853 if (err == REG_NOMATCH)
2855 if (BE (err != REG_NOERROR, 0))
2857 sub_last = match_ctx_add_sublast (sub_top, cls_node, sl_str);
2858 if (BE (sub_last == NULL, 0))
2860 err = get_subexp_sub (mctx, sub_top, sub_last, bkref_node,
2862 if (err == REG_NOMATCH)
2869 /* Helper functions for get_subexp(). */
2871 /* Check SUB_LAST can arrive to the back reference BKREF_NODE at BKREF_STR.
2872 If it can arrive, register the sub expression expressed with SUB_TOP
2875 static reg_errcode_t
2877 get_subexp_sub (re_match_context_t *mctx, const re_sub_match_top_t *sub_top,
2878 re_sub_match_last_t *sub_last, Idx bkref_node, Idx bkref_str)
2882 /* Can the subexpression arrive the back reference? */
2883 err = check_arrival (mctx, &sub_last->path, sub_last->node,
2884 sub_last->str_idx, bkref_node, bkref_str,
2886 if (err != REG_NOERROR)
2888 err = match_ctx_add_entry (mctx, bkref_node, bkref_str, sub_top->str_idx,
2890 if (BE (err != REG_NOERROR, 0))
2892 to_idx = bkref_str + sub_last->str_idx - sub_top->str_idx;
2893 return clean_state_log_if_needed (mctx, to_idx);
2896 /* Find the first node which is '(' or ')' and whose index is SUBEXP_IDX.
2897 Search '(' if FL_OPEN, or search ')' otherwise.
2898 TODO: This function isn't efficient...
2899 Because there might be more than one nodes whose types are
2900 OP_OPEN_SUBEXP and whose index is SUBEXP_IDX, we must check all
2906 find_subexp_node (const re_dfa_t *dfa, const re_node_set *nodes,
2907 Idx subexp_idx, int type)
2910 for (cls_idx = 0; cls_idx < nodes->nelem; ++cls_idx)
2912 Idx cls_node = nodes->elems[cls_idx];
2913 const re_token_t *node = dfa->nodes + cls_node;
2914 if (node->type == type
2915 && node->opr.idx == subexp_idx)
2921 /* Check whether the node TOP_NODE at TOP_STR can arrive to the node
2922 LAST_NODE at LAST_STR. We record the path onto PATH since it will be
2924 Return REG_NOERROR if it can arrive, or REG_NOMATCH otherwise. */
2926 static reg_errcode_t
2927 internal_function __attribute_warn_unused_result__
2928 check_arrival (re_match_context_t *mctx, state_array_t *path, Idx top_node,
2929 Idx top_str, Idx last_node, Idx last_str, int type)
2931 const re_dfa_t *const dfa = mctx->dfa;
2932 reg_errcode_t err = REG_NOERROR;
2933 Idx subexp_num, backup_cur_idx, str_idx, null_cnt;
2934 re_dfastate_t *cur_state = NULL;
2935 re_node_set *cur_nodes, next_nodes;
2936 re_dfastate_t **backup_state_log;
2937 unsigned int context;
2939 subexp_num = dfa->nodes[top_node].opr.idx;
2940 /* Extend the buffer if we need. */
2941 if (BE (path->alloc < last_str + mctx->max_mb_elem_len + 1, 0))
2943 re_dfastate_t **new_array;
2944 Idx old_alloc = path->alloc;
2945 Idx incr_alloc = last_str + mctx->max_mb_elem_len + 1;
2947 if (BE (IDX_MAX - old_alloc < incr_alloc, 0))
2949 new_alloc = old_alloc + incr_alloc;
2950 if (BE (SIZE_MAX / sizeof (re_dfastate_t *) < new_alloc, 0))
2952 new_array = re_realloc (path->array, re_dfastate_t *, new_alloc);
2953 if (BE (new_array == NULL, 0))
2955 path->array = new_array;
2956 path->alloc = new_alloc;
2957 memset (new_array + old_alloc, '\0',
2958 sizeof (re_dfastate_t *) * (path->alloc - old_alloc));
2961 str_idx = path->next_idx ? path->next_idx : top_str;
2963 /* Temporary modify MCTX. */
2964 backup_state_log = mctx->state_log;
2965 backup_cur_idx = mctx->input.cur_idx;
2966 mctx->state_log = path->array;
2967 mctx->input.cur_idx = str_idx;
2969 /* Setup initial node set. */
2970 context = re_string_context_at (&mctx->input, str_idx - 1, mctx->eflags);
2971 if (str_idx == top_str)
2973 err = re_node_set_init_1 (&next_nodes, top_node);
2974 if (BE (err != REG_NOERROR, 0))
2976 err = check_arrival_expand_ecl (dfa, &next_nodes, subexp_num, type);
2977 if (BE (err != REG_NOERROR, 0))
2979 re_node_set_free (&next_nodes);
2985 cur_state = mctx->state_log[str_idx];
2986 if (cur_state && cur_state->has_backref)
2988 err = re_node_set_init_copy (&next_nodes, &cur_state->nodes);
2989 if (BE (err != REG_NOERROR, 0))
2993 re_node_set_init_empty (&next_nodes);
2995 if (str_idx == top_str || (cur_state && cur_state->has_backref))
2997 if (next_nodes.nelem)
2999 err = expand_bkref_cache (mctx, &next_nodes, str_idx,
3001 if (BE (err != REG_NOERROR, 0))
3003 re_node_set_free (&next_nodes);
3007 cur_state = re_acquire_state_context (&err, dfa, &next_nodes, context);
3008 if (BE (cur_state == NULL && err != REG_NOERROR, 0))
3010 re_node_set_free (&next_nodes);
3013 mctx->state_log[str_idx] = cur_state;
3016 for (null_cnt = 0; str_idx < last_str && null_cnt <= mctx->max_mb_elem_len;)
3018 re_node_set_empty (&next_nodes);
3019 if (mctx->state_log[str_idx + 1])
3021 err = re_node_set_merge (&next_nodes,
3022 &mctx->state_log[str_idx + 1]->nodes);
3023 if (BE (err != REG_NOERROR, 0))
3025 re_node_set_free (&next_nodes);
3031 err = check_arrival_add_next_nodes (mctx, str_idx,
3032 &cur_state->non_eps_nodes,
3034 if (BE (err != REG_NOERROR, 0))
3036 re_node_set_free (&next_nodes);
3041 if (next_nodes.nelem)
3043 err = check_arrival_expand_ecl (dfa, &next_nodes, subexp_num, type);
3044 if (BE (err != REG_NOERROR, 0))
3046 re_node_set_free (&next_nodes);
3049 err = expand_bkref_cache (mctx, &next_nodes, str_idx,
3051 if (BE (err != REG_NOERROR, 0))
3053 re_node_set_free (&next_nodes);
3057 context = re_string_context_at (&mctx->input, str_idx - 1, mctx->eflags);
3058 cur_state = re_acquire_state_context (&err, dfa, &next_nodes, context);
3059 if (BE (cur_state == NULL && err != REG_NOERROR, 0))
3061 re_node_set_free (&next_nodes);
3064 mctx->state_log[str_idx] = cur_state;
3065 null_cnt = cur_state == NULL ? null_cnt + 1 : 0;
3067 re_node_set_free (&next_nodes);
3068 cur_nodes = (mctx->state_log[last_str] == NULL ? NULL
3069 : &mctx->state_log[last_str]->nodes);
3070 path->next_idx = str_idx;
3073 mctx->state_log = backup_state_log;
3074 mctx->input.cur_idx = backup_cur_idx;
3076 /* Then check the current node set has the node LAST_NODE. */
3077 if (cur_nodes != NULL && re_node_set_contains (cur_nodes, last_node))
3083 /* Helper functions for check_arrival. */
3085 /* Calculate the destination nodes of CUR_NODES at STR_IDX, and append them
3087 TODO: This function is similar to the functions transit_state*(),
3088 however this function has many additional works.
3089 Can't we unify them? */
3091 static reg_errcode_t
3092 internal_function __attribute_warn_unused_result__
3093 check_arrival_add_next_nodes (re_match_context_t *mctx, Idx str_idx,
3094 re_node_set *cur_nodes, re_node_set *next_nodes)
3096 const re_dfa_t *const dfa = mctx->dfa;
3099 #ifdef RE_ENABLE_I18N
3100 reg_errcode_t err = REG_NOERROR;
3102 re_node_set union_set;
3103 re_node_set_init_empty (&union_set);
3104 for (cur_idx = 0; cur_idx < cur_nodes->nelem; ++cur_idx)
3107 Idx cur_node = cur_nodes->elems[cur_idx];
3109 re_token_type_t type = dfa->nodes[cur_node].type;
3110 assert (!IS_EPSILON_NODE (type));
3112 #ifdef RE_ENABLE_I18N
3113 /* If the node may accept "multi byte". */
3114 if (dfa->nodes[cur_node].accept_mb)
3116 naccepted = check_node_accept_bytes (dfa, cur_node, &mctx->input,
3120 re_dfastate_t *dest_state;
3121 Idx next_node = dfa->nexts[cur_node];
3122 Idx next_idx = str_idx + naccepted;
3123 dest_state = mctx->state_log[next_idx];
3124 re_node_set_empty (&union_set);
3127 err = re_node_set_merge (&union_set, &dest_state->nodes);
3128 if (BE (err != REG_NOERROR, 0))
3130 re_node_set_free (&union_set);
3134 ok = re_node_set_insert (&union_set, next_node);
3137 re_node_set_free (&union_set);
3140 mctx->state_log[next_idx] = re_acquire_state (&err, dfa,
3142 if (BE (mctx->state_log[next_idx] == NULL
3143 && err != REG_NOERROR, 0))
3145 re_node_set_free (&union_set);
3150 #endif /* RE_ENABLE_I18N */
3152 || check_node_accept (mctx, dfa->nodes + cur_node, str_idx))
3154 ok = re_node_set_insert (next_nodes, dfa->nexts[cur_node]);
3157 re_node_set_free (&union_set);
3162 re_node_set_free (&union_set);
3166 /* For all the nodes in CUR_NODES, add the epsilon closures of them to
3167 CUR_NODES, however exclude the nodes which are:
3168 - inside the sub expression whose number is EX_SUBEXP, if FL_OPEN.
3169 - out of the sub expression whose number is EX_SUBEXP, if !FL_OPEN.
3172 static reg_errcode_t
3174 check_arrival_expand_ecl (const re_dfa_t *dfa, re_node_set *cur_nodes,
3175 Idx ex_subexp, int type)
3178 Idx idx, outside_node;
3179 re_node_set new_nodes;
3181 assert (cur_nodes->nelem);
3183 err = re_node_set_alloc (&new_nodes, cur_nodes->nelem);
3184 if (BE (err != REG_NOERROR, 0))
3186 /* Create a new node set NEW_NODES with the nodes which are epsilon
3187 closures of the node in CUR_NODES. */
3189 for (idx = 0; idx < cur_nodes->nelem; ++idx)
3191 Idx cur_node = cur_nodes->elems[idx];
3192 const re_node_set *eclosure = dfa->eclosures + cur_node;
3193 outside_node = find_subexp_node (dfa, eclosure, ex_subexp, type);
3194 if (outside_node == REG_MISSING)
3196 /* There are no problematic nodes, just merge them. */
3197 err = re_node_set_merge (&new_nodes, eclosure);
3198 if (BE (err != REG_NOERROR, 0))
3200 re_node_set_free (&new_nodes);
3206 /* There are problematic nodes, re-calculate incrementally. */
3207 err = check_arrival_expand_ecl_sub (dfa, &new_nodes, cur_node,
3209 if (BE (err != REG_NOERROR, 0))
3211 re_node_set_free (&new_nodes);
3216 re_node_set_free (cur_nodes);
3217 *cur_nodes = new_nodes;
3221 /* Helper function for check_arrival_expand_ecl.
3222 Check incrementally the epsilon closure of TARGET, and if it isn't
3223 problematic append it to DST_NODES. */
3225 static reg_errcode_t
3226 internal_function __attribute_warn_unused_result__
3227 check_arrival_expand_ecl_sub (const re_dfa_t *dfa, re_node_set *dst_nodes,
3228 Idx target, Idx ex_subexp, int type)
3231 for (cur_node = target; !re_node_set_contains (dst_nodes, cur_node);)
3235 if (dfa->nodes[cur_node].type == type
3236 && dfa->nodes[cur_node].opr.idx == ex_subexp)
3238 if (type == OP_CLOSE_SUBEXP)
3240 ok = re_node_set_insert (dst_nodes, cur_node);
3246 ok = re_node_set_insert (dst_nodes, cur_node);
3249 if (dfa->edests[cur_node].nelem == 0)
3251 if (dfa->edests[cur_node].nelem == 2)
3254 err = check_arrival_expand_ecl_sub (dfa, dst_nodes,
3255 dfa->edests[cur_node].elems[1],
3257 if (BE (err != REG_NOERROR, 0))
3260 cur_node = dfa->edests[cur_node].elems[0];
3266 /* For all the back references in the current state, calculate the
3267 destination of the back references by the appropriate entry
3268 in MCTX->BKREF_ENTS. */
3270 static reg_errcode_t
3271 internal_function __attribute_warn_unused_result__
3272 expand_bkref_cache (re_match_context_t *mctx, re_node_set *cur_nodes,
3273 Idx cur_str, Idx subexp_num, int type)
3275 const re_dfa_t *const dfa = mctx->dfa;
3277 Idx cache_idx_start = search_cur_bkref_entry (mctx, cur_str);
3278 struct re_backref_cache_entry *ent;
3280 if (cache_idx_start == REG_MISSING)
3284 ent = mctx->bkref_ents + cache_idx_start;
3287 Idx to_idx, next_node;
3289 /* Is this entry ENT is appropriate? */
3290 if (!re_node_set_contains (cur_nodes, ent->node))
3293 to_idx = cur_str + ent->subexp_to - ent->subexp_from;
3294 /* Calculate the destination of the back reference, and append it
3295 to MCTX->STATE_LOG. */
3296 if (to_idx == cur_str)
3298 /* The backreference did epsilon transit, we must re-check all the
3299 node in the current state. */
3300 re_node_set new_dests;
3301 reg_errcode_t err2, err3;
3302 next_node = dfa->edests[ent->node].elems[0];
3303 if (re_node_set_contains (cur_nodes, next_node))
3305 err = re_node_set_init_1 (&new_dests, next_node);
3306 err2 = check_arrival_expand_ecl (dfa, &new_dests, subexp_num, type);
3307 err3 = re_node_set_merge (cur_nodes, &new_dests);
3308 re_node_set_free (&new_dests);
3309 if (BE (err != REG_NOERROR || err2 != REG_NOERROR
3310 || err3 != REG_NOERROR, 0))
3312 err = (err != REG_NOERROR ? err
3313 : (err2 != REG_NOERROR ? err2 : err3));
3316 /* TODO: It is still inefficient... */
3321 re_node_set union_set;
3322 next_node = dfa->nexts[ent->node];
3323 if (mctx->state_log[to_idx])
3326 if (re_node_set_contains (&mctx->state_log[to_idx]->nodes,
3329 err = re_node_set_init_copy (&union_set,
3330 &mctx->state_log[to_idx]->nodes);
3331 ok = re_node_set_insert (&union_set, next_node);
3332 if (BE (err != REG_NOERROR || ! ok, 0))
3334 re_node_set_free (&union_set);
3335 err = err != REG_NOERROR ? err : REG_ESPACE;
3341 err = re_node_set_init_1 (&union_set, next_node);
3342 if (BE (err != REG_NOERROR, 0))
3345 mctx->state_log[to_idx] = re_acquire_state (&err, dfa, &union_set);
3346 re_node_set_free (&union_set);
3347 if (BE (mctx->state_log[to_idx] == NULL
3348 && err != REG_NOERROR, 0))
3352 while (ent++->more);
3356 /* Build transition table for the state.
3357 Return true if successful. */
3361 build_trtable (const re_dfa_t *dfa, re_dfastate_t *state)
3366 bool need_word_trtable = false;
3367 bitset_word_t elem, mask;
3368 bool dests_node_malloced = false;
3369 bool dest_states_malloced = false;
3370 Idx ndests; /* Number of the destination states from 'state'. */
3371 re_dfastate_t **trtable;
3372 re_dfastate_t **dest_states = NULL, **dest_states_word, **dest_states_nl;
3373 re_node_set follows, *dests_node;
3375 bitset_t acceptable;
3379 re_node_set dests_node[SBC_MAX];
3380 bitset_t dests_ch[SBC_MAX];
3383 /* We build DFA states which corresponds to the destination nodes
3384 from 'state'. 'dests_node[i]' represents the nodes which i-th
3385 destination state contains, and 'dests_ch[i]' represents the
3386 characters which i-th destination state accepts. */
3387 if (__libc_use_alloca (sizeof (struct dests_alloc)))
3388 dests_alloc = (struct dests_alloc *) alloca (sizeof (struct dests_alloc));
3391 dests_alloc = re_malloc (struct dests_alloc, 1);
3392 if (BE (dests_alloc == NULL, 0))
3394 dests_node_malloced = true;
3396 dests_node = dests_alloc->dests_node;
3397 dests_ch = dests_alloc->dests_ch;
3399 /* Initialize transition table. */
3400 state->word_trtable = state->trtable = NULL;
3402 /* At first, group all nodes belonging to 'state' into several
3404 ndests = group_nodes_into_DFAstates (dfa, state, dests_node, dests_ch);
3405 if (BE (! REG_VALID_NONZERO_INDEX (ndests), 0))
3407 if (dests_node_malloced)
3409 /* Return false in case of an error, true otherwise. */
3412 state->trtable = (re_dfastate_t **)
3413 calloc (sizeof (re_dfastate_t *), SBC_MAX);
3414 if (BE (state->trtable == NULL, 0))
3421 err = re_node_set_alloc (&follows, ndests + 1);
3422 if (BE (err != REG_NOERROR, 0))
3425 /* Avoid arithmetic overflow in size calculation. */
3426 if (BE ((((SIZE_MAX - (sizeof (re_node_set) + sizeof (bitset_t)) * SBC_MAX)
3427 / (3 * sizeof (re_dfastate_t *)))
3432 if (__libc_use_alloca ((sizeof (re_node_set) + sizeof (bitset_t)) * SBC_MAX
3433 + ndests * 3 * sizeof (re_dfastate_t *)))
3434 dest_states = (re_dfastate_t **)
3435 alloca (ndests * 3 * sizeof (re_dfastate_t *));
3438 dest_states = (re_dfastate_t **)
3439 malloc (ndests * 3 * sizeof (re_dfastate_t *));
3440 if (BE (dest_states == NULL, 0))
3443 if (dest_states_malloced)
3445 re_node_set_free (&follows);
3446 for (i = 0; i < ndests; ++i)
3447 re_node_set_free (dests_node + i);
3448 if (dests_node_malloced)
3452 dest_states_malloced = true;
3454 dest_states_word = dest_states + ndests;
3455 dest_states_nl = dest_states_word + ndests;
3456 bitset_empty (acceptable);
3458 /* Then build the states for all destinations. */
3459 for (i = 0; i < ndests; ++i)
3462 re_node_set_empty (&follows);
3463 /* Merge the follows of this destination states. */
3464 for (j = 0; j < dests_node[i].nelem; ++j)
3466 next_node = dfa->nexts[dests_node[i].elems[j]];
3467 if (next_node != REG_MISSING)
3469 err = re_node_set_merge (&follows, dfa->eclosures + next_node);
3470 if (BE (err != REG_NOERROR, 0))
3474 dest_states[i] = re_acquire_state_context (&err, dfa, &follows, 0);
3475 if (BE (dest_states[i] == NULL && err != REG_NOERROR, 0))
3477 /* If the new state has context constraint,
3478 build appropriate states for these contexts. */
3479 if (dest_states[i]->has_constraint)
3481 dest_states_word[i] = re_acquire_state_context (&err, dfa, &follows,
3483 if (BE (dest_states_word[i] == NULL && err != REG_NOERROR, 0))
3486 if (dest_states[i] != dest_states_word[i] && dfa->mb_cur_max > 1)
3487 need_word_trtable = true;
3489 dest_states_nl[i] = re_acquire_state_context (&err, dfa, &follows,
3491 if (BE (dest_states_nl[i] == NULL && err != REG_NOERROR, 0))
3496 dest_states_word[i] = dest_states[i];
3497 dest_states_nl[i] = dest_states[i];
3499 bitset_merge (acceptable, dests_ch[i]);
3502 if (!BE (need_word_trtable, 0))
3504 /* We don't care about whether the following character is a word
3505 character, or we are in a single-byte character set so we can
3506 discern by looking at the character code: allocate a
3507 256-entry transition table. */
3508 trtable = state->trtable =
3509 (re_dfastate_t **) calloc (sizeof (re_dfastate_t *), SBC_MAX);
3510 if (BE (trtable == NULL, 0))
3513 /* For all characters ch...: */
3514 for (i = 0; i < BITSET_WORDS; ++i)
3515 for (ch = i * BITSET_WORD_BITS, elem = acceptable[i], mask = 1;
3517 mask <<= 1, elem >>= 1, ++ch)
3518 if (BE (elem & 1, 0))
3520 /* There must be exactly one destination which accepts
3521 character ch. See group_nodes_into_DFAstates. */
3522 for (j = 0; (dests_ch[j][i] & mask) == 0; ++j)
3525 /* j-th destination accepts the word character ch. */
3526 if (dfa->word_char[i] & mask)
3527 trtable[ch] = dest_states_word[j];
3529 trtable[ch] = dest_states[j];
3534 /* We care about whether the following character is a word
3535 character, and we are in a multi-byte character set: discern
3536 by looking at the character code: build two 256-entry
3537 transition tables, one starting at trtable[0] and one
3538 starting at trtable[SBC_MAX]. */
3539 trtable = state->word_trtable =
3540 (re_dfastate_t **) calloc (sizeof (re_dfastate_t *), 2 * SBC_MAX);
3541 if (BE (trtable == NULL, 0))
3544 /* For all characters ch...: */
3545 for (i = 0; i < BITSET_WORDS; ++i)
3546 for (ch = i * BITSET_WORD_BITS, elem = acceptable[i], mask = 1;
3548 mask <<= 1, elem >>= 1, ++ch)
3549 if (BE (elem & 1, 0))
3551 /* There must be exactly one destination which accepts
3552 character ch. See group_nodes_into_DFAstates. */
3553 for (j = 0; (dests_ch[j][i] & mask) == 0; ++j)
3556 /* j-th destination accepts the word character ch. */
3557 trtable[ch] = dest_states[j];
3558 trtable[ch + SBC_MAX] = dest_states_word[j];
3563 if (bitset_contain (acceptable, NEWLINE_CHAR))
3565 /* The current state accepts newline character. */
3566 for (j = 0; j < ndests; ++j)
3567 if (bitset_contain (dests_ch[j], NEWLINE_CHAR))
3569 /* k-th destination accepts newline character. */
3570 trtable[NEWLINE_CHAR] = dest_states_nl[j];
3571 if (need_word_trtable)
3572 trtable[NEWLINE_CHAR + SBC_MAX] = dest_states_nl[j];
3573 /* There must be only one destination which accepts
3574 newline. See group_nodes_into_DFAstates. */
3579 if (dest_states_malloced)
3582 re_node_set_free (&follows);
3583 for (i = 0; i < ndests; ++i)
3584 re_node_set_free (dests_node + i);
3586 if (dests_node_malloced)
3592 /* Group all nodes belonging to STATE into several destinations.
3593 Then for all destinations, set the nodes belonging to the destination
3594 to DESTS_NODE[i] and set the characters accepted by the destination
3595 to DEST_CH[i]. This function return the number of destinations. */
3599 group_nodes_into_DFAstates (const re_dfa_t *dfa, const re_dfastate_t *state,
3600 re_node_set *dests_node, bitset_t *dests_ch)
3605 Idx ndests; /* Number of the destinations from 'state'. */
3606 bitset_t accepts; /* Characters a node can accept. */
3607 const re_node_set *cur_nodes = &state->nodes;
3608 bitset_empty (accepts);
3611 /* For all the nodes belonging to 'state', */
3612 for (i = 0; i < cur_nodes->nelem; ++i)
3614 re_token_t *node = &dfa->nodes[cur_nodes->elems[i]];
3615 re_token_type_t type = node->type;
3616 unsigned int constraint = node->constraint;
3618 /* Enumerate all single byte character this node can accept. */
3619 if (type == CHARACTER)
3620 bitset_set (accepts, node->opr.c);
3621 else if (type == SIMPLE_BRACKET)
3623 bitset_merge (accepts, node->opr.sbcset);
3625 else if (type == OP_PERIOD)
3627 #ifdef RE_ENABLE_I18N
3628 if (dfa->mb_cur_max > 1)
3629 bitset_merge (accepts, dfa->sb_char);
3632 bitset_set_all (accepts);
3633 if (!(dfa->syntax & RE_DOT_NEWLINE))
3634 bitset_clear (accepts, '\n');
3635 if (dfa->syntax & RE_DOT_NOT_NULL)
3636 bitset_clear (accepts, '\0');
3638 #ifdef RE_ENABLE_I18N
3639 else if (type == OP_UTF8_PERIOD)
3641 if (ASCII_CHARS % BITSET_WORD_BITS == 0)
3642 memset (accepts, -1, ASCII_CHARS / CHAR_BIT);
3644 bitset_merge (accepts, utf8_sb_map);
3645 if (!(dfa->syntax & RE_DOT_NEWLINE))
3646 bitset_clear (accepts, '\n');
3647 if (dfa->syntax & RE_DOT_NOT_NULL)
3648 bitset_clear (accepts, '\0');
3654 /* Check the 'accepts' and sift the characters which are not
3655 match it the context. */
3658 if (constraint & NEXT_NEWLINE_CONSTRAINT)
3660 bool accepts_newline = bitset_contain (accepts, NEWLINE_CHAR);
3661 bitset_empty (accepts);
3662 if (accepts_newline)
3663 bitset_set (accepts, NEWLINE_CHAR);
3667 if (constraint & NEXT_ENDBUF_CONSTRAINT)
3669 bitset_empty (accepts);
3673 if (constraint & NEXT_WORD_CONSTRAINT)
3675 bitset_word_t any_set = 0;
3676 if (type == CHARACTER && !node->word_char)
3678 bitset_empty (accepts);
3681 #ifdef RE_ENABLE_I18N
3682 if (dfa->mb_cur_max > 1)
3683 for (j = 0; j < BITSET_WORDS; ++j)
3684 any_set |= (accepts[j] &= (dfa->word_char[j] | ~dfa->sb_char[j]));
3687 for (j = 0; j < BITSET_WORDS; ++j)
3688 any_set |= (accepts[j] &= dfa->word_char[j]);
3692 if (constraint & NEXT_NOTWORD_CONSTRAINT)
3694 bitset_word_t any_set = 0;
3695 if (type == CHARACTER && node->word_char)
3697 bitset_empty (accepts);
3700 #ifdef RE_ENABLE_I18N
3701 if (dfa->mb_cur_max > 1)
3702 for (j = 0; j < BITSET_WORDS; ++j)
3703 any_set |= (accepts[j] &= ~(dfa->word_char[j] & dfa->sb_char[j]));
3706 for (j = 0; j < BITSET_WORDS; ++j)
3707 any_set |= (accepts[j] &= ~dfa->word_char[j]);
3713 /* Then divide 'accepts' into DFA states, or create a new
3714 state. Above, we make sure that accepts is not empty. */
3715 for (j = 0; j < ndests; ++j)
3717 bitset_t intersec; /* Intersection sets, see below. */
3719 /* Flags, see below. */
3720 bitset_word_t has_intersec, not_subset, not_consumed;
3722 /* Optimization, skip if this state doesn't accept the character. */
3723 if (type == CHARACTER && !bitset_contain (dests_ch[j], node->opr.c))
3726 /* Enumerate the intersection set of this state and 'accepts'. */
3728 for (k = 0; k < BITSET_WORDS; ++k)
3729 has_intersec |= intersec[k] = accepts[k] & dests_ch[j][k];
3730 /* And skip if the intersection set is empty. */
3734 /* Then check if this state is a subset of 'accepts'. */
3735 not_subset = not_consumed = 0;
3736 for (k = 0; k < BITSET_WORDS; ++k)
3738 not_subset |= remains[k] = ~accepts[k] & dests_ch[j][k];
3739 not_consumed |= accepts[k] = accepts[k] & ~dests_ch[j][k];
3742 /* If this state isn't a subset of 'accepts', create a
3743 new group state, which has the 'remains'. */
3746 bitset_copy (dests_ch[ndests], remains);
3747 bitset_copy (dests_ch[j], intersec);
3748 err = re_node_set_init_copy (dests_node + ndests, &dests_node[j]);
3749 if (BE (err != REG_NOERROR, 0))
3754 /* Put the position in the current group. */
3755 ok = re_node_set_insert (&dests_node[j], cur_nodes->elems[i]);
3759 /* If all characters are consumed, go to next node. */
3763 /* Some characters remain, create a new group. */
3766 bitset_copy (dests_ch[ndests], accepts);
3767 err = re_node_set_init_1 (dests_node + ndests, cur_nodes->elems[i]);
3768 if (BE (err != REG_NOERROR, 0))
3771 bitset_empty (accepts);
3776 for (j = 0; j < ndests; ++j)
3777 re_node_set_free (dests_node + j);
3781 #ifdef RE_ENABLE_I18N
3782 /* Check how many bytes the node 'dfa->nodes[node_idx]' accepts.
3783 Return the number of the bytes the node accepts.
3784 STR_IDX is the current index of the input string.
3786 This function handles the nodes which can accept one character, or
3787 one collating element like '.', '[a-z]', opposite to the other nodes
3788 can only accept one byte. */
3792 check_node_accept_bytes (const re_dfa_t *dfa, Idx node_idx,
3793 const re_string_t *input, Idx str_idx)
3795 const re_token_t *node = dfa->nodes + node_idx;
3796 int char_len, elem_len;
3799 if (BE (node->type == OP_UTF8_PERIOD, 0))
3801 unsigned char c = re_string_byte_at (input, str_idx), d;
3802 if (BE (c < 0xc2, 1))
3805 if (str_idx + 2 > input->len)
3808 d = re_string_byte_at (input, str_idx + 1);
3810 return (d < 0x80 || d > 0xbf) ? 0 : 2;
3814 if (c == 0xe0 && d < 0xa0)
3820 if (c == 0xf0 && d < 0x90)
3826 if (c == 0xf8 && d < 0x88)
3832 if (c == 0xfc && d < 0x84)
3838 if (str_idx + char_len > input->len)
3841 for (i = 1; i < char_len; ++i)
3843 d = re_string_byte_at (input, str_idx + i);
3844 if (d < 0x80 || d > 0xbf)
3850 char_len = re_string_char_size_at (input, str_idx);
3851 if (node->type == OP_PERIOD)
3855 /* FIXME: I don't think this if is needed, as both '\n'
3856 and '\0' are char_len == 1. */
3857 /* '.' accepts any one character except the following two cases. */
3858 if ((!(dfa->syntax & RE_DOT_NEWLINE) &&
3859 re_string_byte_at (input, str_idx) == '\n') ||
3860 ((dfa->syntax & RE_DOT_NOT_NULL) &&
3861 re_string_byte_at (input, str_idx) == '\0'))
3866 elem_len = re_string_elem_size_at (input, str_idx);
3867 if ((elem_len <= 1 && char_len <= 1) || char_len == 0)
3870 if (node->type == COMPLEX_BRACKET)
3872 const re_charset_t *cset = node->opr.mbcset;
3874 const unsigned char *pin
3875 = ((const unsigned char *) re_string_get_buffer (input) + str_idx);
3880 wchar_t wc = ((cset->nranges || cset->nchar_classes || cset->nmbchars)
3881 ? re_string_wchar_at (input, str_idx) : 0);
3883 /* match with multibyte character? */
3884 for (i = 0; i < cset->nmbchars; ++i)
3885 if (wc == cset->mbchars[i])
3887 match_len = char_len;
3888 goto check_node_accept_bytes_match;
3890 /* match with character_class? */
3891 for (i = 0; i < cset->nchar_classes; ++i)
3893 wctype_t wt = cset->char_classes[i];
3894 if (__iswctype (wc, wt))
3896 match_len = char_len;
3897 goto check_node_accept_bytes_match;
3902 nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3905 unsigned int in_collseq = 0;
3906 const int32_t *table, *indirect;
3907 const unsigned char *weights, *extra;
3908 const char *collseqwc;
3909 /* This #include defines a local function! */
3910 # include <locale/weight.h>
3912 /* match with collating_symbol? */
3913 if (cset->ncoll_syms)
3914 extra = (const unsigned char *)
3915 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
3916 for (i = 0; i < cset->ncoll_syms; ++i)
3918 const unsigned char *coll_sym = extra + cset->coll_syms[i];
3919 /* Compare the length of input collating element and
3920 the length of current collating element. */
3921 if (*coll_sym != elem_len)
3923 /* Compare each bytes. */
3924 for (j = 0; j < *coll_sym; j++)
3925 if (pin[j] != coll_sym[1 + j])
3929 /* Match if every bytes is equal. */
3931 goto check_node_accept_bytes_match;
3937 if (elem_len <= char_len)
3939 collseqwc = _NL_CURRENT (LC_COLLATE, _NL_COLLATE_COLLSEQWC);
3940 in_collseq = __collseq_table_lookup (collseqwc, wc);
3943 in_collseq = find_collation_sequence_value (pin, elem_len);
3945 /* match with range expression? */
3946 for (i = 0; i < cset->nranges; ++i)
3947 if (cset->range_starts[i] <= in_collseq
3948 && in_collseq <= cset->range_ends[i])
3950 match_len = elem_len;
3951 goto check_node_accept_bytes_match;
3954 /* match with equivalence_class? */
3955 if (cset->nequiv_classes)
3957 const unsigned char *cp = pin;
3958 table = (const int32_t *)
3959 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
3960 weights = (const unsigned char *)
3961 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB);
3962 extra = (const unsigned char *)
3963 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
3964 indirect = (const int32_t *)
3965 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB);
3966 int32_t idx = findidx (&cp, elem_len);
3968 for (i = 0; i < cset->nequiv_classes; ++i)
3970 int32_t equiv_class_idx = cset->equiv_classes[i];
3971 size_t weight_len = weights[idx & 0xffffff];
3972 if (weight_len == weights[equiv_class_idx & 0xffffff]
3973 && (idx >> 24) == (equiv_class_idx >> 24))
3978 equiv_class_idx &= 0xffffff;
3980 while (cnt <= weight_len
3981 && (weights[equiv_class_idx + 1 + cnt]
3982 == weights[idx + 1 + cnt]))
3984 if (cnt > weight_len)
3986 match_len = elem_len;
3987 goto check_node_accept_bytes_match;
3996 /* match with range expression? */
3997 #if __GNUC__ >= 2 && ! (__STDC_VERSION__ < 199901L && defined __STRICT_ANSI__)
3998 wchar_t cmp_buf[] = {L'\0', L'\0', wc, L'\0', L'\0', L'\0'};
4000 wchar_t cmp_buf[] = {L'\0', L'\0', L'\0', L'\0', L'\0', L'\0'};
4003 for (i = 0; i < cset->nranges; ++i)
4005 cmp_buf[0] = cset->range_starts[i];
4006 cmp_buf[4] = cset->range_ends[i];
4007 if (wcscoll (cmp_buf, cmp_buf + 2) <= 0
4008 && wcscoll (cmp_buf + 2, cmp_buf + 4) <= 0)
4010 match_len = char_len;
4011 goto check_node_accept_bytes_match;
4015 check_node_accept_bytes_match:
4016 if (!cset->non_match)
4023 return (elem_len > char_len) ? elem_len : char_len;
4032 find_collation_sequence_value (const unsigned char *mbs, size_t mbs_len)
4034 uint32_t nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
4039 /* No valid character. Match it as a single byte character. */
4040 const unsigned char *collseq = (const unsigned char *)
4041 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_COLLSEQMB);
4042 return collseq[mbs[0]];
4049 const unsigned char *extra = (const unsigned char *)
4050 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
4051 int32_t extrasize = (const unsigned char *)
4052 _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB + 1) - extra;
4054 for (idx = 0; idx < extrasize;)
4058 int32_t elem_mbs_len;
4059 /* Skip the name of collating element name. */
4060 idx = idx + extra[idx] + 1;
4061 elem_mbs_len = extra[idx++];
4062 if (mbs_len == elem_mbs_len)
4064 for (mbs_cnt = 0; mbs_cnt < elem_mbs_len; ++mbs_cnt)
4065 if (extra[idx + mbs_cnt] != mbs[mbs_cnt])
4067 if (mbs_cnt == elem_mbs_len)
4068 /* Found the entry. */
4071 /* Skip the byte sequence of the collating element. */
4072 idx += elem_mbs_len;
4073 /* Adjust for the alignment. */
4074 idx = (idx + 3) & ~3;
4075 /* Skip the collation sequence value. */
4076 idx += sizeof (uint32_t);
4077 /* Skip the wide char sequence of the collating element. */
4078 idx = idx + sizeof (uint32_t) * (*(int32_t *) (extra + idx) + 1);
4079 /* If we found the entry, return the sequence value. */
4081 return *(uint32_t *) (extra + idx);
4082 /* Skip the collation sequence value. */
4083 idx += sizeof (uint32_t);
4089 #endif /* RE_ENABLE_I18N */
4091 /* Check whether the node accepts the byte which is IDX-th
4092 byte of the INPUT. */
4096 check_node_accept (const re_match_context_t *mctx, const re_token_t *node,
4100 ch = re_string_byte_at (&mctx->input, idx);
4104 if (node->opr.c != ch)
4108 case SIMPLE_BRACKET:
4109 if (!bitset_contain (node->opr.sbcset, ch))
4113 #ifdef RE_ENABLE_I18N
4114 case OP_UTF8_PERIOD:
4115 if (ch >= ASCII_CHARS)
4120 if ((ch == '\n' && !(mctx->dfa->syntax & RE_DOT_NEWLINE))
4121 || (ch == '\0' && (mctx->dfa->syntax & RE_DOT_NOT_NULL)))
4129 if (node->constraint)
4131 /* The node has constraints. Check whether the current context
4132 satisfies the constraints. */
4133 unsigned int context = re_string_context_at (&mctx->input, idx,
4135 if (NOT_SATISFY_NEXT_CONSTRAINT (node->constraint, context))
4142 /* Extend the buffers, if the buffers have run out. */
4144 static reg_errcode_t
4145 internal_function __attribute_warn_unused_result__
4146 extend_buffers (re_match_context_t *mctx)
4149 re_string_t *pstr = &mctx->input;
4151 /* Avoid overflow. */
4152 if (BE (MIN (IDX_MAX, SIZE_MAX / sizeof (re_dfastate_t *)) / 2
4153 <= pstr->bufs_len, 0))
4156 /* Double the lengths of the buffers. */
4157 ret = re_string_realloc_buffers (pstr, MIN (pstr->len, pstr->bufs_len * 2));
4158 if (BE (ret != REG_NOERROR, 0))
4161 if (mctx->state_log != NULL)
4163 /* And double the length of state_log. */
4164 /* XXX We have no indication of the size of this buffer. If this
4165 allocation fail we have no indication that the state_log array
4166 does not have the right size. */
4167 re_dfastate_t **new_array = re_realloc (mctx->state_log, re_dfastate_t *,
4168 pstr->bufs_len + 1);
4169 if (BE (new_array == NULL, 0))
4171 mctx->state_log = new_array;
4174 /* Then reconstruct the buffers. */
4177 #ifdef RE_ENABLE_I18N
4178 if (pstr->mb_cur_max > 1)
4180 ret = build_wcs_upper_buffer (pstr);
4181 if (BE (ret != REG_NOERROR, 0))
4185 #endif /* RE_ENABLE_I18N */
4186 build_upper_buffer (pstr);
4190 #ifdef RE_ENABLE_I18N
4191 if (pstr->mb_cur_max > 1)
4192 build_wcs_buffer (pstr);
4194 #endif /* RE_ENABLE_I18N */
4196 if (pstr->trans != NULL)
4197 re_string_translate_buffer (pstr);
4204 /* Functions for matching context. */
4206 /* Initialize MCTX. */
4208 static reg_errcode_t
4209 internal_function __attribute_warn_unused_result__
4210 match_ctx_init (re_match_context_t *mctx, int eflags, Idx n)
4212 mctx->eflags = eflags;
4213 mctx->match_last = REG_MISSING;
4216 /* Avoid overflow. */
4217 size_t max_object_size =
4218 MAX (sizeof (struct re_backref_cache_entry),
4219 sizeof (re_sub_match_top_t *));
4220 if (BE (MIN (IDX_MAX, SIZE_MAX / max_object_size) < n, 0))
4223 mctx->bkref_ents = re_malloc (struct re_backref_cache_entry, n);
4224 mctx->sub_tops = re_malloc (re_sub_match_top_t *, n);
4225 if (BE (mctx->bkref_ents == NULL || mctx->sub_tops == NULL, 0))
4228 /* Already zero-ed by the caller.
4230 mctx->bkref_ents = NULL;
4231 mctx->nbkref_ents = 0;
4232 mctx->nsub_tops = 0; */
4233 mctx->abkref_ents = n;
4234 mctx->max_mb_elem_len = 1;
4235 mctx->asub_tops = n;
4239 /* Clean the entries which depend on the current input in MCTX.
4240 This function must be invoked when the matcher changes the start index
4241 of the input, or changes the input string. */
4245 match_ctx_clean (re_match_context_t *mctx)
4248 for (st_idx = 0; st_idx < mctx->nsub_tops; ++st_idx)
4251 re_sub_match_top_t *top = mctx->sub_tops[st_idx];
4252 for (sl_idx = 0; sl_idx < top->nlasts; ++sl_idx)
4254 re_sub_match_last_t *last = top->lasts[sl_idx];
4255 re_free (last->path.array);
4258 re_free (top->lasts);
4261 re_free (top->path->array);
4262 re_free (top->path);
4267 mctx->nsub_tops = 0;
4268 mctx->nbkref_ents = 0;
4271 /* Free all the memory associated with MCTX. */
4275 match_ctx_free (re_match_context_t *mctx)
4277 /* First, free all the memory associated with MCTX->SUB_TOPS. */
4278 match_ctx_clean (mctx);
4279 re_free (mctx->sub_tops);
4280 re_free (mctx->bkref_ents);
4283 /* Add a new backreference entry to MCTX.
4284 Note that we assume that caller never call this function with duplicate
4285 entry, and call with STR_IDX which isn't smaller than any existing entry.
4288 static reg_errcode_t
4289 internal_function __attribute_warn_unused_result__
4290 match_ctx_add_entry (re_match_context_t *mctx, Idx node, Idx str_idx, Idx from,
4293 if (mctx->nbkref_ents >= mctx->abkref_ents)
4295 struct re_backref_cache_entry* new_entry;
4296 new_entry = re_realloc (mctx->bkref_ents, struct re_backref_cache_entry,
4297 mctx->abkref_ents * 2);
4298 if (BE (new_entry == NULL, 0))
4300 re_free (mctx->bkref_ents);
4303 mctx->bkref_ents = new_entry;
4304 memset (mctx->bkref_ents + mctx->nbkref_ents, '\0',
4305 sizeof (struct re_backref_cache_entry) * mctx->abkref_ents);
4306 mctx->abkref_ents *= 2;
4308 if (mctx->nbkref_ents > 0
4309 && mctx->bkref_ents[mctx->nbkref_ents - 1].str_idx == str_idx)
4310 mctx->bkref_ents[mctx->nbkref_ents - 1].more = 1;
4312 mctx->bkref_ents[mctx->nbkref_ents].node = node;
4313 mctx->bkref_ents[mctx->nbkref_ents].str_idx = str_idx;
4314 mctx->bkref_ents[mctx->nbkref_ents].subexp_from = from;
4315 mctx->bkref_ents[mctx->nbkref_ents].subexp_to = to;
4317 /* This is a cache that saves negative results of check_dst_limits_calc_pos.
4318 If bit N is clear, means that this entry won't epsilon-transition to
4319 an OP_OPEN_SUBEXP or OP_CLOSE_SUBEXP for the N+1-th subexpression. If
4320 it is set, check_dst_limits_calc_pos_1 will recurse and try to find one
4323 A backreference does not epsilon-transition unless it is empty, so set
4324 to all zeros if FROM != TO. */
4325 mctx->bkref_ents[mctx->nbkref_ents].eps_reachable_subexps_map
4326 = (from == to ? -1 : 0);
4328 mctx->bkref_ents[mctx->nbkref_ents++].more = 0;
4329 if (mctx->max_mb_elem_len < to - from)
4330 mctx->max_mb_elem_len = to - from;
4334 /* Return the first entry with the same str_idx, or REG_MISSING if none is
4335 found. Note that MCTX->BKREF_ENTS is already sorted by MCTX->STR_IDX. */
4339 search_cur_bkref_entry (const re_match_context_t *mctx, Idx str_idx)
4341 Idx left, right, mid, last;
4342 last = right = mctx->nbkref_ents;
4343 for (left = 0; left < right;)
4345 mid = (left + right) / 2;
4346 if (mctx->bkref_ents[mid].str_idx < str_idx)
4351 if (left < last && mctx->bkref_ents[left].str_idx == str_idx)
4357 /* Register the node NODE, whose type is OP_OPEN_SUBEXP, and which matches
4360 static reg_errcode_t
4361 internal_function __attribute_warn_unused_result__
4362 match_ctx_add_subtop (re_match_context_t *mctx, Idx node, Idx str_idx)
4365 assert (mctx->sub_tops != NULL);
4366 assert (mctx->asub_tops > 0);
4368 if (BE (mctx->nsub_tops == mctx->asub_tops, 0))
4370 Idx new_asub_tops = mctx->asub_tops * 2;
4371 re_sub_match_top_t **new_array = re_realloc (mctx->sub_tops,
4372 re_sub_match_top_t *,
4374 if (BE (new_array == NULL, 0))
4376 mctx->sub_tops = new_array;
4377 mctx->asub_tops = new_asub_tops;
4379 mctx->sub_tops[mctx->nsub_tops] = calloc (1, sizeof (re_sub_match_top_t));
4380 if (BE (mctx->sub_tops[mctx->nsub_tops] == NULL, 0))
4382 mctx->sub_tops[mctx->nsub_tops]->node = node;
4383 mctx->sub_tops[mctx->nsub_tops++]->str_idx = str_idx;
4387 /* Register the node NODE, whose type is OP_CLOSE_SUBEXP, and which matches
4388 at STR_IDX, whose corresponding OP_OPEN_SUBEXP is SUB_TOP. */
4390 static re_sub_match_last_t *
4392 match_ctx_add_sublast (re_sub_match_top_t *subtop, Idx node, Idx str_idx)
4394 re_sub_match_last_t *new_entry;
4395 if (BE (subtop->nlasts == subtop->alasts, 0))
4397 Idx new_alasts = 2 * subtop->alasts + 1;
4398 re_sub_match_last_t **new_array = re_realloc (subtop->lasts,
4399 re_sub_match_last_t *,
4401 if (BE (new_array == NULL, 0))
4403 subtop->lasts = new_array;
4404 subtop->alasts = new_alasts;
4406 new_entry = calloc (1, sizeof (re_sub_match_last_t));
4407 if (BE (new_entry != NULL, 1))
4409 subtop->lasts[subtop->nlasts] = new_entry;
4410 new_entry->node = node;
4411 new_entry->str_idx = str_idx;
4419 sift_ctx_init (re_sift_context_t *sctx, re_dfastate_t **sifted_sts,
4420 re_dfastate_t **limited_sts, Idx last_node, Idx last_str_idx)
4422 sctx->sifted_states = sifted_sts;
4423 sctx->limited_states = limited_sts;
4424 sctx->last_node = last_node;
4425 sctx->last_str_idx = last_str_idx;
4426 re_node_set_init_empty (&sctx->limits);