/[pcre]/code/trunk/pcre_compile.c
ViewVC logotype

Diff of /code/trunk/pcre_compile.c

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 145 by ph10, Wed Apr 4 14:06:52 2007 UTC revision 380 by ph10, Tue Mar 3 12:32:47 2009 UTC
# Line 6  Line 6 
6  and semantics are as close as possible to those of the Perl 5 language.  and semantics are as close as possible to those of the Perl 5 language.
7    
8                         Written by Philip Hazel                         Written by Philip Hazel
9             Copyright (c) 1997-2007 University of Cambridge             Copyright (c) 1997-2008 University of Cambridge
10    
11  -----------------------------------------------------------------------------  -----------------------------------------------------------------------------
12  Redistribution and use in source and binary forms, with or without  Redistribution and use in source and binary forms, with or without
# Line 42  POSSIBILITY OF SUCH DAMAGE. Line 42  POSSIBILITY OF SUCH DAMAGE.
42  supporting internal functions that are not used by other modules. */  supporting internal functions that are not used by other modules. */
43    
44    
45    #ifdef HAVE_CONFIG_H
46    #include "config.h"
47    #endif
48    
49  #define NLBLOCK cd             /* Block containing newline information */  #define NLBLOCK cd             /* Block containing newline information */
50  #define PSSTART start_pattern  /* Field containing processed string start */  #define PSSTART start_pattern  /* Field containing processed string start */
51  #define PSEND   end_pattern    /* Field containing processed string end */  #define PSEND   end_pattern    /* Field containing processed string end */
52    
   
53  #include "pcre_internal.h"  #include "pcre_internal.h"
54    
55    
# Line 58  used by pcretest. DEBUG is not defined w Line 61  used by pcretest. DEBUG is not defined w
61  #endif  #endif
62    
63    
64    /* Macro for setting individual bits in class bitmaps. */
65    
66    #define SETBIT(a,b) a[b/8] |= (1 << (b%8))
67    
68    /* Maximum length value to check against when making sure that the integer that
69    holds the compiled pattern length does not overflow. We make it a bit less than
70    INT_MAX to allow for adding in group terminating bytes, so that we don't have
71    to check them every time. */
72    
73    #define OFLOW_MAX (INT_MAX - 20)
74    
75    
76  /*************************************************  /*************************************************
77  *      Code parameters and static tables         *  *      Code parameters and static tables         *
78  *************************************************/  *************************************************/
# Line 87  static const short int escapes[] = { Line 102  static const short int escapes[] = {
102       0,      0,      0,      0,      0,      0,      0,      0,   /* 0 - 7 */       0,      0,      0,      0,      0,      0,      0,      0,   /* 0 - 7 */
103       0,      0,    ':',    ';',    '<',    '=',    '>',    '?',   /* 8 - ? */       0,      0,    ':',    ';',    '<',    '=',    '>',    '?',   /* 8 - ? */
104     '@', -ESC_A, -ESC_B, -ESC_C, -ESC_D, -ESC_E,      0, -ESC_G,   /* @ - G */     '@', -ESC_A, -ESC_B, -ESC_C, -ESC_D, -ESC_E,      0, -ESC_G,   /* @ - G */
105       0,      0,      0,      0,      0,      0,      0,      0,   /* H - O */  -ESC_H,      0,      0, -ESC_K,      0,      0,      0,      0,   /* H - O */
106  -ESC_P, -ESC_Q, -ESC_R, -ESC_S,      0,      0,      0, -ESC_W,   /* P - W */  -ESC_P, -ESC_Q, -ESC_R, -ESC_S,      0,      0, -ESC_V, -ESC_W,   /* P - W */
107  -ESC_X,      0, -ESC_Z,    '[',   '\\',    ']',    '^',    '_',   /* X - _ */  -ESC_X,      0, -ESC_Z,    '[',   '\\',    ']',    '^',    '_',   /* X - _ */
108     '`',      7, -ESC_b,      0, -ESC_d,  ESC_e,  ESC_f,      0,   /* ` - g */     '`',      7, -ESC_b,      0, -ESC_d,  ESC_e,  ESC_f,      0,   /* ` - g */
109       0,      0,      0, -ESC_k,      0,      0,  ESC_n,      0,   /* h - o */  -ESC_h,      0,      0, -ESC_k,      0,      0,  ESC_n,      0,   /* h - o */
110  -ESC_p,      0,  ESC_r, -ESC_s,  ESC_tee,    0,      0, -ESC_w,   /* p - w */  -ESC_p,      0,  ESC_r, -ESC_s,  ESC_tee,    0, -ESC_v, -ESC_w,   /* p - w */
111       0,      0, -ESC_z                                            /* x - z */       0,      0, -ESC_z                                            /* x - z */
112  };  };
113    
# Line 106  static const short int escapes[] = { Line 121  static const short int escapes[] = {
121  /*  70 */     0,     0,      0,       0,      0,     0,      0,      0,  /*  70 */     0,     0,      0,       0,      0,     0,      0,      0,
122  /*  78 */     0,   '`',    ':',     '#',    '@',  '\'',    '=',    '"',  /*  78 */     0,   '`',    ':',     '#',    '@',  '\'',    '=',    '"',
123  /*  80 */     0,     7, -ESC_b,       0, -ESC_d, ESC_e,  ESC_f,      0,  /*  80 */     0,     7, -ESC_b,       0, -ESC_d, ESC_e,  ESC_f,      0,
124  /*  88 */     0,     0,      0,     '{',      0,     0,      0,      0,  /*  88 */-ESC_h,     0,      0,     '{',      0,     0,      0,      0,
125  /*  90 */     0,     0, -ESC_k,     'l',      0, ESC_n,      0, -ESC_p,  /*  90 */     0,     0, -ESC_k,     'l',      0, ESC_n,      0, -ESC_p,
126  /*  98 */     0, ESC_r,      0,     '}',      0,     0,      0,      0,  /*  98 */     0, ESC_r,      0,     '}',      0,     0,      0,      0,
127  /*  A0 */     0,   '~', -ESC_s, ESC_tee,      0,     0, -ESC_w,      0,  /*  A0 */     0,   '~', -ESC_s, ESC_tee,      0,-ESC_v, -ESC_w,      0,
128  /*  A8 */     0,-ESC_z,      0,       0,      0,   '[',      0,      0,  /*  A8 */     0,-ESC_z,      0,       0,      0,   '[',      0,      0,
129  /*  B0 */     0,     0,      0,       0,      0,     0,      0,      0,  /*  B0 */     0,     0,      0,       0,      0,     0,      0,      0,
130  /*  B8 */     0,     0,      0,       0,      0,   ']',    '=',    '-',  /*  B8 */     0,     0,      0,       0,      0,   ']',    '=',    '-',
131  /*  C0 */   '{',-ESC_A, -ESC_B,  -ESC_C, -ESC_D,-ESC_E,      0, -ESC_G,  /*  C0 */   '{',-ESC_A, -ESC_B,  -ESC_C, -ESC_D,-ESC_E,      0, -ESC_G,
132  /*  C8 */     0,     0,      0,       0,      0,     0,      0,      0,  /*  C8 */-ESC_H,     0,      0,       0,      0,     0,      0,      0,
133  /*  D0 */   '}',     0,      0,       0,      0,     0,      0, -ESC_P,  /*  D0 */   '}',     0, -ESC_K,       0,      0,     0,      0, -ESC_P,
134  /*  D8 */-ESC_Q,-ESC_R,      0,       0,      0,     0,      0,      0,  /*  D8 */-ESC_Q,-ESC_R,      0,       0,      0,     0,      0,      0,
135  /*  E0 */  '\\',     0, -ESC_S,       0,      0,     0, -ESC_W, -ESC_X,  /*  E0 */  '\\',     0, -ESC_S,       0,      0,-ESC_V, -ESC_W, -ESC_X,
136  /*  E8 */     0,-ESC_Z,      0,       0,      0,     0,      0,      0,  /*  E8 */     0,-ESC_Z,      0,       0,      0,     0,      0,      0,
137  /*  F0 */     0,     0,      0,       0,      0,     0,      0,      0,  /*  F0 */     0,     0,      0,       0,      0,     0,      0,      0,
138  /*  F8 */     0,     0,      0,       0,      0,     0,      0,      0  /*  F8 */     0,     0,      0,       0,      0,     0,      0,      0
# Line 125  static const short int escapes[] = { Line 140  static const short int escapes[] = {
140  #endif  #endif
141    
142    
143  /* Tables of names of POSIX character classes and their lengths. The list is  /* Table of special "verbs" like (*PRUNE). This is a short table, so it is
144  terminated by a zero length entry. The first three must be alpha, lower, upper,  searched linearly. Put all the names into a single string, in order to reduce
145  as this is assumed for handling case independence. */  the number of relocations when a shared library is dynamically linked. */
146    
147  static const char *const posix_names[] = {  typedef struct verbitem {
148    "alpha", "lower", "upper",    int   len;
149    "alnum", "ascii", "blank", "cntrl", "digit", "graph",    int   op;
150    "print", "punct", "space", "word",  "xdigit" };  } verbitem;
151    
152    static const char verbnames[] =
153      "ACCEPT\0"
154      "COMMIT\0"
155      "F\0"
156      "FAIL\0"
157      "PRUNE\0"
158      "SKIP\0"
159      "THEN";
160    
161    static const verbitem verbs[] = {
162      { 6, OP_ACCEPT },
163      { 6, OP_COMMIT },
164      { 1, OP_FAIL },
165      { 4, OP_FAIL },
166      { 5, OP_PRUNE },
167      { 4, OP_SKIP  },
168      { 4, OP_THEN  }
169    };
170    
171    static const int verbcount = sizeof(verbs)/sizeof(verbitem);
172    
173    
174    /* Tables of names of POSIX character classes and their lengths. The names are
175    now all in a single string, to reduce the number of relocations when a shared
176    library is dynamically loaded. The list of lengths is terminated by a zero
177    length entry. The first three must be alpha, lower, upper, as this is assumed
178    for handling case independence. */
179    
180    static const char posix_names[] =
181      "alpha\0"  "lower\0"  "upper\0"  "alnum\0"  "ascii\0"  "blank\0"
182      "cntrl\0"  "digit\0"  "graph\0"  "print\0"  "punct\0"  "space\0"
183      "word\0"   "xdigit";
184    
185  static const uschar posix_name_lengths[] = {  static const uschar posix_name_lengths[] = {
186    5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 6, 0 };    5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 6, 0 };
# Line 171  static const int posix_class_maps[] = { Line 219  static const int posix_class_maps[] = {
219  /* The texts of compile-time error messages. These are "char *" because they  /* The texts of compile-time error messages. These are "char *" because they
220  are passed to the outside world. Do not ever re-use any error number, because  are passed to the outside world. Do not ever re-use any error number, because
221  they are documented. Always add a new error instead. Messages marked DEAD below  they are documented. Always add a new error instead. Messages marked DEAD below
222  are no longer used. */  are no longer used. This used to be a table of strings, but in order to reduce
223    the number of relocations needed when a shared library is loaded dynamically,
224  static const char *error_texts[] = {  it is now one long string. We cannot use a table of offsets, because the
225    "no error",  lengths of inserts such as XSTRING(MAX_NAME_SIZE) are not known. Instead, we
226    "\\ at end of pattern",  simply count through to the one we want - this isn't a performance issue
227    "\\c at end of pattern",  because these strings are used only when there is a compilation error. */
228    "unrecognized character follows \\",  
229    "numbers out of order in {} quantifier",  static const char error_texts[] =
230      "no error\0"
231      "\\ at end of pattern\0"
232      "\\c at end of pattern\0"
233      "unrecognized character follows \\\0"
234      "numbers out of order in {} quantifier\0"
235    /* 5 */    /* 5 */
236    "number too big in {} quantifier",    "number too big in {} quantifier\0"
237    "missing terminating ] for character class",    "missing terminating ] for character class\0"
238    "invalid escape sequence in character class",    "invalid escape sequence in character class\0"
239    "range out of order in character class",    "range out of order in character class\0"
240    "nothing to repeat",    "nothing to repeat\0"
241    /* 10 */    /* 10 */
242    "operand of unlimited repeat could match the empty string",  /** DEAD **/    "operand of unlimited repeat could match the empty string\0"  /** DEAD **/
243    "internal error: unexpected repeat",    "internal error: unexpected repeat\0"
244    "unrecognized character after (?",    "unrecognized character after (? or (?-\0"
245    "POSIX named classes are supported only within a class",    "POSIX named classes are supported only within a class\0"
246    "missing )",    "missing )\0"
247    /* 15 */    /* 15 */
248    "reference to non-existent subpattern",    "reference to non-existent subpattern\0"
249    "erroffset passed as NULL",    "erroffset passed as NULL\0"
250    "unknown option bit(s) set",    "unknown option bit(s) set\0"
251    "missing ) after comment",    "missing ) after comment\0"
252    "parentheses nested too deeply",  /** DEAD **/    "parentheses nested too deeply\0"  /** DEAD **/
253    /* 20 */    /* 20 */
254    "regular expression too large",    "regular expression is too large\0"
255    "failed to get memory",    "failed to get memory\0"
256    "unmatched parentheses",    "unmatched parentheses\0"
257    "internal error: code overflow",    "internal error: code overflow\0"
258    "unrecognized character after (?<",    "unrecognized character after (?<\0"
259    /* 25 */    /* 25 */
260    "lookbehind assertion is not fixed length",    "lookbehind assertion is not fixed length\0"
261    "malformed number or name after (?(",    "malformed number or name after (?(\0"
262    "conditional group contains more than two branches",    "conditional group contains more than two branches\0"
263    "assertion expected after (?(",    "assertion expected after (?(\0"
264    "(?R or (?digits must be followed by )",    "(?R or (?[+-]digits must be followed by )\0"
265    /* 30 */    /* 30 */
266    "unknown POSIX class name",    "unknown POSIX class name\0"
267    "POSIX collating elements are not supported",    "POSIX collating elements are not supported\0"
268    "this version of PCRE is not compiled with PCRE_UTF8 support",    "this version of PCRE is not compiled with PCRE_UTF8 support\0"
269    "spare error",  /** DEAD **/    "spare error\0"  /** DEAD **/
270    "character value in \\x{...} sequence is too large",    "character value in \\x{...} sequence is too large\0"
271    /* 35 */    /* 35 */
272    "invalid condition (?(0)",    "invalid condition (?(0)\0"
273    "\\C not allowed in lookbehind assertion",    "\\C not allowed in lookbehind assertion\0"
274    "PCRE does not support \\L, \\l, \\N, \\U, or \\u",    "PCRE does not support \\L, \\l, \\N, \\U, or \\u\0"
275    "number after (?C is > 255",    "number after (?C is > 255\0"
276    "closing ) for (?C expected",    "closing ) for (?C expected\0"
277    /* 40 */    /* 40 */
278    "recursive call could loop indefinitely",    "recursive call could loop indefinitely\0"
279    "unrecognized character after (?P",    "unrecognized character after (?P\0"
280    "syntax error in subpattern name (missing terminator)",    "syntax error in subpattern name (missing terminator)\0"
281    "two named subpatterns have the same name",    "two named subpatterns have the same name\0"
282    "invalid UTF-8 string",    "invalid UTF-8 string\0"
283    /* 45 */    /* 45 */
284    "support for \\P, \\p, and \\X has not been compiled",    "support for \\P, \\p, and \\X has not been compiled\0"
285    "malformed \\P or \\p sequence",    "malformed \\P or \\p sequence\0"
286    "unknown property name after \\P or \\p",    "unknown property name after \\P or \\p\0"
287    "subpattern name is too long (maximum " XSTRING(MAX_NAME_SIZE) " characters)",    "subpattern name is too long (maximum " XSTRING(MAX_NAME_SIZE) " characters)\0"
288    "too many named subpatterns (maximum " XSTRING(MAX_NAME_COUNT) ")",    "too many named subpatterns (maximum " XSTRING(MAX_NAME_COUNT) ")\0"
289    /* 50 */    /* 50 */
290    "repeated subpattern is too long",    "repeated subpattern is too long\0"    /** DEAD **/
291    "octal value is greater than \\377 (not in UTF-8 mode)",    "octal value is greater than \\377 (not in UTF-8 mode)\0"
292    "internal error: overran compiling workspace",    "internal error: overran compiling workspace\0"
293    "internal error: previously-checked referenced subpattern not found",    "internal error: previously-checked referenced subpattern not found\0"
294    "DEFINE group contains more than one branch",    "DEFINE group contains more than one branch\0"
295    /* 55 */    /* 55 */
296    "repeating a DEFINE group is not allowed",    "repeating a DEFINE group is not allowed\0"
297    "inconsistent NEWLINE options",    "inconsistent NEWLINE options\0"
298    "\\g is not followed by an (optionally braced) non-zero number"    "\\g is not followed by a braced, angle-bracketed, or quoted name/number or by a plain number\0"
299  };    "a numbered reference must not be zero\0"
300      "(*VERB) with an argument is not supported\0"
301      /* 60 */
302      "(*VERB) not recognized\0"
303      "number is too big\0"
304      "subpattern name expected\0"
305      "digit expected after (?+\0"
306      "] is an invalid data character in JavaScript compatibility mode";
307    
308    
309  /* Table to identify digits and hex digits. This is used when compiling  /* Table to identify digits and hex digits. This is used when compiling
# Line 373  static const unsigned char ebcdic_charta Line 433  static const unsigned char ebcdic_charta
433  /* Definition to allow mutual recursion */  /* Definition to allow mutual recursion */
434    
435  static BOOL  static BOOL
436    compile_regex(int, int, uschar **, const uschar **, int *, BOOL, int, int *,    compile_regex(int, int, uschar **, const uschar **, int *, BOOL, BOOL, int,
437      int *, branch_chain *, compile_data *, int *);      int *, int *, branch_chain *, compile_data *, int *);
438    
439    
440    
441  /*************************************************  /*************************************************
442    *            Find an error text                  *
443    *************************************************/
444    
445    /* The error texts are now all in one long string, to save on relocations. As
446    some of the text is of unknown length, we can't use a table of offsets.
447    Instead, just count through the strings. This is not a performance issue
448    because it happens only when there has been a compilation error.
449    
450    Argument:   the error number
451    Returns:    pointer to the error string
452    */
453    
454    static const char *
455    find_error_text(int n)
456    {
457    const char *s = error_texts;
458    for (; n > 0; n--) while (*s++ != 0) {};
459    return s;
460    }
461    
462    
463    /*************************************************
464  *            Handle escapes                      *  *            Handle escapes                      *
465  *************************************************/  *************************************************/
466    
# Line 399  Arguments: Line 481  Arguments:
481    
482  Returns:         zero or positive => a data character  Returns:         zero or positive => a data character
483                   negative => a special escape sequence                   negative => a special escape sequence
484                   on error, errorptr is set                   on error, errorcodeptr is set
485  */  */
486    
487  static int  static int
# Line 417  ptr--;                            /* Set Line 499  ptr--;                            /* Set
499    
500  if (c == 0) *errorcodeptr = ERR1;  if (c == 0) *errorcodeptr = ERR1;
501    
502  /* Non-alphamerics are literals. For digits or letters, do an initial lookup in  /* Non-alphanumerics are literals. For digits or letters, do an initial lookup
503  a table. A non-zero result is something that can be returned immediately.  in a table. A non-zero result is something that can be returned immediately.
504  Otherwise further processing may be required. */  Otherwise further processing may be required. */
505    
506  #ifndef EBCDIC  /* ASCII coding */  #ifndef EBCDIC  /* ASCII coding */
507  else if (c < '0' || c > 'z') {}                           /* Not alphameric */  else if (c < '0' || c > 'z') {}                           /* Not alphanumeric */
508  else if ((i = escapes[c - '0']) != 0) c = i;  else if ((i = escapes[c - '0']) != 0) c = i;
509    
510  #else           /* EBCDIC coding */  #else           /* EBCDIC coding */
511  else if (c < 'a' || (ebcdic_chartab[c] & 0x0E) == 0) {}   /* Not alphameric */  else if (c < 'a' || (ebcdic_chartab[c] & 0x0E) == 0) {}   /* Not alphanumeric */
512  else if ((i = escapes[c - 0x48]) != 0)  c = i;  else if ((i = escapes[c - 0x48]) != 0)  c = i;
513  #endif  #endif
514    
# Line 450  else Line 532  else
532      *errorcodeptr = ERR37;      *errorcodeptr = ERR37;
533      break;      break;
534    
535      /* \g must be followed by a number, either plain or braced. If positive, it      /* \g must be followed by one of a number of specific things:
536      is an absolute backreference. If negative, it is a relative backreference.  
537      This is a Perl 5.10 feature. */      (1) A number, either plain or braced. If positive, it is an absolute
538        backreference. If negative, it is a relative backreference. This is a Perl
539        5.10 feature.
540    
541        (2) Perl 5.10 also supports \g{name} as a reference to a named group. This
542        is part of Perl's movement towards a unified syntax for back references. As
543        this is synonymous with \k{name}, we fudge it up by pretending it really
544        was \k.
545    
546        (3) For Oniguruma compatibility we also support \g followed by a name or a
547        number either in angle brackets or in single quotes. However, these are
548        (possibly recursive) subroutine calls, _not_ backreferences. Just return
549        the -ESC_g code (cf \k). */
550    
551      case 'g':      case 'g':
552        if (ptr[1] == '<' || ptr[1] == '\'')
553          {
554          c = -ESC_g;
555          break;
556          }
557    
558        /* Handle the Perl-compatible cases */
559    
560      if (ptr[1] == '{')      if (ptr[1] == '{')
561        {        {
562          const uschar *p;
563          for (p = ptr+2; *p != 0 && *p != '}'; p++)
564            if (*p != '-' && (digitab[*p] & ctype_digit) == 0) break;
565          if (*p != 0 && *p != '}')
566            {
567            c = -ESC_k;
568            break;
569            }
570        braced = TRUE;        braced = TRUE;
571        ptr++;        ptr++;
572        }        }
# Line 473  else Line 583  else
583      while ((digitab[ptr[1]] & ctype_digit) != 0)      while ((digitab[ptr[1]] & ctype_digit) != 0)
584        c = c * 10 + *(++ptr) - '0';        c = c * 10 + *(++ptr) - '0';
585    
586      if (c == 0 || (braced && *(++ptr) != '}'))      if (c < 0)   /* Integer overflow */
587          {
588          *errorcodeptr = ERR61;
589          break;
590          }
591    
592        if (braced && *(++ptr) != '}')
593        {        {
594        *errorcodeptr = ERR57;        *errorcodeptr = ERR57;
595        return 0;        break;
596          }
597    
598        if (c == 0)
599          {
600          *errorcodeptr = ERR58;
601          break;
602        }        }
603    
604      if (negated)      if (negated)
# Line 484  else Line 606  else
606        if (c > bracount)        if (c > bracount)
607          {          {
608          *errorcodeptr = ERR15;          *errorcodeptr = ERR15;
609          return 0;          break;
610          }          }
611        c = bracount - (c - 1);        c = bracount - (c - 1);
612        }        }
# Line 513  else Line 635  else
635        c -= '0';        c -= '0';
636        while ((digitab[ptr[1]] & ctype_digit) != 0)        while ((digitab[ptr[1]] & ctype_digit) != 0)
637          c = c * 10 + *(++ptr) - '0';          c = c * 10 + *(++ptr) - '0';
638          if (c < 0)    /* Integer overflow */
639            {
640            *errorcodeptr = ERR61;
641            break;
642            }
643        if (c < 10 || c <= bracount)        if (c < 10 || c <= bracount)
644          {          {
645          c = -(ESC_REF + c);          c = -(ESC_REF + c);
# Line 608  else Line 735  else
735      if (c == 0)      if (c == 0)
736        {        {
737        *errorcodeptr = ERR2;        *errorcodeptr = ERR2;
738        return 0;        break;
739        }        }
740    
741  #ifndef EBCDIC  /* ASCII coding */  #ifndef EBCDIC  /* ASCII coding */
# Line 621  else Line 748  else
748      break;      break;
749    
750      /* PCRE_EXTRA enables extensions to Perl in the matter of escapes. Any      /* PCRE_EXTRA enables extensions to Perl in the matter of escapes. Any
751      other alphameric following \ is an error if PCRE_EXTRA was set; otherwise,      other alphanumeric following \ is an error if PCRE_EXTRA was set;
752      for Perl compatibility, it is a literal. This code looks a bit odd, but      otherwise, for Perl compatibility, it is a literal. This code looks a bit
753      there used to be some cases other than the default, and there may be again      odd, but there used to be some cases other than the default, and there may
754      in future, so I haven't "optimized" it. */      be again in future, so I haven't "optimized" it. */
755    
756      default:      default:
757      if ((options & PCRE_EXTRA) != 0) switch(c)      if ((options & PCRE_EXTRA) != 0) switch(c)
# Line 684  if (c == '{') Line 811  if (c == '{')
811      *negptr = TRUE;      *negptr = TRUE;
812      ptr++;      ptr++;
813      }      }
814    for (i = 0; i < sizeof(name) - 1; i++)    for (i = 0; i < (int)sizeof(name) - 1; i++)
815      {      {
816      c = *(++ptr);      c = *(++ptr);
817      if (c == 0) goto ERROR_RETURN;      if (c == 0) goto ERROR_RETURN;
# Line 713  top = _pcre_utt_size; Line 840  top = _pcre_utt_size;
840  while (bot < top)  while (bot < top)
841    {    {
842    i = (bot + top) >> 1;    i = (bot + top) >> 1;
843    c = strcmp(name, _pcre_utt[i].name);    c = strcmp(name, _pcre_utt_names + _pcre_utt[i].name_offset);
844    if (c == 0)    if (c == 0)
845      {      {
846      *dptr = _pcre_utt[i].value;      *dptr = _pcre_utt[i].value;
# Line 849  be terminated by '>' because that is che Line 976  be terminated by '>' because that is che
976    
977  Arguments:  Arguments:
978    ptr          current position in the pattern    ptr          current position in the pattern
979    count        current count of capturing parens so far encountered    cd           compile background data
980    name         name to seek, or NULL if seeking a numbered subpattern    name         name to seek, or NULL if seeking a numbered subpattern
981    lorn         name length, or subpattern number if name is NULL    lorn         name length, or subpattern number if name is NULL
982    xmode        TRUE if we are in /x mode    xmode        TRUE if we are in /x mode
# Line 858  Returns:       the number of the named s Line 985  Returns:       the number of the named s
985  */  */
986    
987  static int  static int
988  find_parens(const uschar *ptr, int count, const uschar *name, int lorn,  find_parens(const uschar *ptr, compile_data *cd, const uschar *name, int lorn,
989    BOOL xmode)    BOOL xmode)
990  {  {
991  const uschar *thisname;  const uschar *thisname;
992    int count = cd->bracount;
993    
994  for (; *ptr != 0; ptr++)  for (; *ptr != 0; ptr++)
995    {    {
# Line 874  for (; *ptr != 0; ptr++) Line 1002  for (; *ptr != 0; ptr++)
1002      if (*(++ptr) == 0) return -1;      if (*(++ptr) == 0) return -1;
1003      if (*ptr == 'Q') for (;;)      if (*ptr == 'Q') for (;;)
1004        {        {
1005        while (*(++ptr) != 0 && *ptr != '\\');        while (*(++ptr) != 0 && *ptr != '\\') {};
1006        if (*ptr == 0) return -1;        if (*ptr == 0) return -1;
1007        if (*(++ptr) == 'E') break;        if (*(++ptr) == 'E') break;
1008        }        }
1009      continue;      continue;
1010      }      }
1011    
1012    /* Skip over character classes */    /* Skip over character classes; this logic must be similar to the way they
1013      are handled for real. If the first character is '^', skip it. Also, if the
1014      first few characters (either before or after ^) are \Q\E or \E we skip them
1015      too. This makes for compatibility with Perl. */
1016    
1017    if (*ptr == '[')    if (*ptr == '[')
1018      {      {
1019        BOOL negate_class = FALSE;
1020        for (;;)
1021          {
1022          int c = *(++ptr);
1023          if (c == '\\')
1024            {
1025            if (ptr[1] == 'E') ptr++;
1026              else if (strncmp((const char *)ptr+1, "Q\\E", 3) == 0) ptr += 3;
1027                else break;
1028            }
1029          else if (!negate_class && c == '^')
1030            negate_class = TRUE;
1031          else break;
1032          }
1033    
1034        /* If the next character is ']', it is a data character that must be
1035        skipped, except in JavaScript compatibility mode. */
1036    
1037        if (ptr[1] == ']' && (cd->external_options & PCRE_JAVASCRIPT_COMPAT) == 0)
1038          ptr++;
1039    
1040      while (*(++ptr) != ']')      while (*(++ptr) != ']')
1041        {        {
1042          if (*ptr == 0) return -1;
1043        if (*ptr == '\\')        if (*ptr == '\\')
1044          {          {
1045          if (*(++ptr) == 0) return -1;          if (*(++ptr) == 0) return -1;
1046          if (*ptr == 'Q') for (;;)          if (*ptr == 'Q') for (;;)
1047            {            {
1048            while (*(++ptr) != 0 && *ptr != '\\');            while (*(++ptr) != 0 && *ptr != '\\') {};
1049            if (*ptr == 0) return -1;            if (*ptr == 0) return -1;
1050            if (*(++ptr) == 'E') break;            if (*(++ptr) == 'E') break;
1051            }            }
# Line 906  for (; *ptr != 0; ptr++) Line 1059  for (; *ptr != 0; ptr++)
1059    
1060    if (xmode && *ptr == '#')    if (xmode && *ptr == '#')
1061      {      {
1062      while (*(++ptr) != 0 && *ptr != '\n');      while (*(++ptr) != 0 && *ptr != '\n') {};
1063      if (*ptr == 0) return -1;      if (*ptr == 0) return -1;
1064      continue;      continue;
1065      }      }
# Line 914  for (; *ptr != 0; ptr++) Line 1067  for (; *ptr != 0; ptr++)
1067    /* An opening parens must now be a real metacharacter */    /* An opening parens must now be a real metacharacter */
1068    
1069    if (*ptr != '(') continue;    if (*ptr != '(') continue;
1070    if (ptr[1] != '?')    if (ptr[1] != '?' && ptr[1] != '*')
1071      {      {
1072      count++;      count++;
1073      if (name == NULL && count == lorn) return count;      if (name == NULL && count == lorn) return count;
# Line 1042  for (;;) Line 1195  for (;;)
1195    {    {
1196    int d;    int d;
1197    register int op = *cc;    register int op = *cc;
   
1198    switch (op)    switch (op)
1199      {      {
1200      case OP_CBRA:      case OP_CBRA:
# Line 1131  for (;;) Line 1283  for (;;)
1283    
1284      case OP_TYPEEXACT:      case OP_TYPEEXACT:
1285      branchlength += GET2(cc,1);      branchlength += GET2(cc,1);
1286        if (cc[3] == OP_PROP || cc[3] == OP_NOTPROP) cc += 2;
1287      cc += 4;      cc += 4;
1288      break;      break;
1289    
# Line 1148  for (;;) Line 1301  for (;;)
1301      case OP_NOT_WORDCHAR:      case OP_NOT_WORDCHAR:
1302      case OP_WORDCHAR:      case OP_WORDCHAR:
1303      case OP_ANY:      case OP_ANY:
1304        case OP_ALLANY:
1305      branchlength++;      branchlength++;
1306      cc++;      cc++;
1307      break;      break;
# Line 1239  for (;;) Line 1393  for (;;)
1393      code += _pcre_OP_lengths[c];      code += _pcre_OP_lengths[c];
1394      }      }
1395    
1396    /* In UTF-8 mode, opcodes that are followed by a character may be followed by    /* Otherwise, we can get the item's length from the table, except that for
1397    a multi-byte character. The length in the table is a minimum, so we have to    repeated character types, we have to test for \p and \P, which have an extra
1398    arrange to skip the extra bytes. */    two bytes of parameters. */
1399    
1400    else    else
1401      {      {
1402        switch(c)
1403          {
1404          case OP_TYPESTAR:
1405          case OP_TYPEMINSTAR:
1406          case OP_TYPEPLUS:
1407          case OP_TYPEMINPLUS:
1408          case OP_TYPEQUERY:
1409          case OP_TYPEMINQUERY:
1410          case OP_TYPEPOSSTAR:
1411          case OP_TYPEPOSPLUS:
1412          case OP_TYPEPOSQUERY:
1413          if (code[1] == OP_PROP || code[1] == OP_NOTPROP) code += 2;
1414          break;
1415    
1416          case OP_TYPEUPTO:
1417          case OP_TYPEMINUPTO:
1418          case OP_TYPEEXACT:
1419          case OP_TYPEPOSUPTO:
1420          if (code[3] == OP_PROP || code[3] == OP_NOTPROP) code += 2;
1421          break;
1422          }
1423    
1424        /* Add in the fixed length from the table */
1425    
1426      code += _pcre_OP_lengths[c];      code += _pcre_OP_lengths[c];
1427    
1428      /* In UTF-8 mode, opcodes that are followed by a character may be followed by
1429      a multi-byte character. The length in the table is a minimum, so we have to
1430      arrange to skip the extra bytes. */
1431    
1432  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF8
1433      if (utf8) switch(c)      if (utf8) switch(c)
1434        {        {
# Line 1267  for (;;) Line 1450  for (;;)
1450        if (code[-1] >= 0xc0) code += _pcre_utf8_table4[code[-1] & 0x3f];        if (code[-1] >= 0xc0) code += _pcre_utf8_table4[code[-1] & 0x3f];
1451        break;        break;
1452        }        }
1453    #else
1454        (void)(utf8);  /* Keep compiler happy by referencing function argument */
1455  #endif  #endif
1456      }      }
1457    }    }
# Line 1303  for (;;) Line 1488  for (;;)
1488    
1489    if (c == OP_XCLASS) code += GET(code, 1);    if (c == OP_XCLASS) code += GET(code, 1);
1490    
1491    /* Otherwise, we get the item's length from the table. In UTF-8 mode, opcodes    /* Otherwise, we can get the item's length from the table, except that for
1492    that are followed by a character may be followed by a multi-byte character.    repeated character types, we have to test for \p and \P, which have an extra
1493    The length in the table is a minimum, so we have to arrange to skip the extra    two bytes of parameters. */
   bytes. */  
1494    
1495    else    else
1496      {      {
1497        switch(c)
1498          {
1499          case OP_TYPESTAR:
1500          case OP_TYPEMINSTAR:
1501          case OP_TYPEPLUS:
1502          case OP_TYPEMINPLUS:
1503          case OP_TYPEQUERY:
1504          case OP_TYPEMINQUERY:
1505          case OP_TYPEPOSSTAR:
1506          case OP_TYPEPOSPLUS:
1507          case OP_TYPEPOSQUERY:
1508          if (code[1] == OP_PROP || code[1] == OP_NOTPROP) code += 2;
1509          break;
1510    
1511          case OP_TYPEPOSUPTO:
1512          case OP_TYPEUPTO:
1513          case OP_TYPEMINUPTO:
1514          case OP_TYPEEXACT:
1515          if (code[3] == OP_PROP || code[3] == OP_NOTPROP) code += 2;
1516          break;
1517          }
1518    
1519        /* Add in the fixed length from the table */
1520    
1521      code += _pcre_OP_lengths[c];      code += _pcre_OP_lengths[c];
1522    
1523        /* In UTF-8 mode, opcodes that are followed by a character may be followed
1524        by a multi-byte character. The length in the table is a minimum, so we have
1525        to arrange to skip the extra bytes. */
1526    
1527  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF8
1528      if (utf8) switch(c)      if (utf8) switch(c)
1529        {        {
# Line 1332  for (;;) Line 1545  for (;;)
1545        if (code[-1] >= 0xc0) code += _pcre_utf8_table4[code[-1] & 0x3f];        if (code[-1] >= 0xc0) code += _pcre_utf8_table4[code[-1] & 0x3f];
1546        break;        break;
1547        }        }
1548    #else
1549        (void)(utf8);  /* Keep compiler happy by referencing function argument */
1550  #endif  #endif
1551      }      }
1552    }    }
# Line 1347  for (;;) Line 1562  for (;;)
1562  can match the empty string or not. It is called from could_be_empty()  can match the empty string or not. It is called from could_be_empty()
1563  below and from compile_branch() when checking for an unlimited repeat of a  below and from compile_branch() when checking for an unlimited repeat of a
1564  group that can match nothing. Note that first_significant_code() skips over  group that can match nothing. Note that first_significant_code() skips over
1565  assertions. If we hit an unclosed bracket, we return "empty" - this means we've  backward and negative forward assertions when its final argument is TRUE. If we
1566  struck an inner bracket whose current branch will already have been scanned.  hit an unclosed bracket, we return "empty" - this means we've struck an inner
1567    bracket whose current branch will already have been scanned.
1568    
1569  Arguments:  Arguments:
1570    code        points to start of search    code        points to start of search
# Line 1370  for (code = first_significant_code(code Line 1586  for (code = first_significant_code(code
1586    
1587    c = *code;    c = *code;
1588    
1589    if (c == OP_BRA || c == OP_CBRA || c == OP_ONCE)    /* Skip over forward assertions; the other assertions are skipped by
1590      first_significant_code() with a TRUE final argument. */
1591    
1592      if (c == OP_ASSERT)
1593        {
1594        do code += GET(code, 1); while (*code == OP_ALT);
1595        c = *code;
1596        continue;
1597        }
1598    
1599      /* Groups with zero repeats can of course be empty; skip them. */
1600    
1601      if (c == OP_BRAZERO || c == OP_BRAMINZERO || c == OP_SKIPZERO)
1602        {
1603        code += _pcre_OP_lengths[c];
1604        do code += GET(code, 1); while (*code == OP_ALT);
1605        c = *code;
1606        continue;
1607        }
1608    
1609      /* For other groups, scan the branches. */
1610    
1611      if (c == OP_BRA || c == OP_CBRA || c == OP_ONCE || c == OP_COND)
1612      {      {
1613      BOOL empty_branch;      BOOL empty_branch;
1614      if (GET(code, 1) == 0) return TRUE;    /* Hit unclosed bracket */      if (GET(code, 1) == 0) return TRUE;    /* Hit unclosed bracket */
# Line 1386  for (code = first_significant_code(code Line 1624  for (code = first_significant_code(code
1624        }        }
1625      while (*code == OP_ALT);      while (*code == OP_ALT);
1626      if (!empty_branch) return FALSE;   /* All branches are non-empty */      if (!empty_branch) return FALSE;   /* All branches are non-empty */
1627        c = *code;
     /* Move past the KET and fudge things so that the increment in the "for"  
     above has no effect. */  
   
     c = OP_END;  
     code += 1 + LINK_SIZE - _pcre_OP_lengths[c];  
1628      continue;      continue;
1629      }      }
1630    
# Line 1399  for (code = first_significant_code(code Line 1632  for (code = first_significant_code(code
1632    
1633    switch (c)    switch (c)
1634      {      {
1635      /* Check for quantifiers after a class */      /* Check for quantifiers after a class. XCLASS is used for classes that
1636        cannot be represented just by a bit map. This includes negated single
1637        high-valued characters. The length in _pcre_OP_lengths[] is zero; the
1638        actual length is stored in the compiled code, so we must update "code"
1639        here. */
1640    
1641  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF8
1642      case OP_XCLASS:      case OP_XCLASS:
1643      ccode = code + GET(code, 1);      ccode = code += GET(code, 1);
1644      goto CHECK_CLASS_REPEAT;      goto CHECK_CLASS_REPEAT;
1645  #endif  #endif
1646    
# Line 1447  for (code = first_significant_code(code Line 1684  for (code = first_significant_code(code
1684      case OP_NOT_WORDCHAR:      case OP_NOT_WORDCHAR:
1685      case OP_WORDCHAR:      case OP_WORDCHAR:
1686      case OP_ANY:      case OP_ANY:
1687        case OP_ALLANY:
1688      case OP_ANYBYTE:      case OP_ANYBYTE:
1689      case OP_CHAR:      case OP_CHAR:
1690      case OP_CHARNC:      case OP_CHARNC:
# Line 1465  for (code = first_significant_code(code Line 1703  for (code = first_significant_code(code
1703      case OP_TYPEEXACT:      case OP_TYPEEXACT:
1704      return FALSE;      return FALSE;
1705    
1706        /* These are going to continue, as they may be empty, but we have to
1707        fudge the length for the \p and \P cases. */
1708    
1709        case OP_TYPESTAR:
1710        case OP_TYPEMINSTAR:
1711        case OP_TYPEPOSSTAR:
1712        case OP_TYPEQUERY:
1713        case OP_TYPEMINQUERY:
1714        case OP_TYPEPOSQUERY:
1715        if (code[1] == OP_PROP || code[1] == OP_NOTPROP) code += 2;
1716        break;
1717    
1718        /* Same for these */
1719    
1720        case OP_TYPEUPTO:
1721        case OP_TYPEMINUPTO:
1722        case OP_TYPEPOSUPTO:
1723        if (code[3] == OP_PROP || code[3] == OP_NOTPROP) code += 2;
1724        break;
1725    
1726      /* End of branch */      /* End of branch */
1727    
1728      case OP_KET:      case OP_KET:
# Line 1534  return TRUE; Line 1792  return TRUE;
1792  *************************************************/  *************************************************/
1793    
1794  /* This function is called when the sequence "[:" or "[." or "[=" is  /* This function is called when the sequence "[:" or "[." or "[=" is
1795  encountered in a character class. It checks whether this is followed by an  encountered in a character class. It checks whether this is followed by a
1796  optional ^ and then a sequence of letters, terminated by a matching ":]" or  sequence of characters terminated by a matching ":]" or ".]" or "=]". If we
1797  ".]" or "=]".  reach an unescaped ']' without the special preceding character, return FALSE.
1798    
1799    Originally, this function only recognized a sequence of letters between the
1800    terminators, but it seems that Perl recognizes any sequence of characters,
1801    though of course unknown POSIX names are subsequently rejected. Perl gives an
1802    "Unknown POSIX class" error for [:f\oo:] for example, where previously PCRE
1803    didn't consider this to be a POSIX class. Likewise for [:1234:].
1804    
1805    The problem in trying to be exactly like Perl is in the handling of escapes. We
1806    have to be sure that [abc[:x\]pqr] is *not* treated as containing a POSIX
1807    class, but [abc[:x\]pqr:]] is (so that an error can be generated). The code
1808    below handles the special case of \], but does not try to do any other escape
1809    processing. This makes it different from Perl for cases such as [:l\ower:]
1810    where Perl recognizes it as the POSIX class "lower" but PCRE does not recognize
1811    "l\ower". This is a lesser evil that not diagnosing bad classes when Perl does,
1812    I think.
1813    
1814  Argument:  Arguments:
1815    ptr      pointer to the initial [    ptr      pointer to the initial [
1816    endptr   where to return the end pointer    endptr   where to return the end pointer
   cd       pointer to compile data  
1817    
1818  Returns:   TRUE or FALSE  Returns:   TRUE or FALSE
1819  */  */
1820    
1821  static BOOL  static BOOL
1822  check_posix_syntax(const uschar *ptr, const uschar **endptr, compile_data *cd)  check_posix_syntax(const uschar *ptr, const uschar **endptr)
1823  {  {
1824  int terminator;          /* Don't combine these lines; the Solaris cc */  int terminator;          /* Don't combine these lines; the Solaris cc */
1825  terminator = *(++ptr);   /* compiler warns about "non-constant" initializer. */  terminator = *(++ptr);   /* compiler warns about "non-constant" initializer. */
1826  if (*(++ptr) == '^') ptr++;  for (++ptr; *ptr != 0; ptr++)
 while ((cd->ctypes[*ptr] & ctype_letter) != 0) ptr++;  
 if (*ptr == terminator && ptr[1] == ']')  
1827    {    {
1828    *endptr = ptr;    if (*ptr == '\\' && ptr[1] == ']') ptr++; else
1829    return TRUE;      {
1830        if (*ptr == ']') return FALSE;
1831        if (*ptr == terminator && ptr[1] == ']')
1832          {
1833          *endptr = ptr;
1834          return TRUE;
1835          }
1836        }
1837    }    }
1838  return FALSE;  return FALSE;
1839  }  }
# Line 1581  Returns:     a value representing the na Line 1858  Returns:     a value representing the na
1858  static int  static int
1859  check_posix_name(const uschar *ptr, int len)  check_posix_name(const uschar *ptr, int len)
1860  {  {
1861    const char *pn = posix_names;
1862  register int yield = 0;  register int yield = 0;
1863  while (posix_name_lengths[yield] != 0)  while (posix_name_lengths[yield] != 0)
1864    {    {
1865    if (len == posix_name_lengths[yield] &&    if (len == posix_name_lengths[yield] &&
1866      strncmp((const char *)ptr, posix_names[yield], len) == 0) return yield;      strncmp((const char *)ptr, pn, len) == 0) return yield;
1867      pn += posix_name_lengths[yield] + 1;
1868    yield++;    yield++;
1869    }    }
1870  return -1;  return -1;
# Line 1600  return -1; Line 1879  return -1;
1879  that is referenced. This means that groups can be replicated for fixed  that is referenced. This means that groups can be replicated for fixed
1880  repetition simply by copying (because the recursion is allowed to refer to  repetition simply by copying (because the recursion is allowed to refer to
1881  earlier groups that are outside the current group). However, when a group is  earlier groups that are outside the current group). However, when a group is
1882  optional (i.e. the minimum quantifier is zero), OP_BRAZERO is inserted before  optional (i.e. the minimum quantifier is zero), OP_BRAZERO or OP_SKIPZERO is
1883  it, after it has been compiled. This means that any OP_RECURSE items within it  inserted before it, after it has been compiled. This means that any OP_RECURSE
1884  that refer to the group itself or any contained groups have to have their  items within it that refer to the group itself or any contained groups have to
1885  offsets adjusted. That one of the jobs of this function. Before it is called,  have their offsets adjusted. That one of the jobs of this function. Before it
1886  the partially compiled regex must be temporarily terminated with OP_END.  is called, the partially compiled regex must be temporarily terminated with
1887    OP_END.
1888    
1889  This function has been extended with the possibility of forward references for  This function has been extended with the possibility of forward references for
1890  recursions and subroutine calls. It must also check the list of such references  recursions and subroutine calls. It must also check the list of such references
# Line 1627  adjust_recurse(uschar *group, int adjust Line 1907  adjust_recurse(uschar *group, int adjust
1907    uschar *save_hwm)    uschar *save_hwm)
1908  {  {
1909  uschar *ptr = group;  uschar *ptr = group;
1910    
1911  while ((ptr = (uschar *)find_recurse(ptr, utf8)) != NULL)  while ((ptr = (uschar *)find_recurse(ptr, utf8)) != NULL)
1912    {    {
1913    int offset;    int offset;
# Line 1738  get_othercase_range(unsigned int *cptr, Line 2019  get_othercase_range(unsigned int *cptr,
2019  unsigned int c, othercase, next;  unsigned int c, othercase, next;
2020    
2021  for (c = *cptr; c <= d; c++)  for (c = *cptr; c <= d; c++)
2022    { if ((othercase = _pcre_ucp_othercase(c)) != NOTACHAR) break; }    { if ((othercase = UCD_OTHERCASE(c)) != c) break; }
2023    
2024  if (c > d) return FALSE;  if (c > d) return FALSE;
2025    
# Line 1747  next = othercase + 1; Line 2028  next = othercase + 1;
2028    
2029  for (++c; c <= d; c++)  for (++c; c <= d; c++)
2030    {    {
2031    if (_pcre_ucp_othercase(c) != next) break;    if (UCD_OTHERCASE(c) != next) break;
2032    next++;    next++;
2033    }    }
2034    
# Line 1857  if (next >= 0) switch(op_code) Line 2138  if (next >= 0) switch(op_code)
2138    case OP_CHAR:    case OP_CHAR:
2139  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF8
2140    if (utf8 && item > 127) { GETCHAR(item, utf8_char); }    if (utf8 && item > 127) { GETCHAR(item, utf8_char); }
2141    #else
2142      (void)(utf8_char);  /* Keep compiler happy by referencing function argument */
2143  #endif  #endif
2144    return item != next;    return item != next;
2145    
# Line 1875  if (next >= 0) switch(op_code) Line 2158  if (next >= 0) switch(op_code)
2158      unsigned int othercase;      unsigned int othercase;
2159      if (next < 128) othercase = cd->fcc[next]; else      if (next < 128) othercase = cd->fcc[next]; else
2160  #ifdef SUPPORT_UCP  #ifdef SUPPORT_UCP
2161      othercase = _pcre_ucp_othercase((unsigned int)next);      othercase = UCD_OTHERCASE((unsigned int)next);
2162  #else  #else
2163      othercase = NOTACHAR;      othercase = NOTACHAR;
2164  #endif  #endif
# Line 1888  if (next >= 0) switch(op_code) Line 2171  if (next >= 0) switch(op_code)
2171    /* For OP_NOT, "item" must be a single-byte character. */    /* For OP_NOT, "item" must be a single-byte character. */
2172    
2173    case OP_NOT:    case OP_NOT:
   if (next < 0) return FALSE;  /* Not a character */  
2174    if (item == next) return TRUE;    if (item == next) return TRUE;
2175    if ((options & PCRE_CASELESS) == 0) return FALSE;    if ((options & PCRE_CASELESS) == 0) return FALSE;
2176  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF8
# Line 1897  if (next >= 0) switch(op_code) Line 2179  if (next >= 0) switch(op_code)
2179      unsigned int othercase;      unsigned int othercase;
2180      if (next < 128) othercase = cd->fcc[next]; else      if (next < 128) othercase = cd->fcc[next]; else
2181  #ifdef SUPPORT_UCP  #ifdef SUPPORT_UCP
2182      othercase = _pcre_ucp_othercase(next);      othercase = UCD_OTHERCASE(next);
2183  #else  #else
2184      othercase = NOTACHAR;      othercase = NOTACHAR;
2185  #endif  #endif
# Line 1925  if (next >= 0) switch(op_code) Line 2207  if (next >= 0) switch(op_code)
2207    case OP_NOT_WORDCHAR:    case OP_NOT_WORDCHAR:
2208    return next <= 127 && (cd->ctypes[next] & ctype_word) != 0;    return next <= 127 && (cd->ctypes[next] & ctype_word) != 0;
2209    
2210      case OP_HSPACE:
2211      case OP_NOT_HSPACE:
2212      switch(next)
2213        {
2214        case 0x09:
2215        case 0x20:
2216        case 0xa0:
2217        case 0x1680:
2218        case 0x180e:
2219        case 0x2000:
2220        case 0x2001:
2221        case 0x2002:
2222        case 0x2003:
2223        case 0x2004:
2224        case 0x2005:
2225        case 0x2006:
2226        case 0x2007:
2227        case 0x2008:
2228        case 0x2009:
2229        case 0x200A:
2230        case 0x202f:
2231        case 0x205f:
2232        case 0x3000:
2233        return op_code != OP_HSPACE;
2234        default:
2235        return op_code == OP_HSPACE;
2236        }
2237    
2238      case OP_VSPACE:
2239      case OP_NOT_VSPACE:
2240      switch(next)
2241        {
2242        case 0x0a:
2243        case 0x0b:
2244        case 0x0c:
2245        case 0x0d:
2246        case 0x85:
2247        case 0x2028:
2248        case 0x2029:
2249        return op_code != OP_VSPACE;
2250        default:
2251        return op_code == OP_VSPACE;
2252        }
2253    
2254    default:    default:
2255    return FALSE;    return FALSE;
2256    }    }
# Line 1959  switch(op_code) Line 2285  switch(op_code)
2285      case ESC_W:      case ESC_W:
2286      return item <= 127 && (cd->ctypes[item] & ctype_word) != 0;      return item <= 127 && (cd->ctypes[item] & ctype_word) != 0;
2287    
2288        case ESC_h:
2289        case ESC_H:
2290        switch(item)
2291          {
2292          case 0x09:
2293          case 0x20:
2294          case 0xa0:
2295          case 0x1680:
2296          case 0x180e:
2297          case 0x2000:
2298          case 0x2001:
2299          case 0x2002:
2300          case 0x2003:
2301          case 0x2004:
2302          case 0x2005:
2303          case 0x2006:
2304          case 0x2007:
2305          case 0x2008:
2306          case 0x2009:
2307          case 0x200A:
2308          case 0x202f:
2309          case 0x205f:
2310          case 0x3000:
2311          return -next != ESC_h;
2312          default:
2313          return -next == ESC_h;
2314          }
2315    
2316        case ESC_v:
2317        case ESC_V:
2318        switch(item)
2319          {
2320          case 0x0a:
2321          case 0x0b:
2322          case 0x0c:
2323          case 0x0d:
2324          case 0x85:
2325          case 0x2028:
2326          case 0x2029:
2327          return -next != ESC_v;
2328          default:
2329          return -next == ESC_v;
2330          }
2331    
2332      default:      default:
2333      return FALSE;      return FALSE;
2334      }      }
2335    
2336    case OP_DIGIT:    case OP_DIGIT:
2337    return next == -ESC_D || next == -ESC_s || next == -ESC_W;    return next == -ESC_D || next == -ESC_s || next == -ESC_W ||
2338             next == -ESC_h || next == -ESC_v;
2339    
2340    case OP_NOT_DIGIT:    case OP_NOT_DIGIT:
2341    return next == -ESC_d;    return next == -ESC_d;
# Line 1973  switch(op_code) Line 2344  switch(op_code)
2344    return next == -ESC_S || next == -ESC_d || next == -ESC_w;    return next == -ESC_S || next == -ESC_d || next == -ESC_w;
2345    
2346    case OP_NOT_WHITESPACE:    case OP_NOT_WHITESPACE:
2347    return next == -ESC_s;    return next == -ESC_s || next == -ESC_h || next == -ESC_v;
2348    
2349      case OP_HSPACE:
2350      return next == -ESC_S || next == -ESC_H || next == -ESC_d || next == -ESC_w;
2351    
2352      case OP_NOT_HSPACE:
2353      return next == -ESC_h;
2354    
2355      /* Can't have \S in here because VT matches \S (Perl anomaly) */
2356      case OP_VSPACE:
2357      return next == -ESC_V || next == -ESC_d || next == -ESC_w;
2358    
2359      case OP_NOT_VSPACE:
2360      return next == -ESC_v;
2361    
2362    case OP_WORDCHAR:    case OP_WORDCHAR:
2363    return next == -ESC_W || next == -ESC_s;    return next == -ESC_W || next == -ESC_s || next == -ESC_h || next == -ESC_v;
2364    
2365    case OP_NOT_WORDCHAR:    case OP_NOT_WORDCHAR:
2366    return next == -ESC_w || next == -ESC_d;    return next == -ESC_w || next == -ESC_d;
# Line 2049  uschar classbits[32]; Line 2433  uschar classbits[32];
2433  BOOL class_utf8;  BOOL class_utf8;
2434  BOOL utf8 = (options & PCRE_UTF8) != 0;  BOOL utf8 = (options & PCRE_UTF8) != 0;
2435  uschar *class_utf8data;  uschar *class_utf8data;
2436    uschar *class_utf8data_base;
2437  uschar utf8_char[6];  uschar utf8_char[6];
2438  #else  #else
2439  BOOL utf8 = FALSE;  BOOL utf8 = FALSE;
# Line 2088  req_caseopt = ((options & PCRE_CASELESS) Line 2473  req_caseopt = ((options & PCRE_CASELESS)
2473  for (;; ptr++)  for (;; ptr++)
2474    {    {
2475    BOOL negate_class;    BOOL negate_class;
2476      BOOL should_flip_negation;
2477    BOOL possessive_quantifier;    BOOL possessive_quantifier;
2478    BOOL is_quantifier;    BOOL is_quantifier;
2479    BOOL is_recurse;    BOOL is_recurse;
2480      BOOL reset_bracount;
2481    int class_charcount;    int class_charcount;
2482    int class_lastchar;    int class_lastchar;
2483    int newoptions;    int newoptions;
2484    int recno;    int recno;
2485      int refsign;
2486    int skipbytes;    int skipbytes;
2487    int subreqbyte;    int subreqbyte;
2488    int subfirstbyte;    int subfirstbyte;
# Line 2127  for (;; ptr++) Line 2515  for (;; ptr++)
2515      */      */
2516    
2517      if (code < last_code) code = last_code;      if (code < last_code) code = last_code;
2518    
2519        /* Paranoid check for integer overflow */
2520    
2521        if (OFLOW_MAX - *lengthptr < code - last_code)
2522          {
2523          *errorcodeptr = ERR20;
2524          goto FAILED;
2525          }
2526    
2527      *lengthptr += code - last_code;      *lengthptr += code - last_code;
2528      DPRINTF(("length=%d added %d c=%c\n", *lengthptr, code - last_code, c));      DPRINTF(("length=%d added %d c=%c\n", *lengthptr, code - last_code, c));
2529    
# Line 2239  for (;; ptr++) Line 2636  for (;; ptr++)
2636      *ptrptr = ptr;      *ptrptr = ptr;
2637      if (lengthptr != NULL)      if (lengthptr != NULL)
2638        {        {
2639          if (OFLOW_MAX - *lengthptr < code - last_code)
2640            {
2641            *errorcodeptr = ERR20;
2642            goto FAILED;
2643            }
2644        *lengthptr += code - last_code;   /* To include callout length */        *lengthptr += code - last_code;   /* To include callout length */
2645        DPRINTF((">> end branch\n"));        DPRINTF((">> end branch\n"));
2646        }        }
# Line 2271  for (;; ptr++) Line 2673  for (;; ptr++)
2673      zerofirstbyte = firstbyte;      zerofirstbyte = firstbyte;
2674      zeroreqbyte = reqbyte;      zeroreqbyte = reqbyte;
2675      previous = code;      previous = code;
2676      *code++ = OP_ANY;      *code++ = ((options & PCRE_DOTALL) != 0)? OP_ALLANY: OP_ANY;
2677      break;      break;
2678    
2679    
# Line 2286  for (;; ptr++) Line 2688  for (;; ptr++)
2688      opcode is compiled. It may optionally have a bit map for characters < 256,      opcode is compiled. It may optionally have a bit map for characters < 256,
2689      but those above are are explicitly listed afterwards. A flag byte tells      but those above are are explicitly listed afterwards. A flag byte tells
2690      whether the bitmap is present, and whether this is a negated class or not.      whether the bitmap is present, and whether this is a negated class or not.
2691      */  
2692        In JavaScript compatibility mode, an isolated ']' causes an error. In
2693        default (Perl) mode, it is treated as a data character. */
2694    
2695        case ']':
2696        if ((cd->external_options & PCRE_JAVASCRIPT_COMPAT) != 0)
2697          {
2698          *errorcodeptr = ERR64;
2699          goto FAILED;
2700          }
2701        goto NORMAL_CHAR;
2702    
2703      case '[':      case '[':
2704      previous = code;      previous = code;
# Line 2295  for (;; ptr++) Line 2707  for (;; ptr++)
2707      they are encountered at the top level, so we'll do that too. */      they are encountered at the top level, so we'll do that too. */
2708    
2709      if ((ptr[1] == ':' || ptr[1] == '.' || ptr[1] == '=') &&      if ((ptr[1] == ':' || ptr[1] == '.' || ptr[1] == '=') &&
2710          check_posix_syntax(ptr, &tempptr, cd))          check_posix_syntax(ptr, &tempptr))
2711        {        {
2712        *errorcodeptr = (ptr[1] == ':')? ERR13 : ERR31;        *errorcodeptr = (ptr[1] == ':')? ERR13 : ERR31;
2713        goto FAILED;        goto FAILED;
2714        }        }
2715    
2716      /* If the first character is '^', set the negation flag and skip it. */      /* If the first character is '^', set the negation flag and skip it. Also,
2717        if the first few characters (either before or after ^) are \Q\E or \E we
2718        skip them too. This makes for compatibility with Perl. */
2719    
2720      if ((c = *(++ptr)) == '^')      negate_class = FALSE;
2721        for (;;)
2722        {        {
       negate_class = TRUE;  
2723        c = *(++ptr);        c = *(++ptr);
2724          if (c == '\\')
2725            {
2726            if (ptr[1] == 'E') ptr++;
2727              else if (strncmp((const char *)ptr+1, "Q\\E", 3) == 0) ptr += 3;
2728                else break;
2729            }
2730          else if (!negate_class && c == '^')
2731            negate_class = TRUE;
2732          else break;
2733        }        }
2734      else  
2735        /* Empty classes are allowed in JavaScript compatibility mode. Otherwise,
2736        an initial ']' is taken as a data character -- the code below handles
2737        that. In JS mode, [] must always fail, so generate OP_FAIL, whereas
2738        [^] must match any character, so generate OP_ALLANY. */
2739    
2740        if (c ==']' && (cd->external_options & PCRE_JAVASCRIPT_COMPAT) != 0)
2741        {        {
2742        negate_class = FALSE;        *code++ = negate_class? OP_ALLANY : OP_FAIL;
2743          if (firstbyte == REQ_UNSET) firstbyte = REQ_NONE;
2744          zerofirstbyte = firstbyte;
2745          break;
2746        }        }
2747    
2748        /* If a class contains a negative special such as \S, we need to flip the
2749        negation flag at the end, so that support for characters > 255 works
2750        correctly (they are all included in the class). */
2751    
2752        should_flip_negation = FALSE;
2753    
2754      /* Keep a count of chars with values < 256 so that we can optimize the case      /* Keep a count of chars with values < 256 so that we can optimize the case
2755      of just a single character (as long as it's < 256). However, For higher      of just a single character (as long as it's < 256). However, For higher
2756      valued UTF-8 characters, we don't yet do any optimization. */      valued UTF-8 characters, we don't yet do any optimization. */
# Line 2330  for (;; ptr++) Line 2768  for (;; ptr++)
2768  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF8
2769      class_utf8 = FALSE;                       /* No chars >= 256 */      class_utf8 = FALSE;                       /* No chars >= 256 */
2770      class_utf8data = code + LINK_SIZE + 2;    /* For UTF-8 items */      class_utf8data = code + LINK_SIZE + 2;    /* For UTF-8 items */
2771        class_utf8data_base = class_utf8data;     /* For resetting in pass 1 */
2772  #endif  #endif
2773    
2774      /* Process characters until ] is reached. By writing this as a "do" it      /* Process characters until ] is reached. By writing this as a "do" it
# Line 2345  for (;; ptr++) Line 2784  for (;; ptr++)
2784          {                           /* Braces are required because the */          {                           /* Braces are required because the */
2785          GETCHARLEN(c, ptr, ptr);    /* macro generates multiple statements */          GETCHARLEN(c, ptr, ptr);    /* macro generates multiple statements */
2786          }          }
2787    
2788          /* In the pre-compile phase, accumulate the length of any UTF-8 extra
2789          data and reset the pointer. This is so that very large classes that
2790          contain a zillion UTF-8 characters no longer overwrite the work space
2791          (which is on the stack). */
2792    
2793          if (lengthptr != NULL)
2794            {
2795            *lengthptr += class_utf8data - class_utf8data_base;
2796            class_utf8data = class_utf8data_base;
2797            }
2798    
2799  #endif  #endif
2800    
2801        /* Inside \Q...\E everything is literal except \E */        /* Inside \Q...\E everything is literal except \E */
# Line 2368  for (;; ptr++) Line 2819  for (;; ptr++)
2819    
2820        if (c == '[' &&        if (c == '[' &&
2821            (ptr[1] == ':' || ptr[1] == '.' || ptr[1] == '=') &&            (ptr[1] == ':' || ptr[1] == '.' || ptr[1] == '=') &&
2822            check_posix_syntax(ptr, &tempptr, cd))            check_posix_syntax(ptr, &tempptr))
2823          {          {
2824          BOOL local_negate = FALSE;          BOOL local_negate = FALSE;
2825          int posix_class, taboffset, tabopt;          int posix_class, taboffset, tabopt;
# Line 2385  for (;; ptr++) Line 2836  for (;; ptr++)
2836          if (*ptr == '^')          if (*ptr == '^')
2837            {            {
2838            local_negate = TRUE;            local_negate = TRUE;
2839              should_flip_negation = TRUE;  /* Note negative special */
2840            ptr++;            ptr++;
2841            }            }
2842    
# Line 2451  for (;; ptr++) Line 2903  for (;; ptr++)
2903        of the specials, which just set a flag. The sequence \b is a special        of the specials, which just set a flag. The sequence \b is a special
2904        case. Inside a class (and only there) it is treated as backspace.        case. Inside a class (and only there) it is treated as backspace.
2905        Elsewhere it marks a word boundary. Other escapes have preset maps ready        Elsewhere it marks a word boundary. Other escapes have preset maps ready
2906        to or into the one we are building. We assume they have more than one        to 'or' into the one we are building. We assume they have more than one
2907        character in them, so set class_charcount bigger than one. */        character in them, so set class_charcount bigger than one. */
2908    
2909        if (c == '\\')        if (c == '\\')
# Line 2459  for (;; ptr++) Line 2911  for (;; ptr++)
2911          c = check_escape(&ptr, errorcodeptr, cd->bracount, options, TRUE);          c = check_escape(&ptr, errorcodeptr, cd->bracount, options, TRUE);
2912          if (*errorcodeptr != 0) goto FAILED;          if (*errorcodeptr != 0) goto FAILED;
2913    
2914          if (-c == ESC_b) c = '\b';       /* \b is backslash in a class */          if (-c == ESC_b) c = '\b';       /* \b is backspace in a class */
2915          else if (-c == ESC_X) c = 'X';   /* \X is literal X in a class */          else if (-c == ESC_X) c = 'X';   /* \X is literal X in a class */
2916          else if (-c == ESC_R) c = 'R';   /* \R is literal R in a class */          else if (-c == ESC_R) c = 'R';   /* \R is literal R in a class */
2917          else if (-c == ESC_Q)            /* Handle start of quoted string */          else if (-c == ESC_Q)            /* Handle start of quoted string */
# Line 2471  for (;; ptr++) Line 2923  for (;; ptr++)
2923            else inescq = TRUE;            else inescq = TRUE;
2924            continue;            continue;
2925            }            }
2926            else if (-c == ESC_E) continue;  /* Ignore orphan \E */
2927    
2928          if (c < 0)          if (c < 0)
2929            {            {
# Line 2486  for (;; ptr++) Line 2939  for (;; ptr++)
2939              continue;              continue;
2940    
2941              case ESC_D:              case ESC_D:
2942                should_flip_negation = TRUE;
2943              for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_digit];              for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_digit];
2944              continue;              continue;
2945    
# Line 2494  for (;; ptr++) Line 2948  for (;; ptr++)
2948              continue;              continue;
2949    
2950              case ESC_W:              case ESC_W:
2951                should_flip_negation = TRUE;
2952              for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_word];              for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_word];
2953              continue;              continue;
2954    
# Line 2503  for (;; ptr++) Line 2958  for (;; ptr++)
2958              continue;              continue;
2959    
2960              case ESC_S:              case ESC_S:
2961                should_flip_negation = TRUE;
2962              for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_space];              for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_space];
2963              classbits[1] |= 0x08;    /* Perl 5.004 onwards omits VT from \s */              classbits[1] |= 0x08;    /* Perl 5.004 onwards omits VT from \s */
2964              continue;              continue;
2965    
             case ESC_E: /* Perl ignores an orphan \E */  
             continue;  
   
2966              default:    /* Not recognized; fall through */              default:    /* Not recognized; fall through */
2967              break;      /* Need "default" setting to stop compiler warning. */              break;      /* Need "default" setting to stop compiler warning. */
2968              }              }
# Line 2519  for (;; ptr++) Line 2972  for (;; ptr++)
2972            else if (c == -ESC_d || c == -ESC_D || c == -ESC_w ||            else if (c == -ESC_d || c == -ESC_D || c == -ESC_w ||
2973                     c == -ESC_W || c == -ESC_s || c == -ESC_S) continue;                     c == -ESC_W || c == -ESC_s || c == -ESC_S) continue;
2974    
2975              /* We need to deal with \H, \h, \V, and \v in both phases because
2976              they use extra memory. */
2977    
2978              if (-c == ESC_h)
2979                {
2980                SETBIT(classbits, 0x09); /* VT */
2981                SETBIT(classbits, 0x20); /* SPACE */
2982                SETBIT(classbits, 0xa0); /* NSBP */
2983    #ifdef SUPPORT_UTF8
2984                if (utf8)
2985                  {
2986                  class_utf8 = TRUE;
2987                  *class_utf8data++ = XCL_SINGLE;
2988                  class_utf8data += _pcre_ord2utf8(0x1680, class_utf8data);
2989                  *class_utf8data++ = XCL_SINGLE;
2990                  class_utf8data += _pcre_ord2utf8(0x180e, class_utf8data);
2991                  *class_utf8data++ = XCL_RANGE;
2992                  class_utf8data += _pcre_ord2utf8(0x2000, class_utf8data);
2993                  class_utf8data += _pcre_ord2utf8(0x200A, class_utf8data);
2994                  *class_utf8data++ = XCL_SINGLE;
2995                  class_utf8data += _pcre_ord2utf8(0x202f, class_utf8data);
2996                  *class_utf8data++ = XCL_SINGLE;
2997                  class_utf8data += _pcre_ord2utf8(0x205f, class_utf8data);
2998                  *class_utf8data++ = XCL_SINGLE;
2999                  class_utf8data += _pcre_ord2utf8(0x3000, class_utf8data);
3000                  }
3001    #endif
3002                continue;
3003                }
3004    
3005              if (-c == ESC_H)
3006                {
3007                for (c = 0; c < 32; c++)
3008                  {
3009                  int x = 0xff;
3010                  switch (c)
3011                    {
3012                    case 0x09/8: x ^= 1 << (0x09%8); break;
3013                    case 0x20/8: x ^= 1 << (0x20%8); break;
3014                    case 0xa0/8: x ^= 1 << (0xa0%8); break;
3015                    default: break;
3016                    }
3017                  classbits[c] |= x;
3018                  }
3019    
3020    #ifdef SUPPORT_UTF8
3021                if (utf8)
3022                  {
3023                  class_utf8 = TRUE;
3024                  *class_utf8data++ = XCL_RANGE;
3025                  class_utf8data += _pcre_ord2utf8(0x0100, class_utf8data);
3026                  class_utf8data += _pcre_ord2utf8(0x167f, class_utf8data);
3027                  *class_utf8data++ = XCL_RANGE;
3028                  class_utf8data += _pcre_ord2utf8(0x1681, class_utf8data);
3029                  class_utf8data += _pcre_ord2utf8(0x180d, class_utf8data);
3030                  *class_utf8data++ = XCL_RANGE;
3031                  class_utf8data += _pcre_ord2utf8(0x180f, class_utf8data);
3032                  class_utf8data += _pcre_ord2utf8(0x1fff, class_utf8data);
3033                  *class_utf8data++ = XCL_RANGE;
3034                  class_utf8data += _pcre_ord2utf8(0x200B, class_utf8data);
3035                  class_utf8data += _pcre_ord2utf8(0x202e, class_utf8data);
3036                  *class_utf8data++ = XCL_RANGE;
3037                  class_utf8data += _pcre_ord2utf8(0x2030, class_utf8data);
3038                  class_utf8data += _pcre_ord2utf8(0x205e, class_utf8data);
3039                  *class_utf8data++ = XCL_RANGE;
3040                  class_utf8data += _pcre_ord2utf8(0x2060, class_utf8data);
3041                  class_utf8data += _pcre_ord2utf8(0x2fff, class_utf8data);
3042                  *class_utf8data++ = XCL_RANGE;
3043                  class_utf8data += _pcre_ord2utf8(0x3001, class_utf8data);
3044                  class_utf8data += _pcre_ord2utf8(0x7fffffff, class_utf8data);
3045                  }
3046    #endif
3047                continue;
3048                }
3049    
3050              if (-c == ESC_v)
3051                {
3052                SETBIT(classbits, 0x0a); /* LF */
3053                SETBIT(classbits, 0x0b); /* VT */
3054                SETBIT(classbits, 0x0c); /* FF */
3055                SETBIT(classbits, 0x0d); /* CR */
3056                SETBIT(classbits, 0x85); /* NEL */
3057    #ifdef SUPPORT_UTF8
3058                if (utf8)
3059                  {
3060                  class_utf8 = TRUE;
3061                  *class_utf8data++ = XCL_RANGE;
3062                  class_utf8data += _pcre_ord2utf8(0x2028, class_utf8data);
3063                  class_utf8data += _pcre_ord2utf8(0x2029, class_utf8data);
3064                  }
3065    #endif
3066                continue;
3067                }
3068    
3069              if (-c == ESC_V)
3070                {
3071                for (c = 0; c < 32; c++)
3072                  {
3073                  int x = 0xff;
3074                  switch (c)
3075                    {
3076                    case 0x0a/8: x ^= 1 << (0x0a%8);
3077                                 x ^= 1 << (0x0b%8);
3078                                 x ^= 1 << (0x0c%8);
3079                                 x ^= 1 << (0x0d%8);
3080                                 break;
3081                    case 0x85/8: x ^= 1 << (0x85%8); break;
3082                    default: break;
3083                    }
3084                  classbits[c] |= x;
3085                  }
3086    
3087    #ifdef SUPPORT_UTF8
3088                if (utf8)
3089                  {
3090                  class_utf8 = TRUE;
3091                  *class_utf8data++ = XCL_RANGE;
3092                  class_utf8data += _pcre_ord2utf8(0x0100, class_utf8data);
3093                  class_utf8data += _pcre_ord2utf8(0x2027, class_utf8data);
3094                  *class_utf8data++ = XCL_RANGE;
3095                  class_utf8data += _pcre_ord2utf8(0x2029, class_utf8data);
3096                  class_utf8data += _pcre_ord2utf8(0x7fffffff, class_utf8data);
3097                  }
3098    #endif
3099                continue;
3100                }
3101    
3102            /* We need to deal with \P and \p in both phases. */            /* We need to deal with \P and \p in both phases. */
3103    
3104  #ifdef SUPPORT_UCP  #ifdef SUPPORT_UCP
# Line 2570  for (;; ptr++) Line 3150  for (;; ptr++)
3150    
3151        oldptr = ptr;        oldptr = ptr;
3152    
3153          /* Remember \r or \n */
3154    
3155          if (c == '\r' || c == '\n') cd->external_flags |= PCRE_HASCRORLF;
3156    
3157          /* Check for range */
3158    
3159        if (!inescq && ptr[1] == '-')        if (!inescq && ptr[1] == '-')
3160          {          {
3161          int d;          int d;
# Line 2611  for (;; ptr++) Line 3197  for (;; ptr++)
3197            d = check_escape(&ptr, errorcodeptr, cd->bracount, options, TRUE);            d = check_escape(&ptr, errorcodeptr, cd->bracount, options, TRUE);
3198            if (*errorcodeptr != 0) goto FAILED;            if (*errorcodeptr != 0) goto FAILED;
3199    
3200            /* \b is backslash; \X is literal X; \R is literal R; any other            /* \b is backspace; \X is literal X; \R is literal R; any other
3201            special means the '-' was literal */            special means the '-' was literal */
3202    
3203            if (d < 0)            if (d < 0)
# Line 2637  for (;; ptr++) Line 3223  for (;; ptr++)
3223    
3224          if (d == c) goto LONE_SINGLE_CHARACTER;  /* A few lines below */          if (d == c) goto LONE_SINGLE_CHARACTER;  /* A few lines below */
3225    
3226            /* Remember \r or \n */
3227    
3228            if (d == '\r' || d == '\n') cd->external_flags |= PCRE_HASCRORLF;
3229    
3230          /* In UTF-8 mode, if the upper limit is > 255, or > 127 for caseless          /* In UTF-8 mode, if the upper limit is > 255, or > 127 for caseless
3231          matching, we have to use an XCLASS with extra data items. Caseless          matching, we have to use an XCLASS with extra data items. Caseless
3232          matching for characters > 127 is available only if UCP support is          matching for characters > 127 is available only if UCP support is
# Line 2659  for (;; ptr++) Line 3249  for (;; ptr++)
3249              unsigned int origd = d;              unsigned int origd = d;
3250              while (get_othercase_range(&cc, origd, &occ, &ocd))              while (get_othercase_range(&cc, origd, &occ, &ocd))
3251                {                {
3252                if (occ >= c && ocd <= d) continue;  /* Skip embedded ranges */                if (occ >= (unsigned int)c &&
3253                      ocd <= (unsigned int)d)
3254                    continue;                          /* Skip embedded ranges */
3255    
3256                if (occ < c  && ocd >= c - 1)        /* Extend the basic range */                if (occ < (unsigned int)c  &&
3257                      ocd >= (unsigned int)c - 1)      /* Extend the basic range */
3258                  {                                  /* if there is overlap,   */                  {                                  /* if there is overlap,   */
3259                  c = occ;                           /* noting that if occ < c */                  c = occ;                           /* noting that if occ < c */
3260                  continue;                          /* we can't have ocd > d  */                  continue;                          /* we can't have ocd > d  */
3261                  }                                  /* because a subrange is  */                  }                                  /* because a subrange is  */
3262                if (ocd > d && occ <= d + 1)         /* always shorter than    */                if (ocd > (unsigned int)d &&
3263                      occ <= (unsigned int)d + 1)      /* always shorter than    */
3264                  {                                  /* the basic range.       */                  {                                  /* the basic range.       */
3265                  d = ocd;                  d = ocd;
3266                  continue;                  continue;
# Line 2751  for (;; ptr++) Line 3345  for (;; ptr++)
3345          if ((options & PCRE_CASELESS) != 0)          if ((options & PCRE_CASELESS) != 0)
3346            {            {
3347            unsigned int othercase;            unsigned int othercase;
3348            if ((othercase = _pcre_ucp_othercase(c)) != NOTACHAR)            if ((othercase = UCD_OTHERCASE(c)) != c)
3349              {              {
3350              *class_utf8data++ = XCL_SINGLE;              *class_utf8data++ = XCL_SINGLE;
3351              class_utf8data += _pcre_ord2utf8(othercase, class_utf8data);              class_utf8data += _pcre_ord2utf8(othercase, class_utf8data);
# Line 2786  for (;; ptr++) Line 3380  for (;; ptr++)
3380        goto FAILED;        goto FAILED;
3381        }        }
3382    
3383    
3384    /* This code has been disabled because it would mean that \s counts as
3385    an explicit \r or \n reference, and that's not really what is wanted. Now
3386    we set the flag only if there is a literal "\r" or "\n" in the class. */
3387    
3388    #if 0
3389        /* Remember whether \r or \n are in this class */
3390    
3391        if (negate_class)
3392          {
3393          if ((classbits[1] & 0x24) != 0x24) cd->external_flags |= PCRE_HASCRORLF;
3394          }
3395        else
3396          {
3397          if ((classbits[1] & 0x24) != 0) cd->external_flags |= PCRE_HASCRORLF;
3398          }
3399    #endif
3400    
3401    
3402      /* If class_charcount is 1, we saw precisely one character whose value is      /* If class_charcount is 1, we saw precisely one character whose value is
3403      less than 256. In non-UTF-8 mode we can always optimize. In UTF-8 mode, we      less than 256. As long as there were no characters >= 128 and there was no
3404      can optimize the negative case only if there were no characters >= 128      use of \p or \P, in other words, no use of any XCLASS features, we can
3405      because OP_NOT and the related opcodes like OP_NOTSTAR operate on      optimize.
3406      single-bytes only. This is an historical hangover. Maybe one day we can  
3407      tidy these opcodes to handle multi-byte characters.      In UTF-8 mode, we can optimize the negative case only if there were no
3408        characters >= 128 because OP_NOT and the related opcodes like OP_NOTSTAR
3409        operate on single-bytes only. This is an historical hangover. Maybe one day
3410        we can tidy these opcodes to handle multi-byte characters.
3411    
3412      The optimization throws away the bit map. We turn the item into a      The optimization throws away the bit map. We turn the item into a
3413      1-character OP_CHAR[NC] if it's positive, or OP_NOT if it's negative. Note      1-character OP_CHAR[NC] if it's positive, or OP_NOT if it's negative. Note
# Line 2801  for (;; ptr++) Line 3417  for (;; ptr++)
3417      reqbyte, save the previous value for reinstating. */      reqbyte, save the previous value for reinstating. */
3418    
3419  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF8
3420      if (class_charcount == 1 &&      if (class_charcount == 1 && !class_utf8 &&
3421            (!utf8 ||        (!utf8 || !negate_class || class_lastchar < 128))
           (!class_utf8 && (!negate_class || class_lastchar < 128))))  
   
3422  #else  #else
3423      if (class_charcount == 1)      if (class_charcount == 1)
3424  #endif  #endif
# Line 2847  for (;; ptr++) Line 3461  for (;; ptr++)
3461      zeroreqbyte = reqbyte;      zeroreqbyte = reqbyte;
3462    
3463      /* If there are characters with values > 255, we have to compile an      /* If there are characters with values > 255, we have to compile an
3464      extended class, with its own opcode. If there are no characters < 256,      extended class, with its own opcode, unless there was a negated special
3465      we can omit the bitmap in the actual compiled code. */      such as \S in the class, because in that case all characters > 255 are in
3466        the class, so any that were explicitly given as well can be ignored. If
3467        (when there are explicit characters > 255 that must be listed) there are no
3468        characters < 256, we can omit the bitmap in the actual compiled code. */
3469    
3470  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF8
3471      if (class_utf8)      if (class_utf8 && !should_flip_negation)
3472        {        {
3473        *class_utf8data++ = XCL_END;    /* Marks the end of extra data */        *class_utf8data++ = XCL_END;    /* Marks the end of extra data */
3474        *code++ = OP_XCLASS;        *code++ = OP_XCLASS;
# Line 2877  for (;; ptr++) Line 3494  for (;; ptr++)
3494        }        }
3495  #endif  #endif
3496    
3497      /* If there are no characters > 255, negate the 32-byte map if necessary,      /* If there are no characters > 255, set the opcode to OP_CLASS or
3498      and copy it into the code vector. If this is the first thing in the branch,      OP_NCLASS, depending on whether the whole class was negated and whether
3499      there can be no first char setting, whatever the repeat count. Any reqbyte      there were negative specials such as \S in the class. Then copy the 32-byte
3500      setting must remain unchanged after any kind of repeat. */      map into the code vector, negating it if necessary. */
3501    
3502        *code++ = (negate_class == should_flip_negation) ? OP_CLASS : OP_NCLASS;
3503      if (negate_class)      if (negate_class)
3504        {        {
       *code++ = OP_NCLASS;  
3505        if (lengthptr == NULL)    /* Save time in the pre-compile phase */        if (lengthptr == NULL)    /* Save time in the pre-compile phase */
3506          for (c = 0; c < 32; c++) code[c] = ~classbits[c];          for (c = 0; c < 32; c++) code[c] = ~classbits[c];
3507        }        }
3508      else      else
3509        {        {
       *code++ = OP_CLASS;  
3510        memcpy(code, classbits, 32);        memcpy(code, classbits, 32);
3511        }        }
3512      code += 32;      code += 32;
# Line 3076  for (;; ptr++) Line 3692  for (;; ptr++)
3692        /* All real repeats make it impossible to handle partial matching (maybe        /* All real repeats make it impossible to handle partial matching (maybe
3693        one day we will be able to remove this restriction). */        one day we will be able to remove this restriction). */
3694    
3695        if (repeat_max != 1) cd->nopartial = TRUE;        if (repeat_max != 1) cd->external_flags |= PCRE_NOPARTIAL;
3696    
3697        /* Combine the op_type with the repeat_type */        /* Combine the op_type with the repeat_type */
3698    
# Line 3226  for (;; ptr++) Line 3842  for (;; ptr++)
3842        /* All real repeats make it impossible to handle partial matching (maybe        /* All real repeats make it impossible to handle partial matching (maybe
3843        one day we will be able to remove this restriction). */        one day we will be able to remove this restriction). */
3844    
3845        if (repeat_max != 1) cd->nopartial = TRUE;        if (repeat_max != 1) cd->external_flags |= PCRE_NOPARTIAL;
3846    
3847        if (repeat_min == 0 && repeat_max == -1)        if (repeat_min == 0 && repeat_max == -1)
3848          *code++ = OP_CRSTAR + repeat_type;          *code++ = OP_CRSTAR + repeat_type;
# Line 3262  for (;; ptr++) Line 3878  for (;; ptr++)
3878          goto FAILED;          goto FAILED;
3879          }          }
3880    
       /* This is a paranoid check to stop integer overflow later on */  
   
       if (len > MAX_DUPLENGTH)  
         {  
         *errorcodeptr = ERR50;  
         goto FAILED;  
         }  
   
3881        /* If the maximum repeat count is unlimited, find the end of the bracket        /* If the maximum repeat count is unlimited, find the end of the bracket
3882        by scanning through from the start, and compute the offset back to it        by scanning through from the start, and compute the offset back to it
3883        from the current code pointer. There may be an OP_OPT setting following        from the current code pointer. There may be an OP_OPT setting following
# Line 3292  for (;; ptr++) Line 3900  for (;; ptr++)
3900    
3901        if (repeat_min == 0)        if (repeat_min == 0)
3902          {          {
3903          /* If the maximum is also zero, we just omit the group from the output          /* If the maximum is also zero, we used to just omit the group from the
3904          altogether. */          output altogether, like this:
   
         if (repeat_max == 0)  
           {  
           code = previous;  
           goto END_REPEAT;  
           }  
3905    
3906          /* If the maximum is 1 or unlimited, we just have to stick in the          ** if (repeat_max == 0)
3907          BRAZERO and do no more at this point. However, we do need to adjust          **   {
3908          any OP_RECURSE calls inside the group that refer to the group itself or          **   code = previous;
3909          any internal or forward referenced group, because the offset is from          **   goto END_REPEAT;
3910          the start of the whole regex. Temporarily terminate the pattern while          **   }
3911          doing this. */  
3912            However, that fails when a group is referenced as a subroutine from
3913            elsewhere in the pattern, so now we stick in OP_SKIPZERO in front of it
3914            so that it is skipped on execution. As we don't have a list of which
3915            groups are referenced, we cannot do this selectively.
3916    
3917            If the maximum is 1 or unlimited, we just have to stick in the BRAZERO
3918            and do no more at this point. However, we do need to adjust any
3919            OP_RECURSE calls inside the group that refer to the group itself or any
3920            internal or forward referenced group, because the offset is from the
3921            start of the whole regex. Temporarily terminate the pattern while doing
3922            this. */
3923    
3924          if (repeat_max <= 1)          if (repeat_max <= 1)    /* Covers 0, 1, and unlimited */
3925            {            {
3926            *code = OP_END;            *code = OP_END;
3927            adjust_recurse(previous, 1, utf8, cd, save_hwm);            adjust_recurse(previous, 1, utf8, cd, save_hwm);
3928            memmove(previous+1, previous, len);            memmove(previous+1, previous, len);
3929            code++;            code++;
3930              if (repeat_max == 0)
3931                {
3932                *previous++ = OP_SKIPZERO;
3933                goto END_REPEAT;
3934                }
3935            *previous++ = OP_BRAZERO + repeat_type;            *previous++ = OP_BRAZERO + repeat_type;
3936            }            }
3937    
# Line 3358  for (;; ptr++) Line 3976  for (;; ptr++)
3976          if (repeat_min > 1)          if (repeat_min > 1)
3977            {            {
3978            /* In the pre-compile phase, we don't actually do the replication. We            /* In the pre-compile phase, we don't actually do the replication. We
3979            just adjust the length as if we had. */            just adjust the length as if we had. Do some paranoid checks for
3980              potential integer overflow. */
3981    
3982            if (lengthptr != NULL)            if (lengthptr != NULL)
3983              *lengthptr += (repeat_min - 1)*length_prevgroup;              {
3984                int delta = (repeat_min - 1)*length_prevgroup;
3985                if ((double)(repeat_min - 1)*(double)length_prevgroup >
3986                                                                (double)INT_MAX ||
3987                    OFLOW_MAX - *lengthptr < delta)
3988                  {
3989                  *errorcodeptr = ERR20;
3990                  goto FAILED;
3991                  }
3992                *lengthptr += delta;
3993                }
3994    
3995            /* This is compiling for real */            /* This is compiling for real */
3996    
# Line 3399  for (;; ptr++) Line 4028  for (;; ptr++)
4028          /* In the pre-compile phase, we don't actually do the replication. We          /* In the pre-compile phase, we don't actually do the replication. We
4029          just adjust the length as if we had. For each repetition we must add 1          just adjust the length as if we had. For each repetition we must add 1
4030          to the length for BRAZERO and for all but the last repetition we must          to the length for BRAZERO and for all but the last repetition we must
4031          add 2 + 2*LINKSIZE to allow for the nesting that occurs. */          add 2 + 2*LINKSIZE to allow for the nesting that occurs. Do some
4032            paranoid checks to avoid integer overflow. */
4033    
4034          if (lengthptr != NULL && repeat_max > 0)          if (lengthptr != NULL && repeat_max > 0)
4035            *lengthptr += repeat_max * (length_prevgroup + 1 + 2 + 2*LINK_SIZE) -            {
4036              2 - 2*LINK_SIZE;  /* Last one doesn't nest */            int delta = repeat_max * (length_prevgroup + 1 + 2 + 2*LINK_SIZE) -
4037                          2 - 2*LINK_SIZE;   /* Last one doesn't nest */
4038              if ((double)repeat_max *
4039                    (double)(length_prevgroup + 1 + 2 + 2*LINK_SIZE)
4040                      > (double)INT_MAX ||
4041                  OFLOW_MAX - *lengthptr < delta)
4042                {
4043                *errorcodeptr = ERR20;
4044                goto FAILED;
4045                }
4046              *lengthptr += delta;
4047              }
4048    
4049          /* This is compiling for real */          /* This is compiling for real */
4050    
# Line 3485  for (;; ptr++) Line 4126  for (;; ptr++)
4126          }          }
4127        }        }
4128    
4129        /* If previous is OP_FAIL, it was generated by an empty class [] in
4130        JavaScript mode. The other ways in which OP_FAIL can be generated, that is
4131        by (*FAIL) or (?!) set previous to NULL, which gives a "nothing to repeat"
4132        error above. We can just ignore the repeat in JS case. */
4133    
4134        else if (*previous == OP_FAIL) goto END_REPEAT;
4135    
4136      /* Else there's some kind of shambles */      /* Else there's some kind of shambles */
4137    
4138      else      else
# Line 3511  for (;; ptr++) Line 4159  for (;; ptr++)
4159        int len;        int len;
4160        if (*tempcode == OP_EXACT || *tempcode == OP_TYPEEXACT ||        if (*tempcode == OP_EXACT || *tempcode == OP_TYPEEXACT ||
4161            *tempcode == OP_NOTEXACT)            *tempcode == OP_NOTEXACT)
4162          tempcode += _pcre_OP_lengths[*tempcode];          tempcode += _pcre_OP_lengths[*tempcode] +
4163              ((*tempcode == OP_TYPEEXACT &&
4164                 (tempcode[3] == OP_PROP || tempcode[3] == OP_NOTPROP))? 2:0);
4165        len = code - tempcode;        len = code - tempcode;
4166        if (len > 0) switch (*tempcode)        if (len > 0) switch (*tempcode)
4167          {          {
# Line 3555  for (;; ptr++) Line 4205  for (;; ptr++)
4205      /* ===================================================================*/      /* ===================================================================*/
4206      /* Start of nested parenthesized sub-expression, or comment or lookahead or      /* Start of nested parenthesized sub-expression, or comment or lookahead or
4207      lookbehind or option setting or condition or all the other extended      lookbehind or option setting or condition or all the other extended
4208      parenthesis forms. First deal with the specials; all are introduced by ?,      parenthesis forms.  */
     and the appearance of any of them means that this is not a capturing  
     group. */  
4209    
4210      case '(':      case '(':
4211      newoptions = options;      newoptions = options;
4212      skipbytes = 0;      skipbytes = 0;
4213      bravalue = OP_CBRA;      bravalue = OP_CBRA;
4214      save_hwm = cd->hwm;      save_hwm = cd->hwm;
4215        reset_bracount = FALSE;
4216    
4217        /* First deal with various "verbs" that can be introduced by '*'. */
4218    
4219      if (*(++ptr) == '?')      if (*(++ptr) == '*' && (cd->ctypes[ptr[1]] & ctype_letter) != 0)
4220          {
4221          int i, namelen;
4222          const char *vn = verbnames;
4223          const uschar *name = ++ptr;
4224          previous = NULL;
4225          while ((cd->ctypes[*++ptr] & ctype_letter) != 0) {};
4226          if (*ptr == ':')
4227            {
4228            *errorcodeptr = ERR59;   /* Not supported */
4229            goto FAILED;
4230            }
4231          if (*ptr != ')')
4232            {
4233            *errorcodeptr = ERR60;
4234            goto FAILED;
4235            }
4236          namelen = ptr - name;
4237          for (i = 0; i < verbcount; i++)
4238            {
4239            if (namelen == verbs[i].len &&
4240                strncmp((char *)name, vn, namelen) == 0)
4241              {
4242              *code = verbs[i].op;
4243              if (*code++ == OP_ACCEPT) cd->had_accept = TRUE;
4244              break;
4245              }
4246            vn += verbs[i].len + 1;
4247            }
4248          if (i < verbcount) continue;
4249          *errorcodeptr = ERR60;
4250          goto FAILED;
4251          }
4252    
4253        /* Deal with the extended parentheses; all are introduced by '?', and the
4254        appearance of any of them means that this is not a capturing group. */
4255    
4256        else if (*ptr == '?')
4257        {        {
4258        int i, set, unset, namelen;        int i, set, unset, namelen;
4259        int *optset;        int *optset;
# Line 3586  for (;; ptr++) Line 4274  for (;; ptr++)
4274    
4275    
4276          /* ------------------------------------------------------------ */          /* ------------------------------------------------------------ */
4277            case '|':                 /* Reset capture count for each branch */
4278            reset_bracount = TRUE;
4279            /* Fall through */
4280    
4281            /* ------------------------------------------------------------ */
4282          case ':':                 /* Non-capturing bracket */          case ':':                 /* Non-capturing bracket */
4283          bravalue = OP_BRA;          bravalue = OP_BRA;
4284          ptr++;          ptr++;
# Line 3621  for (;; ptr++) Line 4314  for (;; ptr++)
4314    
4315          code[1+LINK_SIZE] = OP_CREF;          code[1+LINK_SIZE] = OP_CREF;
4316          skipbytes = 3;          skipbytes = 3;
4317            refsign = -1;
4318    
4319          /* Check for a test for recursion in a named group. */          /* Check for a test for recursion in a named group. */
4320    
# Line 3644  for (;; ptr++) Line 4338  for (;; ptr++)
4338            terminator = '\'';            terminator = '\'';
4339            ptr++;            ptr++;
4340            }            }
4341          else terminator = 0;          else
4342              {
4343              terminator = 0;
4344              if (ptr[1] == '-' || ptr[1] == '+') refsign = *(++ptr);
4345              }
4346    
4347          /* We now expect to read a name; any thing else is an error */          /* We now expect to read a name; any thing else is an error */
4348    
# Line 3680  for (;; ptr++) Line 4378  for (;; ptr++)
4378          if (lengthptr != NULL) break;          if (lengthptr != NULL) break;
4379    
4380          /* In the real compile we do the work of looking for the actual          /* In the real compile we do the work of looking for the actual
4381          reference. */          reference. If the string started with "+" or "-" we require the rest to
4382            be digits, in which case recno will be set. */
4383    
4384            if (refsign > 0)
4385              {
4386              if (recno <= 0)
4387                {
4388                *errorcodeptr = ERR58;
4389                goto FAILED;
4390                }
4391              recno = (refsign == '-')?
4392                cd->bracount - recno + 1 : recno +cd->bracount;
4393              if (recno <= 0 || recno > cd->final_bracount)
4394                {
4395                *errorcodeptr = ERR15;
4396                goto FAILED;
4397                }
4398              PUT2(code, 2+LINK_SIZE, recno);
4399              break;
4400              }
4401    
4402            /* Otherwise (did not start with "+" or "-"), start by looking for the
4403            name. */
4404    
4405          slot = cd->name_table;          slot = cd->name_table;
4406          for (i = 0; i < cd->names_found; i++)          for (i = 0; i < cd->names_found; i++)
# Line 3699  for (;; ptr++) Line 4419  for (;; ptr++)
4419    
4420          /* Search the pattern for a forward reference */          /* Search the pattern for a forward reference */
4421    
4422          else if ((i = find_parens(ptr, cd->bracount, name, namelen,          else if ((i = find_parens(ptr, cd, name, namelen,
4423                          (options & PCRE_EXTENDED) != 0)) > 0)                          (options & PCRE_EXTENDED) != 0)) > 0)
4424            {            {
4425            PUT2(code, 2+LINK_SIZE, i);            PUT2(code, 2+LINK_SIZE, i);
# Line 3746  for (;; ptr++) Line 4466  for (;; ptr++)
4466            skipbytes = 1;            skipbytes = 1;
4467            }            }
4468    
4469          /* Check for the "name" actually being a subpattern number. */          /* Check for the "name" actually being a subpattern number. We are
4470            in the second pass here, so final_bracount is set. */
4471    
4472          else if (recno > 0)          else if (recno > 0 && recno <= cd->final_bracount)
4473            {            {
4474            PUT2(code, 2+LINK_SIZE, recno);            PUT2(code, 2+LINK_SIZE, recno);
4475            }            }
# Line 3772  for (;; ptr++) Line 4493  for (;; ptr++)
4493    
4494          /* ------------------------------------------------------------ */          /* ------------------------------------------------------------ */
4495          case '!':                 /* Negative lookahead */          case '!':                 /* Negative lookahead */
         bravalue = OP_ASSERT_NOT;  
4496          ptr++;          ptr++;
4497            if (*ptr == ')')          /* Optimize (?!) */
4498              {
4499              *code++ = OP_FAIL;
4500              previous = NULL;
4501              continue;
4502              }
4503            bravalue = OP_ASSERT_NOT;
4504          break;          break;
4505    
4506    
# Line 3936  for (;; ptr++) Line 4663  for (;; ptr++)
4663    
4664          /* We come here from the Python syntax above that handles both          /* We come here from the Python syntax above that handles both
4665          references (?P=name) and recursion (?P>name), as well as falling          references (?P=name) and recursion (?P>name), as well as falling
4666          through from the Perl recursion syntax (?&name). */          through from the Perl recursion syntax (?&name). We also come here from
4667            the Perl \k<name> or \k'name' back reference syntax and the \k{name}
4668            .NET syntax, and the Oniguruma \g<...> and \g'...' subroutine syntax. */
4669    
4670          NAMED_REF_OR_RECURSE:          NAMED_REF_OR_RECURSE:
4671          name = ++ptr;          name = ++ptr;
# Line 3948  for (;; ptr++) Line 4677  for (;; ptr++)
4677    
4678          if (lengthptr != NULL)          if (lengthptr != NULL)
4679            {            {
4680              if (namelen == 0)
4681                {
4682                *errorcodeptr = ERR62;
4683                goto FAILED;
4684                }
4685            if (*ptr != terminator)            if (*ptr != terminator)
4686              {              {
4687              *errorcodeptr = ERR42;              *errorcodeptr = ERR42;
# Line 3961  for (;; ptr++) Line 4695  for (;; ptr++)
4695            recno = 0;            recno = 0;
4696            }            }
4697    
4698          /* In the real compile, seek the name in the table */          /* In the real compile, seek the name in the table. We check the name
4699            first, and then check that we have reached the end of the name in the
4700            table. That way, if the name that is longer than any in the table,
4701            the comparison will fail without reading beyond the table entry. */
4702    
4703          else          else
4704            {            {
4705            slot = cd->name_table;            slot = cd->name_table;
4706            for (i = 0; i < cd->names_found; i++)            for (i = 0; i < cd->names_found; i++)
4707              {              {
4708              if (strncmp((char *)name, (char *)slot+2, namelen) == 0) break;              if (strncmp((char *)name, (char *)slot+2, namelen) == 0 &&
4709                    slot[2+namelen] == 0)
4710                  break;
4711              slot += cd->name_entry_size;              slot += cd->name_entry_size;
4712              }              }
4713    
# Line 3977  for (;; ptr++) Line 4716  for (;; ptr++)
4716              recno = GET2(slot, 0);              recno = GET2(slot, 0);
4717              }              }
4718            else if ((recno =                /* Forward back reference */            else if ((recno =                /* Forward back reference */
4719                      find_parens(ptr, cd->bracount, name, namelen,                      find_parens(ptr, cd, name, namelen,
4720                        (options & PCRE_EXTENDED) != 0)) <= 0)                        (options & PCRE_EXTENDED) != 0)) <= 0)
4721              {              {
4722              *errorcodeptr = ERR15;              *errorcodeptr = ERR15;
# Line 3999  for (;; ptr++) Line 4738  for (;; ptr++)
4738    
4739    
4740          /* ------------------------------------------------------------ */          /* ------------------------------------------------------------ */
4741            case '-': case '+':
4742          case '0': case '1': case '2': case '3': case '4':   /* Recursion or */          case '0': case '1': case '2': case '3': case '4':   /* Recursion or */
4743          case '5': case '6': case '7': case '8': case '9':   /* subroutine */          case '5': case '6': case '7': case '8': case '9':   /* subroutine */
4744            {            {
4745            const uschar *called;            const uschar *called;
4746              terminator = ')';
4747    
4748              /* Come here from the \g<...> and \g'...' code (Oniguruma
4749              compatibility). However, the syntax has been checked to ensure that
4750              the ... are a (signed) number, so that neither ERR63 nor ERR29 will
4751              be called on this path, nor with the jump to OTHER_CHAR_AFTER_QUERY
4752              ever be taken. */
4753    
4754              HANDLE_NUMERICAL_RECURSION:
4755    
4756              if ((refsign = *ptr) == '+')
4757                {
4758                ptr++;
4759                if ((digitab[*ptr] & ctype_digit) == 0)
4760                  {
4761                  *errorcodeptr = ERR63;
4762                  goto FAILED;
4763                  }
4764                }
4765              else if (refsign == '-')
4766                {
4767                if ((digitab[ptr[1]] & ctype_digit) == 0)
4768                  goto OTHER_CHAR_AFTER_QUERY;
4769                ptr++;
4770                }
4771    
4772            recno = 0;            recno = 0;
4773            while((digitab[*ptr] & ctype_digit) != 0)            while((digitab[*ptr] & ctype_digit) != 0)
4774              recno = recno * 10 + *ptr++ - '0';              recno = recno * 10 + *ptr++ - '0';
4775            if (*ptr != ')')  
4776              if (*ptr != terminator)
4777              {              {
4778              *errorcodeptr = ERR29;              *errorcodeptr = ERR29;
4779              goto FAILED;              goto FAILED;
4780              }              }
4781    
4782              if (refsign == '-')
4783                {
4784                if (recno == 0)
4785                  {
4786                  *errorcodeptr = ERR58;
4787                  goto FAILED;
4788                  }
4789                recno = cd->bracount - recno + 1;
4790                if (recno <= 0)
4791                  {
4792                  *errorcodeptr = ERR15;
4793                  goto FAILED;
4794                  }
4795                }
4796              else if (refsign == '+')
4797                {
4798                if (recno == 0)
4799                  {
4800                  *errorcodeptr = ERR58;
4801                  goto FAILED;
4802                  }
4803                recno += cd->bracount;
4804                }
4805    
4806            /* Come here from code above that handles a named recursion */            /* Come here from code above that handles a named recursion */
4807    
4808            HANDLE_RECURSION:            HANDLE_RECURSION:
# Line 4035  for (;; ptr++) Line 4826  for (;; ptr++)
4826    
4827              if (called == NULL)              if (called == NULL)
4828                {                {
4829                if (find_parens(ptr, cd->bracount, NULL, recno,                if (find_parens(ptr, cd, NULL, recno,
4830                     (options & PCRE_EXTENDED) != 0) < 0)                      (options & PCRE_EXTENDED) != 0) < 0)
4831                  {                  {
4832                  *errorcodeptr = ERR15;                  *errorcodeptr = ERR15;
4833                  goto FAILED;                  goto FAILED;
# Line 4084  for (;; ptr++) Line 4875  for (;; ptr++)
4875    
4876          /* ------------------------------------------------------------ */          /* ------------------------------------------------------------ */
4877          default:              /* Other characters: check option setting */          default:              /* Other characters: check option setting */
4878            OTHER_CHAR_AFTER_QUERY:
4879          set = unset = 0;          set = unset = 0;
4880          optset = &set;          optset = &set;
4881    
# Line 4095  for (;; ptr++) Line 4887  for (;; ptr++)
4887    
4888              case 'J':    /* Record that it changed in the external options */              case 'J':    /* Record that it changed in the external options */
4889              *optset |= PCRE_DUPNAMES;              *optset |= PCRE_DUPNAMES;
4890              cd->external_options |= PCRE_JCHANGED;              cd->external_flags |= PCRE_JCHANGED;
4891              break;              break;
4892    
4893              case 'i': *optset |= PCRE_CASELESS; break;              case 'i': *optset |= PCRE_CASELESS; break;
# Line 4134  for (;; ptr++) Line 4926  for (;; ptr++)
4926          both phases.          both phases.
4927    
4928          If we are not at the pattern start, compile code to change the ims          If we are not at the pattern start, compile code to change the ims
4929          options if this setting actually changes any of them. We also pass the          options if this setting actually changes any of them, and reset the
4930          new setting back so that it can be put at the start of any following          greedy defaults and the case value for firstbyte and reqbyte. */
         branches, and when this group ends (if we are in a group), a resetting  
         item can be compiled. */  
4931    
4932          if (*ptr == ')')          if (*ptr == ')')
4933            {            {
# Line 4145  for (;; ptr++) Line 4935  for (;; ptr++)
4935                 (lengthptr == NULL || *lengthptr == 2 + 2*LINK_SIZE))                 (lengthptr == NULL || *lengthptr == 2 + 2*LINK_SIZE))
4936              {              {
4937              cd->external_options = newoptions;              cd->external_options = newoptions;
             options = newoptions;  
4938              }              }
4939           else           else
4940              {              {
# Line 4154  for (;; ptr++) Line 4943  for (;; ptr++)
4943                *code++ = OP_OPT;                *code++ = OP_OPT;
4944                *code++ = newoptions & PCRE_IMS;                *code++ = newoptions & PCRE_IMS;
4945                }                }
   
             /* Change options at this level, and pass them back for use  
             in subsequent branches. Reset the greedy defaults and the case  
             value for firstbyte and reqbyte. */  
   
             *optionsptr = options = newoptions;  
4946              greedy_default = ((newoptions & PCRE_UNGREEDY) != 0);              greedy_default = ((newoptions & PCRE_UNGREEDY) != 0);
4947              greedy_non_default = greedy_default ^ 1;              greedy_non_default = greedy_default ^ 1;
4948              req_caseopt = ((options & PCRE_CASELESS) != 0)? REQ_CASELESS : 0;              req_caseopt = ((newoptions & PCRE_CASELESS) != 0)? REQ_CASELESS : 0;
4949              }              }
4950    
4951              /* Change options at this level, and pass them back for use
4952              in subsequent branches. When not at the start of the pattern, this
4953              information is also necessary so that a resetting item can be
4954              compiled at the end of a group (if we are in a group). */
4955    
4956              *optionsptr = options = newoptions;
4957            previous = NULL;       /* This item can't be repeated */            previous = NULL;       /* This item can't be repeated */
4958            continue;              /* It is complete */            continue;              /* It is complete */
4959            }            }
# Line 4218  for (;; ptr++) Line 5007  for (;; ptr++)
5007           errorcodeptr,                 /* Where to put an error message */           errorcodeptr,                 /* Where to put an error message */
5008           (bravalue == OP_ASSERTBACK ||           (bravalue == OP_ASSERTBACK ||
5009            bravalue == OP_ASSERTBACK_NOT), /* TRUE if back assert */            bravalue == OP_ASSERTBACK_NOT), /* TRUE if back assert */
5010             reset_bracount,               /* True if (?| group */
5011           skipbytes,                    /* Skip over bracket number */           skipbytes,                    /* Skip over bracket number */
5012           &subfirstbyte,                /* For possible first char */           &subfirstbyte,                /* For possible first char */
5013           &subreqbyte,                  /* For possible last char */           &subreqbyte,                  /* For possible last char */
# Line 4234  for (;; ptr++) Line 5024  for (;; ptr++)
5024      is on the bracket. */      is on the bracket. */
5025    
5026      /* If this is a conditional bracket, check that there are no more than      /* If this is a conditional bracket, check that there are no more than
5027      two branches in the group, or just one if it's a DEFINE group. */      two branches in the group, or just one if it's a DEFINE group. We do this
5028        in the real compile phase, not in the pre-pass, where the whole group may
5029        not be available. */
5030    
5031      if (bravalue == OP_COND)      if (bravalue == OP_COND && lengthptr == NULL)
5032        {        {
5033        uschar *tc = code;        uschar *tc = code;
5034        int condcount = 0;        int condcount = 0;
# Line 4283  for (;; ptr++) Line 5075  for (;; ptr++)
5075        goto FAILED;        goto FAILED;
5076        }        }
5077    
5078      /* In the pre-compile phase, update the length by the length of the nested      /* In the pre-compile phase, update the length by the length of the group,
5079      group, less the brackets at either end. Then reduce the compiled code to      less the brackets at either end. Then reduce the compiled code to just a
5080      just the brackets so that it doesn't use much memory if it is duplicated by      set of non-capturing brackets so that it doesn't use much memory if it is
5081      a quantifier. */      duplicated by a quantifier.*/
5082    
5083      if (lengthptr != NULL)      if (lengthptr != NULL)
5084        {        {
5085          if (OFLOW_MAX - *lengthptr < length_prevgroup - 2 - 2*LINK_SIZE)
5086            {
5087            *errorcodeptr = ERR20;
5088            goto FAILED;
5089            }
5090        *lengthptr += length_prevgroup - 2 - 2*LINK_SIZE;        *lengthptr += length_prevgroup - 2 - 2*LINK_SIZE;
5091        code++;        *code++ = OP_BRA;
5092        PUTINC(code, 0, 1 + LINK_SIZE);        PUTINC(code, 0, 1 + LINK_SIZE);
5093        *code++ = OP_KET;        *code++ = OP_KET;
5094        PUTINC(code, 0, 1 + LINK_SIZE);        PUTINC(code, 0, 1 + LINK_SIZE);
5095          break;    /* No need to waste time with special character handling */
5096        }        }
5097    
5098      /* Otherwise update the main code pointer to the end of the group. */      /* Otherwise update the main code pointer to the end of the group. */
5099    
5100      else code = tempcode;      code = tempcode;
5101    
5102      /* For a DEFINE group, required and first character settings are not      /* For a DEFINE group, required and first character settings are not
5103      relevant. */      relevant. */
# Line 4396  for (;; ptr++) Line 5194  for (;; ptr++)
5194        zerofirstbyte = firstbyte;        zerofirstbyte = firstbyte;
5195        zeroreqbyte = reqbyte;        zeroreqbyte = reqbyte;
5196    
5197        /* \k<name> or \k'name' is a back reference by name (Perl syntax) */        /* \g<name> or \g'name' is a subroutine call by name and \g<n> or \g'n'
5198          is a subroutine call by number (Oniguruma syntax). In fact, the value
5199          -ESC_g is returned only for these cases. So we don't need to check for <
5200          or ' if the value is -ESC_g. For the Perl syntax \g{n} the value is
5201          -ESC_REF+n, and for the Perl syntax \g{name} the result is -ESC_k (as
5202          that is a synonym for a named back reference). */
5203    
5204        if (-c == ESC_k && (ptr[1] == '<' || ptr[1] == '\''))        if (-c == ESC_g)
5205          {          {
5206          is_recurse = FALSE;          const uschar *p;
5207            save_hwm = cd->hwm;   /* Normally this is set when '(' is read */
5208          terminator = (*(++ptr) == '<')? '>' : '\'';          terminator = (*(++ptr) == '<')? '>' : '\'';
5209    
5210            /* These two statements stop the compiler for warning about possibly
5211            unset variables caused by the jump to HANDLE_NUMERICAL_RECURSION. In
5212            fact, because we actually check for a number below, the paths that
5213            would actually be in error are never taken. */
5214    
5215            skipbytes = 0;
5216            reset_bracount = FALSE;
5217    
5218            /* Test for a name */
5219    
5220            if (ptr[1] != '+' && ptr[1] != '-')
5221              {
5222              BOOL isnumber = TRUE;
5223              for (p = ptr + 1; *p != 0 && *p != terminator; p++)
5224                {
5225                if ((cd->ctypes[*p] & ctype_digit) == 0) isnumber = FALSE;
5226                if ((cd->ctypes[*p] & ctype_word) == 0) break;
5227                }
5228              if (*p != terminator)
5229                {
5230                *errorcodeptr = ERR57;
5231                break;
5232                }
5233              if (isnumber)
5234                {
5235                ptr++;
5236                goto HANDLE_NUMERICAL_RECURSION;
5237                }
5238              is_recurse = TRUE;
5239              goto NAMED_REF_OR_RECURSE;
5240              }
5241    
5242            /* Test a signed number in angle brackets or quotes. */
5243    
5244            p = ptr + 2;
5245            while ((digitab[*p] & ctype_digit) != 0) p++;
5246            if (*p != terminator)
5247              {
5248              *errorcodeptr = ERR57;
5249              break;
5250              }
5251            ptr++;
5252            goto HANDLE_NUMERICAL_RECURSION;
5253            }
5254    
5255          /* \k<name> or \k'name' is a back reference by name (Perl syntax).
5256          We also support \k{name} (.NET syntax) */
5257    
5258          if (-c == ESC_k && (ptr[1] == '<' || ptr[1] == '\'' || ptr[1] == '{'))
5259            {
5260            is_recurse = FALSE;
5261            terminator = (*(++ptr) == '<')? '>' : (*ptr == '\'')? '\'' : '}';
5262          goto NAMED_REF_OR_RECURSE;          goto NAMED_REF_OR_RECURSE;
5263          }          }
5264    
# Line 4502  for (;; ptr++) Line 5359  for (;; ptr++)
5359      *code++ = ((options & PCRE_CASELESS) != 0)? OP_CHARNC : OP_CHAR;      *code++ = ((options & PCRE_CASELESS) != 0)? OP_CHARNC : OP_CHAR;
5360      for (c = 0; c < mclength; c++) *code++ = mcbuffer[c];      for (c = 0; c < mclength; c++) *code++ = mcbuffer[c];
5361    
5362        /* Remember if \r or \n were seen */
5363    
5364        if (mcbuffer[0] == '\r' || mcbuffer[0] == '\n')
5365          cd->external_flags |= PCRE_HASCRORLF;
5366    
5367      /* Set the first and required bytes appropriately. If no previous first      /* Set the first and required bytes appropriately. If no previous first
5368      byte, set it from this character, but revert to none on a zero repeat.      byte, set it from this character, but revert to none on a zero repeat.
5369      Otherwise, leave the firstbyte value alone, and don't change it on a zero      Otherwise, leave the firstbyte value alone, and don't change it on a zero
# Line 4567  This function is used during the pre-com Line 5429  This function is used during the pre-com
5429  out the amount of memory needed, as well as during the real compile phase. The  out the amount of memory needed, as well as during the real compile phase. The
5430  value of lengthptr distinguishes the two phases.  value of lengthptr distinguishes the two phases.
5431    
5432  Argument:  Arguments:
5433    options        option bits, including any changes for this subpattern    options        option bits, including any changes for this subpattern
5434    oldims         previous settings of ims option bits    oldims         previous settings of ims option bits
5435    codeptr        -> the address of the current code pointer    codeptr        -> the address of the current code pointer
5436    ptrptr         -> the address of the current pattern pointer    ptrptr         -> the address of the current pattern pointer
5437    errorcodeptr   -> pointer to error code variable    errorcodeptr   -> pointer to error code variable
5438    lookbehind     TRUE if this is a lookbehind assertion    lookbehind     TRUE if this is a lookbehind assertion
5439      reset_bracount TRUE to reset the count for each branch
5440    skipbytes      skip this many bytes at start (for brackets and OP_COND)    skipbytes      skip this many bytes at start (for brackets and OP_COND)
5441    firstbyteptr   place to put the first required character, or a negative number    firstbyteptr   place to put the first required character, or a negative number
5442    reqbyteptr     place to put the last required character, or a negative number    reqbyteptr     place to put the last required character, or a negative number
# Line 4587  Returns:         TRUE on success Line 5450  Returns:         TRUE on success
5450    
5451  static BOOL  static BOOL
5452  compile_regex(int options, int oldims, uschar **codeptr, const uschar **ptrptr,  compile_regex(int options, int oldims, uschar **codeptr, const uschar **ptrptr,
5453    int *errorcodeptr, BOOL lookbehind, int skipbytes, int *firstbyteptr,    int *errorcodeptr, BOOL lookbehind, BOOL reset_bracount, int skipbytes,
5454    int *reqbyteptr, branch_chain *bcptr, compile_data *cd, int *lengthptr)    int *firstbyteptr, int *reqbyteptr, branch_chain *bcptr, compile_data *cd,
5455      int *lengthptr)
5456  {  {
5457  const uschar *ptr = *ptrptr;  const uschar *ptr = *ptrptr;
5458  uschar *code = *codeptr;  uschar *code = *codeptr;
# Line 4598  uschar *reverse_count = NULL; Line 5462  uschar *reverse_count = NULL;
5462  int firstbyte, reqbyte;  int firstbyte, reqbyte;
5463  int branchfirstbyte, branchreqbyte;  int branchfirstbyte, branchreqbyte;
5464  int length;  int length;
5465    int orig_bracount;
5466    int max_bracount;
5467  branch_chain bc;  branch_chain bc;
5468    
5469  bc.outer = bcptr;  bc.outer = bcptr;
# Line 4626  code += 1 + LINK_SIZE + skipbytes; Line 5492  code += 1 + LINK_SIZE + skipbytes;
5492    
5493  /* Loop for each alternative branch */  /* Loop for each alternative branch */
5494    
5495    orig_bracount = max_bracount = cd->bracount;
5496  for (;;)  for (;;)
5497    {    {
5498      /* For a (?| group, reset the capturing bracket count so that each branch
5499      uses the same numbers. */
5500    
5501      if (reset_bracount) cd->bracount = orig_bracount;
5502    
5503    /* Handle a change of ims options at the start of the branch */    /* Handle a change of ims options at the start of the branch */
5504    
5505    if ((options & PCRE_IMS) != oldims)    if ((options & PCRE_IMS) != oldims)
# Line 4657  for (;;) Line 5529  for (;;)
5529      return FALSE;      return FALSE;
5530      }      }
5531    
5532      /* Keep the highest bracket count in case (?| was used and some branch
5533      has fewer than the rest. */
5534    
5535      if (cd->bracount > max_bracount) max_bracount = cd->bracount;
5536    
5537    /* In the real compile phase, there is some post-processing to be done. */    /* In the real compile phase, there is some post-processing to be done. */
5538    
5539    if (lengthptr == NULL)    if (lengthptr == NULL)
# Line 4720  for (;;) Line 5597  for (;;)
5597        }        }
5598      }      }
5599    
5600    /* Reached end of expression, either ')' or end of pattern. Go back through    /* Reached end of expression, either ')' or end of pattern. In the real
5601    the alternative branches and reverse the chain of offsets, with the field in    compile phase, go back through the alternative branches and reverse the chain
5602    the BRA item now becoming an offset to the first alternative. If there are    of offsets, with the field in the BRA item now becoming an offset to the
5603    no alternatives, it points to the end of the group. The length in the    first alternative. If there are no alternatives, it points to the end of the
5604    terminating ket is always the length of the whole bracketed item. If any of    group. The length in the terminating ket is always the length of the whole
5605    the ims options were changed inside the group, compile a resetting op-code    bracketed item. If any of the ims options were changed inside the group,
5606    following, except at the very end of the pattern. Return leaving the pointer    compile a resetting op-code following, except at the very end of the pattern.
5607    at the terminating char. */    Return leaving the pointer at the terminating char. */
5608    
5609    if (*ptr != '|')    if (*ptr != '|')
5610      {      {
5611      int branch_length = code - last_branch;      if (lengthptr == NULL)
     do  
5612        {        {
5613        int prev_length = GET(last_branch, 1);        int branch_length = code - last_branch;
5614        PUT(last_branch, 1, branch_length);        do
5615        branch_length = prev_length;          {
5616        last_branch -= branch_length;          int prev_length = GET(last_branch, 1);
5617            PUT(last_branch, 1, branch_length);
5618            branch_length = prev_length;
5619            last_branch -= branch_length;
5620            }
5621          while (branch_length > 0);
5622        }        }
     while (branch_length > 0);  
5623    
5624      /* Fill in the ket */      /* Fill in the ket */
5625    
# Line 4756  for (;;) Line 5636  for (;;)
5636        length += 2;        length += 2;
5637        }        }
5638    
5639        /* Retain the highest bracket number, in case resetting was used. */
5640    
5641        cd->bracount = max_bracount;
5642    
5643      /* Set values to pass back */      /* Set values to pass back */
5644    
5645      *codeptr = code;      *codeptr = code;
5646      *ptrptr = ptr;      *ptrptr = ptr;
5647      *firstbyteptr = firstbyte;      *firstbyteptr = firstbyte;
5648      *reqbyteptr = reqbyte;      *reqbyteptr = reqbyte;
5649      if (lengthptr != NULL) *lengthptr += length;      if (lengthptr != NULL)
5650          {
5651          if (OFLOW_MAX - *lengthptr < length)
5652            {
5653            *errorcodeptr = ERR20;
5654            return FALSE;
5655            }
5656          *lengthptr += length;
5657          }
5658      return TRUE;      return TRUE;
5659      }      }
5660    
5661    /* Another branch follows; insert an "or" node. Its length field points back    /* Another branch follows. In the pre-compile phase, we can move the code
5662      pointer back to where it was for the start of the first branch. (That is,
5663      pretend that each branch is the only one.)
5664    
5665      In the real compile phase, insert an ALT node. Its length field points back
5666    to the previous branch while the bracket remains open. At the end the chain    to the previous branch while the bracket remains open. At the end the chain
5667    is reversed. It's done like this so that the start of the bracket has a    is reversed. It's done like this so that the start of the bracket has a
5668    zero offset until it is closed, making it possible to detect recursion. */    zero offset until it is closed, making it possible to detect recursion. */
5669    
5670    *code = OP_ALT;    if (lengthptr != NULL)
5671    PUT(code, 1, code - last_branch);      {
5672    bc.current = last_branch = code;      code = *codeptr + 1 + LINK_SIZE + skipbytes;
5673    code += 1 + LINK_SIZE;      length += 1 + LINK_SIZE;
5674        }
5675      else
5676        {
5677        *code = OP_ALT;
5678        PUT(code, 1, code - last_branch);
5679        bc.current = last_branch = code;
5680        code += 1 + LINK_SIZE;
5681        }
5682    
5683    ptr++;    ptr++;
   length += 1 + LINK_SIZE;  
5684    }    }
5685  /* Control never reaches here */  /* Control never reaches here */
5686  }  }
# Line 4854  do { Line 5758  do {
5758       if (!is_anchored(scode, options, bracket_map, backref_map)) return FALSE;       if (!is_anchored(scode, options, bracket_map, backref_map)) return FALSE;
5759       }       }
5760    
5761     /* .* is not anchored unless DOTALL is set and it isn't in brackets that     /* .* is not anchored unless DOTALL is set (which generates OP_ALLANY) and
5762     are or may be referenced. */     it isn't in brackets that are or may be referenced. */
5763    
5764     else if ((op == OP_TYPESTAR || op == OP_TYPEMINSTAR ||     else if ((op == OP_TYPESTAR || op == OP_TYPEMINSTAR ||
5765               op == OP_TYPEPOSSTAR) &&               op == OP_TYPEPOSSTAR))
             (*options & PCRE_DOTALL) != 0)  
5766       {       {
5767       if (scode[1] != OP_ANY || (bracket_map & backref_map) != 0) return FALSE;       if (scode[1] != OP_ALLANY || (bracket_map & backref_map) != 0)
5768           return FALSE;
5769       }       }
5770    
5771     /* Check for explicit anchoring */     /* Check for explicit anchoring */
# Line 4906  do { Line 5810  do {
5810     const uschar *scode = first_significant_code(code + _pcre_OP_lengths[*code],     const uschar *scode = first_significant_code(code + _pcre_OP_lengths[*code],
5811       NULL, 0, FALSE);       NULL, 0, FALSE);
5812     register int op = *scode;     register int op = *scode;
5813    
5814       /* If we are at the start of a conditional group, skip over the condition.
5815       before inspecting the first opcode after the condition. */
5816    
5817       if (op == OP_COND)
5818         {
5819         scode += 1 + LINK_SIZE;
5820         switch (*scode)
5821           {
5822           case OP_CREF:
5823           case OP_RREF:
5824           scode += 3;
5825           break;
5826    
5827           case OP_DEF:
5828           scode += 1;
5829           break;
5830    
5831           default:     /* Assertion */
5832           do scode += GET(scode, 1); while (*scode == OP_ALT);
5833           break;
5834           }
5835    
5836         scode = first_significant_code(scode, NULL, 0, FALSE);
5837         op = *scode;
5838         }
5839    
5840     /* Non-capturing brackets */     /* Non-capturing brackets */
5841    
# Line 4925  do { Line 5855  do {
5855    
5856     /* Other brackets */     /* Other brackets */
5857    
5858     else if (op == OP_ASSERT || op == OP_ONCE || op == OP_COND)     else if (op == OP_ASSERT || op == OP_ONCE)
5859       { if (!is_startline(scode, bracket_map, backref_map)) return FALSE; }       {
5860         if (!is_startline(scode, bracket_map, backref_map)) return FALSE;
5861         }
5862    
5863     /* .* means "start at start or after \n" if it isn't in brackets that     /* .* means "start at start or after \n" if it isn't in brackets that
5864     may be referenced. */     may be referenced. */
# Line 5043  Returns:        pointer to compiled data Line 5975  Returns:        pointer to compiled data
5975                  with errorptr and erroroffset set                  with errorptr and erroroffset set
5976  */  */
5977    
5978  PCRE_EXP_DEFN pcre *  PCRE_EXP_DEFN pcre * PCRE_CALL_CONVENTION
5979  pcre_compile(const char *pattern, int options, const char **errorptr,  pcre_compile(const char *pattern, int options, const char **errorptr,
5980    int *erroroffset, const unsigned char *tables)    int *erroroffset, const unsigned char *tables)
5981  {  {
# Line 5051  return pcre_compile2(pattern, options, N Line 5983  return pcre_compile2(pattern, options, N
5983  }  }
5984    
5985    
5986  PCRE_EXP_DEFN pcre *  PCRE_EXP_DEFN pcre * PCRE_CALL_CONVENTION
5987  pcre_compile2(const char *pattern, int options, int *errorcodeptr,  pcre_compile2(const char *pattern, int options, int *errorcodeptr,
5988    const char **errorptr, int *erroroffset, const unsigned char *tables)    const char **errorptr, int *erroroffset, const unsigned char *tables)
5989  {  {
# Line 5059  real_pcre *re; Line 5991  real_pcre *re;
5991  int length = 1;  /* For final END opcode */  int length = 1;  /* For final END opcode */
5992  int firstbyte, reqbyte, newline;  int firstbyte, reqbyte, newline;
5993  int errorcode = 0;  int errorcode = 0;
5994    int skipatstart = 0;
5995  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF8
5996  BOOL utf8;  BOOL utf8;
5997  #endif  #endif
# Line 5077  to fill in forward references to subpatt Line 6010  to fill in forward references to subpatt
6010    
6011  uschar cworkspace[COMPILE_WORK_SIZE];  uschar cworkspace[COMPILE_WORK_SIZE];
6012    
   
6013  /* Set this early so that early errors get offset 0. */  /* Set this early so that early errors get offset 0. */
6014    
6015  ptr = (const uschar *)pattern;  ptr = (const uschar *)pattern;
# Line 5137  cd->fcc = tables + fcc_offset; Line 6069  cd->fcc = tables + fcc_offset;
6069  cd->cbits = tables + cbits_offset;  cd->cbits = tables + cbits_offset;
6070  cd->ctypes = tables + ctypes_offset;  cd->ctypes = tables + ctypes_offset;
6071    
6072    /* Check for global one-time settings at the start of the pattern, and remember
6073    the offset for later. */
6074    
6075    while (ptr[skipatstart] == '(' && ptr[skipatstart+1] == '*')
6076      {
6077      int newnl = 0;
6078      int newbsr = 0;
6079    
6080      if (strncmp((char *)(ptr+skipatstart+2), "CR)", 3) == 0)
6081        { skipatstart += 5; newnl = PCRE_NEWLINE_CR; }
6082      else if (strncmp((char *)(ptr+skipatstart+2), "LF)", 3)  == 0)
6083        { skipatstart += 5; newnl = PCRE_NEWLINE_LF; }
6084      else if (strncmp((char *)(ptr+skipatstart+2), "CRLF)", 5)  == 0)
6085        { skipatstart += 7; newnl = PCRE_NEWLINE_CR + PCRE_NEWLINE_LF; }
6086      else if (strncmp((char *)(ptr+skipatstart+2), "ANY)", 4) == 0)
6087        { skipatstart += 6; newnl = PCRE_NEWLINE_ANY; }
6088      else if (strncmp((char *)(ptr+skipatstart+2), "ANYCRLF)", 8)  == 0)
6089        { skipatstart += 10; newnl = PCRE_NEWLINE_ANYCRLF; }
6090    
6091      else if (strncmp((char *)(ptr+skipatstart+2), "BSR_ANYCRLF)", 12) == 0)
6092        { skipatstart += 14; newbsr = PCRE_BSR_ANYCRLF; }
6093      else if (strncmp((char *)(ptr+skipatstart+2), "BSR_UNICODE)", 12) == 0)
6094        { skipatstart += 14; newbsr = PCRE_BSR_UNICODE; }
6095    
6096      if (newnl != 0)
6097        options = (options & ~PCRE_NEWLINE_BITS) | newnl;
6098      else if (newbsr != 0)
6099        options = (options & ~(PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE)) | newbsr;
6100      else break;
6101      }
6102    
6103    /* Check validity of \R options. */
6104    
6105    switch (options & (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE))
6106      {
6107      case 0:
6108      case PCRE_BSR_ANYCRLF:
6109      case PCRE_BSR_UNICODE:
6110      break;
6111      default: errorcode = ERR56; goto PCRE_EARLY_ERROR_RETURN;
6112      }
6113    
6114  /* Handle different types of newline. The three bits give seven cases. The  /* Handle different types of newline. The three bits give seven cases. The
6115  current code allows for fixed one- or two-byte sequences, plus "any". */  current code allows for fixed one- or two-byte sequences, plus "any" and
6116    "anycrlf". */
6117    
6118  switch (options & (PCRE_NEWLINE_CRLF | PCRE_NEWLINE_ANY))  switch (options & PCRE_NEWLINE_BITS)
6119    {    {
6120    case 0: newline = NEWLINE; break;   /* Compile-time default */    case 0: newline = NEWLINE; break;   /* Build-time default */
6121    case PCRE_NEWLINE_CR: newline = '\r'; break;    case PCRE_NEWLINE_CR: newline = '\r'; break;
6122    case PCRE_NEWLINE_LF: newline = '\n'; break;    case PCRE_NEWLINE_LF: newline = '\n'; break;
6123    case PCRE_NEWLINE_CR+    case PCRE_NEWLINE_CR+
6124         PCRE_NEWLINE_LF: newline = ('\r' << 8) | '\n'; break;         PCRE_NEWLINE_LF: newline = ('\r' << 8) | '\n'; break;
6125    case PCRE_NEWLINE_ANY: newline = -1; break;    case PCRE_NEWLINE_ANY: newline = -1; break;
6126      case PCRE_NEWLINE_ANYCRLF: newline = -2; break;
6127    default: errorcode = ERR56; goto PCRE_EARLY_ERROR_RETURN;    default: errorcode = ERR56; goto PCRE_EARLY_ERROR_RETURN;
6128    }    }
6129    
6130  if (newline < 0)  if (newline == -2)
6131      {
6132      cd->nltype = NLTYPE_ANYCRLF;
6133      }
6134    else if (newline < 0)
6135    {    {
6136    cd->nltype = NLTYPE_ANY;    cd->nltype = NLTYPE_ANY;
6137    }    }
# Line 5190  to compile parts of the pattern into; th Line 6170  to compile parts of the pattern into; th
6170  no longer needed, so hopefully this workspace will never overflow, though there  no longer needed, so hopefully this workspace will never overflow, though there
6171  is a test for its doing so. */  is a test for its doing so. */
6172    
6173  cd->bracount = 0;  cd->bracount = cd->final_bracount = 0;
6174  cd->names_found = 0;  cd->names_found = 0;
6175  cd->name_entry_size = 0;  cd->name_entry_size = 0;
6176  cd->name_table = NULL;  cd->name_table = NULL;
# Line 5200  cd->hwm = cworkspace; Line 6180  cd->hwm = cworkspace;
6180  cd->start_pattern = (const uschar *)pattern;  cd->start_pattern = (const uschar *)pattern;
6181  cd->end_pattern = (const uschar *)(pattern + strlen(pattern));  cd->end_pattern = (const uschar *)(pattern + strlen(pattern));
6182  cd->req_varyopt = 0;  cd->req_varyopt = 0;
 cd->nopartial = FALSE;  
6183  cd->external_options = options;  cd->external_options = options;
6184    cd->external_flags = 0;
6185    
6186  /* Now do the pre-compile. On error, errorcode will be set non-zero, so we  /* Now do the pre-compile. On error, errorcode will be set non-zero, so we
6187  don't need to look at the result of the function here. The initial options have  don't need to look at the result of the function here. The initial options have
# Line 5209  been put into the cd block so that they Line 6189  been put into the cd block so that they
6189  found within the regex right at the beginning. Bringing initial option settings  found within the regex right at the beginning. Bringing initial option settings
6190  outside can help speed up starting point checks. */  outside can help speed up starting point checks. */
6191    
6192    ptr += skipatstart;
6193  code = cworkspace;  code = cworkspace;
6194  *code = OP_BRA;  *code = OP_BRA;
6195  (void)compile_regex(cd->external_options, cd->external_options & PCRE_IMS,  (void)compile_regex(cd->external_options, cd->external_options & PCRE_IMS,
6196    &code, &ptr, &errorcode, FALSE, 0, &firstbyte, &reqbyte, NULL, cd, &length);    &code, &ptr, &errorcode, FALSE, FALSE, 0, &firstbyte, &reqbyte, NULL, cd,
6197      &length);
6198  if (errorcode != 0) goto PCRE_EARLY_ERROR_RETURN;  if (errorcode != 0) goto PCRE_EARLY_ERROR_RETURN;
6199    
6200  DPRINTF(("end pre-compile: length=%d workspace=%d\n", length,  DPRINTF(("end pre-compile: length=%d workspace=%d\n", length,
# Line 5238  if (re == NULL) Line 6220  if (re == NULL)
6220    goto PCRE_EARLY_ERROR_RETURN;    goto PCRE_EARLY_ERROR_RETURN;
6221    }    }
6222    
6223  /* Put in the magic number, and save the sizes, initial options, and character  /* Put in the magic number, and save the sizes, initial options, internal
6224  table pointer. NULL is used for the default character tables. The nullpad field  flags, and character table pointer. NULL is used for the default character
6225  is at the end; it's there to help in the case when a regex compiled on a system  tables. The nullpad field is at the end; it's there to help in the case when a
6226  with 4-byte pointers is run on another with 8-byte pointers. */  regex compiled on a system with 4-byte pointers is run on another with 8-byte
6227    pointers. */
6228    
6229  re->magic_number = MAGIC_NUMBER;  re->magic_number = MAGIC_NUMBER;
6230  re->size = size;  re->size = size;
6231  re->options = cd->external_options;  re->options = cd->external_options;
6232    re->flags = cd->external_flags;
6233  re->dummy1 = 0;  re->dummy1 = 0;
6234  re->first_byte = 0;  re->first_byte = 0;
6235  re->req_byte = 0;  re->req_byte = 0;
# Line 5263  field. Reset the bracket count and the n Line 6247  field. Reset the bracket count and the n
6247  field; this time it's used for remembering forward references to subpatterns.  field; this time it's used for remembering forward references to subpatterns.
6248  */  */
6249    
6250    cd->final_bracount = cd->bracount;  /* Save for checking forward references */
6251  cd->bracount = 0;  cd->bracount = 0;
6252  cd->names_found = 0;  cd->names_found = 0;
6253  cd->name_table = (uschar *)re + re->name_table_offset;  cd->name_table = (uschar *)re + re->name_table_offset;
# Line 5270  codestart = cd->name_table + re->name_en Line 6255  codestart = cd->name_table + re->name_en
6255  cd->start_code = codestart;  cd->start_code = codestart;
6256  cd->hwm = cworkspace;  cd->hwm = cworkspace;
6257  cd->req_varyopt = 0;  cd->req_varyopt = 0;
6258  cd->nopartial = FALSE;  cd->had_accept = FALSE;
6259    
6260  /* Set up a starting, non-extracting bracket, then compile the expression. On  /* Set up a starting, non-extracting bracket, then compile the expression. On
6261  error, errorcode will be set non-zero, so we don't need to look at the result  error, errorcode will be set non-zero, so we don't need to look at the result
6262  of the function here. */  of the function here. */
6263    
6264  ptr = (const uschar *)pattern;  ptr = (const uschar *)pattern + skipatstart;
6265  code = (uschar *)codestart;  code = (uschar *)codestart;
6266  *code = OP_BRA;  *code = OP_BRA;
6267  (void)compile_regex(re->options, re->options & PCRE_IMS, &code, &ptr,  (void)compile_regex(re->options, re->options & PCRE_IMS, &code, &ptr,
6268    &errorcode, FALSE, 0, &firstbyte, &reqbyte, NULL, cd, NULL);    &errorcode, FALSE, FALSE, 0, &firstbyte, &reqbyte, NULL, cd, NULL);
6269  re->top_bracket = cd->bracount;  re->top_bracket = cd->bracount;
6270  re->top_backref = cd->top_backref;  re->top_backref = cd->top_backref;
6271    re->flags = cd->external_flags;
6272    
6273  if (cd->nopartial) re->options |= PCRE_NOPARTIAL;  if (cd->had_accept) reqbyte = -1;   /* Must disable after (*ACCEPT) */
6274    
6275  /* If not reached end of pattern on success, there's an excess bracket. */  /* If not reached end of pattern on success, there's an excess bracket. */
6276    
# Line 5326  if (errorcode != 0) Line 6312  if (errorcode != 0)
6312    PCRE_EARLY_ERROR_RETURN:    PCRE_EARLY_ERROR_RETURN:
6313    *erroroffset = ptr - (const uschar *)pattern;    *erroroffset = ptr - (const uschar *)pattern;
6314    PCRE_EARLY_ERROR_RETURN2:    PCRE_EARLY_ERROR_RETURN2:
6315    *errorptr = error_texts[errorcode];    *errorptr = find_error_text(errorcode);
6316    if (errorcodeptr != NULL) *errorcodeptr = errorcode;    if (errorcodeptr != NULL) *errorcodeptr = errorcode;
6317    return NULL;    return NULL;
6318    }    }
# Line 5355  if ((re->options & PCRE_ANCHORED) == 0) Line 6341  if ((re->options & PCRE_ANCHORED) == 0)
6341        int ch = firstbyte & 255;        int ch = firstbyte & 255;
6342        re->first_byte = ((firstbyte & REQ_CASELESS) != 0 &&        re->first_byte = ((firstbyte & REQ_CASELESS) != 0 &&
6343           cd->fcc[ch] == ch)? ch : firstbyte;           cd->fcc[ch] == ch)? ch : firstbyte;
6344        re->options |= PCRE_FIRSTSET;        re->flags |= PCRE_FIRSTSET;
6345        }        }
6346      else if (is_startline(codestart, 0, cd->backref_map))      else if (is_startline(codestart, 0, cd->backref_map))
6347        re->options |= PCRE_STARTLINE;        re->flags |= PCRE_STARTLINE;
6348      }      }
6349    }    }
6350    
# Line 5372  if (reqbyte >= 0 && Line 6358  if (reqbyte >= 0 &&
6358    int ch = reqbyte & 255;    int ch = reqbyte & 255;
6359    re->req_byte = ((reqbyte & REQ_CASELESS) != 0 &&    re->req_byte = ((reqbyte & REQ_CASELESS) != 0 &&
6360      cd->fcc[ch] == ch)? (reqbyte & ~REQ_CASELESS) : reqbyte;      cd->fcc[ch] == ch)? (reqbyte & ~REQ_CASELESS) : reqbyte;
6361    re->options |= PCRE_REQCHSET;    re->flags |= PCRE_REQCHSET;
6362    }    }
6363    
6364  /* Print out the compiled data if debugging is enabled. This is never the  /* Print out the compiled data if debugging is enabled. This is never the
# Line 5383  case when building a production library. Line 6369  case when building a production library.
6369  printf("Length = %d top_bracket = %d top_backref = %d\n",  printf("Length = %d top_bracket = %d top_backref = %d\n",
6370    length, re->top_bracket, re->top_backref);    length, re->top_bracket, re->top_backref);
6371    
6372  if (re->options != 0)  printf("Options=%08x\n", re->options);
   {  
   printf("%s%s%s%s%s%s%s%s%s\n",  
     ((re->options & PCRE_NOPARTIAL) != 0)? "nopartial " : "",  
     ((re->options & PCRE_ANCHORED) != 0)? "anchored " : "",  
     ((re->options & PCRE_CASELESS) != 0)? "caseless " : "",  
     ((re->options & PCRE_EXTENDED) != 0)? "extended " : "",  
     ((re->options & PCRE_MULTILINE) != 0)? "multiline " : "",  
     ((re->options & PCRE_DOTALL) != 0)? "dotall " : "",  
     ((re->options & PCRE_DOLLAR_ENDONLY) != 0)? "endonly " : "",  
     ((re->options & PCRE_EXTRA) != 0)? "extra " : "",  
     ((re->options & PCRE_UNGREEDY) != 0)? "ungreedy " : "");  
   }  
6373    
6374  if ((re->options & PCRE_FIRSTSET) != 0)  if ((re->flags & PCRE_FIRSTSET) != 0)
6375    {    {
6376    int ch = re->first_byte & 255;    int ch = re->first_byte & 255;
6377    const char *caseless = ((re->first_byte & REQ_CASELESS) == 0)?    const char *caseless = ((re->first_byte & REQ_CASELESS) == 0)?
# Line 5406  if ((re->options & PCRE_FIRSTSET) != 0) Line 6380  if ((re->options & PCRE_FIRSTSET) != 0)
6380      else printf("First char = \\x%02x%s\n", ch, caseless);      else printf("First char = \\x%02x%s\n", ch, caseless);
6381    }    }
6382    
6383  if ((re->options & PCRE_REQCHSET) != 0)  if ((re->flags & PCRE_REQCHSET) != 0)
6384    {    {
6385    int ch = re->req_byte & 255;    int ch = re->req_byte & 255;
6386    const char *caseless = ((re->req_byte & REQ_CASELESS) == 0)?    const char *caseless = ((re->req_byte & REQ_CASELESS) == 0)?
# Line 5423  was compiled can be seen. */ Line 6397  was compiled can be seen. */
6397  if (code - codestart > length)  if (code - codestart > length)
6398    {    {
6399    (pcre_free)(re);    (pcre_free)(re);
6400    *errorptr = error_texts[ERR23];    *errorptr = find_error_text(ERR23);
6401    *erroroffset = ptr - (uschar *)pattern;    *erroroffset = ptr - (uschar *)pattern;
6402    if (errorcodeptr != NULL) *errorcodeptr = ERR23;    if (errorcodeptr != NULL) *errorcodeptr = ERR23;
6403    return NULL;    return NULL;

Legend:
Removed from v.145  
changed lines
  Added in v.380

  ViewVC Help
Powered by ViewVC 1.1.5