1 /*    regexp.h
2  *
3  *    Copyright (C) 1993, 1994, 1996, 1997, 1999, 2000, 2001, 2003,
4  *    2005, 2006, 2007, 2008 by Larry Wall and others
5  *
6  *    You may distribute under the terms of either the GNU General Public
7  *    License or the Artistic License, as specified in the README file.
8  *
9  */
10 
11 /*
12  * Definitions etc. for regexp(3) routines.
13  *
14  * Caveat:  this is V8 regexp(3) [actually, a reimplementation thereof],
15  * not the System V one.
16  */
17 #ifndef PLUGGABLE_RE_EXTENSION
18 /* we don't want to include this stuff if we are inside of
19    an external regex engine based on the core one - like re 'debug'*/
20 
21 #include "utf8.h"
22 
23 typedef SSize_t regnode_offset;
24 
25 struct regnode {
26     U8	flags;
27     U8  type;
28     U16 next_off;
29 };
30 
31 typedef struct regnode regnode;
32 
33 struct reg_substr_data;
34 
35 struct reg_data;
36 
37 struct regexp_engine;
38 struct regexp;
39 
40 struct reg_substr_datum {
41     SSize_t min_offset; /* min pos (in chars) that substr must appear */
42     SSize_t max_offset  /* max pos (in chars) that substr must appear */;
43     SV *substr;		/* non-utf8 variant */
44     SV *utf8_substr;	/* utf8 variant */
45     SSize_t end_shift;  /* how many fixed chars must end the string */
46 };
47 struct reg_substr_data {
48     U8      check_ix;   /* index into data[] of check substr */
49     struct reg_substr_datum data[3];	/* Actual array */
50 };
51 
52 #ifdef PERL_ANY_COW
53 #define SV_SAVED_COPY   SV *saved_copy; /* If non-NULL, SV which is COW from original */
54 #else
55 #define SV_SAVED_COPY
56 #endif
57 
58 /* offsets within a string of a particular /(.)/ capture */
59 
60 typedef struct regexp_paren_pair {
61     SSize_t start;
62     SSize_t end;
63     /* 'start_tmp' records a new opening position before the matching end
64      * has been found, so that the old start and end values are still
65      * valid, e.g.
66      *	  "abc" =~ /(.(?{print "[$1]"}))+/
67      *outputs [][a][b]
68      * This field is not part of the API.  */
69     SSize_t start_tmp;
70 } regexp_paren_pair;
71 
72 #if defined(PERL_IN_REGCOMP_C) || defined(PERL_IN_UTF8_C)
73 #define _invlist_union(a, b, output) _invlist_union_maybe_complement_2nd(a, b, FALSE, output)
74 #define _invlist_intersection(a, b, output) _invlist_intersection_maybe_complement_2nd(a, b, FALSE, output)
75 
76 /* Subtracting b from a leaves in a everything that was there that isn't in b,
77  * that is the intersection of a with b's complement */
78 #define _invlist_subtract(a, b, output) _invlist_intersection_maybe_complement_2nd(a, b, TRUE, output)
79 #endif
80 
81 /* record the position of a (?{...}) within a pattern */
82 
83 struct reg_code_block {
84     STRLEN start;
85     STRLEN end;
86     OP     *block;
87     REGEXP *src_regex;
88 };
89 
90 /* array of reg_code_block's plus header info */
91 
92 struct reg_code_blocks {
93     int refcnt; /* we may be pointed to from a regex and from the savestack */
94     int  count;    /* how many code blocks */
95     struct reg_code_block *cb; /* array of reg_code_block's */
96 };
97 
98 
99 /*
100   The regexp/REGEXP struct, see L<perlreapi> for further documentation
101   on the individual fields. The struct is ordered so that the most
102   commonly used fields are placed at the start.
103 
104   Any patch that adds items to this struct will need to include
105   changes to F<sv.c> (C<Perl_re_dup()>) and F<regcomp.c>
106   (C<pregfree()>). This involves freeing or cloning items in the
107   regexp's data array based on the data item's type.
108 */
109 
110 typedef struct regexp {
111     _XPV_HEAD;
112     const struct regexp_engine* engine; /* what engine created this regexp? */
113     REGEXP *mother_re; /* what re is this a lightweight copy of? */
114     HV *paren_names;   /* Optional hash of paren names */
115 
116     /*----------------------------------------------------------------------
117      * Information about the match that the perl core uses to manage things
118      */
119 
120     U32 extflags;      /* Flags used both externally and internally */
121     SSize_t minlen;    /* minimum possible number of chars in string to match */
122     SSize_t minlenret; /* mininum possible number of chars in $& */
123     STRLEN gofs;       /* chars left of pos that we search from */
124                        /* substring data about strings that must appear in
125                         * the final match, used for optimisations */
126     struct reg_substr_data *substrs;
127     U32 nparens;       /* number of capture buffers */
128 
129     /* private engine specific data */
130 
131     U32 intflags;      /* Engine Specific Internal flags */
132     void *pprivate;    /* Data private to the regex engine which
133                         * created this object. */
134 
135     /*----------------------------------------------------------------------
136      * Data about the last/current match. These are modified during matching
137      */
138 
139     U32 lastparen;           /* highest close paren matched ($+) */
140     U32 lastcloseparen;      /* last close paren matched ($^N) */
141     regexp_paren_pair *offs; /* Array of offsets for (@-) and (@+) */
142     char **recurse_locinput; /* used to detect infinite recursion, XXX: move to internal */
143 
144     /*---------------------------------------------------------------------- */
145 
146     char *subbeg;       /* saved or original string so \digit works forever. */
147     SV_SAVED_COPY       /* If non-NULL, SV which is COW from original */
148     SSize_t sublen;     /* Length of string pointed by subbeg */
149     SSize_t suboffset;  /* byte offset of subbeg from logical start of str */
150     SSize_t subcoffset; /* suboffset equiv, but in chars (for @-/@+) */
151 
152     /* Information about the match that isn't often used */
153 
154     SSize_t maxlen;  /* minimum possible number of chars in string to match */
155 
156     /*---------------------------------------------------------------------- */
157 
158     /* offset from wrapped to the start of precomp */
159     PERL_BITFIELD32 pre_prefix:4;
160 
161     /* original flags used to compile the pattern, may differ from
162      * extflags in various ways */
163     PERL_BITFIELD32 compflags:9;
164 
165     /*---------------------------------------------------------------------- */
166 
167     CV *qr_anoncv;      /* the anon sub wrapped round qr/(?{..})/ */
168 } regexp;
169 
170 
171 #define RXp_PAREN_NAMES(rx)	((rx)->paren_names)
172 
173 /* used for high speed searches */
174 typedef struct re_scream_pos_data_s
175 {
176     char **scream_olds;		/* match pos */
177     SSize_t *scream_pos;	/* Internal iterator of scream. */
178 } re_scream_pos_data;
179 
180 /* regexp_engine structure. This is the dispatch table for regexes.
181  * Any regex engine implementation must be able to build one of these.
182  */
183 typedef struct regexp_engine {
184     REGEXP* (*comp) (pTHX_ SV * const pattern, U32 flags);
185     I32     (*exec) (pTHX_ REGEXP * const rx, char* stringarg, char* strend,
186                      char* strbeg, SSize_t minend, SV* sv,
187                      void* data, U32 flags);
188     char*   (*intuit) (pTHX_
189                         REGEXP * const rx,
190                         SV *sv,
191                         const char * const strbeg,
192                         char *strpos,
193                         char *strend,
194                         const U32 flags,
195                        re_scream_pos_data *data);
196     SV*     (*checkstr) (pTHX_ REGEXP * const rx);
197     void    (*rxfree) (pTHX_ REGEXP * const rx);
198     void    (*numbered_buff_FETCH) (pTHX_ REGEXP * const rx, const I32 paren,
199                                     SV * const sv);
200     void    (*numbered_buff_STORE) (pTHX_ REGEXP * const rx, const I32 paren,
201                                    SV const * const value);
202     I32     (*numbered_buff_LENGTH) (pTHX_ REGEXP * const rx, const SV * const sv,
203                                     const I32 paren);
204     SV*     (*named_buff) (pTHX_ REGEXP * const rx, SV * const key,
205                            SV * const value, const U32 flags);
206     SV*     (*named_buff_iter) (pTHX_ REGEXP * const rx, const SV * const lastkey,
207                                 const U32 flags);
208     SV*     (*qr_package)(pTHX_ REGEXP * const rx);
209 #ifdef USE_ITHREADS
210     void*   (*dupe) (pTHX_ REGEXP * const rx, CLONE_PARAMS *param);
211 #endif
212     REGEXP* (*op_comp) (pTHX_ SV ** const patternp, int pat_count,
213 		    OP *expr, const struct regexp_engine* eng,
214 		    REGEXP *old_re,
215 		    bool *is_bare_re, U32 orig_rx_flags, U32 pm_flags);
216 } regexp_engine;
217 
218 /*
219   These are passed to the numbered capture variable callbacks as the
220   paren name. >= 1 is reserved for actual numbered captures, i.e. $1,
221   $2 etc.
222 */
223 #define RX_BUFF_IDX_CARET_PREMATCH  -5 /* ${^PREMATCH}  */
224 #define RX_BUFF_IDX_CARET_POSTMATCH -4 /* ${^POSTMATCH} */
225 #define RX_BUFF_IDX_CARET_FULLMATCH -3 /* ${^MATCH}     */
226 #define RX_BUFF_IDX_PREMATCH        -2 /* $` */
227 #define RX_BUFF_IDX_POSTMATCH       -1 /* $' */
228 #define RX_BUFF_IDX_FULLMATCH        0 /* $& */
229 
230 /*
231   Flags that are passed to the named_buff and named_buff_iter
232   callbacks above. Those routines are called from universal.c via the
233   Tie::Hash::NamedCapture interface for %+ and %- and the re::
234   functions in the same file.
235 */
236 
237 /* The Tie::Hash::NamedCapture operation this is part of, if any */
238 #define RXapif_FETCH     0x0001
239 #define RXapif_STORE     0x0002
240 #define RXapif_DELETE    0x0004
241 #define RXapif_CLEAR     0x0008
242 #define RXapif_EXISTS    0x0010
243 #define RXapif_SCALAR    0x0020
244 #define RXapif_FIRSTKEY  0x0040
245 #define RXapif_NEXTKEY   0x0080
246 
247 /* Whether %+ or %- is being operated on */
248 #define RXapif_ONE       0x0100 /* %+ */
249 #define RXapif_ALL       0x0200 /* %- */
250 
251 /* Whether this is being called from a re:: function */
252 #define RXapif_REGNAME         0x0400
253 #define RXapif_REGNAMES        0x0800
254 #define RXapif_REGNAMES_COUNT  0x1000
255 
256 /*
257 =head1 REGEXP Functions
258 
259 =for apidoc Am|REGEXP *|SvRX|SV *sv
260 
261 Convenience macro to get the REGEXP from a SV.  This is approximately
262 equivalent to the following snippet:
263 
264     if (SvMAGICAL(sv))
265         mg_get(sv);
266     if (SvROK(sv))
267         sv = MUTABLE_SV(SvRV(sv));
268     if (SvTYPE(sv) == SVt_REGEXP)
269         return (REGEXP*) sv;
270 
271 C<NULL> will be returned if a REGEXP* is not found.
272 
273 =for apidoc Am|bool|SvRXOK|SV* sv
274 
275 Returns a boolean indicating whether the SV (or the one it references)
276 is a REGEXP.
277 
278 If you want to do something with the REGEXP* later use SvRX instead
279 and check for NULL.
280 
281 =cut
282 */
283 
284 #define SvRX(sv)   (Perl_get_re_arg(aTHX_ sv))
285 #define SvRXOK(sv) cBOOL(Perl_get_re_arg(aTHX_ sv))
286 
287 
288 /* Flags stored in regexp->extflags
289  * These are used by code external to the regexp engine
290  *
291  * Note that the flags whose names start with RXf_PMf_ are defined in
292  * op_reg_common.h, being copied from the parallel flags of op_pmflags
293  *
294  * NOTE: if you modify any RXf flags you should run regen.pl or
295  * regen/regcomp.pl so that regnodes.h is updated with the changes.
296  *
297  */
298 
299 #include "op_reg_common.h"
300 
301 #define RXf_PMf_STD_PMMOD	(RXf_PMf_MULTILINE|RXf_PMf_SINGLELINE|RXf_PMf_FOLD|RXf_PMf_EXTENDED|RXf_PMf_EXTENDED_MORE|RXf_PMf_NOCAPTURE)
302 
303 #define CASE_STD_PMMOD_FLAGS_PARSE_SET(pmfl, x_count)                       \
304     case IGNORE_PAT_MOD:    *(pmfl) |= RXf_PMf_FOLD;       break;           \
305     case MULTILINE_PAT_MOD: *(pmfl) |= RXf_PMf_MULTILINE;  break;           \
306     case SINGLE_PAT_MOD:    *(pmfl) |= RXf_PMf_SINGLELINE; break;           \
307     case XTENDED_PAT_MOD:   if (x_count == 0) {                             \
308                                 *(pmfl) |= RXf_PMf_EXTENDED;                \
309                                 *(pmfl) &= ~RXf_PMf_EXTENDED_MORE;          \
310                             }                                               \
311                             else {                                          \
312                                 *(pmfl) |= RXf_PMf_EXTENDED                 \
313                                           |RXf_PMf_EXTENDED_MORE;           \
314                             }                                               \
315                             (x_count)++; break;                             \
316     case NOCAPTURE_PAT_MOD: *(pmfl) |= RXf_PMf_NOCAPTURE; break;
317 
318 /* Note, includes charset ones, assumes 0 is the default for them */
319 #define STD_PMMOD_FLAGS_CLEAR(pmfl)                        \
320     *(pmfl) &= ~(RXf_PMf_FOLD|RXf_PMf_MULTILINE|RXf_PMf_SINGLELINE|RXf_PMf_EXTENDED|RXf_PMf_EXTENDED_MORE|RXf_PMf_CHARSET|RXf_PMf_NOCAPTURE)
321 
322 /* chars and strings used as regex pattern modifiers
323  * Singular is a 'c'har, plural is a "string"
324  *
325  * NOTE, KEEPCOPY was originally 'k', but was changed to 'p' for preserve
326  * for compatibility reasons with Regexp::Common which highjacked (?k:...)
327  * for its own uses. So 'k' is out as well.
328  */
329 #define DEFAULT_PAT_MOD      '^'    /* Short for all the default modifiers */
330 #define EXEC_PAT_MOD         'e'
331 #define KEEPCOPY_PAT_MOD     'p'
332 #define NOCAPTURE_PAT_MOD    'n'
333 #define ONCE_PAT_MOD         'o'
334 #define GLOBAL_PAT_MOD       'g'
335 #define CONTINUE_PAT_MOD     'c'
336 #define MULTILINE_PAT_MOD    'm'
337 #define SINGLE_PAT_MOD       's'
338 #define IGNORE_PAT_MOD       'i'
339 #define XTENDED_PAT_MOD      'x'
340 #define NONDESTRUCT_PAT_MOD  'r'
341 #define LOCALE_PAT_MOD       'l'
342 #define UNICODE_PAT_MOD      'u'
343 #define DEPENDS_PAT_MOD      'd'
344 #define ASCII_RESTRICT_PAT_MOD 'a'
345 
346 #define ONCE_PAT_MODS        "o"
347 #define KEEPCOPY_PAT_MODS    "p"
348 #define NOCAPTURE_PAT_MODS   "n"
349 #define EXEC_PAT_MODS        "e"
350 #define LOOP_PAT_MODS        "gc"
351 #define NONDESTRUCT_PAT_MODS "r"
352 #define LOCALE_PAT_MODS      "l"
353 #define UNICODE_PAT_MODS     "u"
354 #define DEPENDS_PAT_MODS     "d"
355 #define ASCII_RESTRICT_PAT_MODS "a"
356 #define ASCII_MORE_RESTRICT_PAT_MODS "aa"
357 
358 /* This string is expected by regcomp.c to be ordered so that the first
359  * character is the flag in bit RXf_PMf_STD_PMMOD_SHIFT of extflags; the next
360  * character is bit +1, etc. */
361 #define STD_PAT_MODS        "msixxn"
362 
363 #define CHARSET_PAT_MODS    ASCII_RESTRICT_PAT_MODS DEPENDS_PAT_MODS LOCALE_PAT_MODS UNICODE_PAT_MODS
364 
365 /* This string is expected by XS_re_regexp_pattern() in universal.c to be ordered
366  * so that the first character is the flag in bit RXf_PMf_STD_PMMOD_SHIFT of
367  * extflags; the next character is in bit +1, etc. */
368 #define INT_PAT_MODS    STD_PAT_MODS    KEEPCOPY_PAT_MODS
369 
370 #define EXT_PAT_MODS    ONCE_PAT_MODS   KEEPCOPY_PAT_MODS  NOCAPTURE_PAT_MODS
371 #define QR_PAT_MODS     STD_PAT_MODS    EXT_PAT_MODS	   CHARSET_PAT_MODS
372 #define M_PAT_MODS      QR_PAT_MODS     LOOP_PAT_MODS
373 #define S_PAT_MODS      M_PAT_MODS      EXEC_PAT_MODS      NONDESTRUCT_PAT_MODS
374 
375 /*
376  * NOTE: if you modify any RXf flags you should run regen.pl or
377  * regen/regcomp.pl so that regnodes.h is updated with the changes.
378  *
379  */
380 
381 /*
382   Set in Perl_pmruntime for a split. Will be used by regex engines to
383   check whether they should set RXf_SKIPWHITE
384 */
385 #define RXf_SPLIT   RXf_PMf_SPLIT
386 
387 /* Currently the regex flags occupy a single 32-bit word.  Not all bits are
388  * currently used.  The lower bits are shared with their corresponding PMf flag
389  * bits, up to but not including _RXf_PMf_SHIFT_NEXT.  The unused bits
390  * immediately follow; finally the used RXf-only (unshared) bits, so that the
391  * highest bit in the word is used.  This gathers all the unused bits as a pool
392  * in the middle, like so: 11111111111111110000001111111111
393  * where the '1's represent used bits, and the '0's unused.  This design allows
394  * us to allocate off one end of the pool if we need to add a shared bit, and
395  * off the other end if we need a non-shared bit, without disturbing the other
396  * bits.  This maximizes the likelihood of being able to change things without
397  * breaking binary compatibility.
398  *
399  * To add shared bits, do so in op_reg_common.h.  This should change
400  * _RXf_PMf_SHIFT_NEXT so that things won't compile.  Then come to regexp.h and
401  * op.h and adjust the constant adders in the definitions of RXf_BASE_SHIFT and
402  * Pmf_BASE_SHIFT down by the number of shared bits you added.  That's it.
403  * Things should be binary compatible.  But if either of these gets to having
404  * to subtract rather than add, leave at 0 and instead adjust all the entries
405  * that are in terms of it.  But if the first one of those is already
406  * RXf_BASE_SHIFT+0, there are no bits left, and a redesign is in order.
407  *
408  * To remove unshared bits, just delete its entry.  If you're where breaking
409  * binary compatibility is ok to do, you might want to adjust things to move
410  * the newly opened space so that it gets absorbed into the common pool.
411  *
412  * To add unshared bits, first use up any gaps in the middle.  Otherwise,
413  * allocate off the low end until you get to RXf_BASE_SHIFT+0.  If that isn't
414  * enough, move RXf_BASE_SHIFT down (if possible) and add the new bit at the
415  * other end instead; this preserves binary compatibility.
416  *
417  * For the regexp bits, PL_reg_extflags_name[] in regnodes.h has a comment
418  * giving which bits are used/unused */
419 
420 #define RXf_BASE_SHIFT (_RXf_PMf_SHIFT_NEXT + 2)
421 
422 /* What we have seen */
423 #define RXf_NO_INPLACE_SUBST    (1U<<(RXf_BASE_SHIFT+2))
424 #define RXf_EVAL_SEEN   	(1U<<(RXf_BASE_SHIFT+3))
425 
426 /* Special */
427 #define RXf_UNBOUNDED_QUANTIFIER_SEEN   (1U<<(RXf_BASE_SHIFT+4))
428 #define RXf_CHECK_ALL   	(1U<<(RXf_BASE_SHIFT+5))
429 
430 /* UTF8 related */
431 #define RXf_MATCH_UTF8  	(1U<<(RXf_BASE_SHIFT+6)) /* $1 etc are utf8 */
432 
433 /* Intuit related */
434 #define RXf_USE_INTUIT_NOML	(1U<<(RXf_BASE_SHIFT+7))
435 #define RXf_USE_INTUIT_ML	(1U<<(RXf_BASE_SHIFT+8))
436 #define RXf_INTUIT_TAIL 	(1U<<(RXf_BASE_SHIFT+9))
437 #define RXf_USE_INTUIT		(RXf_USE_INTUIT_NOML|RXf_USE_INTUIT_ML)
438 
439 /* Do we have some sort of anchor? */
440 #define RXf_IS_ANCHORED         (1U<<(RXf_BASE_SHIFT+10))
441 
442 /* Copy and tainted info */
443 #define RXf_COPY_DONE   	(1U<<(RXf_BASE_SHIFT+11))
444 
445 /* post-execution: $1 et al are tainted */
446 #define RXf_TAINTED_SEEN	(1U<<(RXf_BASE_SHIFT+12))
447 /* this pattern was tainted during compilation */
448 #define RXf_TAINTED		(1U<<(RXf_BASE_SHIFT+13))
449 
450 /* Flags indicating special patterns */
451 #define RXf_START_ONLY		(1U<<(RXf_BASE_SHIFT+14)) /* Pattern is /^/ */
452 #define RXf_SKIPWHITE           (1U<<(RXf_BASE_SHIFT+15)) /* Pattern is for a */
453                                                           /* split " " */
454 #define RXf_WHITE		(1U<<(RXf_BASE_SHIFT+16)) /* Pattern is /\s+/ */
455 #define RXf_NULL		(1U<<(RXf_BASE_SHIFT+17)) /* Pattern is // */
456 
457 /* See comments at the beginning of these defines about adding bits.  The
458  * highest bit position should be used, so that if RXf_BASE_SHIFT gets
459  * increased, the #error below will be triggered so that you will be reminded
460  * to adjust things at the other end to keep the bit positions unchanged */
461 #if RXf_BASE_SHIFT+17 > 31
462 #   error Too many RXf_PMf bits used.  See comments at beginning of these for what to do
463 #endif
464 
465 /*
466  * NOTE: if you modify any RXf flags you should run regen.pl or
467  * regen/regcomp.pl so that regnodes.h is updated with the changes.
468  *
469  */
470 
471 #ifdef NO_TAINT_SUPPORT
472 #  define RX_ISTAINTED(rx_sv)           0
473 #  define RXp_ISTAINTED(prog)           0
474 #  define RX_TAINT_on(rx_sv)            NOOP
475 #  define RXp_MATCH_TAINTED(prog)       0
476 #  define RX_MATCH_TAINTED(rx_sv)       0
477 #  define RXp_MATCH_TAINTED_on(prog)    NOOP
478 #  define RX_MATCH_TAINTED_on(rx_sv)    NOOP
479 #  define RXp_MATCH_TAINTED_off(prog)   NOOP
480 #  define RX_MATCH_TAINTED_off(rx_sv)   NOOP
481 #else
482 #  define RX_ISTAINTED(rx_sv)           (RX_EXTFLAGS(rx_sv) & RXf_TAINTED)
483 #  define RXp_ISTAINTED(prog)           (RXp_EXTFLAGS(prog) & RXf_TAINTED)
484 #  define RX_TAINT_on(rx_sv)            (RX_EXTFLAGS(rx_sv) |= RXf_TAINTED)
485 #  define RXp_MATCH_TAINTED(prog)       (RXp_EXTFLAGS(prog) & RXf_TAINTED_SEEN)
486 #  define RX_MATCH_TAINTED(rx_sv)       (RX_EXTFLAGS(rx_sv) & RXf_TAINTED_SEEN)
487 #  define RXp_MATCH_TAINTED_on(prog)    (RXp_EXTFLAGS(prog) |= RXf_TAINTED_SEEN)
488 #  define RX_MATCH_TAINTED_on(rx_sv)    (RX_EXTFLAGS(rx_sv) |= RXf_TAINTED_SEEN)
489 #  define RXp_MATCH_TAINTED_off(prog)   (RXp_EXTFLAGS(prog) &= ~RXf_TAINTED_SEEN)
490 #  define RX_MATCH_TAINTED_off(rx_sv)   (RX_EXTFLAGS(rx_sv) &= ~RXf_TAINTED_SEEN)
491 #endif
492 
493 #define RXp_HAS_CUTGROUP(prog)          ((prog)->intflags & PREGf_CUTGROUP_SEEN)
494 
495 #define RX_MATCH_TAINTED_set(rx_sv, t)  ((t) \
496                                         ? RX_MATCH_TAINTED_on(rx_sv) \
497                                         : RX_MATCH_TAINTED_off(rx_sv))
498 
499 #define RXp_MATCH_COPIED(prog)          (RXp_EXTFLAGS(prog) & RXf_COPY_DONE)
500 #define RX_MATCH_COPIED(rx_sv)          (RX_EXTFLAGS(rx_sv) & RXf_COPY_DONE)
501 #define RXp_MATCH_COPIED_on(prog)       (RXp_EXTFLAGS(prog) |= RXf_COPY_DONE)
502 #define RX_MATCH_COPIED_on(rx_sv)       (RX_EXTFLAGS(rx_sv) |= RXf_COPY_DONE)
503 #define RXp_MATCH_COPIED_off(prog)      (RXp_EXTFLAGS(prog) &= ~RXf_COPY_DONE)
504 #define RX_MATCH_COPIED_off(rx_sv)      (RX_EXTFLAGS(rx_sv) &= ~RXf_COPY_DONE)
505 #define RX_MATCH_COPIED_set(rx_sv,t)    ((t) \
506                                          ? RX_MATCH_COPIED_on(rx_sv) \
507                                          : RX_MATCH_COPIED_off(rx_sv))
508 
509 #define RXp_EXTFLAGS(rx)                ((rx)->extflags)
510 #define RXp_COMPFLAGS(rx)               ((rx)->compflags)
511 
512 /* For source compatibility. We used to store these explicitly.  */
513 #define RX_PRECOMP(rx_sv)              (RX_WRAPPED(rx_sv) \
514                                             + ReANY(rx_sv)->pre_prefix)
515 #define RX_PRECOMP_const(rx_sv)        (RX_WRAPPED_const(rx_sv) \
516                                             + ReANY(rx_sv)->pre_prefix)
517 /* FIXME? Are we hardcoding too much here and constraining plugin extension
518    writers? Specifically, the value 1 assumes that the wrapped version always
519    has exactly one character at the end, a ')'. Will that always be true?  */
520 #define RX_PRELEN(rx_sv)                (RX_WRAPLEN(rx_sv) \
521                                             - ReANY(rx_sv)->pre_prefix - 1)
522 
523 #define RX_WRAPPED(rx_sv)               SvPVX(rx_sv)
524 #define RX_WRAPPED_const(rx_sv)         SvPVX_const(rx_sv)
525 #define RX_WRAPLEN(rx_sv)               SvCUR(rx_sv)
526 #define RX_CHECK_SUBSTR(rx_sv)          (ReANY(rx_sv)->check_substr)
527 #define RX_REFCNT(rx_sv)                SvREFCNT(rx_sv)
528 #define RX_EXTFLAGS(rx_sv)              RXp_EXTFLAGS(ReANY(rx_sv))
529 #define RX_COMPFLAGS(rx_sv)             RXp_COMPFLAGS(ReANY(rx_sv))
530 #define RXp_ENGINE(prog)                ((prog)->engine)
531 #define RX_ENGINE(rx_sv)                (RXp_ENGINE(ReANY(rx_sv)))
532 #define RXp_SUBBEG(prog)                (prog->subbeg)
533 #define RX_SUBBEG(rx_sv)                (RXp_SUBBEG(ReANY(rx_sv)))
534 #define RXp_SUBOFFSET(prog)             (prog->suboffset)
535 #define RX_SUBOFFSET(rx_sv)             (RXp_SUBOFFSET(ReANY(rx_sv)))
536 #define RX_SUBCOFFSET(rx_sv)            (ReANY(rx_sv)->subcoffset)
537 #define RXp_OFFS(prog)                  (prog->offs)
538 #define RX_OFFS(rx_sv)                  (RXp_OFFS(ReANY(rx_sv)))
539 #define RXp_NPARENS(prog)               (prog->nparens)
540 #define RX_NPARENS(rx_sv)               (RXp_NPARENS(ReANY(rx_sv)))
541 #define RX_SUBLEN(rx_sv)                (ReANY(rx_sv)->sublen)
542 #define RXp_MINLEN(prog)                (prog->minlen)
543 #define RX_MINLEN(rx_sv)                (RXp_MINLEN(ReANY(rx_sv)))
544 #define RXp_MINLENRET(prog)             (prog->minlenret)
545 #define RX_MINLENRET(rx_sv)             (RXp_MINLENRET(ReANY(rx_sv)))
546 #define RXp_GOFS(prog)                  (prog->gofs)
547 #define RX_GOFS(rx_sv)                  (RXp_GOFS(ReANY(rx_sv)))
548 #define RX_LASTPAREN(rx_sv)             (ReANY(rx_sv)->lastparen)
549 #define RX_LASTCLOSEPAREN(rx_sv)        (ReANY(rx_sv)->lastcloseparen)
550 #define RXp_SAVED_COPY(prog)            (prog->saved_copy)
551 #define RX_SAVED_COPY(rx_sv)            (RXp_SAVED_COPY(ReANY(rx_sv)))
552 /* last match was zero-length */
553 #define RXp_ZERO_LEN(prog) \
554         (RXp_OFFS(prog)[0].start + (SSize_t)RXp_GOFS(prog) \
555           == RXp_OFFS(prog)[0].end)
556 #define RX_ZERO_LEN(rx_sv)              (RXp_ZERO_LEN(ReANY(rx_sv)))
557 
558 #endif /* PLUGGABLE_RE_EXTENSION */
559 
560 /* Stuff that needs to be included in the pluggable extension goes below here */
561 
562 #ifdef PERL_ANY_COW
563 #define RXp_MATCH_COPY_FREE(prog) \
564 	STMT_START {if (RXp_SAVED_COPY(prog)) { \
565 	    SV_CHECK_THINKFIRST_COW_DROP(RXp_SAVED_COPY(prog)); \
566 	} \
567 	if (RXp_MATCH_COPIED(prog)) { \
568 	    Safefree(RXp_SUBBEG(prog)); \
569 	    RXp_MATCH_COPIED_off(prog); \
570 	}} STMT_END
571 #else
572 #define RXp_MATCH_COPY_FREE(prog) \
573 	STMT_START {if (RXp_MATCH_COPIED(prog)) { \
574 	    Safefree(RXp_SUBBEG(prog)); \
575 	    RXp_MATCH_COPIED_off(prog); \
576 	}} STMT_END
577 #endif
578 #define RX_MATCH_COPY_FREE(rx_sv)       RXp_MATCH_COPY_FREE(ReANY(rx_sv))
579 
580 #define RXp_MATCH_UTF8(prog)            (RXp_EXTFLAGS(prog) & RXf_MATCH_UTF8)
581 #define RX_MATCH_UTF8(rx_sv)            (RX_EXTFLAGS(rx_sv) & RXf_MATCH_UTF8)
582 #define RXp_MATCH_UTF8_on(prog)         (RXp_EXTFLAGS(prog) |= RXf_MATCH_UTF8)
583 #define RX_MATCH_UTF8_on(rx_sv)         (RXp_MATCH_UTF8_on(ReANY(rx_sv)))
584 #define RXp_MATCH_UTF8_off(prog)        (RXp_EXTFLAGS(prog) &= ~RXf_MATCH_UTF8)
585 #define RX_MATCH_UTF8_off(rx_sv)        (RXp_MATCH_UTF8_off(ReANY(rx_sv))
586 #define RXp_MATCH_UTF8_set(prog, t)     ((t) \
587                                         ? RXp_MATCH_UTF8_on(prog) \
588                                         : RXp_MATCH_UTF8_off(prog))
589 #define RX_MATCH_UTF8_set(rx_sv, t)     (RXp_MATCH_UTF8_set(ReANY(rx_sv), t))
590 
591 /* Whether the pattern stored at RX_WRAPPED is in UTF-8  */
592 #define RX_UTF8(rx_sv)                  SvUTF8(rx_sv)
593 
594 
595 /* bits in flags arg of Perl_regexec_flags() */
596 
597 #define REXEC_COPY_STR  0x01    /* Need to copy the string for captures. */
598 #define REXEC_CHECKED   0x02    /* re_intuit_start() already called. */
599 #define REXEC_SCREAM    0x04    /* currently unused. */
600 #define REXEC_IGNOREPOS 0x08    /* use stringarg, not pos(), for \G match */
601 #define REXEC_NOT_FIRST 0x10    /* This is another iteration of //g:
602                                    no need to copy string again */
603 
604                                      /* under REXEC_COPY_STR, it's ok for the
605                                         engine (modulo PL_sawamperand etc)
606                                         to skip copying: ... */
607 #define REXEC_COPY_SKIP_PRE  0x20    /* ...the $` part of the string, or */
608 #define REXEC_COPY_SKIP_POST 0x40    /* ...the $' part of the string */
609 #define REXEC_FAIL_ON_UNDERFLOW 0x80 /* fail the match if $& would start before
610                                         the start pos (so s/.\G// would fail
611                                         on second iteration */
612 
613 #if defined(__GNUC__) && !defined(PERL_GCC_BRACE_GROUPS_FORBIDDEN)
614 #  define ReREFCNT_inc(re)						\
615     ({									\
616 	/* This is here to generate a casting warning if incorrect.  */	\
617 	REGEXP *const _rerefcnt_inc = (re);				\
618 	assert(SvTYPE(_rerefcnt_inc) == SVt_REGEXP);			\
619 	SvREFCNT_inc(_rerefcnt_inc);					\
620 	_rerefcnt_inc;							\
621     })
622 #  define ReREFCNT_dec(re)						\
623     ({									\
624 	/* This is here to generate a casting warning if incorrect.  */	\
625 	REGEXP *const _rerefcnt_dec = (re);				\
626 	SvREFCNT_dec(_rerefcnt_dec);					\
627     })
628 #else
629 #  define ReREFCNT_dec(re)	SvREFCNT_dec(re)
630 #  define ReREFCNT_inc(re)	((REGEXP *) SvREFCNT_inc(re))
631 #endif
632 #define ReANY(re)		S_ReANY((const REGEXP *)(re))
633 
634 /* FIXME for plugins. */
635 
636 #define FBMcf_TAIL_DOLLAR	1
637 #define FBMcf_TAIL_DOLLARM	2
638 #define FBMcf_TAIL_Z		4
639 #define FBMcf_TAIL_z		8
640 #define FBMcf_TAIL		(FBMcf_TAIL_DOLLAR|FBMcf_TAIL_DOLLARM|FBMcf_TAIL_Z|FBMcf_TAIL_z)
641 
642 #define FBMrf_MULTILINE	1
643 
644 struct regmatch_state;
645 struct regmatch_slab;
646 
647 /* like regmatch_info_aux, but contains extra fields only needed if the
648  * pattern contains (?{}). If used, is snuck into the second slot in the
649  * regmatch_state stack at the start of execution */
650 
651 typedef struct {
652     regexp *rex;
653     PMOP    *curpm;     /* saved PL_curpm */
654 #ifdef PERL_ANY_COW
655     SV      *saved_copy; /* saved saved_copy field from rex */
656 #endif
657     char    *subbeg;    /* saved subbeg     field from rex */
658     STRLEN  sublen;     /* saved sublen     field from rex */
659     STRLEN  suboffset;  /* saved suboffset  field from rex */
660     STRLEN  subcoffset; /* saved subcoffset field from rex */
661     SV      *sv;        /* $_  during (?{}) */
662     MAGIC   *pos_magic; /* pos() magic attached to $_ */
663     SSize_t pos;        /* the original value of pos() in pos_magic */
664     U8      pos_flags;  /* flags to be restored; currently only MGf_BYTES*/
665 } regmatch_info_aux_eval;
666 
667 
668 /* fields that logically  live in regmatch_info, but which need cleaning
669  * up on croak(), and so are instead are snuck into the first slot in
670  * the regmatch_state stack at the start of execution */
671 
672 typedef struct {
673     regmatch_info_aux_eval *info_aux_eval;
674     struct regmatch_state *old_regmatch_state; /* saved PL_regmatch_state */
675     struct regmatch_slab  *old_regmatch_slab;  /* saved PL_regmatch_slab */
676     char *poscache;	/* S-L cache of fail positions of WHILEMs */
677 } regmatch_info_aux;
678 
679 
680 /* some basic information about the current match that is created by
681  * Perl_regexec_flags and then passed to regtry(), regmatch() etc.
682  * It is allocated as a local var on the stack, so nothing should be
683  * stored in it that needs preserving or clearing up on croak().
684  * For that, see the aux_info and aux_info_eval members of the
685  * regmatch_state union. */
686 
687 typedef struct {
688     REGEXP *prog;        /* the regex being executed */
689     const char * strbeg; /* real start of string */
690     char *strend;        /* one byte beyond last char of match string */
691     char *till;          /* matches shorter than this fail (see minlen arg) */
692     SV *sv;              /* the SV string currently being matched */
693     char *ganch;         /* position of \G anchor */
694     char *cutpoint;      /* (*COMMIT) position (if any) */
695     regmatch_info_aux      *info_aux; /* extra fields that need cleanup */
696     regmatch_info_aux_eval *info_aux_eval; /* extra saved state for (?{}) */
697     I32  poscache_maxiter; /* how many whilems todo before S-L cache kicks in */
698     I32  poscache_iter;    /* current countdown from _maxiter to zero */
699     STRLEN poscache_size;  /* size of regmatch_info_aux.poscache */
700     bool intuit;    /* re_intuit_start() is the top-level caller */
701     bool is_utf8_pat;    /* regex is utf8 */
702     bool is_utf8_target; /* string being matched is utf8 */
703     bool warned; /* we have issued a recursion warning; no need for more */
704 } regmatch_info;
705 
706 
707 /* structures for holding and saving the state maintained by regmatch() */
708 
709 #ifndef MAX_RECURSE_EVAL_NOCHANGE_DEPTH
710 #define MAX_RECURSE_EVAL_NOCHANGE_DEPTH 10
711 #endif
712 
713 typedef I32 CHECKPOINT;
714 
715 typedef struct regmatch_state {
716     int resume_state;		/* where to jump to on return */
717     char *locinput;		/* where to backtrack in string on failure */
718     char *loceol;
719     U8 *sr0;                    /* position of start of script run, or NULL */
720 
721     union {
722 
723         /* the 'info_aux' and 'info_aux_eval' union members are cuckoos in
724          * the nest. They aren't saved backtrack state; rather they
725          * represent one or two extra chunks of data that need allocating
726          * at the start of a match. These fields would logically live in
727          * the regmatch_info struct, except that is allocated on the
728          * C stack, and these fields are all things that require cleanup
729          * after a croak(), when the stack is lost.
730          * As a convenience, we just use the first 1 or 2 regmatch_state
731          * slots to store this info, as we will be allocating a slab of
732          * these anyway. Otherwise we'd have to malloc and then free them,
733          * or allocate them on the save stack (where they will get
734          * realloced if the save stack grows).
735          * info_aux contains the extra fields that are always needed;
736          * info_aux_eval contains extra fields that only needed if
737          * the pattern contains code blocks
738          * We split them into two separate structs to avoid increasing
739          * the size of the union.
740          */
741 
742         regmatch_info_aux info_aux;
743 
744         regmatch_info_aux_eval info_aux_eval;
745 
746 	/* this is a fake union member that matches the first element
747 	 * of each member that needs to store positive backtrack
748 	 * information */
749 	struct {
750 	    struct regmatch_state *prev_yes_state;
751 	} yes;
752 
753         /* branchlike members */
754         /* this is a fake union member that matches the first elements
755          * of each member that needs to behave like a branch */
756         struct {
757 	    /* this first element must match u.yes */
758 	    struct regmatch_state *prev_yes_state;
759 	    U32 lastparen;
760 	    U32 lastcloseparen;
761 	    CHECKPOINT cp;
762 
763         } branchlike;
764 
765 	struct {
766 	    /* the first elements must match u.branchlike */
767 	    struct regmatch_state *prev_yes_state;
768 	    U32 lastparen;
769 	    U32 lastcloseparen;
770 	    CHECKPOINT cp;
771 
772 	    regnode *next_branch; /* next branch node */
773 	} branch;
774 
775 	struct {
776 	    /* the first elements must match u.branchlike */
777 	    struct regmatch_state *prev_yes_state;
778 	    U32 lastparen;
779 	    U32 lastcloseparen;
780 	    CHECKPOINT cp;
781 
782 	    U32		accepted; /* how many accepting states left */
783 	    bool	longfold;/* saw a fold with a 1->n char mapping */
784 	    U16         *jump;  /* positive offsets from me */
785 	    regnode	*me;	/* Which node am I - needed for jump tries*/
786 	    U8		*firstpos;/* pos in string of first trie match */
787 	    U32		firstchars;/* len in chars of firstpos from start */
788 	    U16		nextword;/* next word to try */
789 	    U16		topword; /* longest accepted word */
790 	} trie;
791 
792         /* special types - these members are used to store state for special
793            regops like eval, if/then, lookaround and the markpoint state */
794 	struct {
795 	    /* this first element must match u.yes */
796 	    struct regmatch_state *prev_yes_state;
797 	    struct regmatch_state *prev_curlyx;
798             struct regmatch_state *prev_eval;
799 	    REGEXP	*prev_rex;
800 	    CHECKPOINT	cp;	/* remember current savestack indexes */
801 	    CHECKPOINT	lastcp;
802             U32         close_paren; /* which close bracket is our end (+1) */
803 	    regnode	*B;	/* the node following us  */
804             char        *prev_recurse_locinput;
805 	} eval;
806 
807 	struct {
808 	    /* this first element must match u.yes */
809 	    struct regmatch_state *prev_yes_state;
810 	    I32 wanted;
811 	    I32 logical;	/* saved copy of 'logical' var */
812             U8  count;          /* number of beginning positions */
813             char *start;
814             char *end;
815 	    regnode  *me; /* the IFMATCH/SUSPEND/UNLESSM node  */
816 	} ifmatch; /* and SUSPEND/UNLESSM */
817 
818 	struct {
819 	    /* this first element must match u.yes */
820 	    struct regmatch_state *prev_yes_state;
821 	    struct regmatch_state *prev_mark;
822 	    SV* mark_name;
823 	    char *mark_loc;
824 	} mark;
825 
826 	struct {
827 	    int val;
828 	} keeper;
829 
830         /* quantifiers - these members are used for storing state for
831            for the regops used to implement quantifiers */
832 	struct {
833 	    /* this first element must match u.yes */
834 	    struct regmatch_state *prev_yes_state;
835 	    struct regmatch_state *prev_curlyx; /* previous cur_curlyx */
836 	    regnode	*me;	/* the CURLYX node  */
837 	    regnode	*B;	/* the B node in /A*B/  */
838 	    CHECKPOINT	cp;	/* remember current savestack index */
839 	    bool	minmod;
840 	    int		parenfloor;/* how far back to strip paren data */
841 
842 	    /* these two are modified by WHILEM */
843 	    int		count;	/* how many instances of A we've matched */
844 	    char	*lastloc;/* where previous A matched (0-len detect) */
845 	} curlyx;
846 
847 	struct {
848 	    /* this first element must match u.yes */
849 	    struct regmatch_state *prev_yes_state;
850 	    struct regmatch_state *save_curlyx;
851 	    CHECKPOINT	cp;	/* remember current savestack indexes */
852 	    CHECKPOINT	lastcp;
853 	    char	*save_lastloc;	/* previous curlyx.lastloc */
854 	    I32		cache_offset;
855 	    I32		cache_mask;
856 	} whilem;
857 
858 	struct {
859 	    /* this first element must match u.yes */
860 	    struct regmatch_state *prev_yes_state;
861 	    int c1, c2;		/* case fold search */
862 	    CHECKPOINT cp;
863 	    U32 lastparen;
864 	    U32 lastcloseparen;
865 	    I32 alen;		/* length of first-matched A string */
866 	    I32 count;
867 	    bool minmod;
868 	    regnode *A, *B;	/* the nodes corresponding to /A*B/  */
869 	    regnode *me;	/* the curlym node */
870             U8 c1_utf8[UTF8_MAXBYTES+1];  /* */
871             U8 c2_utf8[UTF8_MAXBYTES+1];
872 	} curlym;
873 
874 	struct {
875 	    U32 paren;
876 	    CHECKPOINT cp;
877 	    U32 lastparen;
878 	    U32 lastcloseparen;
879 	    int c1, c2;		/* case fold search */
880 	    char *maxpos;	/* highest possible point in string to match */
881 	    char *oldloc;	/* the previous locinput */
882 	    int count;
883 	    int min, max;	/* {m,n} */
884 	    regnode *A, *B;	/* the nodes corresponding to /A*B/  */
885             U8 c1_utf8[UTF8_MAXBYTES+1];  /* */
886             U8 c2_utf8[UTF8_MAXBYTES+1];
887 	} curly; /* and CURLYN/PLUS/STAR */
888 
889     } u;
890 } regmatch_state;
891 
892 
893 
894 /* how many regmatch_state structs to allocate as a single slab.
895  * We do it in 4K blocks for efficiency. The "3" is 2 for the next/prev
896  * pointers, plus 1 for any mythical malloc overhead. */
897 
898 #define PERL_REGMATCH_SLAB_SLOTS \
899     ((4096 - 3 * sizeof (void*)) / sizeof(regmatch_state))
900 
901 typedef struct regmatch_slab {
902     regmatch_state states[PERL_REGMATCH_SLAB_SLOTS];
903     struct regmatch_slab *prev, *next;
904 } regmatch_slab;
905 
906 
907 
908 /*
909  * ex: set ts=8 sts=4 sw=4 et:
910  */
911