1 /*************************************************
2 * Perl-Compatible Regular Expressions *
3 *************************************************/
5 /* PCRE is a library of functions to support regular expressions whose syntax
6 and semantics are as close as possible to those of the Perl 5 language.
8 Written by Philip Hazel
9 Copyright (c) 1997-2010 University of Cambridge
11 -----------------------------------------------------------------------------
12 Redistribution and use in source and binary forms, with or without
13 modification, are permitted provided that the following conditions are met:
15 * Redistributions of source code must retain the above copyright notice,
16 this list of conditions and the following disclaimer.
18 * Redistributions in binary form must reproduce the above copyright
19 notice, this list of conditions and the following disclaimer in the
20 documentation and/or other materials provided with the distribution.
22 * Neither the name of the University of Cambridge nor the names of its
23 contributors may be used to endorse or promote products derived from
24 this software without specific prior written permission.
26 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
27 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
30 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 POSSIBILITY OF SUCH DAMAGE.
37 -----------------------------------------------------------------------------
41 /* This module contains the external function pcre_study(), along with local
42 supporting functions. */
49 #include "pcre_internal.h"
51 #define SET_BIT(c) start_bits[c/8] |= (1 << (c&7))
53 /* Returns from set_start_bits() */
55 enum { SSB_FAIL, SSB_DONE, SSB_CONTINUE };
59 /*************************************************
60 * Find the minimum subject length for a group *
61 *************************************************/
63 /* Scan a parenthesized group and compute the minimum length of subject that
64 is needed to match it. This is a lower bound; it does not mean there is a
65 string of that length that matches. In UTF8 mode, the result is in characters
69 code pointer to start of group (the bracket)
70 startcode pointer to start of the whole pattern
71 options the compiling options
73 Returns: the minimum length
74 -1 if \C was encountered
75 -2 internal error (missing capturing bracket)
79 find_minlength(const uschar *code, const uschar *startcode, int options)
82 BOOL utf8 = (options & PCRE_UTF8) != 0;
83 BOOL had_recurse = FALSE;
84 register int branchlength = 0;
85 register uschar *cc = (uschar *)code + 1 + LINK_SIZE;
87 if (*code == OP_CBRA || *code == OP_SCBRA) cc += 2;
89 /* Scan along the opcodes for this branch. If we get to the end of the
90 branch, check the length against that of the other branches. */
96 register int op = *cc;
103 /* If there is only one branch in a condition, the implied branch has zero
104 length, so we don't add anything. This covers the DEFINE "condition"
107 cs = cc + GET(cc, 1);
110 cc = cs + 1 + LINK_SIZE;
114 /* Otherwise we can fall through and treat it the same as any other
122 d = find_minlength(cc, startcode, options);
125 do cc += GET(cc, 1); while (*cc == OP_ALT);
129 /* Reached end of a branch; if it's a ket it is the end of a nested
130 call. If it's ALT it is an alternation in a nested call. If it is
131 END it's the end of the outer call. All can be handled by the same code. */
138 if (length < 0 || (!had_recurse && branchlength < length))
139 length = branchlength;
140 if (*cc != OP_ALT) return length;
146 /* Skip over assertive subpatterns */
151 case OP_ASSERTBACK_NOT:
152 do cc += GET(cc, 1); while (*cc == OP_ALT);
155 /* Skip over things that don't match chars */
171 case OP_NOT_WORD_BOUNDARY:
172 case OP_WORD_BOUNDARY:
173 cc += _pcre_OP_lengths[*cc];
176 /* Skip over a subpattern that has a {0} or {0,x} quantifier */
181 cc += _pcre_OP_lengths[*cc];
182 do cc += GET(cc, 1); while (*cc == OP_ALT);
186 /* Handle literal characters and + repetitions */
200 if (utf8 && cc[-1] >= 0xc0) cc += _pcre_utf8_table4[cc[-1] & 0x3f];
208 cc += (cc[1] == OP_PROP || cc[1] == OP_NOTPROP)? 4 : 2;
211 /* Handle exact repetitions. The count is already in characters, but we
212 need to skip over a multibyte character in UTF8 mode. */
216 branchlength += GET2(cc,1);
219 if (utf8 && cc[-1] >= 0xc0) cc += _pcre_utf8_table4[cc[-1] & 0x3f];
224 branchlength += GET2(cc,1);
225 cc += (cc[3] == OP_PROP || cc[3] == OP_NOTPROP)? 6 : 4;
228 /* Handle single-char non-literal matchers */
237 case OP_NOT_WHITESPACE:
239 case OP_NOT_WORDCHAR:
252 /* "Any newline" might match two characters */
259 /* The single-byte matcher means we can't proceed in UTF-8 mode */
269 /* For repeated character types, we have to test for \p and \P, which have
270 an extra two bytes of parameters. */
275 case OP_TYPEMINQUERY:
277 case OP_TYPEPOSQUERY:
278 if (cc[1] == OP_PROP || cc[1] == OP_NOTPROP) cc += 2;
279 cc += _pcre_OP_lengths[op];
285 if (cc[3] == OP_PROP || cc[3] == OP_NOTPROP) cc += 2;
286 cc += _pcre_OP_lengths[op];
289 /* Check a class for variable quantification */
293 cc += GET(cc, 1) - 33;
317 branchlength += GET2(cc,1);
327 /* Backreferences and subroutine calls are treated in the same way: we find
328 the minimum length for the subpattern. A recursion, however, causes an
329 a flag to be set that causes the length of this branch to be ignored. The
330 logic is that a recursion can only make sense if there is another
331 alternation that stops the recursing. That will provide the minimum length
332 (when no recursion happens). A backreference within the group that it is
333 referencing behaves in the same way.
335 If PCRE_JAVASCRIPT_COMPAT is set, a backreference to an unset bracket
336 matches an empty string (by default it causes a matching failure), so in
337 that case we must set the minimum length to zero. */
340 if ((options & PCRE_JAVASCRIPT_COMPAT) == 0)
342 ce = cs = (uschar *)_pcre_find_bracket(startcode, utf8, GET2(cc, 1));
343 if (cs == NULL) return -2;
344 do ce += GET(ce, 1); while (*ce == OP_ALT);
345 if (cc > cs && cc < ce)
350 else d = find_minlength(cs, startcode, options);
355 /* Handle repeated back references */
378 branchlength += min * d;
382 cs = ce = (uschar *)startcode + GET(cc, 1);
383 if (cs == NULL) return -2;
384 do ce += GET(ce, 1); while (*ce == OP_ALT);
385 if (cc > cs && cc < ce)
388 branchlength += find_minlength(cs, startcode, options);
392 /* Anything else does not or need not match a character. We can get the
393 item's length from the table, but for those that can match zero occurrences
394 of a character, we must take special action for UTF-8 characters. */
411 cc += _pcre_OP_lengths[op];
413 if (utf8 && cc[-1] >= 0xc0) cc += _pcre_utf8_table4[cc[-1] & 0x3f];
417 /* Skip these, but we need to add in the name length. */
422 cc += _pcre_OP_lengths[op] + cc[1];
426 cc += _pcre_OP_lengths[op] + cc[1+LINK_SIZE];
429 /* For the record, these are the opcodes that are matched by "default":
430 OP_ACCEPT, OP_CLOSE, OP_COMMIT, OP_FAIL, OP_PRUNE, OP_SET_SOM, OP_SKIP,
434 cc += _pcre_OP_lengths[op];
438 /* Control never gets here */
443 /*************************************************
444 * Set a bit and maybe its alternate case *
445 *************************************************/
447 /* Given a character, set its first byte's bit in the table, and also the
448 corresponding bit for the other version of a letter if we are caseless. In
449 UTF-8 mode, for characters greater than 127, we can only do the caseless thing
450 when Unicode property support is available.
453 start_bits points to the bit map
454 p points to the character
455 caseless the caseless flag
456 cd the block with char table pointers
457 utf8 TRUE for UTF-8 mode
459 Returns: pointer after the character
462 static const uschar *
463 set_table_bit(uschar *start_bits, const uschar *p, BOOL caseless,
464 compile_data *cd, BOOL utf8)
478 c = UCD_OTHERCASE(c);
479 (void)_pcre_ord2utf8(c, buff);
487 /* Not UTF-8 mode, or character is less than 127. */
489 if (caseless && (cd->ctypes[c] & ctype_letter) != 0) SET_BIT(cd->fcc[c]);
495 /*************************************************
496 * Set bits for a positive character type *
497 *************************************************/
499 /* This function sets starting bits for a character type. In UTF-8 mode, we can
500 only do a direct setting for bytes less than 128, as otherwise there can be
501 confusion with bytes in the middle of UTF-8 characters. In a "traditional"
502 environment, the tables will only recognize ASCII characters anyway, but in at
503 least one Windows environment, some higher bytes bits were set in the tables.
504 So we deal with that case by considering the UTF-8 encoding.
507 start_bits the starting bitmap
508 cbit type the type of character wanted
509 table_limit 32 for non-UTF-8; 16 for UTF-8
510 cd the block with char table pointers
516 set_type_bits(uschar *start_bits, int cbit_type, int table_limit,
520 for (c = 0; c < table_limit; c++) start_bits[c] |= cd->cbits[c+cbit_type];
521 if (table_limit == 32) return;
522 for (c = 128; c < 256; c++)
524 if ((cd->cbits[c/8] & (1 << (c&7))) != 0)
527 (void)_pcre_ord2utf8(c, buff);
534 /*************************************************
535 * Set bits for a negative character type *
536 *************************************************/
538 /* This function sets starting bits for a negative character type such as \D.
539 In UTF-8 mode, we can only do a direct setting for bytes less than 128, as
540 otherwise there can be confusion with bytes in the middle of UTF-8 characters.
541 Unlike in the positive case, where we can set appropriate starting bits for
542 specific high-valued UTF-8 characters, in this case we have to set the bits for
543 all high-valued characters. The lowest is 0xc2, but we overkill by starting at
544 0xc0 (192) for simplicity.
547 start_bits the starting bitmap
548 cbit type the type of character wanted
549 table_limit 32 for non-UTF-8; 16 for UTF-8
550 cd the block with char table pointers
556 set_nottype_bits(uschar *start_bits, int cbit_type, int table_limit,
560 for (c = 0; c < table_limit; c++) start_bits[c] |= ~cd->cbits[c+cbit_type];
561 if (table_limit != 32) for (c = 24; c < 32; c++) start_bits[c] = 0xff;
566 /*************************************************
567 * Create bitmap of starting bytes *
568 *************************************************/
570 /* This function scans a compiled unanchored expression recursively and
571 attempts to build a bitmap of the set of possible starting bytes. As time goes
572 by, we may be able to get more clever at doing this. The SSB_CONTINUE return is
573 useful for parenthesized groups in patterns such as (a*)b where the group
574 provides some optional starting bytes but scanning must continue at the outer
575 level to find at least one mandatory byte. At the outermost level, this
576 function fails unless the result is SSB_DONE.
579 code points to an expression
580 start_bits points to a 32-byte table, initialized to 0
581 caseless the current state of the caseless flag
582 utf8 TRUE if in UTF-8 mode
583 cd the block with char table pointers
585 Returns: SSB_FAIL => Failed to find any starting bytes
586 SSB_DONE => Found mandatory starting bytes
587 SSB_CONTINUE => Found optional starting bytes
591 set_start_bits(const uschar *code, uschar *start_bits, BOOL caseless,
592 BOOL utf8, compile_data *cd)
595 int yield = SSB_DONE;
596 int table_limit = utf8? 16:32;
599 /* ========================================================================= */
600 /* The following comment and code was inserted in January 1999. In May 2006,
601 when it was observed to cause compiler warnings about unused values, I took it
602 out again. If anybody is still using OS/2, they will have to put it back
605 /* This next statement and the later reference to dummy are here in order to
606 trick the optimizer of the IBM C compiler for OS/2 into generating correct
607 code. Apparently IBM isn't going to fix the problem, and we would rather not
608 disable optimization (in this module it actually makes a big difference, and
609 the pcre module can use all the optimization it can get). */
612 /* ========================================================================= */
617 const uschar *tcode = code + (((int)*code == OP_CBRA)? 3:1) + LINK_SIZE;
618 BOOL try_next = TRUE;
620 while (try_next) /* Loop for items in this branch */
625 /* Fail if we reach something we don't understand */
630 /* If we hit a bracket or a positive lookahead assertion, recurse to set
631 bits from within the subpattern. If it can't find anything, we have to
632 give up. If it finds some mandatory character(s), we are done for this
633 branch. Otherwise, carry on scanning after the subpattern. */
641 rc = set_start_bits(tcode, start_bits, caseless, utf8, cd);
642 if (rc == SSB_FAIL) return SSB_FAIL;
643 if (rc == SSB_DONE) try_next = FALSE; else
645 do tcode += GET(tcode, 1); while (*tcode == OP_ALT);
646 tcode += 1 + LINK_SIZE;
650 /* If we hit ALT or KET, it means we haven't found anything mandatory in
651 this branch, though we might have found something optional. For ALT, we
652 continue with the next alternative, but we have to arrange that the final
653 result from subpattern is SSB_CONTINUE rather than SSB_DONE. For KET,
654 return SSB_CONTINUE: if this is the top level, that indicates failure,
655 but after a nested subpattern, it causes scanning to continue. */
658 yield = SSB_CONTINUE;
667 /* Skip over callout */
670 tcode += 2 + 2*LINK_SIZE;
673 /* Skip over lookbehind and negative lookahead assertions */
677 case OP_ASSERTBACK_NOT:
678 do tcode += GET(tcode, 1); while (*tcode == OP_ALT);
679 tcode += 1 + LINK_SIZE;
682 /* Skip over an option setting, changing the caseless flag */
685 caseless = (tcode[1] & PCRE_CASELESS) != 0;
689 /* BRAZERO does the bracket, but carries on. */
693 if (set_start_bits(++tcode, start_bits, caseless, utf8, cd) == SSB_FAIL)
695 /* =========================================================================
696 See the comment at the head of this function concerning the next line,
697 which was an old fudge for the benefit of OS/2.
699 ========================================================================= */
700 do tcode += GET(tcode,1); while (*tcode == OP_ALT);
701 tcode += 1 + LINK_SIZE;
704 /* SKIPZERO skips the bracket. */
708 do tcode += GET(tcode,1); while (*tcode == OP_ALT);
709 tcode += 1 + LINK_SIZE;
712 /* Single-char * or ? sets the bit and tries the next item */
720 tcode = set_table_bit(start_bits, tcode + 1, caseless, cd, utf8);
723 /* Single-char upto sets the bit and tries the next */
728 tcode = set_table_bit(start_bits, tcode + 3, caseless, cd, utf8);
731 /* At least one single char sets the bit and stops */
733 case OP_EXACT: /* Fall through */
741 (void)set_table_bit(start_bits, tcode + 1, caseless, cd, utf8);
745 /* Special spacing and line-terminating items. These recognize specific
746 lists of characters. The difference between VSPACE and ANYNL is that the
747 latter can match the two-character CRLF sequence, but that is not
748 relevant for finding the first character, so their code here is
756 SET_BIT(0xC2); /* For U+00A0 */
757 SET_BIT(0xE1); /* For U+1680, U+180E */
758 SET_BIT(0xE2); /* For U+2000 - U+200A, U+202F, U+205F */
759 SET_BIT(0xE3); /* For U+3000 */
773 SET_BIT(0xC2); /* For U+0085 */
774 SET_BIT(0xE2); /* For U+2028, U+2029 */
780 /* Single character types set the bits and stop. Note that if PCRE_UCP
781 is set, we do not see these op codes because \d etc are converted to
782 properties. Therefore, these apply in the case when only characters less
783 than 256 are recognized to match the types. */
786 set_nottype_bits(start_bits, cbit_digit, table_limit, cd);
791 set_type_bits(start_bits, cbit_digit, table_limit, cd);
795 /* The cbit_space table has vertical tab as whitespace; we have to
796 ensure it is set as not whitespace. */
798 case OP_NOT_WHITESPACE:
799 set_nottype_bits(start_bits, cbit_space, table_limit, cd);
800 start_bits[1] |= 0x08;
804 /* The cbit_space table has vertical tab as whitespace; we have to
805 not set it from the table. */
808 c = start_bits[1]; /* Save in case it was already set */
809 set_type_bits(start_bits, cbit_space, table_limit, cd);
810 start_bits[1] = (start_bits[1] & ~0x08) | c;
814 case OP_NOT_WORDCHAR:
815 set_nottype_bits(start_bits, cbit_word, table_limit, cd);
820 set_type_bits(start_bits, cbit_word, table_limit, cd);
824 /* One or more character type fudges the pointer and restarts, knowing
825 it will hit a single character type and stop there. */
837 /* Zero or more repeats of character types set the bits and then
843 tcode += 2; /* Fall through */
849 case OP_TYPEMINQUERY:
850 case OP_TYPEPOSQUERY:
863 SET_BIT(0xC2); /* For U+00A0 */
864 SET_BIT(0xE1); /* For U+1680, U+180E */
865 SET_BIT(0xE2); /* For U+2000 - U+200A, U+202F, U+205F */
866 SET_BIT(0xE3); /* For U+3000 */
879 SET_BIT(0xC2); /* For U+0085 */
880 SET_BIT(0xE2); /* For U+2028, U+2029 */
886 set_nottype_bits(start_bits, cbit_digit, table_limit, cd);
890 set_type_bits(start_bits, cbit_digit, table_limit, cd);
893 /* The cbit_space table has vertical tab as whitespace; we have to
894 ensure it gets set as not whitespace. */
896 case OP_NOT_WHITESPACE:
897 set_nottype_bits(start_bits, cbit_space, table_limit, cd);
898 start_bits[1] |= 0x08;
901 /* The cbit_space table has vertical tab as whitespace; we have to
905 c = start_bits[1]; /* Save in case it was already set */
906 set_type_bits(start_bits, cbit_space, table_limit, cd);
907 start_bits[1] = (start_bits[1] & ~0x08) | c;
910 case OP_NOT_WORDCHAR:
911 set_nottype_bits(start_bits, cbit_word, table_limit, cd);
915 set_type_bits(start_bits, cbit_word, table_limit, cd);
922 /* Character class where all the information is in a bit map: set the
923 bits and either carry on or not, according to the repeat count. If it was
924 a negative class, and we are operating with UTF-8 characters, any byte
925 with a value >= 0xc4 is a potentially valid starter because it starts a
926 character with a value > 255. */
932 start_bits[24] |= 0xf0; /* Bits for 0xc4 - 0xc8 */
933 memset(start_bits+25, 0xff, 7); /* Bits for 0xc9 - 0xff */
942 /* In UTF-8 mode, the bits in a bit map correspond to character
943 values, not to byte values. However, the bit map we are constructing is
944 for byte values. So we have to do a conversion for characters whose
945 value is > 127. In fact, there are only two possible starting bytes for
946 characters in the range 128 - 255. */
951 for (c = 0; c < 16; c++) start_bits[c] |= tcode[c];
952 for (c = 128; c < 256; c++)
954 if ((tcode[c/8] && (1 << (c&7))) != 0)
956 int d = (c >> 6) | 0xc0; /* Set bit for this starter */
957 start_bits[d/8] |= (1 << (d&7)); /* and then skip on to the */
958 c = (c & 0xc0) + 0x40 - 1; /* next relevant character. */
963 /* In non-UTF-8 mode, the two bit maps are completely compatible. */
968 for (c = 0; c < 32; c++) start_bits[c] |= tcode[c];
971 /* Advance past the bit map, and act on what follows */
985 if (((tcode[1] << 8) + tcode[2]) == 0) tcode += 5;
986 else try_next = FALSE;
994 break; /* End of bitmap class handling */
996 } /* End of switch */
997 } /* End of try_next loop */
999 code += GET(code, 1); /* Advance to next branch */
1001 while (*code == OP_ALT);
1007 /*************************************************
1008 * Study a compiled expression *
1009 *************************************************/
1011 /* This function is handed a compiled expression that it must study to produce
1012 information that will speed up the matching. It returns a pcre_extra block
1013 which then gets handed back to pcre_exec().
1016 re points to the compiled expression
1017 options contains option bits
1018 errorptr points to where to place error messages;
1019 set NULL unless error
1021 Returns: pointer to a pcre_extra block, with study_data filled in and the
1022 appropriate flags set;
1023 NULL on error or if no optimization possible
1026 PCRE_EXP_DEFN pcre_extra * PCRE_CALL_CONVENTION
1027 pcre_study(const pcre *external_re, int options, const char **errorptr)
1030 BOOL bits_set = FALSE;
1031 uschar start_bits[32];
1033 pcre_study_data *study;
1034 const uschar *tables;
1036 compile_data compile_block;
1037 const real_pcre *re = (const real_pcre *)external_re;
1041 if (re == NULL || re->magic_number != MAGIC_NUMBER)
1043 *errorptr = "argument is not a compiled regular expression";
1047 if ((options & ~PUBLIC_STUDY_OPTIONS) != 0)
1049 *errorptr = "unknown or incorrect option bit(s) set";
1053 code = (uschar *)re + re->name_table_offset +
1054 (re->name_count * re->name_entry_size);
1056 /* For an anchored pattern, or an unanchored pattern that has a first char, or
1057 a multiline pattern that matches only at "line starts", there is no point in
1058 seeking a list of starting bytes. */
1060 if ((re->options & PCRE_ANCHORED) == 0 &&
1061 (re->flags & (PCRE_FIRSTSET|PCRE_STARTLINE)) == 0)
1063 /* Set the character tables in the block that is passed around */
1065 tables = re->tables;
1067 (void)pcre_fullinfo(external_re, NULL, PCRE_INFO_DEFAULT_TABLES,
1070 compile_block.lcc = tables + lcc_offset;
1071 compile_block.fcc = tables + fcc_offset;
1072 compile_block.cbits = tables + cbits_offset;
1073 compile_block.ctypes = tables + ctypes_offset;
1075 /* See if we can find a fixed set of initial characters for the pattern. */
1077 memset(start_bits, 0, 32 * sizeof(uschar));
1078 bits_set = set_start_bits(code, start_bits,
1079 (re->options & PCRE_CASELESS) != 0, (re->options & PCRE_UTF8) != 0,
1080 &compile_block) == SSB_DONE;
1083 /* Find the minimum length of subject string. */
1085 min = find_minlength(code, code, re->options);
1087 /* Return NULL if no optimization is possible. */
1089 if (!bits_set && min < 0) return NULL;
1091 /* Get a pcre_extra block and a pcre_study_data block. The study data is put in
1092 the latter, which is pointed to by the former, which may also get additional
1093 data set later by the calling program. At the moment, the size of
1094 pcre_study_data is fixed. We nevertheless save it in a field for returning via
1095 the pcre_fullinfo() function so that if it becomes variable in the future, we
1096 don't have to change that code. */
1098 extra = (pcre_extra *)(pcre_malloc)
1099 (sizeof(pcre_extra) + sizeof(pcre_study_data));
1103 *errorptr = "failed to get memory";
1107 study = (pcre_study_data *)((char *)extra + sizeof(pcre_extra));
1108 extra->flags = PCRE_EXTRA_STUDY_DATA;
1109 extra->study_data = study;
1111 study->size = sizeof(pcre_study_data);
1116 study->flags |= PCRE_STUDY_MAPPED;
1117 memcpy(study->start_bits, start_bits, sizeof(start_bits));
1122 study->flags |= PCRE_STUDY_MINLEN;
1123 study->minlength = min;
1129 /* End of pcre_study.c */