Coverage Report

Created: 2026-12-01 06:48

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/augeas/gnulib/lib/regexec.c
Line
Count
Source
1
/* Extended regular expression matching and search library.
2
   Copyright (C) 2002-2026 Free Software Foundation, Inc.
3
   This file is part of the GNU C Library.
4
   Contributed by Isamu Hasegawa <isamu@yamato.ibm.com>.
5
6
   The GNU C Library is free software; you can redistribute it and/or
7
   modify it under the terms of the GNU Lesser General Public
8
   License as published by the Free Software Foundation; either
9
   version 2.1 of the License, or (at your option) any later version.
10
11
   The GNU C Library 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 GNU
14
   Lesser General Public License for more details.
15
16
   You should have received a copy of the GNU Lesser General Public
17
   License along with the GNU C Library; if not, see
18
   <https://www.gnu.org/licenses/>.  */
19
20
static reg_errcode_t match_ctx_init (re_match_context_t *cache, int eflags,
21
             Idx n);
22
static void match_ctx_clean (re_match_context_t *mctx);
23
static void match_ctx_free (re_match_context_t *cache);
24
static reg_errcode_t match_ctx_add_entry (re_match_context_t *cache, Idx node,
25
            Idx str_idx, Idx from, Idx to);
26
static Idx search_cur_bkref_entry (const re_match_context_t *mctx, Idx str_idx);
27
static reg_errcode_t match_ctx_add_subtop (re_match_context_t *mctx, Idx node,
28
             Idx str_idx);
29
static re_sub_match_last_t * match_ctx_add_sublast (re_sub_match_top_t *subtop,
30
                Idx node, Idx str_idx);
31
static void sift_ctx_init (re_sift_context_t *sctx, re_dfastate_t **sifted_sts,
32
         re_dfastate_t **limited_sts, Idx last_node,
33
         Idx last_str_idx);
34
static reg_errcode_t re_search_internal (const regex_t *preg,
35
           const char *string, Idx length,
36
           Idx start, Idx last_start, Idx stop,
37
           size_t nmatch, regmatch_t pmatch[],
38
           int eflags);
39
static regoff_t re_search_2_stub (struct re_pattern_buffer *bufp,
40
          const char *string1, Idx length1,
41
          const char *string2, Idx length2,
42
          Idx start, regoff_t range,
43
          struct re_registers *regs,
44
          Idx stop, bool ret_len);
45
static regoff_t re_search_stub (struct re_pattern_buffer *bufp,
46
        const char *string, Idx length, Idx start,
47
        regoff_t range, Idx stop,
48
        struct re_registers *regs,
49
        bool ret_len);
50
static unsigned re_copy_regs (struct re_registers *regs, regmatch_t *pmatch,
51
                              Idx nregs, int regs_allocated);
52
static reg_errcode_t prune_impossible_nodes (re_match_context_t *mctx);
53
static Idx check_matching (re_match_context_t *mctx, bool fl_longest_match,
54
         Idx *p_match_first);
55
static Idx check_halt_state_context (const re_match_context_t *mctx,
56
             const re_dfastate_t *state, Idx idx);
57
static void update_regs (const re_dfa_t *dfa, regmatch_t *pmatch,
58
       regmatch_t *prev_idx_match, Idx cur_node,
59
       Idx cur_idx, Idx nmatch);
60
static reg_errcode_t push_fail_stack (struct re_fail_stack_t *fs,
61
              Idx str_idx, Idx dest_node, Idx nregs,
62
              regmatch_t *regs, regmatch_t *prevregs,
63
              re_node_set *eps_via_nodes);
64
static reg_errcode_t set_regs (const regex_t *preg,
65
             const re_match_context_t *mctx,
66
             size_t nmatch, regmatch_t *pmatch,
67
             bool fl_backtrack);
68
static reg_errcode_t free_fail_stack_return (struct re_fail_stack_t *fs);
69
70
static int sift_states_iter_mb (const re_match_context_t *mctx,
71
        re_sift_context_t *sctx,
72
        Idx node_idx, Idx str_idx, Idx max_str_idx);
73
static reg_errcode_t sift_states_backward (const re_match_context_t *mctx,
74
             re_sift_context_t *sctx);
75
static reg_errcode_t build_sifted_states (const re_match_context_t *mctx,
76
            re_sift_context_t *sctx, Idx str_idx,
77
            re_node_set *cur_dest);
78
static reg_errcode_t update_cur_sifted_state (const re_match_context_t *mctx,
79
                re_sift_context_t *sctx,
80
                Idx str_idx,
81
                re_node_set *dest_nodes);
82
static reg_errcode_t add_epsilon_src_nodes (const re_dfa_t *dfa,
83
              re_node_set *dest_nodes,
84
              const re_node_set *candidates);
85
static bool check_dst_limits (const re_match_context_t *mctx,
86
            const re_node_set *limits,
87
            Idx dst_node, Idx dst_idx, Idx src_node,
88
            Idx src_idx);
89
static int check_dst_limits_calc_pos_1 (const re_match_context_t *mctx,
90
          int boundaries, Idx subexp_idx,
91
          Idx from_node, Idx bkref_idx);
92
static int check_dst_limits_calc_pos (const re_match_context_t *mctx,
93
              Idx limit, Idx subexp_idx,
94
              Idx node, Idx str_idx,
95
              Idx bkref_idx);
96
static reg_errcode_t check_subexp_limits (const re_dfa_t *dfa,
97
            re_node_set *dest_nodes,
98
            const re_node_set *candidates,
99
            re_node_set *limits,
100
            struct re_backref_cache_entry *bkref_ents,
101
            Idx str_idx);
102
static reg_errcode_t sift_states_bkref (const re_match_context_t *mctx,
103
          re_sift_context_t *sctx,
104
          Idx str_idx, const re_node_set *candidates);
105
static reg_errcode_t merge_state_array (const re_dfa_t *dfa,
106
          re_dfastate_t **dst,
107
          re_dfastate_t **src, Idx num);
108
static re_dfastate_t *find_recover_state (reg_errcode_t *err,
109
           re_match_context_t *mctx);
110
static re_dfastate_t *transit_state (reg_errcode_t *err,
111
             re_match_context_t *mctx,
112
             re_dfastate_t *state);
113
static re_dfastate_t *merge_state_with_log (reg_errcode_t *err,
114
              re_match_context_t *mctx,
115
              re_dfastate_t *next_state);
116
static reg_errcode_t check_subexp_matching_top (re_match_context_t *mctx,
117
            re_node_set *cur_nodes,
118
            Idx str_idx);
119
#if 0
120
static re_dfastate_t *transit_state_sb (reg_errcode_t *err,
121
          re_match_context_t *mctx,
122
          re_dfastate_t *pstate);
123
#endif
124
static reg_errcode_t transit_state_mb (re_match_context_t *mctx,
125
               re_dfastate_t *pstate);
126
static reg_errcode_t transit_state_bkref (re_match_context_t *mctx,
127
            const re_node_set *nodes);
128
static reg_errcode_t get_subexp (re_match_context_t *mctx,
129
         Idx bkref_node, Idx bkref_str_idx);
130
static reg_errcode_t get_subexp_sub (re_match_context_t *mctx,
131
             const re_sub_match_top_t *sub_top,
132
             re_sub_match_last_t *sub_last,
133
             Idx bkref_node, Idx bkref_str);
134
static Idx find_subexp_node (const re_dfa_t *dfa, const re_node_set *nodes,
135
           Idx subexp_idx, int type);
136
static reg_errcode_t check_arrival (re_match_context_t *mctx,
137
            state_array_t *path, Idx top_node,
138
            Idx top_str, Idx last_node, Idx last_str,
139
            int type);
140
static reg_errcode_t check_arrival_add_next_nodes (re_match_context_t *mctx,
141
               Idx str_idx,
142
               re_node_set *cur_nodes,
143
               re_node_set *next_nodes);
144
static reg_errcode_t check_arrival_expand_ecl (const re_dfa_t *dfa,
145
                 re_node_set *cur_nodes,
146
                 Idx ex_subexp, int type);
147
static reg_errcode_t check_arrival_expand_ecl_sub (const re_dfa_t *dfa,
148
               re_node_set *dst_nodes,
149
               Idx target, Idx ex_subexp,
150
               int type);
151
static reg_errcode_t expand_bkref_cache (re_match_context_t *mctx,
152
           re_node_set *cur_nodes, Idx cur_str,
153
           Idx subexp_num, int type);
154
static bool build_trtable (const re_dfa_t *dfa, re_dfastate_t *state);
155
static int check_node_accept_bytes (const re_dfa_t *dfa, Idx node_idx,
156
            const re_string_t *input, Idx idx);
157
#ifdef _LIBC
158
static unsigned int find_collation_sequence_value (const unsigned char *mbs,
159
               size_t name_len);
160
#endif
161
static Idx group_nodes_into_DFAstates (const re_dfa_t *dfa,
162
               const re_dfastate_t *state,
163
               re_node_set *states_node,
164
               bitset_t *states_ch);
165
static bool check_node_accept (const re_match_context_t *mctx,
166
             const re_token_t *node, Idx idx);
167
static reg_errcode_t extend_buffers (re_match_context_t *mctx, int min_len);
168

169
/* Entry point for POSIX code.  */
170
171
/* regexec searches for a given pattern, specified by PREG, in the
172
   string STRING.
173
174
   If NMATCH is zero or REG_NOSUB was set in the cflags argument to
175
   'regcomp', we ignore PMATCH.  Otherwise, we assume PMATCH has at
176
   least NMATCH elements, and we set them to the offsets of the
177
   corresponding matched substrings.
178
179
   EFLAGS specifies "execution flags" which affect matching: if
180
   REG_NOTBOL is set, then ^ does not match at the beginning of the
181
   string; if REG_NOTEOL is set, then $ does not match at the end.
182
183
   Return 0 if a match is found, REG_NOMATCH if not, REG_BADPAT if
184
   EFLAGS is invalid.  */
185
186
int
187
regexec (const regex_t *__restrict preg, const char *__restrict string,
188
   size_t nmatch, regmatch_t pmatch[], int eflags)
189
0
{
190
0
  reg_errcode_t err;
191
0
  Idx start, length;
192
0
  re_dfa_t *dfa = preg->buffer;
193
194
0
  if (eflags & ~(REG_NOTBOL | REG_NOTEOL | REG_STARTEND))
195
0
    return REG_BADPAT;
196
197
0
  if (eflags & REG_STARTEND)
198
0
    {
199
0
      start = pmatch[0].rm_so;
200
0
      length = pmatch[0].rm_eo;
201
0
    }
202
0
  else
203
0
    {
204
0
      start = 0;
205
0
      length = strlen (string);
206
0
    }
207
208
0
  lock_lock (dfa->lock);
209
0
  if (preg->no_sub)
210
0
    err = re_search_internal (preg, string, length, start, length,
211
0
            length, 0, NULL, eflags);
212
0
  else
213
0
    err = re_search_internal (preg, string, length, start, length,
214
0
            length, nmatch, pmatch, eflags);
215
0
  lock_unlock (dfa->lock);
216
0
  return err != REG_NOERROR;
217
0
}
218
219
#ifdef _LIBC
220
libc_hidden_def (__regexec)
221
222
# include <shlib-compat.h>
223
versioned_symbol (libc, __regexec, regexec, GLIBC_2_3_4);
224
225
# if SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_3_4)
226
__typeof__ (__regexec) __compat_regexec;
227
228
int
229
attribute_compat_text_section
230
__compat_regexec (const regex_t *__restrict preg,
231
      const char *__restrict string, size_t nmatch,
232
      regmatch_t pmatch[], int eflags)
233
{
234
  return regexec (preg, string, nmatch, pmatch,
235
      eflags & (REG_NOTBOL | REG_NOTEOL));
236
}
237
compat_symbol (libc, __compat_regexec, regexec, GLIBC_2_0);
238
# endif
239
#endif
240
241
/* Entry points for GNU code.  */
242
243
/* re_match, re_search, re_match_2, re_search_2
244
245
   The former two functions operate on STRING with length LENGTH,
246
   while the later two operate on concatenation of STRING1 and STRING2
247
   with lengths LENGTH1 and LENGTH2, respectively.
248
249
   re_match() matches the compiled pattern in BUFP against the string,
250
   starting at index START.
251
252
   re_search() first tries matching at index START, then it tries to match
253
   starting from index START + 1, and so on.  The last start position tried
254
   is START + RANGE.  (Thus RANGE = 0 forces re_search to operate the same
255
   way as re_match().)
256
257
   The parameter STOP of re_{match,search}_2 specifies that no match exceeding
258
   the first STOP characters of the concatenation of the strings should be
259
   concerned.
260
261
   If REGS is not NULL, and BUFP->no_sub is not set, the offsets of the match
262
   and all groups is stored in REGS.  (For the "_2" variants, the offsets are
263
   computed relative to the concatenation, not relative to the individual
264
   strings.)
265
266
   On success, re_match* functions return the length of the match, re_search*
267
   return the position of the start of the match.  They return -1 on
268
   match failure, -2 on error.  */
269
270
regoff_t
271
re_match (struct re_pattern_buffer *bufp, const char *string, Idx length,
272
    Idx start, struct re_registers *regs)
273
57
{
274
57
  return re_search_stub (bufp, string, length, start, 0, length, regs, true);
275
57
}
276
#ifdef _LIBC
277
weak_alias (__re_match, re_match)
278
#endif
279
280
regoff_t
281
re_search (struct re_pattern_buffer *bufp, const char *string, Idx length,
282
     Idx start, regoff_t range, struct re_registers *regs)
283
0
{
284
0
  return re_search_stub (bufp, string, length, start, range, length, regs,
285
0
       false);
286
0
}
287
#ifdef _LIBC
288
weak_alias (__re_search, re_search)
289
#endif
290
291
regoff_t
292
re_match_2 (struct re_pattern_buffer *bufp, const char *string1, Idx length1,
293
      const char *string2, Idx length2, Idx start,
294
      struct re_registers *regs, Idx stop)
295
0
{
296
0
  return re_search_2_stub (bufp, string1, length1, string2, length2,
297
0
         start, 0, regs, stop, true);
298
0
}
299
#ifdef _LIBC
300
weak_alias (__re_match_2, re_match_2)
301
#endif
302
303
regoff_t
304
re_search_2 (struct re_pattern_buffer *bufp, const char *string1, Idx length1,
305
       const char *string2, Idx length2, Idx start, regoff_t range,
306
       struct re_registers *regs, Idx stop)
307
0
{
308
0
  return re_search_2_stub (bufp, string1, length1, string2, length2,
309
0
         start, range, regs, stop, false);
310
0
}
311
#ifdef _LIBC
312
weak_alias (__re_search_2, re_search_2)
313
#endif
314
315
static regoff_t
316
re_search_2_stub (struct re_pattern_buffer *bufp, const char *string1,
317
      Idx length1, const char *string2, Idx length2, Idx start,
318
      regoff_t range, struct re_registers *regs,
319
      Idx stop, bool ret_len)
320
0
{
321
0
  const char *str;
322
0
  regoff_t rval;
323
0
  Idx len;
324
0
  char *s = NULL;
325
326
0
  if (__glibc_unlikely ((length1 < 0 || length2 < 0 || stop < 0
327
0
       || ckd_add (&len, length1, length2))))
328
0
    return -2;
329
330
  /* Concatenate the strings.  */
331
0
  if (length2 > 0)
332
0
    if (length1 > 0)
333
0
      {
334
0
  s = re_malloc (char, len);
335
336
0
  if (__glibc_unlikely (s == NULL))
337
0
    return -2;
338
#ifdef _LIBC
339
  memcpy (__mempcpy (s, string1, length1), string2, length2);
340
#else
341
0
  memcpy (s, string1, length1);
342
0
  memcpy (s + length1, string2, length2);
343
0
#endif
344
0
  str = s;
345
0
      }
346
0
    else
347
0
      str = string2;
348
0
  else
349
0
    str = string1;
350
351
0
  rval = re_search_stub (bufp, str, len, start, range, stop, regs,
352
0
       ret_len);
353
0
  re_free (s);
354
0
  return rval;
355
0
}
356
357
/* The parameters have the same meaning as those of re_search.
358
   Additional parameters:
359
   If RET_LEN is true the length of the match is returned (re_match style);
360
   otherwise the position of the match is returned.  */
361
362
static regoff_t
363
re_search_stub (struct re_pattern_buffer *bufp, const char *string, Idx length,
364
    Idx start, regoff_t range, Idx stop, struct re_registers *regs,
365
    bool ret_len)
366
57
{
367
57
  reg_errcode_t result;
368
57
  regmatch_t *pmatch;
369
57
  Idx nregs;
370
57
  regoff_t rval;
371
57
  int eflags = 0;
372
57
  re_dfa_t *dfa = bufp->buffer;
373
57
  Idx last_start = start + range;
374
375
  /* Check for out-of-range.  */
376
57
  if (__glibc_unlikely (start < 0 || start > length))
377
0
    return -1;
378
57
  if (__glibc_unlikely (length < last_start
379
57
      || (0 <= range && last_start < start)))
380
0
    last_start = length;
381
57
  else if (__glibc_unlikely (last_start < 0
382
57
           || (range < 0 && start <= last_start)))
383
0
    last_start = 0;
384
385
57
  lock_lock (dfa->lock);
386
387
57
  eflags |= (bufp->not_bol) ? REG_NOTBOL : 0;
388
57
  eflags |= (bufp->not_eol) ? REG_NOTEOL : 0;
389
390
  /* Compile fastmap if we haven't yet.  */
391
57
  if (start < last_start && bufp->fastmap != NULL && !bufp->fastmap_accurate)
392
0
    re_compile_fastmap (bufp);
393
394
57
  if (__glibc_unlikely (bufp->no_sub))
395
0
    regs = NULL;
396
397
  /* We need at least 1 register.  */
398
57
  if (regs == NULL)
399
57
    nregs = 1;
400
0
  else if (__glibc_unlikely (bufp->regs_allocated == REGS_FIXED
401
0
           && regs->num_regs <= bufp->re_nsub))
402
0
    {
403
0
      nregs = regs->num_regs;
404
0
      if (__glibc_unlikely (nregs < 1))
405
0
  {
406
    /* Nothing can be copied to regs.  */
407
0
    regs = NULL;
408
0
    nregs = 1;
409
0
  }
410
0
    }
411
0
  else
412
0
    nregs = bufp->re_nsub + 1;
413
57
  pmatch = re_malloc (regmatch_t, nregs);
414
57
  if (__glibc_unlikely (pmatch == NULL))
415
0
    {
416
0
      rval = -2;
417
0
      goto out;
418
0
    }
419
420
57
  result = re_search_internal (bufp, string, length, start, last_start, stop,
421
57
             nregs, pmatch, eflags);
422
423
57
  rval = 0;
424
425
  /* I hope we needn't fill their regs with -1's when no match was found.  */
426
57
  if (result != REG_NOERROR)
427
48
    rval = result == REG_NOMATCH ? -1 : -2;
428
9
  else if (regs != NULL)
429
0
    {
430
      /* If caller wants register contents data back, copy them.  */
431
0
      bufp->regs_allocated = re_copy_regs (regs, pmatch, nregs,
432
0
             bufp->regs_allocated);
433
0
      if (__glibc_unlikely (bufp->regs_allocated == REGS_UNALLOCATED))
434
0
  rval = -2;
435
0
    }
436
437
57
  if (__glibc_likely (rval == 0))
438
9
    {
439
9
      if (ret_len)
440
9
  {
441
9
    DEBUG_ASSERT (pmatch[0].rm_so == start);
442
9
    rval = pmatch[0].rm_eo - start;
443
9
  }
444
0
      else
445
0
  rval = pmatch[0].rm_so;
446
9
    }
447
57
  re_free (pmatch);
448
57
 out:
449
57
  lock_unlock (dfa->lock);
450
57
  return rval;
451
57
}
452
453
static unsigned
454
re_copy_regs (struct re_registers *regs, regmatch_t *pmatch, Idx nregs,
455
        int regs_allocated)
456
0
{
457
0
  int rval = REGS_REALLOCATE;
458
0
  Idx i;
459
0
  Idx need_regs = nregs + 1;
460
  /* We need one extra element beyond 'num_regs' for the '-1' marker GNU code
461
     uses.  */
462
463
  /* Have the register data arrays been allocated?  */
464
0
  if (regs_allocated == REGS_UNALLOCATED)
465
0
    { /* No.  So allocate them with malloc.  */
466
0
      regs->start = re_malloc (regoff_t, need_regs);
467
0
      if (__glibc_unlikely (regs->start == NULL))
468
0
  return REGS_UNALLOCATED;
469
0
      regs->end = re_malloc (regoff_t, need_regs);
470
0
      if (__glibc_unlikely (regs->end == NULL))
471
0
  {
472
0
    re_free (regs->start);
473
0
    return REGS_UNALLOCATED;
474
0
  }
475
0
      regs->num_regs = need_regs;
476
0
    }
477
0
  else if (regs_allocated == REGS_REALLOCATE)
478
0
    { /* Yes.  If we need more elements than were already
479
   allocated, reallocate them.  If we need fewer, just
480
   leave it alone.  */
481
0
      if (__glibc_unlikely (need_regs > regs->num_regs))
482
0
  {
483
0
    regoff_t *new_start = re_realloc (regs->start, regoff_t, need_regs);
484
0
    regoff_t *new_end;
485
0
    if (__glibc_unlikely (new_start == NULL))
486
0
      return REGS_UNALLOCATED;
487
0
    new_end = re_realloc (regs->end, regoff_t, need_regs);
488
0
    if (__glibc_unlikely (new_end == NULL))
489
0
      {
490
0
        re_free (new_start);
491
0
        return REGS_UNALLOCATED;
492
0
      }
493
0
    regs->start = new_start;
494
0
    regs->end = new_end;
495
0
    regs->num_regs = need_regs;
496
0
  }
497
0
    }
498
0
  else
499
0
    {
500
0
      DEBUG_ASSERT (regs_allocated == REGS_FIXED);
501
      /* This function may not be called with REGS_FIXED and nregs too big.  */
502
0
      DEBUG_ASSERT (nregs <= regs->num_regs);
503
0
      rval = REGS_FIXED;
504
0
    }
505
506
  /* Copy the regs.  */
507
0
  for (i = 0; i < nregs; ++i)
508
0
    {
509
0
      regs->start[i] = pmatch[i].rm_so;
510
0
      regs->end[i] = pmatch[i].rm_eo;
511
0
    }
512
0
  for ( ; i < regs->num_regs; ++i)
513
0
    regs->start[i] = regs->end[i] = -1;
514
515
0
  return rval;
516
0
}
517
518
/* Set REGS to hold NUM_REGS registers, storing them in STARTS and
519
   ENDS.  Subsequent matches using PATTERN_BUFFER and REGS will use
520
   this memory for recording register information.  STARTS and ENDS
521
   must be allocated using the malloc library routine, and must each
522
   be at least NUM_REGS * sizeof (regoff_t) bytes long.
523
524
   If NUM_REGS == 0, then subsequent matches should allocate their own
525
   register data.
526
527
   Unless this function is called, the first search or match using
528
   PATTERN_BUFFER will allocate its own register data, without
529
   freeing the old data.  */
530
531
void
532
re_set_registers (struct re_pattern_buffer *bufp, struct re_registers *regs,
533
      __re_size_t num_regs, regoff_t *starts, regoff_t *ends)
534
0
{
535
0
  if (num_regs)
536
0
    {
537
0
      bufp->regs_allocated = REGS_REALLOCATE;
538
0
      regs->num_regs = num_regs;
539
0
      regs->start = starts;
540
0
      regs->end = ends;
541
0
    }
542
0
  else
543
0
    {
544
0
      bufp->regs_allocated = REGS_UNALLOCATED;
545
0
      regs->num_regs = 0;
546
0
      regs->start = regs->end = NULL;
547
0
    }
548
0
}
549
#ifdef _LIBC
550
weak_alias (__re_set_registers, re_set_registers)
551
#endif
552

553
/* Entry points compatible with 4.2 BSD regex library.  We don't define
554
   them unless specifically requested.  */
555
556
#if defined _REGEX_RE_COMP || defined _LIBC
557
int
558
# ifdef _LIBC
559
weak_function
560
# endif
561
re_exec (const char *s)
562
{
563
  return 0 == regexec (&re_comp_buf, s, 0, NULL, 0);
564
}
565
#endif /* _REGEX_RE_COMP */
566

567
/* Internal entry point.  */
568
569
/* Searches for a compiled pattern PREG in the string STRING, whose
570
   length is LENGTH.  NMATCH, PMATCH, and EFLAGS have the same
571
   meaning as with regexec.  LAST_START is START + RANGE, where
572
   START and RANGE have the same meaning as with re_search.
573
   Return REG_NOERROR if we find a match, and REG_NOMATCH if not,
574
   otherwise return the error code.
575
   Note: We assume front end functions already check ranges.
576
   (0 <= LAST_START && LAST_START <= LENGTH)  */
577
578
static reg_errcode_t
579
__attribute_warn_unused_result__
580
re_search_internal (const regex_t *preg, const char *string, Idx length,
581
        Idx start, Idx last_start, Idx stop, size_t nmatch,
582
        regmatch_t pmatch[], int eflags)
583
57
{
584
57
  reg_errcode_t err;
585
57
  const re_dfa_t *dfa = preg->buffer;
586
57
  Idx left_lim, right_lim;
587
57
  int incr;
588
57
  bool fl_longest_match;
589
57
  int match_kind;
590
57
  Idx match_first;
591
57
  Idx match_last = -1;
592
57
  Idx extra_nmatch;
593
57
  bool sb;
594
57
  int ch;
595
57
  re_match_context_t mctx = { .dfa = dfa };
596
57
  char *fastmap = ((preg->fastmap != NULL && preg->fastmap_accurate
597
0
        && start != last_start && !preg->can_be_null)
598
57
       ? preg->fastmap : NULL);
599
57
  RE_TRANSLATE_TYPE t = preg->translate;
600
601
57
  extra_nmatch = (nmatch > preg->re_nsub) ? nmatch - (preg->re_nsub + 1) : 0;
602
57
  nmatch -= extra_nmatch;
603
604
  /* Check if the DFA haven't been compiled.  */
605
57
  if (__glibc_unlikely (preg->used == 0 || dfa->init_state == NULL
606
57
      || dfa->init_state_word == NULL
607
57
      || dfa->init_state_nl == NULL
608
57
      || dfa->init_state_begbuf == NULL))
609
0
    return REG_NOMATCH;
610
611
  /* We assume front-end functions already check them.  */
612
57
  DEBUG_ASSERT (0 <= last_start && last_start <= length);
613
614
  /* If initial states with non-begbuf contexts have no elements,
615
     the regex must be anchored.  If preg->newline_anchor is set,
616
     we'll never use init_state_nl, so do not check it.  */
617
57
  if (dfa->init_state->nodes.nelem == 0
618
0
      && dfa->init_state_word->nodes.nelem == 0
619
0
      && (dfa->init_state_nl->nodes.nelem == 0
620
0
    || !preg->newline_anchor))
621
0
    {
622
0
      if (start != 0 && last_start != 0)
623
0
        return REG_NOMATCH;
624
0
      start = last_start = 0;
625
0
    }
626
627
  /* We must check the longest matching, if nmatch > 0.  */
628
57
  fl_longest_match = (nmatch != 0 || dfa->nbackref);
629
630
57
  re_dfastate_t **save_state_log = NULL;
631
632
57
  err = re_string_allocate (&mctx.input, string, length, dfa->nodes_len + 1,
633
57
          preg->translate, (preg->syntax & RE_ICASE) != 0,
634
57
          dfa);
635
57
  if (__glibc_unlikely (err != REG_NOERROR))
636
0
    goto free_return;
637
57
  mctx.input.stop = stop;
638
57
  mctx.input.raw_stop = stop;
639
57
  mctx.input.newline_anchor = preg->newline_anchor;
640
641
57
  err = match_ctx_init (&mctx, eflags, dfa->nbackref * 2);
642
57
  if (__glibc_unlikely (err != REG_NOERROR))
643
0
    goto free_return;
644
645
  /* We will log all the DFA states through which the dfa pass,
646
     if nmatch > 1, or this dfa has "multibyte node", which is a
647
     back-reference or a node which can accept multibyte character or
648
     multi character collating element.  */
649
57
  if (nmatch > 1 || dfa->has_mb_node)
650
0
    {
651
      /* Avoid overflow.  */
652
0
      if (__glibc_unlikely ((MIN (IDX_MAX, SIZE_MAX / sizeof (re_dfastate_t *))
653
0
           <= mctx.input.bufs_len)))
654
0
  {
655
0
    err = REG_ESPACE;
656
0
    goto free_return;
657
0
  }
658
659
0
      mctx.state_log = re_malloc (re_dfastate_t *, mctx.input.bufs_len + 1);
660
0
      if (__glibc_unlikely (mctx.state_log == NULL))
661
0
  {
662
0
    err = REG_ESPACE;
663
0
    goto free_return;
664
0
  }
665
0
    }
666
667
57
  match_first = start;
668
57
  mctx.input.tip_context = (eflags & REG_NOTBOL) ? CONTEXT_BEGBUF
669
57
         : CONTEXT_NEWLINE | CONTEXT_BEGBUF;
670
671
  /* Check incrementally whether the input string matches.  */
672
57
  incr = (last_start < start) ? -1 : 1;
673
57
  left_lim = (last_start < start) ? last_start : start;
674
57
  right_lim = (last_start < start) ? start : last_start;
675
57
  sb = dfa->mb_cur_max == 1;
676
57
  match_kind =
677
57
    (fastmap
678
57
     ? ((sb || !(preg->syntax & RE_ICASE || t) ? 4 : 0)
679
0
  | (start <= last_start ? 2 : 0)
680
0
  | (t != NULL ? 1 : 0))
681
57
     : 8);
682
683
57
  for (;; match_first += incr)
684
105
    {
685
105
      err = REG_NOMATCH;
686
105
      if (match_first < left_lim || right_lim < match_first)
687
48
  goto free_return;
688
689
      /* Advance as rapidly as possible through the string, until we
690
   find a plausible place to start matching.  This may be done
691
   with varying efficiency, so there are various possibilities:
692
   only the most common of them are specialized, in order to
693
   save on code size.  We use a switch statement for speed.  */
694
57
      switch (match_kind)
695
57
  {
696
57
  case 8:
697
    /* No fastmap.  */
698
57
    break;
699
700
0
  case 7:
701
    /* Fastmap with single-byte translation, match forward.  */
702
0
    while (__glibc_likely (match_first < right_lim)
703
0
     && !fastmap[t[(unsigned char) string[match_first]]])
704
0
      ++match_first;
705
0
    goto forward_match_found_start_or_reached_end;
706
707
0
  case 6:
708
    /* Fastmap without translation, match forward.  */
709
0
    while (__glibc_likely (match_first < right_lim)
710
0
     && !fastmap[(unsigned char) string[match_first]])
711
0
      ++match_first;
712
713
0
  forward_match_found_start_or_reached_end:
714
0
    if (__glibc_unlikely (match_first == right_lim))
715
0
      {
716
0
        ch = match_first >= length
717
0
           ? 0 : (unsigned char) string[match_first];
718
0
        if (!fastmap[t ? t[ch] : ch])
719
0
    goto free_return;
720
0
      }
721
0
    break;
722
723
0
  case 4:
724
0
  case 5:
725
    /* Fastmap without multi-byte translation, match backwards.  */
726
0
    while (match_first >= left_lim)
727
0
      {
728
0
        ch = match_first >= length
729
0
           ? 0 : (unsigned char) string[match_first];
730
0
        if (fastmap[t ? t[ch] : ch])
731
0
    break;
732
0
        --match_first;
733
0
      }
734
0
    if (match_first < left_lim)
735
0
      goto free_return;
736
0
    break;
737
738
0
  default:
739
    /* In this case, we can't determine easily the current byte,
740
       since it might be a component byte of a multibyte
741
       character.  Then we use the constructed buffer instead.  */
742
0
    for (;;)
743
0
      {
744
        /* If MATCH_FIRST is out of the valid range, reconstruct the
745
     buffers.  */
746
0
        __re_size_t offset = match_first - mctx.input.raw_mbs_idx;
747
0
        if (__glibc_unlikely (offset
748
0
            >= (__re_size_t) mctx.input.valid_raw_len))
749
0
    {
750
0
      err = re_string_reconstruct (&mctx.input, match_first,
751
0
                 eflags);
752
0
      if (__glibc_unlikely (err != REG_NOERROR))
753
0
        goto free_return;
754
755
0
      offset = match_first - mctx.input.raw_mbs_idx;
756
0
    }
757
        /* Use buffer byte if OFFSET is in buffer, otherwise '\0'.  */
758
0
        ch = (offset < mctx.input.valid_len
759
0
        ? re_string_byte_at (&mctx.input, offset) : 0);
760
0
        if (fastmap[ch])
761
0
    break;
762
0
        match_first += incr;
763
0
        if (match_first < left_lim || match_first > right_lim)
764
0
    {
765
0
      err = REG_NOMATCH;
766
0
      goto free_return;
767
0
    }
768
0
      }
769
0
    break;
770
57
  }
771
772
      /* Reconstruct the buffers so that the matcher can assume that
773
   the matching starts from the beginning of the buffer.  */
774
57
      err = re_string_reconstruct (&mctx.input, match_first, eflags);
775
57
      if (__glibc_unlikely (err != REG_NOERROR))
776
0
  goto free_return;
777
778
      /* Don't consider this char as a possible match start if it part,
779
         yet isn't the head, of a multibyte character.  */
780
57
      if (!sb && !re_string_first_byte (&mctx.input, 0))
781
0
  continue;
782
783
      /* It seems to be appropriate one, then use the matcher.  */
784
      /* We assume that the matching starts from 0.  */
785
57
      mctx.state_log_top = mctx.nbkref_ents = mctx.max_mb_elem_len = 0;
786
57
      match_last = check_matching (&mctx, fl_longest_match,
787
57
           start <= last_start ? &match_first : NULL);
788
57
      if (match_last != -1)
789
9
  {
790
9
    if (__glibc_unlikely (match_last == -2))
791
0
      {
792
0
        err = REG_ESPACE;
793
0
        goto free_return;
794
0
      }
795
9
    else
796
9
      {
797
9
        mctx.match_last = match_last;
798
9
        if ((!preg->no_sub && nmatch > 1) || dfa->nbackref)
799
0
    {
800
0
      re_dfastate_t *pstate = mctx.state_log[match_last];
801
0
      mctx.last_node = check_halt_state_context (&mctx, pstate,
802
0
                   match_last);
803
0
    }
804
9
        if ((!preg->no_sub && nmatch > 1 && dfa->has_plural_match)
805
9
      || dfa->nbackref)
806
0
    {
807
      /* Save state_log before pruning, in case set_regs
808
         later fails and we need to retry with a shorter
809
         match.  */
810
0
      re_free (save_state_log);
811
0
      save_state_log = NULL;
812
0
      if (!preg->no_sub && nmatch > 1 && dfa->nbackref)
813
0
        {
814
0
          save_state_log
815
0
      = re_malloc (re_dfastate_t *,
816
0
             mctx.match_last + 1);
817
0
          if (__glibc_unlikely (save_state_log == NULL))
818
0
      {
819
0
        err = REG_ESPACE;
820
0
        goto free_return;
821
0
      }
822
0
          memcpy (save_state_log, mctx.state_log,
823
0
            sizeof (re_dfastate_t *)
824
0
            * (mctx.match_last + 1));
825
0
        }
826
0
      err = prune_impossible_nodes (&mctx);
827
0
      if (err == REG_NOERROR)
828
0
        break;
829
0
      if (__glibc_unlikely (err != REG_NOMATCH))
830
0
        goto free_return;
831
0
      re_free (save_state_log);
832
0
      save_state_log = NULL;
833
0
      match_last = -1;
834
0
    }
835
9
        else
836
9
    break; /* We found a match.  */
837
9
      }
838
9
  }
839
840
48
      match_ctx_clean (&mctx);
841
48
    }
842
843
9
  DEBUG_ASSERT (match_last != -1);
844
9
  DEBUG_ASSERT (err == REG_NOERROR);
845
846
  /* Set pmatch[] if we need.  */
847
9
  if (nmatch > 0)
848
9
    {
849
9
      Idx reg_idx;
850
851
      /* When set_regs fails for a backref pattern, the structural
852
   match at match_last has no valid register assignment.  Try
853
   shorter match lengths, since a valid shorter match may
854
   exist (e.g., all groups matching empty).  */
855
9
      for (;;)
856
9
  {
857
    /* Initialize registers.  */
858
9
    for (reg_idx = 1; reg_idx < nmatch; ++reg_idx)
859
0
      pmatch[reg_idx].rm_so = pmatch[reg_idx].rm_eo = -1;
860
9
    pmatch[0].rm_so = 0;
861
9
    pmatch[0].rm_eo = mctx.match_last;
862
863
9
    if (preg->no_sub || nmatch <= 1)
864
9
      break;
865
866
0
    err = set_regs (preg, &mctx, nmatch, pmatch,
867
0
        dfa->has_plural_match && dfa->nbackref > 0);
868
0
    if (__glibc_likely (err == REG_NOERROR)
869
0
        || save_state_log == NULL
870
0
        || err != REG_NOMATCH)
871
0
      break;
872
873
    /* set_regs failed; try a shorter match_last.  */
874
0
    Idx ml = mctx.match_last;
875
0
    re_free (mctx.state_log);
876
0
    do
877
0
      {
878
0
        --ml;
879
0
        if (ml < 0)
880
0
    break;
881
0
      }
882
0
    while (save_state_log[ml] == NULL
883
0
     || !save_state_log[ml]->halt
884
0
     || !check_halt_state_context
885
0
          (&mctx, save_state_log[ml], ml));
886
0
    if (ml < 0)
887
0
      {
888
0
        err = REG_NOMATCH;
889
0
        mctx.state_log = save_state_log;
890
0
        save_state_log = NULL;
891
0
        break;
892
0
      }
893
0
    mctx.state_log
894
0
      = re_malloc (re_dfastate_t *, ml + 1);
895
0
    if (__glibc_unlikely (mctx.state_log == NULL))
896
0
      {
897
0
        mctx.state_log = save_state_log;
898
0
        save_state_log = NULL;
899
0
        err = REG_ESPACE;
900
0
        break;
901
0
      }
902
0
    memcpy (mctx.state_log, save_state_log,
903
0
      sizeof (re_dfastate_t *) * (ml + 1));
904
0
    mctx.match_last = ml;
905
0
    mctx.last_node
906
0
      = check_halt_state_context
907
0
    (&mctx, save_state_log[ml], ml);
908
0
    err = prune_impossible_nodes (&mctx);
909
0
    if (__glibc_unlikely (err != REG_NOERROR))
910
0
      {
911
0
        if (err == REG_NOMATCH)
912
0
    {
913
0
      re_free (mctx.state_log);
914
0
      mctx.state_log = save_state_log;
915
0
      save_state_log = NULL;
916
0
    }
917
0
        break;
918
0
      }
919
0
  }
920
9
      re_free (save_state_log);
921
9
      save_state_log = NULL;
922
9
      if (__glibc_unlikely (err != REG_NOERROR))
923
0
  goto free_return;
924
925
      /* At last, add the offset to each register, since we slid
926
   the buffers so that we could assume that the matching starts
927
   from 0.  */
928
18
      for (reg_idx = 0; reg_idx < nmatch; ++reg_idx)
929
9
  if (pmatch[reg_idx].rm_so != -1)
930
9
    {
931
9
      if (__glibc_unlikely (mctx.input.offsets_needed != 0))
932
0
        {
933
0
    pmatch[reg_idx].rm_so =
934
0
      (pmatch[reg_idx].rm_so == mctx.input.valid_len
935
0
       ? mctx.input.valid_raw_len
936
0
       : mctx.input.offsets[pmatch[reg_idx].rm_so]);
937
0
    pmatch[reg_idx].rm_eo =
938
0
      (pmatch[reg_idx].rm_eo == mctx.input.valid_len
939
0
       ? mctx.input.valid_raw_len
940
0
       : mctx.input.offsets[pmatch[reg_idx].rm_eo]);
941
0
        }
942
9
      pmatch[reg_idx].rm_so += match_first;
943
9
      pmatch[reg_idx].rm_eo += match_first;
944
9
    }
945
9
      for (reg_idx = 0; reg_idx < extra_nmatch; ++reg_idx)
946
0
  {
947
0
    pmatch[nmatch + reg_idx].rm_so = -1;
948
0
    pmatch[nmatch + reg_idx].rm_eo = -1;
949
0
  }
950
951
9
      if (dfa->subexp_map)
952
0
  for (reg_idx = 0; reg_idx + 1 < nmatch; reg_idx++)
953
0
    if (dfa->subexp_map[reg_idx] != reg_idx)
954
0
      {
955
0
        pmatch[reg_idx + 1].rm_so
956
0
    = pmatch[dfa->subexp_map[reg_idx] + 1].rm_so;
957
0
        pmatch[reg_idx + 1].rm_eo
958
0
    = pmatch[dfa->subexp_map[reg_idx] + 1].rm_eo;
959
0
      }
960
9
    }
961
962
57
 free_return:
963
57
  re_free (save_state_log);
964
57
  re_free (mctx.state_log);
965
57
  if (dfa->nbackref)
966
0
    match_ctx_free (&mctx);
967
57
  re_string_destruct (&mctx.input);
968
57
  return err;
969
9
}
970
971
static reg_errcode_t
972
__attribute_warn_unused_result__
973
prune_impossible_nodes (re_match_context_t *mctx)
974
0
{
975
0
  const re_dfa_t *const dfa = mctx->dfa;
976
0
  Idx halt_node, match_last;
977
0
  reg_errcode_t ret;
978
0
  re_dfastate_t **sifted_states;
979
0
  re_dfastate_t **lim_states = NULL;
980
0
  re_sift_context_t sctx;
981
0
  DEBUG_ASSERT (mctx->state_log != NULL);
982
0
  match_last = mctx->match_last;
983
0
  halt_node = mctx->last_node;
984
985
  /* Avoid overflow.  */
986
0
  if (__glibc_unlikely (MIN (IDX_MAX, SIZE_MAX / sizeof (re_dfastate_t *))
987
0
      <= match_last))
988
0
    return REG_ESPACE;
989
990
0
  sifted_states = re_malloc (re_dfastate_t *, match_last + 1);
991
0
  if (__glibc_unlikely (sifted_states == NULL))
992
0
    {
993
0
      ret = REG_ESPACE;
994
0
      goto free_return;
995
0
    }
996
0
  if (dfa->nbackref)
997
0
    {
998
0
      lim_states = re_malloc (re_dfastate_t *, match_last + 1);
999
0
      if (__glibc_unlikely (lim_states == NULL))
1000
0
  {
1001
0
    ret = REG_ESPACE;
1002
0
    goto free_return;
1003
0
  }
1004
0
      while (1)
1005
0
  {
1006
0
    memset (lim_states, '\0',
1007
0
      sizeof (re_dfastate_t *) * (match_last + 1));
1008
0
    sift_ctx_init (&sctx, sifted_states, lim_states, halt_node,
1009
0
       match_last);
1010
0
    ret = sift_states_backward (mctx, &sctx);
1011
0
    re_node_set_free (&sctx.limits);
1012
0
    if (__glibc_unlikely (ret != REG_NOERROR))
1013
0
        goto free_return;
1014
0
    if (sifted_states[0] != NULL || lim_states[0] != NULL)
1015
0
      break;
1016
0
    for (;;)
1017
0
      {
1018
0
        --match_last;
1019
0
        if (match_last < 0)
1020
0
    {
1021
0
      ret = REG_NOMATCH;
1022
0
      goto free_return;
1023
0
    }
1024
0
              if (mctx->state_log[match_last] != NULL
1025
0
                  && mctx->state_log[match_last]->halt)
1026
0
                {
1027
0
                  halt_node
1028
0
                    = check_halt_state_context (mctx,
1029
0
                                                mctx->state_log[match_last],
1030
0
                                                match_last);
1031
0
                  if (halt_node)
1032
0
                    break;
1033
0
                }
1034
0
      }
1035
0
  }
1036
0
      ret = merge_state_array (dfa, sifted_states, lim_states,
1037
0
             match_last + 1);
1038
0
      re_free (lim_states);
1039
0
      lim_states = NULL;
1040
0
      if (__glibc_unlikely (ret != REG_NOERROR))
1041
0
  goto free_return;
1042
0
    }
1043
0
  else
1044
0
    {
1045
0
      sift_ctx_init (&sctx, sifted_states, lim_states, halt_node, match_last);
1046
0
      ret = sift_states_backward (mctx, &sctx);
1047
0
      re_node_set_free (&sctx.limits);
1048
0
      if (__glibc_unlikely (ret != REG_NOERROR))
1049
0
  goto free_return;
1050
0
      if (sifted_states[0] == NULL)
1051
0
  {
1052
0
    ret = REG_NOMATCH;
1053
0
    goto free_return;
1054
0
  }
1055
0
    }
1056
0
  re_free (mctx->state_log);
1057
0
  mctx->state_log = sifted_states;
1058
0
  sifted_states = NULL;
1059
0
  mctx->last_node = halt_node;
1060
0
  mctx->match_last = match_last;
1061
0
  ret = REG_NOERROR;
1062
0
 free_return:
1063
0
  re_free (sifted_states);
1064
0
  re_free (lim_states);
1065
0
  return ret;
1066
0
}
1067
1068
/* Acquire an initial state and return it.
1069
   We must select appropriate initial state depending on the context,
1070
   since initial states may have constraints like "\<", "^", etc..  */
1071
1072
static __always_inline re_dfastate_t *
1073
acquire_init_state_context (reg_errcode_t *err, const re_match_context_t *mctx,
1074
          Idx idx)
1075
57
{
1076
57
  const re_dfa_t *const dfa = mctx->dfa;
1077
57
  if (dfa->init_state->has_constraint)
1078
0
    {
1079
0
      unsigned int context;
1080
0
      context = re_string_context_at (&mctx->input, idx - 1, mctx->eflags);
1081
0
      if (IS_WORD_CONTEXT (context))
1082
0
  return dfa->init_state_word;
1083
0
      else if (IS_ORDINARY_CONTEXT (context))
1084
0
  return dfa->init_state;
1085
0
      else if (IS_BEGBUF_CONTEXT (context) && IS_NEWLINE_CONTEXT (context))
1086
0
  return dfa->init_state_begbuf;
1087
0
      else if (IS_NEWLINE_CONTEXT (context))
1088
0
  return dfa->init_state_nl;
1089
0
      else if (IS_BEGBUF_CONTEXT (context))
1090
0
  {
1091
    /* It is relatively rare case, then calculate on demand.  */
1092
0
    return re_acquire_state_context (err, dfa,
1093
0
             dfa->init_state->entrance_nodes,
1094
0
             context);
1095
0
  }
1096
0
      else
1097
  /* Must not happen?  */
1098
0
  return dfa->init_state;
1099
0
    }
1100
57
  else
1101
57
    return dfa->init_state;
1102
57
}
1103
1104
/* Check whether the regular expression match input string INPUT or not,
1105
   and return the index where the matching end.  Return -1 if
1106
   there is no match, and return -2 in case of an error.
1107
   FL_LONGEST_MATCH means we want the POSIX longest matching.
1108
   If P_MATCH_FIRST is not NULL, and the match fails, it is set to the
1109
   next place where we may want to try matching.
1110
   Note that the matcher assumes that the matching starts from the current
1111
   index of the buffer.  */
1112
1113
static Idx
1114
__attribute_warn_unused_result__
1115
check_matching (re_match_context_t *mctx, bool fl_longest_match,
1116
    Idx *p_match_first)
1117
57
{
1118
57
  const re_dfa_t *const dfa = mctx->dfa;
1119
57
  reg_errcode_t err;
1120
57
  Idx match = 0;
1121
57
  Idx match_last = -1;
1122
57
  Idx cur_str_idx = re_string_cur_idx (&mctx->input);
1123
57
  re_dfastate_t *cur_state;
1124
57
  bool at_init_state = p_match_first != NULL;
1125
57
  Idx next_start_idx = cur_str_idx;
1126
1127
57
  err = REG_NOERROR;
1128
57
  cur_state = acquire_init_state_context (&err, mctx, cur_str_idx);
1129
  /* An initial state must not be NULL (invalid).  */
1130
57
  if (__glibc_unlikely (cur_state == NULL))
1131
0
    {
1132
0
      DEBUG_ASSERT (err == REG_ESPACE);
1133
0
      return -2;
1134
0
    }
1135
1136
57
  if (mctx->state_log != NULL)
1137
0
    {
1138
0
      mctx->state_log[cur_str_idx] = cur_state;
1139
1140
      /* Check OP_OPEN_SUBEXP in the initial state in case that we use them
1141
   later.  E.g. Processing back references.  */
1142
0
      if (__glibc_unlikely (dfa->nbackref))
1143
0
  {
1144
0
    at_init_state = false;
1145
0
    err = check_subexp_matching_top (mctx, &cur_state->nodes, 0);
1146
0
    if (__glibc_unlikely (err != REG_NOERROR))
1147
0
      return err;
1148
1149
0
    if (cur_state->has_backref)
1150
0
      {
1151
0
        err = transit_state_bkref (mctx, &cur_state->nodes);
1152
0
        if (__glibc_unlikely (err != REG_NOERROR))
1153
0
    return err;
1154
0
      }
1155
0
  }
1156
0
    }
1157
1158
  /* If the RE accepts NULL string.  */
1159
57
  if (__glibc_unlikely (cur_state->halt))
1160
0
    {
1161
0
      if (!cur_state->has_constraint
1162
0
    || check_halt_state_context (mctx, cur_state, cur_str_idx))
1163
0
  {
1164
0
    if (!fl_longest_match)
1165
0
      return cur_str_idx;
1166
0
    else
1167
0
      {
1168
0
        match_last = cur_str_idx;
1169
0
        match = 1;
1170
0
      }
1171
0
  }
1172
0
    }
1173
1174
154
  while (!re_string_eoi (&mctx->input))
1175
98
    {
1176
98
      re_dfastate_t *old_state = cur_state;
1177
98
      Idx next_char_idx = re_string_cur_idx (&mctx->input) + 1;
1178
1179
98
      if ((__glibc_unlikely (next_char_idx >= mctx->input.bufs_len)
1180
0
     && mctx->input.bufs_len < mctx->input.len)
1181
98
    || (__glibc_unlikely (next_char_idx >= mctx->input.valid_len)
1182
8
        && mctx->input.valid_len < mctx->input.len))
1183
0
  {
1184
0
    err = extend_buffers (mctx, next_char_idx + 1);
1185
0
    if (__glibc_unlikely (err != REG_NOERROR))
1186
0
      {
1187
0
        DEBUG_ASSERT (err == REG_ESPACE);
1188
0
        return -2;
1189
0
      }
1190
0
  }
1191
1192
98
      cur_state = transit_state (&err, mctx, cur_state);
1193
98
      if (mctx->state_log != NULL)
1194
0
  cur_state = merge_state_with_log (&err, mctx, cur_state);
1195
1196
98
      if (cur_state == NULL)
1197
1
  {
1198
    /* Reached the invalid state or an error.  Try to recover a valid
1199
       state using the state log, if available and if we have not
1200
       already found a valid (even if not the longest) match.  */
1201
1
    if (__glibc_unlikely (err != REG_NOERROR))
1202
0
      return -2;
1203
1204
1
    if (mctx->state_log == NULL
1205
0
        || (match && !fl_longest_match)
1206
0
        || (cur_state = find_recover_state (&err, mctx)) == NULL)
1207
1
      break;
1208
1
  }
1209
1210
97
      if (__glibc_unlikely (at_init_state))
1211
9
  {
1212
9
    if (old_state == cur_state)
1213
0
      next_start_idx = next_char_idx;
1214
9
    else
1215
9
      at_init_state = false;
1216
9
  }
1217
1218
97
      if (cur_state->halt)
1219
9
  {
1220
    /* Reached a halt state.
1221
       Check the halt state can satisfy the current context.  */
1222
9
    if (!cur_state->has_constraint
1223
0
        || check_halt_state_context (mctx, cur_state,
1224
0
             re_string_cur_idx (&mctx->input)))
1225
9
      {
1226
        /* We found an appropriate halt state.  */
1227
9
        match_last = re_string_cur_idx (&mctx->input);
1228
9
        match = 1;
1229
1230
        /* We found a match, do not modify match_first below.  */
1231
9
        p_match_first = NULL;
1232
9
        if (!fl_longest_match)
1233
0
    break;
1234
9
      }
1235
9
  }
1236
97
    }
1237
1238
57
  if (p_match_first)
1239
48
    *p_match_first += next_start_idx;
1240
1241
57
  return match_last;
1242
57
}
1243
1244
/* Check NODE match the current context.  */
1245
1246
static bool
1247
check_halt_node_context (const re_dfa_t *dfa, Idx node, unsigned int context)
1248
0
{
1249
0
  re_token_type_t type = dfa->nodes[node].type;
1250
0
  unsigned int constraint = dfa->nodes[node].constraint;
1251
0
  if (type != END_OF_RE)
1252
0
    return false;
1253
0
  if (!constraint)
1254
0
    return true;
1255
0
  if (NOT_SATISFY_NEXT_CONSTRAINT (constraint, context))
1256
0
    return false;
1257
0
  return true;
1258
0
}
1259
1260
/* Check the halt state STATE match the current context.
1261
   Return 0 if not match, if the node, STATE has, is a halt node and
1262
   match the context, return the node.  */
1263
1264
static Idx
1265
check_halt_state_context (const re_match_context_t *mctx,
1266
        const re_dfastate_t *state, Idx idx)
1267
0
{
1268
0
  Idx i;
1269
0
  unsigned int context;
1270
0
  DEBUG_ASSERT (state->halt);
1271
0
  context = re_string_context_at (&mctx->input, idx, mctx->eflags);
1272
0
  for (i = 0; i < state->nodes.nelem; ++i)
1273
0
    if (check_halt_node_context (mctx->dfa, state->nodes.elems[i], context))
1274
0
      return state->nodes.elems[i];
1275
0
  return 0;
1276
0
}
1277
1278
/* Compute the next node to which "NFA" transit from NODE("NFA" is a NFA
1279
   corresponding to the DFA).
1280
   Return the destination node, and update EPS_VIA_NODES;
1281
   return -1 on match failure, -2 on error.  */
1282
1283
static Idx
1284
proceed_next_node (const re_match_context_t *mctx, Idx nregs, regmatch_t *regs,
1285
       regmatch_t *prevregs,
1286
       Idx *pidx, Idx node, re_node_set *eps_via_nodes,
1287
       struct re_fail_stack_t *fs)
1288
0
{
1289
0
  const re_dfa_t *const dfa = mctx->dfa;
1290
0
  if (IS_EPSILON_NODE (dfa->nodes[node].type))
1291
0
    {
1292
0
      re_node_set *cur_nodes = &mctx->state_log[*pidx]->nodes;
1293
0
      re_node_set *edests = &dfa->edests[node];
1294
1295
0
      if (! re_node_set_contains (eps_via_nodes, node))
1296
0
        {
1297
0
          bool ok = re_node_set_insert (eps_via_nodes, node);
1298
0
          if (__glibc_unlikely (! ok))
1299
0
            return -2;
1300
0
        }
1301
1302
      /* Pick a valid destination, or return -1 if none is found.  */
1303
0
      Idx dest_node = -1;
1304
0
      for (Idx i = 0; i < edests->nelem; i++)
1305
0
  {
1306
0
    Idx candidate = edests->elems[i];
1307
0
    if (!re_node_set_contains (cur_nodes, candidate))
1308
0
      continue;
1309
0
          if (dest_node == -1)
1310
0
      dest_node = candidate;
1311
1312
0
    else
1313
0
      {
1314
        /* In order to avoid infinite loop like "(a*)*", return the second
1315
     epsilon-transition if the first was already considered.  */
1316
0
        if (re_node_set_contains (eps_via_nodes, dest_node))
1317
0
    return candidate;
1318
1319
        /* Otherwise, push the second epsilon-transition on the fail stack.  */
1320
0
        else if (fs != NULL
1321
0
           && push_fail_stack (fs, *pidx, candidate, nregs, regs,
1322
0
             prevregs, eps_via_nodes))
1323
0
    return -2;
1324
1325
        /* We know we are going to exit.  */
1326
0
        break;
1327
0
      }
1328
0
  }
1329
0
      return dest_node;
1330
0
    }
1331
0
  else
1332
0
    {
1333
0
      Idx naccepted = 0;
1334
0
      re_token_type_t type = dfa->nodes[node].type;
1335
1336
0
      if (dfa->nodes[node].accept_mb)
1337
0
  naccepted = check_node_accept_bytes (dfa, node, &mctx->input, *pidx);
1338
0
      else if (type == OP_BACK_REF)
1339
0
  {
1340
0
    Idx subexp_idx = dfa->nodes[node].opr.idx + 1;
1341
0
    if (subexp_idx < nregs)
1342
0
      naccepted = regs[subexp_idx].rm_eo - regs[subexp_idx].rm_so;
1343
0
    if (fs != NULL)
1344
0
      {
1345
0
        if (subexp_idx >= nregs
1346
0
      || regs[subexp_idx].rm_so == -1
1347
0
      || regs[subexp_idx].rm_eo == -1)
1348
0
    return -1;
1349
0
        else if (naccepted)
1350
0
    {
1351
0
      char *buf = (char *) re_string_get_buffer (&mctx->input);
1352
0
      if (mctx->input.valid_len - *pidx < naccepted
1353
0
          || (memcmp (buf + regs[subexp_idx].rm_so, buf + *pidx,
1354
0
          naccepted)
1355
0
        != 0))
1356
0
        return -1;
1357
0
    }
1358
0
      }
1359
1360
0
    if (naccepted == 0)
1361
0
      {
1362
0
        Idx dest_node;
1363
0
        bool ok = re_node_set_insert (eps_via_nodes, node);
1364
0
        if (__glibc_unlikely (! ok))
1365
0
    return -2;
1366
0
        dest_node = dfa->edests[node].elems[0];
1367
0
        if (re_node_set_contains (&mctx->state_log[*pidx]->nodes,
1368
0
          dest_node))
1369
0
    return dest_node;
1370
0
      }
1371
0
  }
1372
1373
0
      if (naccepted != 0
1374
0
    || check_node_accept (mctx, dfa->nodes + node, *pidx))
1375
0
  {
1376
0
    Idx dest_node = dfa->nexts[node];
1377
0
    *pidx = (naccepted == 0) ? *pidx + 1 : *pidx + naccepted;
1378
0
    if (fs && (*pidx > mctx->match_last || mctx->state_log[*pidx] == NULL
1379
0
         || !re_node_set_contains (&mctx->state_log[*pidx]->nodes,
1380
0
                 dest_node)))
1381
0
      return -1;
1382
0
    re_node_set_empty (eps_via_nodes);
1383
0
    return dest_node;
1384
0
  }
1385
0
    }
1386
0
  return -1;
1387
0
}
1388
1389
static reg_errcode_t
1390
__attribute_warn_unused_result__
1391
push_fail_stack (struct re_fail_stack_t *fs, Idx str_idx, Idx dest_node,
1392
     Idx nregs, regmatch_t *regs, regmatch_t *prevregs,
1393
     re_node_set *eps_via_nodes)
1394
0
{
1395
0
  reg_errcode_t err;
1396
0
  Idx num = fs->num;
1397
0
  if (num == fs->alloc)
1398
0
    {
1399
0
      struct re_fail_stack_ent_t *new_array;
1400
0
      new_array = re_realloc (fs->stack, struct re_fail_stack_ent_t,
1401
0
                              fs->alloc * 2);
1402
0
      if (new_array == NULL)
1403
0
  return REG_ESPACE;
1404
0
      fs->alloc *= 2;
1405
0
      fs->stack = new_array;
1406
0
    }
1407
0
  fs->stack[num].idx = str_idx;
1408
0
  fs->stack[num].node = dest_node;
1409
0
  fs->stack[num].regs = re_malloc (regmatch_t, 2 * nregs);
1410
0
  if (fs->stack[num].regs == NULL)
1411
0
    return REG_ESPACE;
1412
0
  fs->num = num + 1;
1413
0
  memcpy (fs->stack[num].regs, regs, sizeof (regmatch_t) * nregs);
1414
0
  memcpy (fs->stack[num].regs + nregs, prevregs, sizeof (regmatch_t) * nregs);
1415
0
  err = re_node_set_init_copy (&fs->stack[num].eps_via_nodes, eps_via_nodes);
1416
0
  return err;
1417
0
}
1418
1419
static Idx
1420
pop_fail_stack (struct re_fail_stack_t *fs, Idx *pidx, Idx nregs,
1421
    regmatch_t *regs, regmatch_t *prevregs,
1422
    re_node_set *eps_via_nodes)
1423
0
{
1424
0
  if (fs == NULL || fs->num == 0)
1425
0
    return -1;
1426
0
  Idx num = --fs->num;
1427
0
  *pidx = fs->stack[num].idx;
1428
0
  memcpy (regs, fs->stack[num].regs, sizeof (regmatch_t) * nregs);
1429
0
  memcpy (prevregs, fs->stack[num].regs + nregs, sizeof (regmatch_t) * nregs);
1430
0
  re_node_set_free (eps_via_nodes);
1431
0
  re_free (fs->stack[num].regs);
1432
0
  *eps_via_nodes = fs->stack[num].eps_via_nodes;
1433
0
  DEBUG_ASSERT (0 <= fs->stack[num].node);
1434
0
  return fs->stack[num].node;
1435
0
}
1436
1437
1438
#define DYNARRAY_STRUCT  regmatch_list
1439
#define DYNARRAY_ELEMENT regmatch_t
1440
#define DYNARRAY_PREFIX  regmatch_list_
1441
#include <malloc/dynarray-skeleton.c>
1442
1443
/* Set the positions where the subexpressions are starts/ends to registers
1444
   PMATCH.
1445
   Note: We assume that pmatch[0] is already set, and
1446
   pmatch[i].rm_so == pmatch[i].rm_eo == -1 for 0 < i < nmatch.  */
1447
1448
static reg_errcode_t
1449
__attribute_warn_unused_result__
1450
set_regs (const regex_t *preg, const re_match_context_t *mctx, size_t nmatch,
1451
    regmatch_t *pmatch, bool fl_backtrack)
1452
0
{
1453
0
  const re_dfa_t *dfa = preg->buffer;
1454
0
  Idx idx, cur_node;
1455
0
  re_node_set eps_via_nodes;
1456
0
  struct re_fail_stack_t *fs;
1457
0
  struct re_fail_stack_t fs_body = { 0, 2, NULL };
1458
0
  struct regmatch_list prev_match;
1459
0
  regmatch_list_init (&prev_match);
1460
1461
0
  DEBUG_ASSERT (nmatch > 1);
1462
0
  DEBUG_ASSERT (mctx->state_log != NULL);
1463
0
  if (fl_backtrack)
1464
0
    {
1465
0
      fs = &fs_body;
1466
0
      fs->stack = re_malloc (struct re_fail_stack_ent_t, fs->alloc);
1467
0
      if (fs->stack == NULL)
1468
0
  return REG_ESPACE;
1469
0
    }
1470
0
  else
1471
0
    fs = NULL;
1472
1473
0
  cur_node = dfa->init_node;
1474
0
  re_node_set_init_empty (&eps_via_nodes);
1475
1476
0
  if (!regmatch_list_resize (&prev_match, nmatch))
1477
0
    {
1478
0
      regmatch_list_free (&prev_match);
1479
0
      free_fail_stack_return (fs);
1480
0
      return REG_ESPACE;
1481
0
    }
1482
0
  regmatch_t *prev_idx_match = regmatch_list_begin (&prev_match);
1483
0
  memcpy (prev_idx_match, pmatch, sizeof (regmatch_t) * nmatch);
1484
1485
0
  for (idx = pmatch[0].rm_so; idx <= pmatch[0].rm_eo ;)
1486
0
    {
1487
0
      update_regs (dfa, pmatch, prev_idx_match, cur_node, idx, nmatch);
1488
1489
0
      if ((idx == pmatch[0].rm_eo && cur_node == mctx->last_node)
1490
0
    || (fs && re_node_set_contains (&eps_via_nodes, cur_node)))
1491
0
  {
1492
0
    Idx reg_idx;
1493
0
    cur_node = -1;
1494
0
    if (fs)
1495
0
      {
1496
0
        for (reg_idx = 0; reg_idx < nmatch; ++reg_idx)
1497
0
    if (pmatch[reg_idx].rm_so > -1 && pmatch[reg_idx].rm_eo == -1)
1498
0
      {
1499
0
        cur_node = pop_fail_stack (fs, &idx, nmatch, pmatch,
1500
0
                 prev_idx_match, &eps_via_nodes);
1501
0
        break;
1502
0
      }
1503
0
      }
1504
0
    if (cur_node < 0)
1505
0
      {
1506
0
        re_node_set_free (&eps_via_nodes);
1507
0
        regmatch_list_free (&prev_match);
1508
0
        return free_fail_stack_return (fs);
1509
0
      }
1510
0
  }
1511
1512
      /* Proceed to next node.  */
1513
0
      cur_node = proceed_next_node (mctx, nmatch, pmatch, prev_idx_match,
1514
0
            &idx, cur_node,
1515
0
            &eps_via_nodes, fs);
1516
1517
0
      if (__glibc_unlikely (cur_node < 0))
1518
0
  {
1519
0
    if (__glibc_unlikely (cur_node == -2))
1520
0
      {
1521
0
        re_node_set_free (&eps_via_nodes);
1522
0
        regmatch_list_free (&prev_match);
1523
0
        free_fail_stack_return (fs);
1524
0
        return REG_ESPACE;
1525
0
      }
1526
0
    cur_node = pop_fail_stack (fs, &idx, nmatch, pmatch,
1527
0
             prev_idx_match, &eps_via_nodes);
1528
0
    if (cur_node < 0)
1529
0
      {
1530
0
        re_node_set_free (&eps_via_nodes);
1531
0
        regmatch_list_free (&prev_match);
1532
0
        free_fail_stack_return (fs);
1533
0
        return REG_NOMATCH;
1534
0
      }
1535
0
  }
1536
0
    }
1537
0
  re_node_set_free (&eps_via_nodes);
1538
0
  regmatch_list_free (&prev_match);
1539
0
  return free_fail_stack_return (fs);
1540
0
}
1541
1542
static reg_errcode_t
1543
free_fail_stack_return (struct re_fail_stack_t *fs)
1544
0
{
1545
0
  if (fs)
1546
0
    {
1547
0
      Idx fs_idx;
1548
0
      for (fs_idx = 0; fs_idx < fs->num; ++fs_idx)
1549
0
  {
1550
0
    re_node_set_free (&fs->stack[fs_idx].eps_via_nodes);
1551
0
    re_free (fs->stack[fs_idx].regs);
1552
0
  }
1553
0
      re_free (fs->stack);
1554
0
    }
1555
0
  return REG_NOERROR;
1556
0
}
1557
1558
static void
1559
update_regs (const re_dfa_t *dfa, regmatch_t *pmatch,
1560
       regmatch_t *prev_idx_match, Idx cur_node, Idx cur_idx, Idx nmatch)
1561
0
{
1562
0
  int type = dfa->nodes[cur_node].type;
1563
0
  if (type == OP_OPEN_SUBEXP)
1564
0
    {
1565
0
      Idx reg_num = dfa->nodes[cur_node].opr.idx + 1;
1566
1567
      /* We are at the first node of this sub expression.  */
1568
0
      if (reg_num < nmatch)
1569
0
  {
1570
0
    pmatch[reg_num].rm_so = cur_idx;
1571
0
    pmatch[reg_num].rm_eo = -1;
1572
0
  }
1573
0
    }
1574
0
  else if (type == OP_CLOSE_SUBEXP)
1575
0
    {
1576
      /* We are at the last node of this sub expression.  */
1577
0
      Idx reg_num = dfa->nodes[cur_node].opr.idx + 1;
1578
0
      if (reg_num < nmatch)
1579
0
  {
1580
0
    if (pmatch[reg_num].rm_so < cur_idx)
1581
0
      {
1582
0
        pmatch[reg_num].rm_eo = cur_idx;
1583
        /* This is a non-empty match or we are not inside an optional
1584
     subexpression.  Accept this right away.  */
1585
0
        memcpy (prev_idx_match, pmatch, sizeof (regmatch_t) * nmatch);
1586
0
      }
1587
0
    else
1588
0
      {
1589
0
        if (dfa->nodes[cur_node].opt_subexp
1590
0
      && prev_idx_match[reg_num].rm_so != -1)
1591
    /* We transited through an empty match for an optional
1592
       subexpression, like (a?)*, and this is not the subexp's
1593
       first match.  Copy back the old content of the registers
1594
       so that matches of an inner subexpression are undone as
1595
       well, like in ((a?))*.  */
1596
0
    memcpy (pmatch, prev_idx_match, sizeof (regmatch_t) * nmatch);
1597
0
        else
1598
    /* We completed a subexpression, but it may be part of
1599
       an optional one, so do not update PREV_IDX_MATCH.  */
1600
0
    pmatch[reg_num].rm_eo = cur_idx;
1601
0
      }
1602
0
  }
1603
0
    }
1604
0
}
1605
1606
/* This function checks the STATE_LOG from the SCTX->last_str_idx to 0
1607
   and sift the nodes in each states according to the following rules.
1608
   Updated state_log will be wrote to STATE_LOG.
1609
1610
   Rules: We throw away the Node 'a' in the STATE_LOG[STR_IDX] if...
1611
     1. When STR_IDX == MATCH_LAST(the last index in the state_log):
1612
  If 'a' isn't the LAST_NODE and 'a' can't epsilon transit to
1613
  the LAST_NODE, we throw away the node 'a'.
1614
     2. When 0 <= STR_IDX < MATCH_LAST and 'a' accepts
1615
  string 's' and transit to 'b':
1616
  i. If 'b' isn't in the STATE_LOG[STR_IDX+strlen('s')], we throw
1617
     away the node 'a'.
1618
  ii. If 'b' is in the STATE_LOG[STR_IDX+strlen('s')] but 'b' is
1619
      thrown away, we throw away the node 'a'.
1620
     3. When 0 <= STR_IDX < MATCH_LAST and 'a' epsilon transit to 'b':
1621
  i. If 'b' isn't in the STATE_LOG[STR_IDX], we throw away the
1622
     node 'a'.
1623
  ii. If 'b' is in the STATE_LOG[STR_IDX] but 'b' is thrown away,
1624
      we throw away the node 'a'.  */
1625
1626
#define STATE_NODE_CONTAINS(state,node) \
1627
0
  ((state) != NULL && re_node_set_contains (&(state)->nodes, node))
1628
1629
static reg_errcode_t
1630
sift_states_backward (const re_match_context_t *mctx, re_sift_context_t *sctx)
1631
0
{
1632
0
  reg_errcode_t err;
1633
0
  int null_cnt = 0;
1634
0
  Idx str_idx = sctx->last_str_idx;
1635
0
  re_node_set cur_dest;
1636
1637
0
  DEBUG_ASSERT (mctx->state_log != NULL && mctx->state_log[str_idx] != NULL);
1638
1639
  /* Build sifted state_log[str_idx].  It has the nodes which can epsilon
1640
     transit to the last_node and the last_node itself.  */
1641
0
  err = re_node_set_init_1 (&cur_dest, sctx->last_node);
1642
0
  if (__glibc_unlikely (err != REG_NOERROR))
1643
0
    return err;
1644
0
  err = update_cur_sifted_state (mctx, sctx, str_idx, &cur_dest);
1645
0
  if (__glibc_unlikely (err != REG_NOERROR))
1646
0
    goto free_return;
1647
1648
  /* Then check each states in the state_log.  */
1649
0
  while (str_idx > 0)
1650
0
    {
1651
      /* Update counters.  */
1652
0
      null_cnt = (sctx->sifted_states[str_idx] == NULL) ? null_cnt + 1 : 0;
1653
0
      if (null_cnt > mctx->max_mb_elem_len)
1654
0
  {
1655
0
    memset (sctx->sifted_states, '\0',
1656
0
      sizeof (re_dfastate_t *) * str_idx);
1657
0
    re_node_set_free (&cur_dest);
1658
0
    return REG_NOERROR;
1659
0
  }
1660
0
      re_node_set_empty (&cur_dest);
1661
0
      --str_idx;
1662
1663
0
      if (mctx->state_log[str_idx])
1664
0
  {
1665
0
    err = build_sifted_states (mctx, sctx, str_idx, &cur_dest);
1666
0
    if (__glibc_unlikely (err != REG_NOERROR))
1667
0
      goto free_return;
1668
0
  }
1669
1670
      /* Add all the nodes which satisfy the following conditions:
1671
   - It can epsilon transit to a node in CUR_DEST.
1672
   - It is in CUR_SRC.
1673
   And update state_log.  */
1674
0
      err = update_cur_sifted_state (mctx, sctx, str_idx, &cur_dest);
1675
0
      if (__glibc_unlikely (err != REG_NOERROR))
1676
0
  goto free_return;
1677
0
    }
1678
0
  err = REG_NOERROR;
1679
0
 free_return:
1680
0
  re_node_set_free (&cur_dest);
1681
0
  return err;
1682
0
}
1683
1684
static reg_errcode_t
1685
__attribute_warn_unused_result__
1686
build_sifted_states (const re_match_context_t *mctx, re_sift_context_t *sctx,
1687
         Idx str_idx, re_node_set *cur_dest)
1688
0
{
1689
0
  const re_dfa_t *const dfa = mctx->dfa;
1690
0
  const re_node_set *cur_src = &mctx->state_log[str_idx]->non_eps_nodes;
1691
0
  Idx i;
1692
1693
  /* Then build the next sifted state.
1694
     We build the next sifted state on 'cur_dest', and update
1695
     'sifted_states[str_idx]' with 'cur_dest'.
1696
     Note:
1697
     'cur_dest' is the sifted state from 'state_log[str_idx + 1]'.
1698
     'cur_src' points the node_set of the old 'state_log[str_idx]'
1699
     (with the epsilon nodes pre-filtered out).  */
1700
0
  for (i = 0; i < cur_src->nelem; i++)
1701
0
    {
1702
0
      Idx prev_node = cur_src->elems[i];
1703
0
      int naccepted = 0;
1704
0
      bool ok;
1705
0
      DEBUG_ASSERT (!IS_EPSILON_NODE (dfa->nodes[prev_node].type));
1706
1707
      /* If the node may accept "multi byte".  */
1708
0
      if (dfa->nodes[prev_node].accept_mb)
1709
0
  naccepted = sift_states_iter_mb (mctx, sctx, prev_node,
1710
0
           str_idx, sctx->last_str_idx);
1711
1712
      /* We don't check backreferences here.
1713
   See update_cur_sifted_state().  */
1714
0
      if (!naccepted
1715
0
    && check_node_accept (mctx, dfa->nodes + prev_node, str_idx)
1716
0
    && STATE_NODE_CONTAINS (sctx->sifted_states[str_idx + 1],
1717
0
          dfa->nexts[prev_node]))
1718
0
  naccepted = 1;
1719
1720
0
      if (naccepted == 0)
1721
0
  continue;
1722
1723
0
      if (sctx->limits.nelem)
1724
0
  {
1725
0
    Idx to_idx = str_idx + naccepted;
1726
0
    if (check_dst_limits (mctx, &sctx->limits,
1727
0
        dfa->nexts[prev_node], to_idx,
1728
0
        prev_node, str_idx))
1729
0
      continue;
1730
0
  }
1731
0
      ok = re_node_set_insert (cur_dest, prev_node);
1732
0
      if (__glibc_unlikely (! ok))
1733
0
  return REG_ESPACE;
1734
0
    }
1735
1736
0
  return REG_NOERROR;
1737
0
}
1738
1739
/* Helper functions.  */
1740
1741
static reg_errcode_t
1742
clean_state_log_if_needed (re_match_context_t *mctx, Idx next_state_log_idx)
1743
0
{
1744
0
  Idx top = mctx->state_log_top;
1745
1746
0
  if ((next_state_log_idx >= mctx->input.bufs_len
1747
0
       && mctx->input.bufs_len < mctx->input.len)
1748
0
      || (next_state_log_idx >= mctx->input.valid_len
1749
0
    && mctx->input.valid_len < mctx->input.len))
1750
0
    {
1751
0
      reg_errcode_t err;
1752
0
      err = extend_buffers (mctx, next_state_log_idx + 1);
1753
0
      if (__glibc_unlikely (err != REG_NOERROR))
1754
0
  return err;
1755
0
    }
1756
1757
0
  if (top < next_state_log_idx)
1758
0
    {
1759
0
      DEBUG_ASSERT (mctx->state_log != NULL);
1760
0
      memset (mctx->state_log + top + 1, '\0',
1761
0
        sizeof (re_dfastate_t *) * (next_state_log_idx - top));
1762
0
      mctx->state_log_top = next_state_log_idx;
1763
0
    }
1764
0
  return REG_NOERROR;
1765
0
}
1766
1767
static reg_errcode_t
1768
merge_state_array (const re_dfa_t *dfa, re_dfastate_t **dst,
1769
       re_dfastate_t **src, Idx num)
1770
0
{
1771
0
  Idx st_idx;
1772
0
  reg_errcode_t err;
1773
0
  for (st_idx = 0; st_idx < num; ++st_idx)
1774
0
    {
1775
0
      if (dst[st_idx] == NULL)
1776
0
  dst[st_idx] = src[st_idx];
1777
0
      else if (src[st_idx] != NULL)
1778
0
  {
1779
0
    re_node_set merged_set;
1780
0
    err = re_node_set_init_union (&merged_set, &dst[st_idx]->nodes,
1781
0
          &src[st_idx]->nodes);
1782
0
    if (__glibc_unlikely (err != REG_NOERROR))
1783
0
      return err;
1784
0
    dst[st_idx] = re_acquire_state (&err, dfa, &merged_set);
1785
0
    re_node_set_free (&merged_set);
1786
0
    if (__glibc_unlikely (err != REG_NOERROR))
1787
0
      return err;
1788
0
  }
1789
0
    }
1790
0
  return REG_NOERROR;
1791
0
}
1792
1793
static reg_errcode_t
1794
update_cur_sifted_state (const re_match_context_t *mctx,
1795
       re_sift_context_t *sctx, Idx str_idx,
1796
       re_node_set *dest_nodes)
1797
0
{
1798
0
  const re_dfa_t *const dfa = mctx->dfa;
1799
0
  reg_errcode_t err = REG_NOERROR;
1800
0
  const re_node_set *candidates;
1801
0
  candidates = ((mctx->state_log[str_idx] == NULL) ? NULL
1802
0
    : &mctx->state_log[str_idx]->nodes);
1803
1804
0
  if (dest_nodes->nelem == 0)
1805
0
    sctx->sifted_states[str_idx] = NULL;
1806
0
  else
1807
0
    {
1808
0
      if (candidates)
1809
0
  {
1810
    /* At first, add the nodes which can epsilon transit to a node in
1811
       DEST_NODE.  */
1812
0
    err = add_epsilon_src_nodes (dfa, dest_nodes, candidates);
1813
0
    if (__glibc_unlikely (err != REG_NOERROR))
1814
0
      return err;
1815
1816
    /* Then, check the limitations in the current sift_context.  */
1817
0
    if (sctx->limits.nelem)
1818
0
      {
1819
0
        err = check_subexp_limits (dfa, dest_nodes, candidates, &sctx->limits,
1820
0
           mctx->bkref_ents, str_idx);
1821
0
        if (__glibc_unlikely (err != REG_NOERROR))
1822
0
    return err;
1823
0
      }
1824
0
  }
1825
1826
0
      sctx->sifted_states[str_idx] = re_acquire_state (&err, dfa, dest_nodes);
1827
0
      if (__glibc_unlikely (err != REG_NOERROR))
1828
0
  return err;
1829
0
    }
1830
1831
0
  if (candidates && mctx->state_log[str_idx]->has_backref)
1832
0
    {
1833
0
      err = sift_states_bkref (mctx, sctx, str_idx, candidates);
1834
0
      if (__glibc_unlikely (err != REG_NOERROR))
1835
0
  return err;
1836
0
    }
1837
0
  return REG_NOERROR;
1838
0
}
1839
1840
static reg_errcode_t
1841
__attribute_warn_unused_result__
1842
add_epsilon_src_nodes (const re_dfa_t *dfa, re_node_set *dest_nodes,
1843
           const re_node_set *candidates)
1844
0
{
1845
0
  reg_errcode_t err = REG_NOERROR;
1846
0
  Idx i;
1847
1848
0
  re_dfastate_t *state = re_acquire_state (&err, dfa, dest_nodes);
1849
0
  if (__glibc_unlikely (err != REG_NOERROR))
1850
0
    return err;
1851
1852
0
  if (!state->inveclosure.alloc)
1853
0
    {
1854
0
      err = re_node_set_alloc (&state->inveclosure, dest_nodes->nelem);
1855
0
      if (__glibc_unlikely (err != REG_NOERROR))
1856
0
  return REG_ESPACE;
1857
0
      for (i = 0; i < dest_nodes->nelem; i++)
1858
0
  {
1859
0
    err = re_node_set_merge (&state->inveclosure,
1860
0
           dfa->inveclosures + dest_nodes->elems[i]);
1861
0
    if (__glibc_unlikely (err != REG_NOERROR))
1862
0
      return REG_ESPACE;
1863
0
  }
1864
0
    }
1865
0
  return re_node_set_add_intersect (dest_nodes, candidates,
1866
0
            &state->inveclosure);
1867
0
}
1868
1869
static reg_errcode_t
1870
sub_epsilon_src_nodes (const re_dfa_t *dfa, Idx node, re_node_set *dest_nodes,
1871
           const re_node_set *candidates)
1872
0
{
1873
0
    Idx ecl_idx;
1874
0
    reg_errcode_t err;
1875
0
    re_node_set *inv_eclosure = dfa->inveclosures + node;
1876
0
    re_node_set except_nodes;
1877
0
    re_node_set_init_empty (&except_nodes);
1878
0
    for (ecl_idx = 0; ecl_idx < inv_eclosure->nelem; ++ecl_idx)
1879
0
      {
1880
0
  Idx cur_node = inv_eclosure->elems[ecl_idx];
1881
0
  if (cur_node == node)
1882
0
    continue;
1883
0
  if (IS_EPSILON_NODE (dfa->nodes[cur_node].type))
1884
0
    {
1885
0
      Idx edst1 = dfa->edests[cur_node].elems[0];
1886
0
      Idx edst2 = ((dfa->edests[cur_node].nelem > 1)
1887
0
       ? dfa->edests[cur_node].elems[1] : -1);
1888
0
      if ((!re_node_set_contains (inv_eclosure, edst1)
1889
0
     && re_node_set_contains (dest_nodes, edst1))
1890
0
    || (edst2 > 0
1891
0
        && !re_node_set_contains (inv_eclosure, edst2)
1892
0
        && re_node_set_contains (dest_nodes, edst2)))
1893
0
        {
1894
0
    err = re_node_set_add_intersect (&except_nodes, candidates,
1895
0
             dfa->inveclosures + cur_node);
1896
0
    if (__glibc_unlikely (err != REG_NOERROR))
1897
0
      {
1898
0
        re_node_set_free (&except_nodes);
1899
0
        return err;
1900
0
      }
1901
0
        }
1902
0
    }
1903
0
      }
1904
0
    for (ecl_idx = 0; ecl_idx < inv_eclosure->nelem; ++ecl_idx)
1905
0
      {
1906
0
  Idx cur_node = inv_eclosure->elems[ecl_idx];
1907
0
  if (!re_node_set_contains (&except_nodes, cur_node))
1908
0
    {
1909
0
      Idx idx = re_node_set_contains (dest_nodes, cur_node) - 1;
1910
0
      re_node_set_remove_at (dest_nodes, idx);
1911
0
    }
1912
0
      }
1913
0
    re_node_set_free (&except_nodes);
1914
0
    return REG_NOERROR;
1915
0
}
1916
1917
static bool
1918
check_dst_limits (const re_match_context_t *mctx, const re_node_set *limits,
1919
      Idx dst_node, Idx dst_idx, Idx src_node, Idx src_idx)
1920
0
{
1921
0
  const re_dfa_t *const dfa = mctx->dfa;
1922
0
  Idx lim_idx, src_pos, dst_pos;
1923
1924
0
  Idx dst_bkref_idx = search_cur_bkref_entry (mctx, dst_idx);
1925
0
  Idx src_bkref_idx = search_cur_bkref_entry (mctx, src_idx);
1926
0
  for (lim_idx = 0; lim_idx < limits->nelem; ++lim_idx)
1927
0
    {
1928
0
      Idx subexp_idx;
1929
0
      struct re_backref_cache_entry *ent;
1930
0
      ent = mctx->bkref_ents + limits->elems[lim_idx];
1931
0
      subexp_idx = dfa->nodes[ent->node].opr.idx;
1932
1933
0
      dst_pos = check_dst_limits_calc_pos (mctx, limits->elems[lim_idx],
1934
0
             subexp_idx, dst_node, dst_idx,
1935
0
             dst_bkref_idx);
1936
0
      src_pos = check_dst_limits_calc_pos (mctx, limits->elems[lim_idx],
1937
0
             subexp_idx, src_node, src_idx,
1938
0
             src_bkref_idx);
1939
1940
      /* In case of:
1941
   <src> <dst> ( <subexp> )
1942
   ( <subexp> ) <src> <dst>
1943
   ( <subexp1> <src> <subexp2> <dst> <subexp3> )  */
1944
0
      if (src_pos == dst_pos)
1945
0
  continue; /* This is unrelated limitation.  */
1946
0
      else
1947
0
  return true;
1948
0
    }
1949
0
  return false;
1950
0
}
1951
1952
static int
1953
check_dst_limits_calc_pos_1 (const re_match_context_t *mctx, int boundaries,
1954
           Idx subexp_idx, Idx from_node, Idx bkref_idx)
1955
0
{
1956
0
  const re_dfa_t *const dfa = mctx->dfa;
1957
0
  const re_node_set *eclosures = dfa->eclosures + from_node;
1958
0
  Idx node_idx;
1959
1960
  /* Else, we are on the boundary: examine the nodes on the epsilon
1961
     closure.  */
1962
0
  for (node_idx = 0; node_idx < eclosures->nelem; ++node_idx)
1963
0
    {
1964
0
      Idx node = eclosures->elems[node_idx];
1965
0
      switch (dfa->nodes[node].type)
1966
0
  {
1967
0
  case OP_BACK_REF:
1968
0
    if (bkref_idx != -1)
1969
0
      {
1970
0
        struct re_backref_cache_entry *ent = mctx->bkref_ents + bkref_idx;
1971
0
        do
1972
0
    {
1973
0
      Idx dst;
1974
0
      int cpos;
1975
1976
0
      if (ent->node != node)
1977
0
        continue;
1978
1979
0
      if (subexp_idx < BITSET_WORD_BITS
1980
0
          && !(ent->eps_reachable_subexps_map
1981
0
         & ((bitset_word_t) 1 << subexp_idx)))
1982
0
        continue;
1983
1984
      /* Recurse trying to reach the OP_OPEN_SUBEXP and
1985
         OP_CLOSE_SUBEXP cases below.  But, if the
1986
         destination node is the same node as the source
1987
         node, don't recurse because it would cause an
1988
         infinite loop: a regex that exhibits this behavior
1989
         is ()\1*\1*  */
1990
0
      dst = dfa->edests[node].elems[0];
1991
0
      if (dst == from_node)
1992
0
        {
1993
0
          if (boundaries & 1)
1994
0
      return -1;
1995
0
          else /* if (boundaries & 2) */
1996
0
      return 0;
1997
0
        }
1998
1999
0
      cpos =
2000
0
        check_dst_limits_calc_pos_1 (mctx, boundaries, subexp_idx,
2001
0
             dst, bkref_idx);
2002
0
      if (cpos == -1 /* && (boundaries & 1) */)
2003
0
        return -1;
2004
0
      if (cpos == 0 && (boundaries & 2))
2005
0
        return 0;
2006
2007
0
      if (subexp_idx < BITSET_WORD_BITS)
2008
0
        ent->eps_reachable_subexps_map
2009
0
          &= ~((bitset_word_t) 1 << subexp_idx);
2010
0
    }
2011
0
        while (ent++->more);
2012
0
      }
2013
0
    break;
2014
2015
0
  case OP_OPEN_SUBEXP:
2016
0
    if ((boundaries & 1) && subexp_idx == dfa->nodes[node].opr.idx)
2017
0
      return -1;
2018
0
    break;
2019
2020
0
  case OP_CLOSE_SUBEXP:
2021
0
    if ((boundaries & 2) && subexp_idx == dfa->nodes[node].opr.idx)
2022
0
      return 0;
2023
0
    break;
2024
2025
0
  default:
2026
0
      break;
2027
0
  }
2028
0
    }
2029
2030
0
  return (boundaries & 2) ? 1 : 0;
2031
0
}
2032
2033
static int
2034
check_dst_limits_calc_pos (const re_match_context_t *mctx, Idx limit,
2035
         Idx subexp_idx, Idx from_node, Idx str_idx,
2036
         Idx bkref_idx)
2037
0
{
2038
0
  struct re_backref_cache_entry *lim = mctx->bkref_ents + limit;
2039
0
  int boundaries;
2040
2041
  /* If we are outside the range of the subexpression, return -1 or 1.  */
2042
0
  if (str_idx < lim->subexp_from)
2043
0
    return -1;
2044
2045
0
  if (lim->subexp_to < str_idx)
2046
0
    return 1;
2047
2048
  /* If we are within the subexpression, return 0.  */
2049
0
  boundaries = (str_idx == lim->subexp_from);
2050
0
  boundaries |= (str_idx == lim->subexp_to) << 1;
2051
0
  if (boundaries == 0)
2052
0
    return 0;
2053
2054
  /* Else, examine epsilon closure.  */
2055
0
  return check_dst_limits_calc_pos_1 (mctx, boundaries, subexp_idx,
2056
0
              from_node, bkref_idx);
2057
0
}
2058
2059
/* Check the limitations of sub expressions LIMITS, and remove the nodes
2060
   which are against limitations from DEST_NODES. */
2061
2062
static reg_errcode_t
2063
check_subexp_limits (const re_dfa_t *dfa, re_node_set *dest_nodes,
2064
         const re_node_set *candidates, re_node_set *limits,
2065
         struct re_backref_cache_entry *bkref_ents, Idx str_idx)
2066
0
{
2067
0
  reg_errcode_t err;
2068
0
  Idx node_idx, lim_idx;
2069
2070
0
  for (lim_idx = 0; lim_idx < limits->nelem; ++lim_idx)
2071
0
    {
2072
0
      Idx subexp_idx;
2073
0
      struct re_backref_cache_entry *ent;
2074
0
      ent = bkref_ents + limits->elems[lim_idx];
2075
2076
0
      if (str_idx <= ent->subexp_from || ent->str_idx < str_idx)
2077
0
  continue; /* This is unrelated limitation.  */
2078
2079
0
      subexp_idx = dfa->nodes[ent->node].opr.idx;
2080
0
      if (ent->subexp_to == str_idx)
2081
0
  {
2082
0
    Idx ops_node = -1;
2083
0
    Idx cls_node = -1;
2084
0
    for (node_idx = 0; node_idx < dest_nodes->nelem; ++node_idx)
2085
0
      {
2086
0
        Idx node = dest_nodes->elems[node_idx];
2087
0
        re_token_type_t type = dfa->nodes[node].type;
2088
0
        if (type == OP_OPEN_SUBEXP
2089
0
      && subexp_idx == dfa->nodes[node].opr.idx)
2090
0
    ops_node = node;
2091
0
        else if (type == OP_CLOSE_SUBEXP
2092
0
           && subexp_idx == dfa->nodes[node].opr.idx)
2093
0
    cls_node = node;
2094
0
      }
2095
2096
    /* Check the limitation of the open subexpression.  */
2097
    /* Note that (ent->subexp_to = str_idx != ent->subexp_from).  */
2098
0
    if (ops_node >= 0)
2099
0
      {
2100
0
        err = sub_epsilon_src_nodes (dfa, ops_node, dest_nodes,
2101
0
             candidates);
2102
0
        if (__glibc_unlikely (err != REG_NOERROR))
2103
0
    return err;
2104
0
      }
2105
2106
    /* Check the limitation of the close subexpression.  */
2107
0
    if (cls_node >= 0)
2108
0
      for (node_idx = 0; node_idx < dest_nodes->nelem; ++node_idx)
2109
0
        {
2110
0
    Idx node = dest_nodes->elems[node_idx];
2111
0
    if (!re_node_set_contains (dfa->inveclosures + node,
2112
0
             cls_node)
2113
0
        && !re_node_set_contains (dfa->eclosures + node,
2114
0
                cls_node))
2115
0
      {
2116
        /* It is against this limitation.
2117
           Remove it form the current sifted state.  */
2118
0
        err = sub_epsilon_src_nodes (dfa, node, dest_nodes,
2119
0
             candidates);
2120
0
        if (__glibc_unlikely (err != REG_NOERROR))
2121
0
          return err;
2122
0
        --node_idx;
2123
0
      }
2124
0
        }
2125
0
  }
2126
0
      else /* (ent->subexp_to != str_idx)  */
2127
0
  {
2128
0
    for (node_idx = 0; node_idx < dest_nodes->nelem; ++node_idx)
2129
0
      {
2130
0
        Idx node = dest_nodes->elems[node_idx];
2131
0
        re_token_type_t type = dfa->nodes[node].type;
2132
0
        if (type == OP_CLOSE_SUBEXP || type == OP_OPEN_SUBEXP)
2133
0
    {
2134
0
      if (subexp_idx != dfa->nodes[node].opr.idx)
2135
0
        continue;
2136
      /* It is against this limitation.
2137
         Remove it form the current sifted state.  */
2138
0
      err = sub_epsilon_src_nodes (dfa, node, dest_nodes,
2139
0
                 candidates);
2140
0
      if (__glibc_unlikely (err != REG_NOERROR))
2141
0
        return err;
2142
0
    }
2143
0
      }
2144
0
  }
2145
0
    }
2146
0
  return REG_NOERROR;
2147
0
}
2148
2149
static reg_errcode_t
2150
__attribute_warn_unused_result__
2151
sift_states_bkref (const re_match_context_t *mctx, re_sift_context_t *sctx,
2152
       Idx str_idx, const re_node_set *candidates)
2153
0
{
2154
0
  const re_dfa_t *const dfa = mctx->dfa;
2155
0
  reg_errcode_t err;
2156
0
  Idx node_idx, node;
2157
0
  re_sift_context_t local_sctx;
2158
0
  Idx first_idx = search_cur_bkref_entry (mctx, str_idx);
2159
2160
0
  if (first_idx == -1)
2161
0
    return REG_NOERROR;
2162
2163
0
  local_sctx.sifted_states = NULL; /* Mark that it hasn't been initialized.  */
2164
2165
0
  for (node_idx = 0; node_idx < candidates->nelem; ++node_idx)
2166
0
    {
2167
0
      Idx enabled_idx;
2168
0
      re_token_type_t type;
2169
0
      struct re_backref_cache_entry *entry;
2170
0
      node = candidates->elems[node_idx];
2171
0
      type = dfa->nodes[node].type;
2172
      /* Avoid infinite loop for the REs like "()\1+".  */
2173
0
      if (node == sctx->last_node && str_idx == sctx->last_str_idx)
2174
0
  continue;
2175
0
      if (type != OP_BACK_REF)
2176
0
  continue;
2177
2178
0
      entry = mctx->bkref_ents + first_idx;
2179
0
      enabled_idx = first_idx;
2180
0
      do
2181
0
  {
2182
0
    Idx subexp_len;
2183
0
    Idx to_idx;
2184
0
    Idx dst_node;
2185
0
    bool ok;
2186
0
    re_dfastate_t *cur_state;
2187
2188
0
    if (entry->node != node)
2189
0
      continue;
2190
0
    subexp_len = entry->subexp_to - entry->subexp_from;
2191
0
    to_idx = str_idx + subexp_len;
2192
0
    dst_node = (subexp_len ? dfa->nexts[node]
2193
0
          : dfa->edests[node].elems[0]);
2194
2195
0
    if (to_idx > sctx->last_str_idx
2196
0
        || sctx->sifted_states[to_idx] == NULL
2197
0
        || !STATE_NODE_CONTAINS (sctx->sifted_states[to_idx], dst_node)
2198
0
        || check_dst_limits (mctx, &sctx->limits, node,
2199
0
           str_idx, dst_node, to_idx))
2200
0
      continue;
2201
2202
0
    if (local_sctx.sifted_states == NULL)
2203
0
      {
2204
0
        local_sctx = *sctx;
2205
0
        err = re_node_set_init_copy (&local_sctx.limits, &sctx->limits);
2206
0
        if (__glibc_unlikely (err != REG_NOERROR))
2207
0
    goto free_return;
2208
0
      }
2209
0
    local_sctx.last_node = node;
2210
0
    local_sctx.last_str_idx = str_idx;
2211
0
    ok = re_node_set_insert (&local_sctx.limits, enabled_idx);
2212
0
    if (__glibc_unlikely (! ok))
2213
0
      {
2214
0
        err = REG_ESPACE;
2215
0
        goto free_return;
2216
0
      }
2217
0
    cur_state = local_sctx.sifted_states[str_idx];
2218
0
    err = sift_states_backward (mctx, &local_sctx);
2219
0
    if (__glibc_unlikely (err != REG_NOERROR))
2220
0
      goto free_return;
2221
0
    if (sctx->limited_states != NULL)
2222
0
      {
2223
0
        err = merge_state_array (dfa, sctx->limited_states,
2224
0
               local_sctx.sifted_states,
2225
0
               str_idx + 1);
2226
0
        if (__glibc_unlikely (err != REG_NOERROR))
2227
0
    goto free_return;
2228
0
      }
2229
0
    local_sctx.sifted_states[str_idx] = cur_state;
2230
0
    re_node_set_remove (&local_sctx.limits, enabled_idx);
2231
2232
    /* mctx->bkref_ents may have changed, reload the pointer.  */
2233
0
    entry = mctx->bkref_ents + enabled_idx;
2234
0
  }
2235
0
      while (enabled_idx++, entry++->more);
2236
0
    }
2237
0
  err = REG_NOERROR;
2238
0
 free_return:
2239
0
  if (local_sctx.sifted_states != NULL)
2240
0
    {
2241
0
      re_node_set_free (&local_sctx.limits);
2242
0
    }
2243
2244
0
  return err;
2245
0
}
2246
2247
2248
static int
2249
sift_states_iter_mb (const re_match_context_t *mctx, re_sift_context_t *sctx,
2250
         Idx node_idx, Idx str_idx, Idx max_str_idx)
2251
0
{
2252
0
  const re_dfa_t *const dfa = mctx->dfa;
2253
0
  int naccepted;
2254
  /* Check the node can accept "multi byte".  */
2255
0
  naccepted = check_node_accept_bytes (dfa, node_idx, &mctx->input, str_idx);
2256
0
  if (naccepted > 0 && str_idx + naccepted <= max_str_idx
2257
0
      && !STATE_NODE_CONTAINS (sctx->sifted_states[str_idx + naccepted],
2258
0
             dfa->nexts[node_idx]))
2259
    /* The node can't accept the "multi byte", or the
2260
       destination was already thrown away, then the node
2261
       couldn't accept the current input "multi byte".   */
2262
0
    naccepted = 0;
2263
  /* Otherwise, it is sure that the node could accept
2264
     'naccepted' bytes input.  */
2265
0
  return naccepted;
2266
0
}
2267

2268
/* Functions for state transition.  */
2269
2270
/* Return the next state to which the current state STATE will transit by
2271
   accepting the current input byte, and update STATE_LOG if necessary.
2272
   Return NULL on failure.
2273
   If STATE can accept a multibyte char/collating element/back reference
2274
   update the destination of STATE_LOG.  */
2275
2276
static re_dfastate_t *
2277
__attribute_warn_unused_result__
2278
transit_state (reg_errcode_t *err, re_match_context_t *mctx,
2279
         re_dfastate_t *state)
2280
98
{
2281
98
  re_dfastate_t **trtable;
2282
98
  unsigned char ch;
2283
2284
  /* If the current state can accept multibyte.  */
2285
98
  if (__glibc_unlikely (state->accept_mb))
2286
0
    {
2287
0
      *err = transit_state_mb (mctx, state);
2288
0
      if (__glibc_unlikely (*err != REG_NOERROR))
2289
0
  return NULL;
2290
0
    }
2291
2292
  /* Then decide the next state with the single byte.  */
2293
#if 0
2294
  if (0)
2295
    /* don't use transition table  */
2296
    return transit_state_sb (err, mctx, state);
2297
#endif
2298
2299
  /* Use transition table  */
2300
98
  ch = re_string_fetch_byte (&mctx->input);
2301
98
  for (;;)
2302
196
    {
2303
196
      trtable = state->trtable;
2304
196
      if (__glibc_likely (trtable != NULL))
2305
98
  return trtable[ch];
2306
2307
98
      trtable = state->word_trtable;
2308
98
      if (__glibc_likely (trtable != NULL))
2309
0
  {
2310
0
    unsigned int context;
2311
0
    context
2312
0
      = re_string_context_at (&mctx->input,
2313
0
            re_string_cur_idx (&mctx->input) - 1,
2314
0
            mctx->eflags);
2315
0
    if (IS_WORD_CONTEXT (context))
2316
0
      return trtable[ch + SBC_MAX];
2317
0
    else
2318
0
      return trtable[ch];
2319
0
  }
2320
2321
98
      if (!build_trtable (mctx->dfa, state))
2322
0
  {
2323
0
    *err = REG_ESPACE;
2324
0
    return NULL;
2325
0
  }
2326
2327
      /* Retry, we now have a transition table.  */
2328
98
    }
2329
98
}
2330
2331
/* Update the state_log if we need */
2332
static re_dfastate_t *
2333
merge_state_with_log (reg_errcode_t *err, re_match_context_t *mctx,
2334
          re_dfastate_t *next_state)
2335
0
{
2336
0
  const re_dfa_t *const dfa = mctx->dfa;
2337
0
  Idx cur_idx = re_string_cur_idx (&mctx->input);
2338
2339
0
  if (cur_idx > mctx->state_log_top)
2340
0
    {
2341
0
      mctx->state_log[cur_idx] = next_state;
2342
0
      mctx->state_log_top = cur_idx;
2343
0
    }
2344
0
  else if (mctx->state_log[cur_idx] == NULL)
2345
0
    {
2346
0
      mctx->state_log[cur_idx] = next_state;
2347
0
    }
2348
0
  else
2349
0
    {
2350
0
      re_dfastate_t *pstate;
2351
0
      unsigned int context;
2352
0
      re_node_set next_nodes, *log_nodes, *table_nodes = NULL;
2353
      /* If (state_log[cur_idx] != 0), it implies that cur_idx is
2354
   the destination of a multibyte char/collating element/
2355
   back reference.  Then the next state is the union set of
2356
   these destinations and the results of the transition table.  */
2357
0
      pstate = mctx->state_log[cur_idx];
2358
0
      log_nodes = pstate->entrance_nodes;
2359
0
      if (next_state != NULL && next_state->entrance_nodes != NULL)
2360
0
  {
2361
0
    table_nodes = next_state->entrance_nodes;
2362
0
    *err = re_node_set_init_union (&next_nodes, table_nodes,
2363
0
               log_nodes);
2364
0
    if (__glibc_unlikely (*err != REG_NOERROR))
2365
0
      return NULL;
2366
0
  }
2367
0
      else
2368
0
  next_nodes = *log_nodes;
2369
      /* Note: We already add the nodes of the initial state,
2370
   then we don't need to add them here.  */
2371
2372
0
      context = re_string_context_at (&mctx->input,
2373
0
              re_string_cur_idx (&mctx->input) - 1,
2374
0
              mctx->eflags);
2375
0
      next_state = mctx->state_log[cur_idx]
2376
0
  = re_acquire_state_context (err, dfa, &next_nodes, context);
2377
      /* We don't need to check errors here, since the return value of
2378
   this function is next_state and ERR is already set.  */
2379
2380
0
      if (table_nodes != NULL)
2381
0
  re_node_set_free (&next_nodes);
2382
0
    }
2383
2384
0
  if (__glibc_unlikely (dfa->nbackref) && next_state != NULL)
2385
0
    {
2386
      /* Check OP_OPEN_SUBEXP in the current state in case that we use them
2387
   later.  We must check them here, since the back references in the
2388
   next state might use them.  */
2389
0
      *err = check_subexp_matching_top (mctx, &next_state->nodes,
2390
0
          cur_idx);
2391
0
      if (__glibc_unlikely (*err != REG_NOERROR))
2392
0
  return NULL;
2393
2394
      /* If the next state has back references.  */
2395
0
      if (next_state->has_backref)
2396
0
  {
2397
0
    *err = transit_state_bkref (mctx, &next_state->nodes);
2398
0
    if (__glibc_unlikely (*err != REG_NOERROR))
2399
0
      return NULL;
2400
0
    next_state = mctx->state_log[cur_idx];
2401
0
  }
2402
0
    }
2403
2404
0
  return next_state;
2405
0
}
2406
2407
/* Skip bytes in the input that correspond to part of a
2408
   multi-byte match, then look in the log for a state
2409
   from which to restart matching.  */
2410
static re_dfastate_t *
2411
find_recover_state (reg_errcode_t *err, re_match_context_t *mctx)
2412
0
{
2413
0
  re_dfastate_t *cur_state;
2414
0
  do
2415
0
    {
2416
0
      Idx max = mctx->state_log_top;
2417
0
      Idx cur_str_idx = re_string_cur_idx (&mctx->input);
2418
2419
0
      do
2420
0
  {
2421
0
    if (++cur_str_idx > max)
2422
0
      return NULL;
2423
0
    re_string_skip_bytes (&mctx->input, 1);
2424
0
  }
2425
0
      while (mctx->state_log[cur_str_idx] == NULL);
2426
2427
0
      cur_state = merge_state_with_log (err, mctx, NULL);
2428
0
    }
2429
0
  while (*err == REG_NOERROR && cur_state == NULL);
2430
0
  return cur_state;
2431
0
}
2432
2433
/* Helper functions for transit_state.  */
2434
2435
/* From the node set CUR_NODES, pick up the nodes whose types are
2436
   OP_OPEN_SUBEXP and which have corresponding back references in the regular
2437
   expression. And register them to use them later for evaluating the
2438
   corresponding back references.  */
2439
2440
static reg_errcode_t
2441
check_subexp_matching_top (re_match_context_t *mctx, re_node_set *cur_nodes,
2442
         Idx str_idx)
2443
0
{
2444
0
  const re_dfa_t *const dfa = mctx->dfa;
2445
0
  Idx node_idx;
2446
0
  reg_errcode_t err;
2447
2448
  /* TODO: This isn't efficient.
2449
     Because there might be more than one nodes whose types are
2450
     OP_OPEN_SUBEXP and whose index is SUBEXP_IDX, we must check all
2451
     nodes.
2452
     E.g. RE: (a){2}  */
2453
0
  for (node_idx = 0; node_idx < cur_nodes->nelem; ++node_idx)
2454
0
    {
2455
0
      Idx node = cur_nodes->elems[node_idx];
2456
0
      if (dfa->nodes[node].type == OP_OPEN_SUBEXP
2457
0
    && dfa->nodes[node].opr.idx < BITSET_WORD_BITS
2458
0
    && (dfa->used_bkref_map
2459
0
        & ((bitset_word_t) 1 << dfa->nodes[node].opr.idx)))
2460
0
  {
2461
0
    err = match_ctx_add_subtop (mctx, node, str_idx);
2462
0
    if (__glibc_unlikely (err != REG_NOERROR))
2463
0
      return err;
2464
0
  }
2465
0
    }
2466
0
  return REG_NOERROR;
2467
0
}
2468
2469
#if 0
2470
/* Return the next state to which the current state STATE will transit by
2471
   accepting the current input byte.  Return NULL on failure.  */
2472
2473
static re_dfastate_t *
2474
transit_state_sb (reg_errcode_t *err, re_match_context_t *mctx,
2475
      re_dfastate_t *state)
2476
{
2477
  const re_dfa_t *const dfa = mctx->dfa;
2478
  re_node_set next_nodes;
2479
  re_dfastate_t *next_state;
2480
  Idx node_cnt, cur_str_idx = re_string_cur_idx (&mctx->input);
2481
  unsigned int context;
2482
2483
  *err = re_node_set_alloc (&next_nodes, state->nodes.nelem + 1);
2484
  if (__glibc_unlikely (*err != REG_NOERROR))
2485
    return NULL;
2486
  for (node_cnt = 0; node_cnt < state->nodes.nelem; ++node_cnt)
2487
    {
2488
      Idx cur_node = state->nodes.elems[node_cnt];
2489
      if (check_node_accept (mctx, dfa->nodes + cur_node, cur_str_idx))
2490
  {
2491
    *err = re_node_set_merge (&next_nodes,
2492
            dfa->eclosures + dfa->nexts[cur_node]);
2493
    if (__glibc_unlikely (*err != REG_NOERROR))
2494
      {
2495
        re_node_set_free (&next_nodes);
2496
        return NULL;
2497
      }
2498
  }
2499
    }
2500
  context = re_string_context_at (&mctx->input, cur_str_idx, mctx->eflags);
2501
  next_state = re_acquire_state_context (err, dfa, &next_nodes, context);
2502
  /* We don't need to check errors here, since the return value of
2503
     this function is next_state and ERR is already set.  */
2504
2505
  re_node_set_free (&next_nodes);
2506
  re_string_skip_bytes (&mctx->input, 1);
2507
  return next_state;
2508
}
2509
#endif
2510
2511
static reg_errcode_t
2512
transit_state_mb (re_match_context_t *mctx, re_dfastate_t *pstate)
2513
0
{
2514
0
  const re_dfa_t *const dfa = mctx->dfa;
2515
0
  reg_errcode_t err;
2516
0
  Idx i;
2517
2518
0
  for (i = 0; i < pstate->nodes.nelem; ++i)
2519
0
    {
2520
0
      re_node_set dest_nodes, *new_nodes;
2521
0
      Idx cur_node_idx = pstate->nodes.elems[i];
2522
0
      int naccepted;
2523
0
      Idx dest_idx;
2524
0
      unsigned int context;
2525
0
      re_dfastate_t *dest_state;
2526
2527
0
      if (!dfa->nodes[cur_node_idx].accept_mb)
2528
0
  continue;
2529
2530
0
      if (dfa->nodes[cur_node_idx].constraint)
2531
0
  {
2532
0
    context = re_string_context_at (&mctx->input,
2533
0
            re_string_cur_idx (&mctx->input),
2534
0
            mctx->eflags);
2535
0
    if (NOT_SATISFY_NEXT_CONSTRAINT (dfa->nodes[cur_node_idx].constraint,
2536
0
             context))
2537
0
      continue;
2538
0
  }
2539
2540
      /* How many bytes the node can accept?  */
2541
0
      naccepted = check_node_accept_bytes (dfa, cur_node_idx, &mctx->input,
2542
0
             re_string_cur_idx (&mctx->input));
2543
0
      if (naccepted == 0)
2544
0
  continue;
2545
2546
      /* The node can accepts 'naccepted' bytes.  */
2547
0
      dest_idx = re_string_cur_idx (&mctx->input) + naccepted;
2548
0
      mctx->max_mb_elem_len = ((mctx->max_mb_elem_len < naccepted) ? naccepted
2549
0
             : mctx->max_mb_elem_len);
2550
0
      err = clean_state_log_if_needed (mctx, dest_idx);
2551
0
      if (__glibc_unlikely (err != REG_NOERROR))
2552
0
  return err;
2553
0
      DEBUG_ASSERT (dfa->nexts[cur_node_idx] != -1);
2554
0
      new_nodes = dfa->eclosures + dfa->nexts[cur_node_idx];
2555
2556
0
      dest_state = mctx->state_log[dest_idx];
2557
0
      if (dest_state == NULL)
2558
0
  dest_nodes = *new_nodes;
2559
0
      else
2560
0
  {
2561
0
    err = re_node_set_init_union (&dest_nodes,
2562
0
          dest_state->entrance_nodes, new_nodes);
2563
0
    if (__glibc_unlikely (err != REG_NOERROR))
2564
0
      return err;
2565
0
  }
2566
0
      context = re_string_context_at (&mctx->input, dest_idx - 1,
2567
0
              mctx->eflags);
2568
0
      mctx->state_log[dest_idx]
2569
0
  = re_acquire_state_context (&err, dfa, &dest_nodes, context);
2570
0
      if (dest_state != NULL)
2571
0
  re_node_set_free (&dest_nodes);
2572
0
      if (__glibc_unlikely (mctx->state_log[dest_idx] == NULL
2573
0
          && err != REG_NOERROR))
2574
0
  return err;
2575
0
    }
2576
0
  return REG_NOERROR;
2577
0
}
2578
2579
static reg_errcode_t
2580
transit_state_bkref (re_match_context_t *mctx, const re_node_set *nodes)
2581
0
{
2582
0
  const re_dfa_t *const dfa = mctx->dfa;
2583
0
  reg_errcode_t err;
2584
0
  Idx i;
2585
0
  Idx cur_str_idx = re_string_cur_idx (&mctx->input);
2586
2587
0
  for (i = 0; i < nodes->nelem; ++i)
2588
0
    {
2589
0
      Idx dest_str_idx, prev_nelem, bkc_idx;
2590
0
      Idx node_idx = nodes->elems[i];
2591
0
      unsigned int context;
2592
0
      const re_token_t *node = dfa->nodes + node_idx;
2593
0
      re_node_set *new_dest_nodes;
2594
2595
      /* Check whether 'node' is a backreference or not.  */
2596
0
      if (node->type != OP_BACK_REF)
2597
0
  continue;
2598
2599
0
      if (node->constraint)
2600
0
  {
2601
0
    context = re_string_context_at (&mctx->input, cur_str_idx,
2602
0
            mctx->eflags);
2603
0
    if (NOT_SATISFY_NEXT_CONSTRAINT (node->constraint, context))
2604
0
      continue;
2605
0
  }
2606
2607
      /* 'node' is a backreference.
2608
   Check the substring which the substring matched.  */
2609
0
      bkc_idx = mctx->nbkref_ents;
2610
0
      err = get_subexp (mctx, node_idx, cur_str_idx);
2611
0
      if (__glibc_unlikely (err != REG_NOERROR))
2612
0
  goto free_return;
2613
2614
      /* And add the epsilon closures (which is 'new_dest_nodes') of
2615
   the backreference to appropriate state_log.  */
2616
0
      DEBUG_ASSERT (dfa->nexts[node_idx] != -1);
2617
0
      for (; bkc_idx < mctx->nbkref_ents; ++bkc_idx)
2618
0
  {
2619
0
    Idx subexp_len;
2620
0
    re_dfastate_t *dest_state;
2621
0
    struct re_backref_cache_entry *bkref_ent;
2622
0
    bkref_ent = mctx->bkref_ents + bkc_idx;
2623
0
    if (bkref_ent->node != node_idx || bkref_ent->str_idx != cur_str_idx)
2624
0
      continue;
2625
0
    subexp_len = bkref_ent->subexp_to - bkref_ent->subexp_from;
2626
0
    new_dest_nodes = (subexp_len == 0
2627
0
          ? dfa->eclosures + dfa->edests[node_idx].elems[0]
2628
0
          : dfa->eclosures + dfa->nexts[node_idx]);
2629
0
    dest_str_idx = (cur_str_idx + bkref_ent->subexp_to
2630
0
        - bkref_ent->subexp_from);
2631
0
    context = re_string_context_at (&mctx->input, dest_str_idx - 1,
2632
0
            mctx->eflags);
2633
0
    dest_state = mctx->state_log[dest_str_idx];
2634
0
    prev_nelem = ((mctx->state_log[cur_str_idx] == NULL) ? 0
2635
0
      : mctx->state_log[cur_str_idx]->nodes.nelem);
2636
    /* Add 'new_dest_node' to state_log.  */
2637
0
    if (dest_state == NULL)
2638
0
      {
2639
0
        mctx->state_log[dest_str_idx]
2640
0
    = re_acquire_state_context (&err, dfa, new_dest_nodes,
2641
0
              context);
2642
0
        if (__glibc_unlikely (mctx->state_log[dest_str_idx] == NULL
2643
0
            && err != REG_NOERROR))
2644
0
    goto free_return;
2645
0
      }
2646
0
    else
2647
0
      {
2648
0
        re_node_set dest_nodes;
2649
0
        err = re_node_set_init_union (&dest_nodes,
2650
0
              dest_state->entrance_nodes,
2651
0
              new_dest_nodes);
2652
0
        if (__glibc_unlikely (err != REG_NOERROR))
2653
0
    {
2654
0
      re_node_set_free (&dest_nodes);
2655
0
      goto free_return;
2656
0
    }
2657
0
        mctx->state_log[dest_str_idx]
2658
0
    = re_acquire_state_context (&err, dfa, &dest_nodes, context);
2659
0
        re_node_set_free (&dest_nodes);
2660
0
        if (__glibc_unlikely (mctx->state_log[dest_str_idx] == NULL
2661
0
            && err != REG_NOERROR))
2662
0
    goto free_return;
2663
0
      }
2664
    /* We need to check recursively if the backreference can epsilon
2665
       transit.  */
2666
0
    if (subexp_len == 0
2667
0
        && mctx->state_log[cur_str_idx]->nodes.nelem > prev_nelem)
2668
0
      {
2669
0
        err = check_subexp_matching_top (mctx, new_dest_nodes,
2670
0
                 cur_str_idx);
2671
0
        if (__glibc_unlikely (err != REG_NOERROR))
2672
0
    goto free_return;
2673
0
        err = transit_state_bkref (mctx, new_dest_nodes);
2674
0
        if (__glibc_unlikely (err != REG_NOERROR))
2675
0
    goto free_return;
2676
0
      }
2677
0
  }
2678
0
    }
2679
0
  err = REG_NOERROR;
2680
0
 free_return:
2681
0
  return err;
2682
0
}
2683
2684
/* Enumerate all the candidates which the backreference BKREF_NODE can match
2685
   at BKREF_STR_IDX, and register them by match_ctx_add_entry().
2686
   Note that we might collect inappropriate candidates here.
2687
   However, the cost of checking them strictly here is too high, then we
2688
   delay these checking for prune_impossible_nodes().  */
2689
2690
static reg_errcode_t
2691
__attribute_warn_unused_result__
2692
get_subexp (re_match_context_t *mctx, Idx bkref_node, Idx bkref_str_idx)
2693
0
{
2694
0
  const re_dfa_t *const dfa = mctx->dfa;
2695
0
  Idx subexp_num, sub_top_idx;
2696
0
  const char *buf = (const char *) re_string_get_buffer (&mctx->input);
2697
  /* Return if we have already checked BKREF_NODE at BKREF_STR_IDX.  */
2698
0
  Idx cache_idx = search_cur_bkref_entry (mctx, bkref_str_idx);
2699
0
  if (cache_idx != -1)
2700
0
    {
2701
0
      const struct re_backref_cache_entry *entry
2702
0
  = mctx->bkref_ents + cache_idx;
2703
0
      do
2704
0
  if (entry->node == bkref_node)
2705
0
    return REG_NOERROR; /* We already checked it.  */
2706
0
      while (entry++->more);
2707
0
    }
2708
2709
0
  subexp_num = dfa->nodes[bkref_node].opr.idx;
2710
2711
  /* For each sub expression  */
2712
0
  for (sub_top_idx = 0; sub_top_idx < mctx->nsub_tops; ++sub_top_idx)
2713
0
    {
2714
0
      reg_errcode_t err;
2715
0
      re_sub_match_top_t *sub_top = mctx->sub_tops[sub_top_idx];
2716
0
      re_sub_match_last_t *sub_last;
2717
0
      Idx sub_last_idx, sl_str, bkref_str_off;
2718
2719
0
      if (dfa->nodes[sub_top->node].opr.idx != subexp_num)
2720
0
  continue; /* It isn't related.  */
2721
2722
0
      sl_str = sub_top->str_idx;
2723
0
      bkref_str_off = bkref_str_idx;
2724
      /* At first, check the last node of sub expressions we already
2725
   evaluated.  */
2726
0
      for (sub_last_idx = 0; sub_last_idx < sub_top->nlasts; ++sub_last_idx)
2727
0
  {
2728
0
    regoff_t sl_str_diff;
2729
0
    sub_last = sub_top->lasts[sub_last_idx];
2730
0
    sl_str_diff = sub_last->str_idx - sl_str;
2731
    /* The matched string by the sub expression match with the substring
2732
       at the back reference?  */
2733
0
    if (sl_str_diff > 0)
2734
0
      {
2735
0
        if (__glibc_unlikely (bkref_str_off + sl_str_diff
2736
0
            > mctx->input.valid_len))
2737
0
    {
2738
      /* Not enough chars for a successful match.  */
2739
0
      if (bkref_str_off + sl_str_diff > mctx->input.len)
2740
0
        break;
2741
2742
0
      err = clean_state_log_if_needed (mctx,
2743
0
               bkref_str_off
2744
0
               + sl_str_diff);
2745
0
      if (__glibc_unlikely (err != REG_NOERROR))
2746
0
        return err;
2747
0
      buf = (const char *) re_string_get_buffer (&mctx->input);
2748
0
    }
2749
0
        if (memcmp (buf + bkref_str_off, buf + sl_str, sl_str_diff) != 0)
2750
    /* We don't need to search this sub expression any more.  */
2751
0
    break;
2752
0
      }
2753
0
    bkref_str_off += sl_str_diff;
2754
0
    sl_str += sl_str_diff;
2755
0
    err = get_subexp_sub (mctx, sub_top, sub_last, bkref_node,
2756
0
        bkref_str_idx);
2757
2758
    /* Reload buf, since the preceding call might have reallocated
2759
       the buffer.  */
2760
0
    buf = (const char *) re_string_get_buffer (&mctx->input);
2761
2762
0
    if (err == REG_NOMATCH)
2763
0
      continue;
2764
0
    if (__glibc_unlikely (err != REG_NOERROR))
2765
0
      return err;
2766
0
  }
2767
2768
0
      if (sub_last_idx < sub_top->nlasts)
2769
0
  continue;
2770
0
      if (sub_last_idx > 0)
2771
0
  ++sl_str;
2772
      /* Then, search for the other last nodes of the sub expression.  */
2773
0
      for (; sl_str <= bkref_str_idx; ++sl_str)
2774
0
  {
2775
0
    Idx cls_node;
2776
0
    regoff_t sl_str_off;
2777
0
    const re_node_set *nodes;
2778
0
    sl_str_off = sl_str - sub_top->str_idx;
2779
    /* The matched string by the sub expression match with the substring
2780
       at the back reference?  */
2781
0
    if (sl_str_off > 0)
2782
0
      {
2783
0
        if (__glibc_unlikely (bkref_str_off >= mctx->input.valid_len))
2784
0
    {
2785
      /* If we are at the end of the input, we cannot match.  */
2786
0
      if (bkref_str_off >= mctx->input.len)
2787
0
        break;
2788
2789
0
      err = extend_buffers (mctx, bkref_str_off + 1);
2790
0
      if (__glibc_unlikely (err != REG_NOERROR))
2791
0
        return err;
2792
2793
0
      buf = (const char *) re_string_get_buffer (&mctx->input);
2794
0
    }
2795
0
        if (buf [bkref_str_off++] != buf[sl_str - 1])
2796
0
    break; /* We don't need to search this sub expression
2797
        any more.  */
2798
0
      }
2799
0
    if (mctx->state_log[sl_str] == NULL)
2800
0
      continue;
2801
    /* Does this state have a ')' of the sub expression?  */
2802
0
    nodes = &mctx->state_log[sl_str]->nodes;
2803
0
    cls_node = find_subexp_node (dfa, nodes, subexp_num,
2804
0
               OP_CLOSE_SUBEXP);
2805
0
    if (cls_node == -1)
2806
0
      continue; /* No.  */
2807
0
    if (sub_top->path == NULL)
2808
0
      {
2809
0
        sub_top->path = calloc (sl_str - sub_top->str_idx + 1,
2810
0
                                      sizeof (state_array_t));
2811
0
        if (sub_top->path == NULL)
2812
0
    return REG_ESPACE;
2813
0
      }
2814
    /* Can the OP_OPEN_SUBEXP node arrive the OP_CLOSE_SUBEXP node
2815
       in the current context?  */
2816
0
    err = check_arrival (mctx, sub_top->path, sub_top->node,
2817
0
             sub_top->str_idx, cls_node, sl_str,
2818
0
             OP_CLOSE_SUBEXP);
2819
0
    if (err == REG_NOMATCH)
2820
0
        continue;
2821
0
    if (__glibc_unlikely (err != REG_NOERROR))
2822
0
        return err;
2823
0
    sub_last = match_ctx_add_sublast (sub_top, cls_node, sl_str);
2824
0
    if (__glibc_unlikely (sub_last == NULL))
2825
0
      return REG_ESPACE;
2826
0
    err = get_subexp_sub (mctx, sub_top, sub_last, bkref_node,
2827
0
        bkref_str_idx);
2828
0
    buf = (const char *) re_string_get_buffer (&mctx->input);
2829
0
    if (err == REG_NOMATCH)
2830
0
      continue;
2831
0
    if (__glibc_unlikely (err != REG_NOERROR))
2832
0
      return err;
2833
0
  }
2834
0
    }
2835
0
  return REG_NOERROR;
2836
0
}
2837
2838
/* Helper functions for get_subexp().  */
2839
2840
/* Check SUB_LAST can arrive to the back reference BKREF_NODE at BKREF_STR.
2841
   If it can arrive, register the sub expression expressed with SUB_TOP
2842
   and SUB_LAST.  */
2843
2844
static reg_errcode_t
2845
get_subexp_sub (re_match_context_t *mctx, const re_sub_match_top_t *sub_top,
2846
    re_sub_match_last_t *sub_last, Idx bkref_node, Idx bkref_str)
2847
0
{
2848
0
  reg_errcode_t err;
2849
0
  Idx to_idx;
2850
  /* Can the subexpression arrive the back reference?  */
2851
0
  err = check_arrival (mctx, &sub_last->path, sub_last->node,
2852
0
           sub_last->str_idx, bkref_node, bkref_str,
2853
0
           OP_OPEN_SUBEXP);
2854
0
  if (err != REG_NOERROR)
2855
0
    return err;
2856
0
  err = match_ctx_add_entry (mctx, bkref_node, bkref_str, sub_top->str_idx,
2857
0
           sub_last->str_idx);
2858
0
  if (__glibc_unlikely (err != REG_NOERROR))
2859
0
    return err;
2860
0
  to_idx = bkref_str + sub_last->str_idx - sub_top->str_idx;
2861
0
  return clean_state_log_if_needed (mctx, to_idx);
2862
0
}
2863
2864
/* Find the first node which is '(' or ')' and whose index is SUBEXP_IDX.
2865
   Search '(' if FL_OPEN, or search ')' otherwise.
2866
   TODO: This function isn't efficient...
2867
   Because there might be more than one nodes whose types are
2868
   OP_OPEN_SUBEXP and whose index is SUBEXP_IDX, we must check all
2869
   nodes.
2870
   E.g. RE: (a){2}  */
2871
2872
static Idx
2873
find_subexp_node (const re_dfa_t *dfa, const re_node_set *nodes,
2874
      Idx subexp_idx, int type)
2875
0
{
2876
0
  Idx cls_idx;
2877
0
  for (cls_idx = 0; cls_idx < nodes->nelem; ++cls_idx)
2878
0
    {
2879
0
      Idx cls_node = nodes->elems[cls_idx];
2880
0
      const re_token_t *node = dfa->nodes + cls_node;
2881
0
      if (node->type == type
2882
0
    && node->opr.idx == subexp_idx)
2883
0
  return cls_node;
2884
0
    }
2885
0
  return -1;
2886
0
}
2887
2888
/* Check whether the node TOP_NODE at TOP_STR can arrive to the node
2889
   LAST_NODE at LAST_STR.  We record the path onto PATH since it will be
2890
   heavily reused.
2891
   Return REG_NOERROR if it can arrive, REG_NOMATCH if it cannot,
2892
   REG_ESPACE if memory is exhausted.  */
2893
2894
static reg_errcode_t
2895
__attribute_warn_unused_result__
2896
check_arrival (re_match_context_t *mctx, state_array_t *path, Idx top_node,
2897
         Idx top_str, Idx last_node, Idx last_str, int type)
2898
0
{
2899
0
  const re_dfa_t *const dfa = mctx->dfa;
2900
0
  reg_errcode_t err = REG_NOERROR;
2901
0
  Idx subexp_num, backup_cur_idx, str_idx, null_cnt;
2902
0
  re_dfastate_t *cur_state = NULL;
2903
0
  re_node_set *cur_nodes, next_nodes;
2904
0
  re_dfastate_t **backup_state_log;
2905
0
  unsigned int context;
2906
2907
0
  subexp_num = dfa->nodes[top_node].opr.idx;
2908
  /* Extend the buffer if we need.  */
2909
0
  if (__glibc_unlikely (path->alloc < last_str + mctx->max_mb_elem_len + 1))
2910
0
    {
2911
0
      re_dfastate_t **new_array;
2912
0
      Idx old_alloc = path->alloc;
2913
0
      Idx incr_alloc = last_str + mctx->max_mb_elem_len + 1;
2914
0
      Idx new_alloc;
2915
0
      if (__glibc_unlikely (IDX_MAX - old_alloc < incr_alloc))
2916
0
  return REG_ESPACE;
2917
0
      new_alloc = old_alloc + incr_alloc;
2918
0
      if (__glibc_unlikely (SIZE_MAX / sizeof (re_dfastate_t *) < new_alloc))
2919
0
  return REG_ESPACE;
2920
0
      new_array = re_realloc (path->array, re_dfastate_t *, new_alloc);
2921
0
      if (__glibc_unlikely (new_array == NULL))
2922
0
  return REG_ESPACE;
2923
0
      path->array = new_array;
2924
0
      path->alloc = new_alloc;
2925
0
      memset (new_array + old_alloc, '\0',
2926
0
        sizeof (re_dfastate_t *) * (path->alloc - old_alloc));
2927
0
    }
2928
2929
0
  str_idx = path->next_idx ? path->next_idx : top_str;
2930
2931
  /* Temporary modify MCTX.  */
2932
0
  backup_state_log = mctx->state_log;
2933
0
  backup_cur_idx = mctx->input.cur_idx;
2934
0
  mctx->state_log = path->array;
2935
0
  mctx->input.cur_idx = str_idx;
2936
2937
  /* Setup initial node set.  */
2938
0
  context = re_string_context_at (&mctx->input, str_idx - 1, mctx->eflags);
2939
0
  if (str_idx == top_str)
2940
0
    {
2941
0
      err = re_node_set_init_1 (&next_nodes, top_node);
2942
0
      if (__glibc_unlikely (err != REG_NOERROR))
2943
0
  return err;
2944
0
      err = check_arrival_expand_ecl (dfa, &next_nodes, subexp_num, type);
2945
0
      if (__glibc_unlikely (err != REG_NOERROR))
2946
0
  {
2947
0
    re_node_set_free (&next_nodes);
2948
0
    return err;
2949
0
  }
2950
0
    }
2951
0
  else
2952
0
    {
2953
0
      cur_state = mctx->state_log[str_idx];
2954
0
      if (cur_state && cur_state->has_backref)
2955
0
  {
2956
0
    err = re_node_set_init_copy (&next_nodes, &cur_state->nodes);
2957
0
    if (__glibc_unlikely (err != REG_NOERROR))
2958
0
      return err;
2959
0
  }
2960
0
      else
2961
0
  re_node_set_init_empty (&next_nodes);
2962
0
    }
2963
0
  if (str_idx == top_str || (cur_state && cur_state->has_backref))
2964
0
    {
2965
0
      if (next_nodes.nelem)
2966
0
  {
2967
0
    err = expand_bkref_cache (mctx, &next_nodes, str_idx,
2968
0
            subexp_num, type);
2969
0
    if (__glibc_unlikely (err != REG_NOERROR))
2970
0
      {
2971
0
        re_node_set_free (&next_nodes);
2972
0
        return err;
2973
0
      }
2974
0
  }
2975
0
      cur_state = re_acquire_state_context (&err, dfa, &next_nodes, context);
2976
0
      if (__glibc_unlikely (cur_state == NULL && err != REG_NOERROR))
2977
0
  {
2978
0
    re_node_set_free (&next_nodes);
2979
0
    return err;
2980
0
  }
2981
0
      mctx->state_log[str_idx] = cur_state;
2982
0
    }
2983
2984
0
  for (null_cnt = 0; str_idx < last_str && null_cnt <= mctx->max_mb_elem_len;)
2985
0
    {
2986
0
      re_node_set_empty (&next_nodes);
2987
0
      if (mctx->state_log[str_idx + 1])
2988
0
  {
2989
0
    err = re_node_set_merge (&next_nodes,
2990
0
           &mctx->state_log[str_idx + 1]->nodes);
2991
0
    if (__glibc_unlikely (err != REG_NOERROR))
2992
0
      {
2993
0
        re_node_set_free (&next_nodes);
2994
0
        return err;
2995
0
      }
2996
0
  }
2997
0
      if (cur_state)
2998
0
  {
2999
0
    err = check_arrival_add_next_nodes (mctx, str_idx,
3000
0
                &cur_state->non_eps_nodes,
3001
0
                &next_nodes);
3002
0
    if (__glibc_unlikely (err != REG_NOERROR))
3003
0
      {
3004
0
        re_node_set_free (&next_nodes);
3005
0
        return err;
3006
0
      }
3007
0
  }
3008
0
      ++str_idx;
3009
0
      if (next_nodes.nelem)
3010
0
  {
3011
0
    err = check_arrival_expand_ecl (dfa, &next_nodes, subexp_num, type);
3012
0
    if (__glibc_unlikely (err != REG_NOERROR))
3013
0
      {
3014
0
        re_node_set_free (&next_nodes);
3015
0
        return err;
3016
0
      }
3017
0
    err = expand_bkref_cache (mctx, &next_nodes, str_idx,
3018
0
            subexp_num, type);
3019
0
    if (__glibc_unlikely (err != REG_NOERROR))
3020
0
      {
3021
0
        re_node_set_free (&next_nodes);
3022
0
        return err;
3023
0
      }
3024
0
  }
3025
0
      context = re_string_context_at (&mctx->input, str_idx - 1, mctx->eflags);
3026
0
      cur_state = re_acquire_state_context (&err, dfa, &next_nodes, context);
3027
0
      if (__glibc_unlikely (cur_state == NULL && err != REG_NOERROR))
3028
0
  {
3029
0
    re_node_set_free (&next_nodes);
3030
0
    return err;
3031
0
  }
3032
0
      mctx->state_log[str_idx] = cur_state;
3033
0
      null_cnt = cur_state == NULL ? null_cnt + 1 : 0;
3034
0
    }
3035
0
  re_node_set_free (&next_nodes);
3036
0
  cur_nodes = (mctx->state_log[last_str] == NULL ? NULL
3037
0
         : &mctx->state_log[last_str]->nodes);
3038
0
  path->next_idx = str_idx;
3039
3040
  /* Fix MCTX.  */
3041
0
  mctx->state_log = backup_state_log;
3042
0
  mctx->input.cur_idx = backup_cur_idx;
3043
3044
  /* Then check the current node set has the node LAST_NODE.  */
3045
0
  if (cur_nodes != NULL && re_node_set_contains (cur_nodes, last_node))
3046
0
    return REG_NOERROR;
3047
3048
0
  return REG_NOMATCH;
3049
0
}
3050
3051
/* Helper functions for check_arrival.  */
3052
3053
/* Calculate the destination nodes of CUR_NODES at STR_IDX, and append them
3054
   to NEXT_NODES.
3055
   TODO: This function is similar to the functions transit_state*(),
3056
   however this function has many additional works.
3057
   Can't we unify them?  */
3058
3059
static reg_errcode_t
3060
__attribute_warn_unused_result__
3061
check_arrival_add_next_nodes (re_match_context_t *mctx, Idx str_idx,
3062
            re_node_set *cur_nodes, re_node_set *next_nodes)
3063
0
{
3064
0
  const re_dfa_t *const dfa = mctx->dfa;
3065
0
  bool ok;
3066
0
  Idx cur_idx;
3067
0
  reg_errcode_t err = REG_NOERROR;
3068
0
  re_node_set union_set;
3069
0
  re_node_set_init_empty (&union_set);
3070
0
  for (cur_idx = 0; cur_idx < cur_nodes->nelem; ++cur_idx)
3071
0
    {
3072
0
      int naccepted = 0;
3073
0
      Idx cur_node = cur_nodes->elems[cur_idx];
3074
0
      DEBUG_ASSERT (!IS_EPSILON_NODE (dfa->nodes[cur_node].type));
3075
3076
      /* If the node may accept "multi byte".  */
3077
0
      if (dfa->nodes[cur_node].accept_mb)
3078
0
  {
3079
0
    naccepted = check_node_accept_bytes (dfa, cur_node, &mctx->input,
3080
0
                 str_idx);
3081
0
    if (naccepted > 1)
3082
0
      {
3083
0
        re_dfastate_t *dest_state;
3084
0
        Idx next_node = dfa->nexts[cur_node];
3085
0
        Idx next_idx = str_idx + naccepted;
3086
0
        dest_state = mctx->state_log[next_idx];
3087
0
        re_node_set_empty (&union_set);
3088
0
        if (dest_state)
3089
0
    {
3090
0
      err = re_node_set_merge (&union_set, &dest_state->nodes);
3091
0
      if (__glibc_unlikely (err != REG_NOERROR))
3092
0
        {
3093
0
          re_node_set_free (&union_set);
3094
0
          return err;
3095
0
        }
3096
0
    }
3097
0
        ok = re_node_set_insert (&union_set, next_node);
3098
0
        if (__glibc_unlikely (! ok))
3099
0
    {
3100
0
      re_node_set_free (&union_set);
3101
0
      return REG_ESPACE;
3102
0
    }
3103
0
        mctx->state_log[next_idx] = re_acquire_state (&err, dfa,
3104
0
                  &union_set);
3105
0
        if (__glibc_unlikely (mctx->state_log[next_idx] == NULL
3106
0
            && err != REG_NOERROR))
3107
0
    {
3108
0
      re_node_set_free (&union_set);
3109
0
      return err;
3110
0
    }
3111
0
      }
3112
0
  }
3113
3114
0
      if (naccepted
3115
0
    || check_node_accept (mctx, dfa->nodes + cur_node, str_idx))
3116
0
  {
3117
0
    ok = re_node_set_insert (next_nodes, dfa->nexts[cur_node]);
3118
0
    if (__glibc_unlikely (! ok))
3119
0
      {
3120
0
        re_node_set_free (&union_set);
3121
0
        return REG_ESPACE;
3122
0
      }
3123
0
  }
3124
0
    }
3125
0
  re_node_set_free (&union_set);
3126
0
  return REG_NOERROR;
3127
0
}
3128
3129
/* For all the nodes in CUR_NODES, add the epsilon closures of them to
3130
   CUR_NODES, however exclude the nodes which are:
3131
    - inside the sub expression whose number is EX_SUBEXP, if FL_OPEN.
3132
    - out of the sub expression whose number is EX_SUBEXP, if !FL_OPEN.
3133
*/
3134
3135
static reg_errcode_t
3136
check_arrival_expand_ecl (const re_dfa_t *dfa, re_node_set *cur_nodes,
3137
        Idx ex_subexp, int type)
3138
0
{
3139
0
  reg_errcode_t err;
3140
0
  Idx idx, outside_node;
3141
0
  re_node_set new_nodes;
3142
0
  DEBUG_ASSERT (cur_nodes->nelem);
3143
0
  err = re_node_set_alloc (&new_nodes, cur_nodes->nelem);
3144
0
  if (__glibc_unlikely (err != REG_NOERROR))
3145
0
    return err;
3146
  /* Create a new node set NEW_NODES with the nodes which are epsilon
3147
     closures of the node in CUR_NODES.  */
3148
3149
0
  for (idx = 0; idx < cur_nodes->nelem; ++idx)
3150
0
    {
3151
0
      Idx cur_node = cur_nodes->elems[idx];
3152
0
      const re_node_set *eclosure = dfa->eclosures + cur_node;
3153
0
      outside_node = find_subexp_node (dfa, eclosure, ex_subexp, type);
3154
0
      if (outside_node == -1)
3155
0
  {
3156
    /* There are no problematic nodes, just merge them.  */
3157
0
    err = re_node_set_merge (&new_nodes, eclosure);
3158
0
    if (__glibc_unlikely (err != REG_NOERROR))
3159
0
      {
3160
0
        re_node_set_free (&new_nodes);
3161
0
        return err;
3162
0
      }
3163
0
  }
3164
0
      else
3165
0
  {
3166
    /* There are problematic nodes, re-calculate incrementally.  */
3167
0
    err = check_arrival_expand_ecl_sub (dfa, &new_nodes, cur_node,
3168
0
                ex_subexp, type);
3169
0
    if (__glibc_unlikely (err != REG_NOERROR))
3170
0
      {
3171
0
        re_node_set_free (&new_nodes);
3172
0
        return err;
3173
0
      }
3174
0
  }
3175
0
    }
3176
0
  re_node_set_free (cur_nodes);
3177
0
  *cur_nodes = new_nodes;
3178
0
  return REG_NOERROR;
3179
0
}
3180
3181
/* Helper function for check_arrival_expand_ecl.
3182
   Check incrementally the epsilon closure of TARGET, and if it isn't
3183
   problematic append it to DST_NODES.  */
3184
3185
static reg_errcode_t
3186
__attribute_warn_unused_result__
3187
check_arrival_expand_ecl_sub (const re_dfa_t *dfa, re_node_set *dst_nodes,
3188
            Idx target, Idx ex_subexp, int type)
3189
0
{
3190
0
  Idx cur_node;
3191
0
  for (cur_node = target; !re_node_set_contains (dst_nodes, cur_node);)
3192
0
    {
3193
0
      bool ok;
3194
3195
0
      if (dfa->nodes[cur_node].type == type
3196
0
    && dfa->nodes[cur_node].opr.idx == ex_subexp)
3197
0
  {
3198
0
    if (type == OP_CLOSE_SUBEXP)
3199
0
      {
3200
0
        ok = re_node_set_insert (dst_nodes, cur_node);
3201
0
        if (__glibc_unlikely (! ok))
3202
0
    return REG_ESPACE;
3203
0
      }
3204
0
    break;
3205
0
  }
3206
0
      ok = re_node_set_insert (dst_nodes, cur_node);
3207
0
      if (__glibc_unlikely (! ok))
3208
0
  return REG_ESPACE;
3209
0
      if (dfa->edests[cur_node].nelem == 0)
3210
0
  break;
3211
0
      if (dfa->edests[cur_node].nelem == 2)
3212
0
  {
3213
0
    reg_errcode_t err;
3214
0
    err = check_arrival_expand_ecl_sub (dfa, dst_nodes,
3215
0
                dfa->edests[cur_node].elems[1],
3216
0
                ex_subexp, type);
3217
0
    if (__glibc_unlikely (err != REG_NOERROR))
3218
0
      return err;
3219
0
  }
3220
0
      cur_node = dfa->edests[cur_node].elems[0];
3221
0
    }
3222
0
  return REG_NOERROR;
3223
0
}
3224
3225
3226
/* For all the back references in the current state, calculate the
3227
   destination of the back references by the appropriate entry
3228
   in MCTX->BKREF_ENTS.  */
3229
3230
static reg_errcode_t
3231
__attribute_warn_unused_result__
3232
expand_bkref_cache (re_match_context_t *mctx, re_node_set *cur_nodes,
3233
        Idx cur_str, Idx subexp_num, int type)
3234
0
{
3235
0
  const re_dfa_t *const dfa = mctx->dfa;
3236
0
  reg_errcode_t err;
3237
0
  Idx cache_idx_start = search_cur_bkref_entry (mctx, cur_str);
3238
0
  struct re_backref_cache_entry *ent;
3239
3240
0
  if (cache_idx_start == -1)
3241
0
    return REG_NOERROR;
3242
3243
0
 restart:
3244
0
  ent = mctx->bkref_ents + cache_idx_start;
3245
0
  do
3246
0
    {
3247
0
      Idx to_idx, next_node;
3248
3249
      /* Is this entry ENT is appropriate?  */
3250
0
      if (!re_node_set_contains (cur_nodes, ent->node))
3251
0
  continue; /* No.  */
3252
3253
0
      to_idx = cur_str + ent->subexp_to - ent->subexp_from;
3254
      /* Calculate the destination of the back reference, and append it
3255
   to MCTX->STATE_LOG.  */
3256
0
      if (to_idx == cur_str)
3257
0
  {
3258
    /* The backreference did epsilon transit, we must re-check all the
3259
       node in the current state.  */
3260
0
    re_node_set new_dests;
3261
0
    reg_errcode_t err2, err3;
3262
0
    next_node = dfa->edests[ent->node].elems[0];
3263
0
    if (re_node_set_contains (cur_nodes, next_node))
3264
0
      continue;
3265
0
    err = re_node_set_init_1 (&new_dests, next_node);
3266
0
    err2 = check_arrival_expand_ecl (dfa, &new_dests, subexp_num, type);
3267
0
    err3 = re_node_set_merge (cur_nodes, &new_dests);
3268
0
    re_node_set_free (&new_dests);
3269
0
    if (__glibc_unlikely (err != REG_NOERROR || err2 != REG_NOERROR
3270
0
        || err3 != REG_NOERROR))
3271
0
      {
3272
0
        err = (err != REG_NOERROR ? err
3273
0
         : (err2 != REG_NOERROR ? err2 : err3));
3274
0
        return err;
3275
0
      }
3276
    /* TODO: It is still inefficient...  */
3277
0
    goto restart;
3278
0
  }
3279
0
      else
3280
0
  {
3281
0
    re_node_set union_set;
3282
0
    next_node = dfa->nexts[ent->node];
3283
0
    if (mctx->state_log[to_idx])
3284
0
      {
3285
0
        bool ok;
3286
0
        if (re_node_set_contains (&mctx->state_log[to_idx]->nodes,
3287
0
          next_node))
3288
0
    continue;
3289
0
        err = re_node_set_init_copy (&union_set,
3290
0
             &mctx->state_log[to_idx]->nodes);
3291
0
        ok = re_node_set_insert (&union_set, next_node);
3292
0
        if (__glibc_unlikely (err != REG_NOERROR || ! ok))
3293
0
    {
3294
0
      re_node_set_free (&union_set);
3295
0
      err = err != REG_NOERROR ? err : REG_ESPACE;
3296
0
      return err;
3297
0
    }
3298
0
      }
3299
0
    else
3300
0
      {
3301
0
        err = re_node_set_init_1 (&union_set, next_node);
3302
0
        if (__glibc_unlikely (err != REG_NOERROR))
3303
0
    return err;
3304
0
      }
3305
0
    mctx->state_log[to_idx] = re_acquire_state (&err, dfa, &union_set);
3306
0
    re_node_set_free (&union_set);
3307
0
    if (__glibc_unlikely (mctx->state_log[to_idx] == NULL
3308
0
        && err != REG_NOERROR))
3309
0
      return err;
3310
0
  }
3311
0
    }
3312
0
  while (ent++->more);
3313
0
  return REG_NOERROR;
3314
0
}
3315
3316
/* Build transition table for the state.
3317
   Return true if successful.  */
3318
3319
static bool __attribute_noinline__
3320
build_trtable (const re_dfa_t *dfa, re_dfastate_t *state)
3321
98
{
3322
98
  reg_errcode_t err;
3323
98
  Idx i, j;
3324
98
  int ch;
3325
98
  bool need_word_trtable = false;
3326
98
  bitset_word_t elem, mask;
3327
98
  Idx ndests; /* Number of the destination states from 'state'.  */
3328
98
  re_dfastate_t **trtable;
3329
98
  re_dfastate_t *dest_states[SBC_MAX];
3330
98
  re_dfastate_t *dest_states_word[SBC_MAX];
3331
98
  re_dfastate_t *dest_states_nl[SBC_MAX];
3332
98
  re_node_set follows;
3333
98
  bitset_t acceptable;
3334
3335
  /* We build DFA states which corresponds to the destination nodes
3336
     from 'state'.  'dests_node[i]' represents the nodes which i-th
3337
     destination state contains, and 'dests_ch[i]' represents the
3338
     characters which i-th destination state accepts.  */
3339
98
  re_node_set dests_node[SBC_MAX];
3340
98
  bitset_t dests_ch[SBC_MAX];
3341
3342
  /* Initialize transition table.  */
3343
98
  state->word_trtable = state->trtable = NULL;
3344
3345
  /* At first, group all nodes belonging to 'state' into several
3346
     destinations.  */
3347
98
  ndests = group_nodes_into_DFAstates (dfa, state, dests_node, dests_ch);
3348
98
  if (__glibc_unlikely (ndests <= 0))
3349
1
    {
3350
      /* Return false in case of an error, true otherwise.  */
3351
1
      if (ndests == 0)
3352
1
  {
3353
1
    state->trtable = (re_dfastate_t **)
3354
1
      calloc (SBC_MAX, sizeof (re_dfastate_t *));
3355
1
          if (__glibc_unlikely (state->trtable == NULL))
3356
0
            return false;
3357
1
    return true;
3358
1
  }
3359
0
      return false;
3360
1
    }
3361
3362
97
  err = re_node_set_alloc (&follows, ndests + 1);
3363
97
  if (__glibc_unlikely (err != REG_NOERROR))
3364
0
    {
3365
0
    out_free:
3366
0
      re_node_set_free (&follows);
3367
0
      for (i = 0; i < ndests; ++i)
3368
0
  re_node_set_free (dests_node + i);
3369
0
      return false;
3370
0
    }
3371
3372
97
  bitset_empty (acceptable);
3373
3374
  /* Then build the states for all destinations.  */
3375
202
  for (i = 0; i < ndests; ++i)
3376
105
    {
3377
105
      Idx next_node;
3378
105
      re_node_set_empty (&follows);
3379
      /* Merge the follows of this destination states.  */
3380
214
      for (j = 0; j < dests_node[i].nelem; ++j)
3381
109
  {
3382
109
    next_node = dfa->nexts[dests_node[i].elems[j]];
3383
109
    if (next_node != -1)
3384
109
      {
3385
109
        err = re_node_set_merge (&follows, dfa->eclosures + next_node);
3386
109
        if (__glibc_unlikely (err != REG_NOERROR))
3387
0
    goto out_free;
3388
109
      }
3389
109
  }
3390
105
      dest_states[i] = re_acquire_state_context (&err, dfa, &follows, 0);
3391
105
      if (__glibc_unlikely (dest_states[i] == NULL && err != REG_NOERROR))
3392
0
  goto out_free;
3393
      /* If the new state has context constraint,
3394
   build appropriate states for these contexts.  */
3395
105
      if (dest_states[i]->has_constraint)
3396
0
  {
3397
0
    dest_states_word[i] = re_acquire_state_context (&err, dfa, &follows,
3398
0
                CONTEXT_WORD);
3399
0
    if (__glibc_unlikely (dest_states_word[i] == NULL
3400
0
        && err != REG_NOERROR))
3401
0
      goto out_free;
3402
3403
0
    if (dest_states[i] != dest_states_word[i] && dfa->mb_cur_max > 1)
3404
0
      need_word_trtable = true;
3405
3406
0
    dest_states_nl[i] = re_acquire_state_context (&err, dfa, &follows,
3407
0
              CONTEXT_NEWLINE);
3408
0
    if (__glibc_unlikely (dest_states_nl[i] == NULL && err != REG_NOERROR))
3409
0
      goto out_free;
3410
0
  }
3411
105
      else
3412
105
  {
3413
105
    dest_states_word[i] = dest_states[i];
3414
105
    dest_states_nl[i] = dest_states[i];
3415
105
  }
3416
105
      bitset_merge (acceptable, dests_ch[i]);
3417
105
    }
3418
3419
97
  if (!__glibc_unlikely (need_word_trtable))
3420
97
    {
3421
      /* We don't care about whether the following character is a word
3422
   character, or we are in a single-byte character set so we can
3423
   discern by looking at the character code: allocate a
3424
   256-entry transition table.  */
3425
97
      trtable = state->trtable =
3426
97
  (re_dfastate_t **) calloc (SBC_MAX, sizeof (re_dfastate_t *));
3427
97
      if (__glibc_unlikely (trtable == NULL))
3428
0
  goto out_free;
3429
3430
      /* For all characters ch...:  */
3431
485
      for (i = 0; i < BITSET_WORDS; ++i)
3432
388
  for (ch = i * BITSET_WORD_BITS, elem = acceptable[i], mask = 1;
3433
4.89k
       elem;
3434
4.51k
       mask <<= 1, elem >>= 1, ++ch)
3435
4.51k
    if (__glibc_unlikely (elem & 1))
3436
352
      {
3437
        /* There must be exactly one destination which accepts
3438
     character ch.  See group_nodes_into_DFAstates.  */
3439
364
        for (j = 0; (dests_ch[j][i] & mask) == 0; ++j)
3440
12
    ;
3441
3442
        /* j-th destination accepts the word character ch.  */
3443
352
        if (dfa->word_char[i] & mask)
3444
0
    trtable[ch] = dest_states_word[j];
3445
352
        else
3446
352
    trtable[ch] = dest_states[j];
3447
352
      }
3448
97
    }
3449
0
  else
3450
0
    {
3451
      /* We care about whether the following character is a word
3452
   character, and we are in a multi-byte character set: discern
3453
   by looking at the character code: build two 256-entry
3454
   transition tables, one starting at trtable[0] and one
3455
   starting at trtable[SBC_MAX].  */
3456
0
      trtable = state->word_trtable =
3457
0
  (re_dfastate_t **) calloc (2 * SBC_MAX, sizeof (re_dfastate_t *));
3458
0
      if (__glibc_unlikely (trtable == NULL))
3459
0
  goto out_free;
3460
3461
      /* For all characters ch...:  */
3462
0
      for (i = 0; i < BITSET_WORDS; ++i)
3463
0
  for (ch = i * BITSET_WORD_BITS, elem = acceptable[i], mask = 1;
3464
0
       elem;
3465
0
       mask <<= 1, elem >>= 1, ++ch)
3466
0
    if (__glibc_unlikely (elem & 1))
3467
0
      {
3468
        /* There must be exactly one destination which accepts
3469
     character ch.  See group_nodes_into_DFAstates.  */
3470
0
        for (j = 0; (dests_ch[j][i] & mask) == 0; ++j)
3471
0
    ;
3472
3473
        /* j-th destination accepts the word character ch.  */
3474
0
        trtable[ch] = dest_states[j];
3475
0
        trtable[ch + SBC_MAX] = dest_states_word[j];
3476
0
      }
3477
0
    }
3478
3479
  /* new line */
3480
97
  if (bitset_contain (acceptable, NEWLINE_CHAR))
3481
1
    {
3482
      /* The current state accepts newline character.  */
3483
1
      for (j = 0; j < ndests; ++j)
3484
1
  if (bitset_contain (dests_ch[j], NEWLINE_CHAR))
3485
1
    {
3486
      /* k-th destination accepts newline character.  */
3487
1
      trtable[NEWLINE_CHAR] = dest_states_nl[j];
3488
1
      if (need_word_trtable)
3489
0
        trtable[NEWLINE_CHAR + SBC_MAX] = dest_states_nl[j];
3490
      /* There must be only one destination which accepts
3491
         newline.  See group_nodes_into_DFAstates.  */
3492
1
      break;
3493
1
    }
3494
1
    }
3495
3496
97
  re_node_set_free (&follows);
3497
202
  for (i = 0; i < ndests; ++i)
3498
105
    re_node_set_free (dests_node + i);
3499
97
  return true;
3500
97
}
3501
3502
/* Group all nodes belonging to STATE into several destinations.
3503
   Then for all destinations, set the nodes belonging to the destination
3504
   to DESTS_NODE[i] and set the characters accepted by the destination
3505
   to DEST_CH[i].  Return the number of destinations if successful,
3506
   -1 on internal error.  */
3507
3508
static Idx
3509
group_nodes_into_DFAstates (const re_dfa_t *dfa, const re_dfastate_t *state,
3510
          re_node_set *dests_node, bitset_t *dests_ch)
3511
98
{
3512
98
  reg_errcode_t err;
3513
98
  bool ok;
3514
98
  Idx i, j, k;
3515
98
  Idx ndests; /* Number of the destinations from 'state'.  */
3516
98
  bitset_t accepts; /* Characters a node can accept.  */
3517
98
  const re_node_set *cur_nodes = &state->nodes;
3518
98
  bitset_empty (accepts);
3519
98
  ndests = 0;
3520
3521
  /* For all the nodes belonging to 'state',  */
3522
240
  for (i = 0; i < cur_nodes->nelem; ++i)
3523
142
    {
3524
142
      re_token_t *node = &dfa->nodes[cur_nodes->elems[i]];
3525
142
      re_token_type_t type = node->type;
3526
142
      unsigned int constraint = node->constraint;
3527
3528
      /* Enumerate all single byte character this node can accept.  */
3529
142
      if (type == CHARACTER)
3530
108
  bitset_set (accepts, node->opr.c);
3531
34
      else if (type == SIMPLE_BRACKET)
3532
1
  {
3533
1
    bitset_merge (accepts, node->opr.sbcset);
3534
1
  }
3535
33
      else if (type == OP_PERIOD)
3536
0
  {
3537
0
    if (dfa->mb_cur_max > 1)
3538
0
      bitset_merge (accepts, dfa->sb_char);
3539
0
    else
3540
0
      bitset_set_all (accepts);
3541
0
    if (!(dfa->syntax & RE_DOT_NEWLINE))
3542
0
      bitset_clear (accepts, '\n');
3543
0
    if (dfa->syntax & RE_DOT_NOT_NULL)
3544
0
      bitset_clear (accepts, '\0');
3545
0
  }
3546
33
      else if (type == OP_UTF8_PERIOD)
3547
0
  {
3548
0
    if (ASCII_CHARS % BITSET_WORD_BITS == 0)
3549
0
      memset (accepts, -1, ASCII_CHARS / CHAR_BIT);
3550
0
    else
3551
0
      bitset_merge (accepts, utf8_sb_map);
3552
0
    if (!(dfa->syntax & RE_DOT_NEWLINE))
3553
0
      bitset_clear (accepts, '\n');
3554
0
    if (dfa->syntax & RE_DOT_NOT_NULL)
3555
0
      bitset_clear (accepts, '\0');
3556
0
  }
3557
33
      else
3558
33
  continue;
3559
3560
      /* Check the 'accepts' and sift the characters which are not
3561
   match it the context.  */
3562
109
      if (constraint)
3563
0
  {
3564
0
    if (constraint & NEXT_NEWLINE_CONSTRAINT)
3565
0
      {
3566
0
        bool accepts_newline = bitset_contain (accepts, NEWLINE_CHAR);
3567
0
        bitset_empty (accepts);
3568
0
        if (accepts_newline)
3569
0
    bitset_set (accepts, NEWLINE_CHAR);
3570
0
        else
3571
0
    continue;
3572
0
      }
3573
0
    if (constraint & NEXT_ENDBUF_CONSTRAINT)
3574
0
      {
3575
0
        bitset_empty (accepts);
3576
0
        continue;
3577
0
      }
3578
3579
0
    if (constraint & NEXT_WORD_CONSTRAINT)
3580
0
      {
3581
0
        bitset_word_t any_set = 0;
3582
0
        if (type == CHARACTER && !node->word_char)
3583
0
    {
3584
0
      bitset_empty (accepts);
3585
0
      continue;
3586
0
    }
3587
0
        if (dfa->mb_cur_max > 1)
3588
0
    for (j = 0; j < BITSET_WORDS; ++j)
3589
0
      any_set |= (accepts[j] &= (dfa->word_char[j] | ~dfa->sb_char[j]));
3590
0
        else
3591
0
    for (j = 0; j < BITSET_WORDS; ++j)
3592
0
      any_set |= (accepts[j] &= dfa->word_char[j]);
3593
0
        if (!any_set)
3594
0
    continue;
3595
0
      }
3596
0
    if (constraint & NEXT_NOTWORD_CONSTRAINT)
3597
0
      {
3598
0
        bitset_word_t any_set = 0;
3599
0
        if (type == CHARACTER && node->word_char)
3600
0
    {
3601
0
      bitset_empty (accepts);
3602
0
      continue;
3603
0
    }
3604
0
        if (dfa->mb_cur_max > 1)
3605
0
    for (j = 0; j < BITSET_WORDS; ++j)
3606
0
      any_set |= (accepts[j] &= ~(dfa->word_char[j] & dfa->sb_char[j]));
3607
0
        else
3608
0
    for (j = 0; j < BITSET_WORDS; ++j)
3609
0
      any_set |= (accepts[j] &= ~dfa->word_char[j]);
3610
0
        if (!any_set)
3611
0
    continue;
3612
0
      }
3613
0
  }
3614
3615
      /* Then divide 'accepts' into DFA states, or create a new
3616
   state.  Above, we make sure that accepts is not empty.  */
3617
125
      for (j = 0; j < ndests; ++j)
3618
20
  {
3619
20
    bitset_t intersec; /* Intersection sets, see below.  */
3620
20
    bitset_t remains;
3621
    /* Flags, see below.  */
3622
20
    bitset_word_t has_intersec, not_subset, not_consumed;
3623
3624
    /* Optimization, skip if this state doesn't accept the character.  */
3625
20
    if (type == CHARACTER && !bitset_contain (dests_ch[j], node->opr.c))
3626
16
      continue;
3627
3628
    /* Enumerate the intersection set of this state and 'accepts'.  */
3629
4
    has_intersec = 0;
3630
20
    for (k = 0; k < BITSET_WORDS; ++k)
3631
16
      has_intersec |= intersec[k] = accepts[k] & dests_ch[j][k];
3632
    /* And skip if the intersection set is empty.  */
3633
4
    if (!has_intersec)
3634
0
      continue;
3635
3636
    /* Then check if this state is a subset of 'accepts'.  */
3637
4
    not_subset = not_consumed = 0;
3638
20
    for (k = 0; k < BITSET_WORDS; ++k)
3639
16
      {
3640
16
        not_subset |= remains[k] = ~accepts[k] & dests_ch[j][k];
3641
16
        not_consumed |= accepts[k] = accepts[k] & ~dests_ch[j][k];
3642
16
      }
3643
3644
    /* If this state isn't a subset of 'accepts', create a
3645
       new group state, which has the 'remains'. */
3646
4
    if (not_subset)
3647
0
      {
3648
0
        bitset_copy (dests_ch[ndests], remains);
3649
0
        bitset_copy (dests_ch[j], intersec);
3650
0
        err = re_node_set_init_copy (dests_node + ndests, &dests_node[j]);
3651
0
        if (__glibc_unlikely (err != REG_NOERROR))
3652
0
    goto error_return;
3653
0
        ++ndests;
3654
0
      }
3655
3656
    /* Put the position in the current group. */
3657
4
    ok = re_node_set_insert (&dests_node[j], cur_nodes->elems[i]);
3658
4
    if (__glibc_unlikely (! ok))
3659
0
      goto error_return;
3660
3661
    /* If all characters are consumed, go to next node. */
3662
4
    if (!not_consumed)
3663
4
      break;
3664
4
  }
3665
      /* Some characters remain, create a new group. */
3666
109
      if (j == ndests)
3667
105
  {
3668
105
    bitset_copy (dests_ch[ndests], accepts);
3669
105
    err = re_node_set_init_1 (dests_node + ndests, cur_nodes->elems[i]);
3670
105
    if (__glibc_unlikely (err != REG_NOERROR))
3671
0
      goto error_return;
3672
105
    ++ndests;
3673
105
    bitset_empty (accepts);
3674
105
  }
3675
109
    }
3676
98
  assume (ndests <= SBC_MAX);
3677
98
  return ndests;
3678
0
 error_return:
3679
0
  for (j = 0; j < ndests; ++j)
3680
0
    re_node_set_free (dests_node + j);
3681
0
  return -1;
3682
98
}
3683
3684
/* Check how many bytes the node 'dfa->nodes[node_idx]' accepts.
3685
   Return the number of the bytes the node accepts.
3686
   STR_IDX is the current index of the input string.
3687
3688
   This function handles the nodes which can accept one character, or
3689
   one collating element like '.', '[a-z]', opposite to the other nodes
3690
   can only accept one byte.  */
3691
3692
#ifdef _LIBC
3693
# include <locale/weight.h>
3694
#endif
3695
3696
static int
3697
check_node_accept_bytes (const re_dfa_t *dfa, Idx node_idx,
3698
       const re_string_t *input, Idx str_idx)
3699
0
{
3700
0
  const re_token_t *node = dfa->nodes + node_idx;
3701
0
  int char_len, elem_len;
3702
0
  Idx i;
3703
3704
0
  if (__glibc_unlikely (node->type == OP_UTF8_PERIOD))
3705
0
    {
3706
0
      unsigned char c = re_string_byte_at (input, str_idx), d;
3707
0
      if (__glibc_likely (c < 0xc2))
3708
0
  return 0;
3709
3710
0
      if (str_idx + 2 > input->len)
3711
0
  return 0;
3712
3713
0
      d = re_string_byte_at (input, str_idx + 1);
3714
0
      if (c < 0xe0)
3715
0
  return (d < 0x80 || d > 0xbf) ? 0 : 2;
3716
0
      else if (c < 0xf0)
3717
0
  {
3718
0
    char_len = 3;
3719
0
    if (c == 0xe0 && d < 0xa0)
3720
0
      return 0;
3721
0
  }
3722
0
      else if (c < 0xf8)
3723
0
  {
3724
0
    char_len = 4;
3725
0
    if (c == 0xf0 && d < 0x90)
3726
0
      return 0;
3727
0
  }
3728
0
      else if (c < 0xfc)
3729
0
  {
3730
0
    char_len = 5;
3731
0
    if (c == 0xf8 && d < 0x88)
3732
0
      return 0;
3733
0
  }
3734
0
      else if (c < 0xfe)
3735
0
  {
3736
0
    char_len = 6;
3737
0
    if (c == 0xfc && d < 0x84)
3738
0
      return 0;
3739
0
  }
3740
0
      else
3741
0
  return 0;
3742
3743
0
      if (str_idx + char_len > input->len)
3744
0
  return 0;
3745
3746
0
      for (i = 1; i < char_len; ++i)
3747
0
  {
3748
0
    d = re_string_byte_at (input, str_idx + i);
3749
0
    if (d < 0x80 || d > 0xbf)
3750
0
      return 0;
3751
0
  }
3752
0
      return char_len;
3753
0
    }
3754
3755
0
  char_len = re_string_char_size_at (input, str_idx);
3756
0
  if (node->type == OP_PERIOD)
3757
0
    {
3758
0
      if (char_len <= 1)
3759
0
  return 0;
3760
      /* FIXME: I don't think this if is needed, as both '\n'
3761
   and '\0' are char_len == 1.  */
3762
      /* '.' accepts any one character except the following two cases.  */
3763
0
      if ((!(dfa->syntax & RE_DOT_NEWLINE)
3764
0
     && re_string_byte_at (input, str_idx) == '\n')
3765
0
    || ((dfa->syntax & RE_DOT_NOT_NULL)
3766
0
        && re_string_byte_at (input, str_idx) == '\0'))
3767
0
  return 0;
3768
0
      return char_len;
3769
0
    }
3770
3771
0
  elem_len = re_string_elem_size_at (input, str_idx);
3772
0
  if ((elem_len <= 1 && char_len <= 1) || char_len == 0)
3773
0
    return 0;
3774
3775
0
  if (node->type == COMPLEX_BRACKET)
3776
0
    {
3777
0
      const re_charset_t *cset = node->opr.mbcset;
3778
#ifdef _LIBC
3779
      const unsigned char *pin
3780
  = ((const unsigned char *) re_string_get_buffer (input) + str_idx);
3781
      Idx j;
3782
      uint32_t nrules;
3783
#endif
3784
0
      int match_len = 0;
3785
0
      wchar_t wc = ((cset->nranges || cset->nchar_classes || cset->nmbchars)
3786
0
        ? re_string_wchar_at (input, str_idx) : 0);
3787
3788
      /* match with multibyte character?  */
3789
0
      for (i = 0; i < cset->nmbchars; ++i)
3790
0
  if (wc == cset->mbchars[i])
3791
0
    {
3792
0
      match_len = char_len;
3793
0
      goto check_node_accept_bytes_match;
3794
0
    }
3795
      /* match with character_class?  */
3796
0
      for (i = 0; i < cset->nchar_classes; ++i)
3797
0
  {
3798
0
    wctype_t wt = cset->char_classes[i];
3799
0
    if (__iswctype (wc, wt))
3800
0
      {
3801
0
        match_len = char_len;
3802
0
        goto check_node_accept_bytes_match;
3803
0
      }
3804
0
  }
3805
3806
#ifdef _LIBC
3807
      nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3808
      if (nrules != 0)
3809
  {
3810
    unsigned int in_collseq = 0;
3811
    const int32_t *table, *indirect;
3812
    const unsigned char *weights, *extra;
3813
    const char *collseqwc;
3814
3815
    /* match with collating_symbol?  */
3816
    if (cset->ncoll_syms)
3817
      extra = (const unsigned char *)
3818
        _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
3819
    for (i = 0; i < cset->ncoll_syms; ++i)
3820
      {
3821
        const unsigned char *coll_sym = extra + cset->coll_syms[i];
3822
        /* Compare the length of input collating element and
3823
     the length of current collating element.  */
3824
        if (*coll_sym != elem_len)
3825
    continue;
3826
        /* Compare each bytes.  */
3827
        for (j = 0; j < *coll_sym; j++)
3828
    if (pin[j] != coll_sym[1 + j])
3829
      break;
3830
        if (j == *coll_sym)
3831
    {
3832
      /* Match if every bytes is equal.  */
3833
      match_len = j;
3834
      goto check_node_accept_bytes_match;
3835
    }
3836
      }
3837
3838
    if (cset->nranges)
3839
      {
3840
        if (elem_len <= char_len)
3841
    {
3842
      collseqwc = _NL_CURRENT (LC_COLLATE, _NL_COLLATE_COLLSEQWC);
3843
      in_collseq = __collseq_table_lookup (collseqwc, wc);
3844
    }
3845
        else
3846
    in_collseq = find_collation_sequence_value (pin, elem_len);
3847
      }
3848
    /* match with range expression?  */
3849
    /* FIXME: Implement rational ranges here, too.  */
3850
    for (i = 0; i < cset->nranges; ++i)
3851
      if (cset->range_starts[i] <= in_collseq
3852
    && in_collseq <= cset->range_ends[i])
3853
        {
3854
    match_len = elem_len;
3855
    goto check_node_accept_bytes_match;
3856
        }
3857
3858
    /* match with equivalence_class?  */
3859
    if (cset->nequiv_classes)
3860
      {
3861
        const unsigned char *cp = pin;
3862
        table = (const int32_t *)
3863
    _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
3864
        weights = (const unsigned char *)
3865
    _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB);
3866
        extra = (const unsigned char *)
3867
    _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
3868
        indirect = (const int32_t *)
3869
    _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB);
3870
        int32_t idx = findidx (table, indirect, extra, &cp, elem_len);
3871
        int32_t rule = idx >> 24;
3872
        idx &= 0xffffff;
3873
        if (idx > 0)
3874
    {
3875
      size_t weight_len = weights[idx];
3876
      for (i = 0; i < cset->nequiv_classes; ++i)
3877
        {
3878
          int32_t equiv_class_idx = cset->equiv_classes[i];
3879
          int32_t equiv_class_rule = equiv_class_idx >> 24;
3880
          equiv_class_idx &= 0xffffff;
3881
          if (weights[equiv_class_idx] == weight_len
3882
        && equiv_class_rule == rule
3883
        && memcmp (weights + idx + 1,
3884
             weights + equiv_class_idx + 1,
3885
             weight_len) == 0)
3886
      {
3887
        match_len = elem_len;
3888
        goto check_node_accept_bytes_match;
3889
      }
3890
        }
3891
    }
3892
      }
3893
  }
3894
      else
3895
#endif /* _LIBC */
3896
0
  {
3897
    /* match with range expression?  */
3898
0
    for (i = 0; i < cset->nranges; ++i)
3899
0
      {
3900
0
        if (cset->range_starts[i] <= wc && wc <= cset->range_ends[i])
3901
0
    {
3902
0
      match_len = char_len;
3903
0
      goto check_node_accept_bytes_match;
3904
0
    }
3905
0
      }
3906
0
  }
3907
0
    check_node_accept_bytes_match:
3908
0
      if (!cset->non_match)
3909
0
  return match_len;
3910
0
      else
3911
0
  {
3912
0
    if (match_len > 0)
3913
0
      return 0;
3914
0
    else
3915
0
      return (elem_len > char_len) ? elem_len : char_len;
3916
0
  }
3917
0
    }
3918
0
  return 0;
3919
0
}
3920
3921
#ifdef _LIBC
3922
static unsigned int
3923
find_collation_sequence_value (const unsigned char *mbs, size_t mbs_len)
3924
{
3925
  uint32_t nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3926
  if (nrules == 0)
3927
    {
3928
      if (mbs_len == 1)
3929
  {
3930
    /* No valid character.  Match it as a single byte character.  */
3931
    const unsigned char *collseq = (const unsigned char *)
3932
      _NL_CURRENT (LC_COLLATE, _NL_COLLATE_COLLSEQMB);
3933
    return collseq[mbs[0]];
3934
  }
3935
      return UINT_MAX;
3936
    }
3937
  else
3938
    {
3939
      int32_t idx;
3940
      const unsigned char *extra = (const unsigned char *)
3941
  _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
3942
      int32_t extrasize = (const unsigned char *)
3943
  _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB + 1) - extra;
3944
3945
      for (idx = 0; idx < extrasize;)
3946
  {
3947
    int mbs_cnt;
3948
    bool found = false;
3949
    int32_t elem_mbs_len;
3950
    /* Skip the name of collating element name.  */
3951
    idx = idx + extra[idx] + 1;
3952
    elem_mbs_len = extra[idx++];
3953
    if (mbs_len == elem_mbs_len)
3954
      {
3955
        for (mbs_cnt = 0; mbs_cnt < elem_mbs_len; ++mbs_cnt)
3956
    if (extra[idx + mbs_cnt] != mbs[mbs_cnt])
3957
      break;
3958
        if (mbs_cnt == elem_mbs_len)
3959
    /* Found the entry.  */
3960
    found = true;
3961
      }
3962
    /* Skip the byte sequence of the collating element.  */
3963
    idx += elem_mbs_len;
3964
    /* Adjust for the alignment.  */
3965
    idx = (idx + 3) & ~3;
3966
    /* Skip the collation sequence value.  */
3967
    idx += sizeof (uint32_t);
3968
    /* Skip the wide char sequence of the collating element.  */
3969
    idx = idx + sizeof (uint32_t) * (*(int32_t *) (extra + idx) + 1);
3970
    /* If we found the entry, return the sequence value.  */
3971
    if (found)
3972
      return *(uint32_t *) (extra + idx);
3973
    /* Skip the collation sequence value.  */
3974
    idx += sizeof (uint32_t);
3975
  }
3976
      return UINT_MAX;
3977
    }
3978
}
3979
#endif /* _LIBC */
3980
3981
/* Check whether the node accepts the byte which is IDX-th
3982
   byte of the INPUT.  */
3983
3984
static bool
3985
check_node_accept (const re_match_context_t *mctx, const re_token_t *node,
3986
       Idx idx)
3987
0
{
3988
0
  unsigned char ch;
3989
0
  ch = re_string_byte_at (&mctx->input, idx);
3990
0
  switch (node->type)
3991
0
    {
3992
0
    case CHARACTER:
3993
0
      if (node->opr.c != ch)
3994
0
        return false;
3995
0
      break;
3996
3997
0
    case SIMPLE_BRACKET:
3998
0
      if (!bitset_contain (node->opr.sbcset, ch))
3999
0
        return false;
4000
0
      break;
4001
4002
0
    case OP_UTF8_PERIOD:
4003
0
      if (ch >= ASCII_CHARS)
4004
0
        return false;
4005
0
      FALLTHROUGH;
4006
0
    case OP_PERIOD:
4007
0
      if ((ch == '\n' && !(mctx->dfa->syntax & RE_DOT_NEWLINE))
4008
0
    || (ch == '\0' && (mctx->dfa->syntax & RE_DOT_NOT_NULL)))
4009
0
  return false;
4010
0
      break;
4011
4012
0
    default:
4013
0
      return false;
4014
0
    }
4015
4016
0
  if (node->constraint)
4017
0
    {
4018
      /* The node has constraints.  Check whether the current context
4019
   satisfies the constraints.  */
4020
0
      unsigned int context = re_string_context_at (&mctx->input, idx,
4021
0
               mctx->eflags);
4022
0
      if (NOT_SATISFY_NEXT_CONSTRAINT (node->constraint, context))
4023
0
  return false;
4024
0
    }
4025
4026
0
  return true;
4027
0
}
4028
4029
/* Extend the buffers, if the buffers have run out.  */
4030
4031
static reg_errcode_t
4032
__attribute_warn_unused_result__
4033
extend_buffers (re_match_context_t *mctx, int min_len)
4034
0
{
4035
0
  reg_errcode_t ret;
4036
0
  re_string_t *pstr = &mctx->input;
4037
4038
  /* Avoid overflow.  */
4039
0
  if (__glibc_unlikely (MIN (IDX_MAX, SIZE_MAX / sizeof (re_dfastate_t *)) / 2
4040
0
      <= pstr->bufs_len))
4041
0
    return REG_ESPACE;
4042
4043
  /* Double the lengths of the buffers, but allocate at least MIN_LEN.  */
4044
0
  ret = re_string_realloc_buffers (pstr,
4045
0
           MAX (min_len,
4046
0
          MIN (pstr->len, pstr->bufs_len * 2)));
4047
0
  if (__glibc_unlikely (ret != REG_NOERROR))
4048
0
    return ret;
4049
4050
0
  if (mctx->state_log != NULL)
4051
0
    {
4052
      /* And double the length of state_log.  */
4053
      /* XXX We have no indication of the size of this buffer.  If this
4054
   allocation fail we have no indication that the state_log array
4055
   does not have the right size.  */
4056
0
      re_dfastate_t **new_array = re_realloc (mctx->state_log, re_dfastate_t *,
4057
0
                pstr->bufs_len + 1);
4058
0
      if (__glibc_unlikely (new_array == NULL))
4059
0
  return REG_ESPACE;
4060
0
      mctx->state_log = new_array;
4061
0
    }
4062
4063
  /* Then reconstruct the buffers.  */
4064
0
  if (pstr->icase)
4065
0
    {
4066
0
      if (pstr->mb_cur_max > 1)
4067
0
  {
4068
0
    ret = build_wcs_upper_buffer (pstr);
4069
0
    if (__glibc_unlikely (ret != REG_NOERROR))
4070
0
      return ret;
4071
0
  }
4072
0
      else
4073
0
  build_upper_buffer (pstr);
4074
0
    }
4075
0
  else
4076
0
    {
4077
0
      if (pstr->mb_cur_max > 1)
4078
0
  build_wcs_buffer (pstr);
4079
0
      else
4080
0
  {
4081
0
    if (pstr->trans != NULL)
4082
0
      re_string_translate_buffer (pstr);
4083
0
  }
4084
0
    }
4085
0
  return REG_NOERROR;
4086
0
}
4087
4088

4089
/* Functions for matching context.  */
4090
4091
/* Initialize MCTX.  */
4092
4093
static reg_errcode_t
4094
__attribute_warn_unused_result__
4095
match_ctx_init (re_match_context_t *mctx, int eflags, Idx n)
4096
57
{
4097
57
  mctx->eflags = eflags;
4098
57
  mctx->match_last = -1;
4099
57
  if (n > 0)
4100
0
    {
4101
      /* Avoid overflow.  */
4102
0
      size_t max_object_size =
4103
0
  MAX (sizeof (struct re_backref_cache_entry),
4104
0
       sizeof (re_sub_match_top_t *));
4105
0
      if (__glibc_unlikely (MIN (IDX_MAX, SIZE_MAX / max_object_size) < n))
4106
0
  return REG_ESPACE;
4107
4108
0
      mctx->bkref_ents = re_malloc (struct re_backref_cache_entry, n);
4109
0
      mctx->sub_tops = re_malloc (re_sub_match_top_t *, n);
4110
0
      if (__glibc_unlikely (mctx->bkref_ents == NULL || mctx->sub_tops == NULL))
4111
0
  return REG_ESPACE;
4112
0
    }
4113
  /* Already zero-ed by the caller.
4114
     else
4115
       mctx->bkref_ents = NULL;
4116
     mctx->nbkref_ents = 0;
4117
     mctx->nsub_tops = 0;  */
4118
57
  mctx->abkref_ents = n;
4119
57
  mctx->max_mb_elem_len = 1;
4120
57
  mctx->asub_tops = n;
4121
57
  return REG_NOERROR;
4122
57
}
4123
4124
/* Clean the entries which depend on the current input in MCTX.
4125
   This function must be invoked when the matcher changes the start index
4126
   of the input, or changes the input string.  */
4127
4128
static void
4129
match_ctx_clean (re_match_context_t *mctx)
4130
48
{
4131
48
  Idx st_idx;
4132
48
  for (st_idx = 0; st_idx < mctx->nsub_tops; ++st_idx)
4133
0
    {
4134
0
      Idx sl_idx;
4135
0
      re_sub_match_top_t *top = mctx->sub_tops[st_idx];
4136
0
      for (sl_idx = 0; sl_idx < top->nlasts; ++sl_idx)
4137
0
  {
4138
0
    re_sub_match_last_t *last = top->lasts[sl_idx];
4139
0
    re_free (last->path.array);
4140
0
    re_free (last);
4141
0
  }
4142
0
      re_free (top->lasts);
4143
0
      if (top->path)
4144
0
  {
4145
0
    re_free (top->path->array);
4146
0
    re_free (top->path);
4147
0
  }
4148
0
      re_free (top);
4149
0
    }
4150
4151
48
  mctx->nsub_tops = 0;
4152
48
  mctx->nbkref_ents = 0;
4153
48
}
4154
4155
/* Free all the memory associated with MCTX.  */
4156
4157
static void
4158
match_ctx_free (re_match_context_t *mctx)
4159
0
{
4160
  /* First, free all the memory associated with MCTX->SUB_TOPS.  */
4161
0
  match_ctx_clean (mctx);
4162
0
  re_free (mctx->sub_tops);
4163
0
  re_free (mctx->bkref_ents);
4164
0
}
4165
4166
/* Add a new backreference entry to MCTX.
4167
   Note that we assume that caller never call this function with duplicate
4168
   entry, and call with STR_IDX which isn't smaller than any existing entry.
4169
*/
4170
4171
static reg_errcode_t
4172
__attribute_warn_unused_result__
4173
match_ctx_add_entry (re_match_context_t *mctx, Idx node, Idx str_idx, Idx from,
4174
         Idx to)
4175
0
{
4176
0
  if (mctx->nbkref_ents >= mctx->abkref_ents)
4177
0
    {
4178
0
      struct re_backref_cache_entry* new_entry;
4179
0
      new_entry = re_realloc (mctx->bkref_ents, struct re_backref_cache_entry,
4180
0
            mctx->abkref_ents * 2);
4181
0
      if (__glibc_unlikely (new_entry == NULL))
4182
0
  {
4183
0
    re_free (mctx->bkref_ents);
4184
0
    return REG_ESPACE;
4185
0
  }
4186
0
      mctx->bkref_ents = new_entry;
4187
0
      memset (mctx->bkref_ents + mctx->nbkref_ents, '\0',
4188
0
        sizeof (struct re_backref_cache_entry) * mctx->abkref_ents);
4189
0
      mctx->abkref_ents *= 2;
4190
0
    }
4191
0
  if (mctx->nbkref_ents > 0
4192
0
      && mctx->bkref_ents[mctx->nbkref_ents - 1].str_idx == str_idx)
4193
0
    mctx->bkref_ents[mctx->nbkref_ents - 1].more = 1;
4194
4195
0
  mctx->bkref_ents[mctx->nbkref_ents].node = node;
4196
0
  mctx->bkref_ents[mctx->nbkref_ents].str_idx = str_idx;
4197
0
  mctx->bkref_ents[mctx->nbkref_ents].subexp_from = from;
4198
0
  mctx->bkref_ents[mctx->nbkref_ents].subexp_to = to;
4199
4200
  /* This is a cache that saves negative results of check_dst_limits_calc_pos.
4201
     If bit N is clear, means that this entry won't epsilon-transition to
4202
     an OP_OPEN_SUBEXP or OP_CLOSE_SUBEXP for the N+1-th subexpression.  If
4203
     it is set, check_dst_limits_calc_pos_1 will recurse and try to find one
4204
     such node.
4205
4206
     A backreference does not epsilon-transition unless it is empty, so set
4207
     to all zeros if FROM != TO.  */
4208
0
  mctx->bkref_ents[mctx->nbkref_ents].eps_reachable_subexps_map
4209
0
    = (from == to ? -1 : 0);
4210
4211
0
  mctx->bkref_ents[mctx->nbkref_ents++].more = 0;
4212
0
  if (mctx->max_mb_elem_len < to - from)
4213
0
    mctx->max_mb_elem_len = to - from;
4214
0
  return REG_NOERROR;
4215
0
}
4216
4217
/* Return the first entry with the same str_idx, or -1 if none is
4218
   found.  Note that MCTX->BKREF_ENTS is already sorted by MCTX->STR_IDX.  */
4219
4220
static Idx
4221
search_cur_bkref_entry (const re_match_context_t *mctx, Idx str_idx)
4222
0
{
4223
0
  Idx left, right, mid, last;
4224
0
  last = right = mctx->nbkref_ents;
4225
0
  for (left = 0; left < right;)
4226
0
    {
4227
0
      mid = (left + right) / 2;
4228
0
      if (mctx->bkref_ents[mid].str_idx < str_idx)
4229
0
  left = mid + 1;
4230
0
      else
4231
0
  right = mid;
4232
0
    }
4233
0
  if (left < last && mctx->bkref_ents[left].str_idx == str_idx)
4234
0
    return left;
4235
0
  else
4236
0
    return -1;
4237
0
}
4238
4239
/* Register the node NODE, whose type is OP_OPEN_SUBEXP, and which matches
4240
   at STR_IDX.  */
4241
4242
static reg_errcode_t
4243
__attribute_warn_unused_result__
4244
match_ctx_add_subtop (re_match_context_t *mctx, Idx node, Idx str_idx)
4245
0
{
4246
0
  DEBUG_ASSERT (mctx->sub_tops != NULL);
4247
0
  DEBUG_ASSERT (mctx->asub_tops > 0);
4248
0
  if (__glibc_unlikely (mctx->nsub_tops == mctx->asub_tops))
4249
0
    {
4250
0
      Idx new_asub_tops = mctx->asub_tops * 2;
4251
0
      re_sub_match_top_t **new_array = re_realloc (mctx->sub_tops,
4252
0
               re_sub_match_top_t *,
4253
0
               new_asub_tops);
4254
0
      if (__glibc_unlikely (new_array == NULL))
4255
0
  return REG_ESPACE;
4256
0
      mctx->sub_tops = new_array;
4257
0
      mctx->asub_tops = new_asub_tops;
4258
0
    }
4259
0
  mctx->sub_tops[mctx->nsub_tops] = calloc (1, sizeof (re_sub_match_top_t));
4260
0
  if (__glibc_unlikely (mctx->sub_tops[mctx->nsub_tops] == NULL))
4261
0
    return REG_ESPACE;
4262
0
  mctx->sub_tops[mctx->nsub_tops]->node = node;
4263
0
  mctx->sub_tops[mctx->nsub_tops++]->str_idx = str_idx;
4264
0
  return REG_NOERROR;
4265
0
}
4266
4267
/* Register the node NODE, whose type is OP_CLOSE_SUBEXP, and which matches
4268
   at STR_IDX, whose corresponding OP_OPEN_SUBEXP is SUB_TOP.
4269
   Return the new entry if successful, NULL if memory is exhausted.  */
4270
4271
static re_sub_match_last_t *
4272
match_ctx_add_sublast (re_sub_match_top_t *subtop, Idx node, Idx str_idx)
4273
0
{
4274
0
  re_sub_match_last_t *new_entry;
4275
0
  if (__glibc_unlikely (subtop->nlasts == subtop->alasts))
4276
0
    {
4277
0
      Idx new_alasts = 2 * subtop->alasts + 1;
4278
0
      re_sub_match_last_t **new_array = re_realloc (subtop->lasts,
4279
0
                re_sub_match_last_t *,
4280
0
                new_alasts);
4281
0
      if (__glibc_unlikely (new_array == NULL))
4282
0
  return NULL;
4283
0
      subtop->lasts = new_array;
4284
0
      subtop->alasts = new_alasts;
4285
0
    }
4286
0
  new_entry = calloc (1, sizeof (re_sub_match_last_t));
4287
0
  if (__glibc_likely (new_entry != NULL))
4288
0
    {
4289
0
      subtop->lasts[subtop->nlasts] = new_entry;
4290
0
      new_entry->node = node;
4291
0
      new_entry->str_idx = str_idx;
4292
0
      ++subtop->nlasts;
4293
0
    }
4294
0
  return new_entry;
4295
0
}
4296
4297
static void
4298
sift_ctx_init (re_sift_context_t *sctx, re_dfastate_t **sifted_sts,
4299
         re_dfastate_t **limited_sts, Idx last_node, Idx last_str_idx)
4300
0
{
4301
0
  sctx->sifted_states = sifted_sts;
4302
0
  sctx->limited_states = limited_sts;
4303
0
  sctx->last_node = last_node;
4304
0
  sctx->last_str_idx = last_str_idx;
4305
0
  re_node_set_init_empty (&sctx->limits);
4306
0
}