/[pcre]/code/branches/pcre16/pcre_compile.c
ViewVC logotype

Diff of /code/branches/pcre16/pcre_compile.c

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

code/trunk/pcre_compile.c revision 264 by ph10, Tue Nov 13 11:07:16 2007 UTC code/branches/pcre16/pcre_compile.c revision 757 by ph10, Mon Nov 21 11:44:55 2011 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-2011 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 53  supporting internal functions that are n Line 53  supporting internal functions that are n
53  #include "pcre_internal.h"  #include "pcre_internal.h"
54    
55    
56  /* When DEBUG is defined, we need the pcre_printint() function, which is also  /* When PCRE_DEBUG is defined, we need the pcre_printint() function, which is
57  used by pcretest. DEBUG is not defined when building a production library. */  also used by pcretest. PCRE_DEBUG is not defined when building a production
58    library. */
59    
60  #ifdef DEBUG  #ifdef PCRE_DEBUG
61  #include "pcre_printint.src"  #include "pcre_printint.src"
62  #endif  #endif
63    
# Line 91  is 4 there is plenty of room. */ Line 92  is 4 there is plenty of room. */
92    
93  #define COMPILE_WORK_SIZE (4096)  #define COMPILE_WORK_SIZE (4096)
94    
95    /* The overrun tests check for a slightly smaller size so that they detect the
96    overrun before it actually does run off the end of the data block. */
97    
98    #define WORK_SIZE_CHECK (COMPILE_WORK_SIZE - 100)
99    
100    
101  /* Table for handling escaped characters in the range '0'-'z'. Positive returns  /* Table for handling escaped characters in the range '0'-'z'. Positive returns
102  are simple data values; negative values are for special things like \d and so  are simple data values; negative values are for special things like \d and so
103  on. Zero means further processing is needed (for things like \x), or the escape  on. Zero means further processing is needed (for things like \x), or the escape
104  is invalid. */  is invalid. */
105    
106  #ifndef EBCDIC  /* This is the "normal" table for ASCII systems */  #ifndef EBCDIC
107    
108    /* This is the "normal" table for ASCII systems or for EBCDIC systems running
109    in UTF-8 mode. */
110    
111  static const short int escapes[] = {  static const short int escapes[] = {
112       0,      0,      0,      0,      0,      0,      0,      0,   /* 0 - 7 */       0,                       0,
113       0,      0,    ':',    ';',    '<',    '=',    '>',    '?',   /* 8 - ? */       0,                       0,
114     '@', -ESC_A, -ESC_B, -ESC_C, -ESC_D, -ESC_E,      0, -ESC_G,   /* @ - G */       0,                       0,
115  -ESC_H,      0,      0, -ESC_K,      0,      0,      0,      0,   /* H - O */       0,                       0,
116  -ESC_P, -ESC_Q, -ESC_R, -ESC_S,      0,      0, -ESC_V, -ESC_W,   /* P - W */       0,                       0,
117  -ESC_X,      0, -ESC_Z,    '[',   '\\',    ']',    '^',    '_',   /* X - _ */       CHAR_COLON,              CHAR_SEMICOLON,
118     '`',      7, -ESC_b,      0, -ESC_d,  ESC_e,  ESC_f,      0,   /* ` - g */       CHAR_LESS_THAN_SIGN,     CHAR_EQUALS_SIGN,
119  -ESC_h,      0,      0, -ESC_k,      0,      0,  ESC_n,      0,   /* h - o */       CHAR_GREATER_THAN_SIGN,  CHAR_QUESTION_MARK,
120  -ESC_p,      0,  ESC_r, -ESC_s,  ESC_tee,    0, -ESC_v, -ESC_w,   /* p - w */       CHAR_COMMERCIAL_AT,      -ESC_A,
121       0,      0, -ESC_z                                            /* x - z */       -ESC_B,                  -ESC_C,
122         -ESC_D,                  -ESC_E,
123         0,                       -ESC_G,
124         -ESC_H,                  0,
125         0,                       -ESC_K,
126         0,                       0,
127         -ESC_N,                  0,
128         -ESC_P,                  -ESC_Q,
129         -ESC_R,                  -ESC_S,
130         0,                       0,
131         -ESC_V,                  -ESC_W,
132         -ESC_X,                  0,
133         -ESC_Z,                  CHAR_LEFT_SQUARE_BRACKET,
134         CHAR_BACKSLASH,          CHAR_RIGHT_SQUARE_BRACKET,
135         CHAR_CIRCUMFLEX_ACCENT,  CHAR_UNDERSCORE,
136         CHAR_GRAVE_ACCENT,       7,
137         -ESC_b,                  0,
138         -ESC_d,                  ESC_e,
139         ESC_f,                   0,
140         -ESC_h,                  0,
141         0,                       -ESC_k,
142         0,                       0,
143         ESC_n,                   0,
144         -ESC_p,                  0,
145         ESC_r,                   -ESC_s,
146         ESC_tee,                 0,
147         -ESC_v,                  -ESC_w,
148         0,                       0,
149         -ESC_z
150  };  };
151    
152  #else           /* This is the "abnormal" table for EBCDIC systems */  #else
153    
154    /* This is the "abnormal" table for EBCDIC systems without UTF-8 support. */
155    
156  static const short int escapes[] = {  static const short int escapes[] = {
157  /*  48 */     0,     0,      0,     '.',    '<',   '(',    '+',    '|',  /*  48 */     0,     0,      0,     '.',    '<',   '(',    '+',    '|',
158  /*  50 */   '&',     0,      0,       0,      0,     0,      0,      0,  /*  50 */   '&',     0,      0,       0,      0,     0,      0,      0,
# Line 130  static const short int escapes[] = { Line 171  static const short int escapes[] = {
171  /*  B8 */     0,     0,      0,       0,      0,   ']',    '=',    '-',  /*  B8 */     0,     0,      0,       0,      0,   ']',    '=',    '-',
172  /*  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,
173  /*  C8 */-ESC_H,     0,      0,       0,      0,     0,      0,      0,  /*  C8 */-ESC_H,     0,      0,       0,      0,     0,      0,      0,
174  /*  D0 */   '}',     0, -ESC_K,       0,      0,     0,      0, -ESC_P,  /*  D0 */   '}',     0, -ESC_K,       0,      0,-ESC_N,      0, -ESC_P,
175  /*  D8 */-ESC_Q,-ESC_R,      0,       0,      0,     0,      0,      0,  /*  D8 */-ESC_Q,-ESC_R,      0,       0,      0,     0,      0,      0,
176  /*  E0 */  '\\',     0, -ESC_S,       0,      0,-ESC_V, -ESC_W, -ESC_X,  /*  E0 */  '\\',     0, -ESC_S,       0,      0,-ESC_V, -ESC_W, -ESC_X,
177  /*  E8 */     0,-ESC_Z,      0,       0,      0,     0,      0,      0,  /*  E8 */     0,-ESC_Z,      0,       0,      0,     0,      0,      0,
# Line 142  static const short int escapes[] = { Line 183  static const short int escapes[] = {
183    
184  /* Table of special "verbs" like (*PRUNE). This is a short table, so it is  /* Table of special "verbs" like (*PRUNE). This is a short table, so it is
185  searched linearly. Put all the names into a single string, in order to reduce  searched linearly. Put all the names into a single string, in order to reduce
186  the number of relocations when a shared library is dynamically linked. */  the number of relocations when a shared library is dynamically linked. The
187    string is built from string macros so that it works in UTF-8 mode on EBCDIC
188    platforms. */
189    
190  typedef struct verbitem {  typedef struct verbitem {
191    int   len;    int   len;                 /* Length of verb name */
192    int   op;    int   op;                  /* Op when no arg, or -1 if arg mandatory */
193      int   op_arg;              /* Op when arg present, or -1 if not allowed */
194  } verbitem;  } verbitem;
195    
196  static const char verbnames[] =  static const char verbnames[] =
197    "ACCEPT\0"    "\0"                       /* Empty name is a shorthand for MARK */
198    "COMMIT\0"    STRING_MARK0
199    "F\0"    STRING_ACCEPT0
200    "FAIL\0"    STRING_COMMIT0
201    "PRUNE\0"    STRING_F0
202    "SKIP\0"    STRING_FAIL0
203    "THEN";    STRING_PRUNE0
204      STRING_SKIP0
205  static verbitem verbs[] = {    STRING_THEN;
206    { 6, OP_ACCEPT },  
207    { 6, OP_COMMIT },  static const verbitem verbs[] = {
208    { 1, OP_FAIL },    { 0, -1,        OP_MARK },
209    { 4, OP_FAIL },    { 4, -1,        OP_MARK },
210    { 5, OP_PRUNE },    { 6, OP_ACCEPT, -1 },
211    { 4, OP_SKIP  },    { 6, OP_COMMIT, -1 },
212    { 4, OP_THEN  }    { 1, OP_FAIL,   -1 },
213      { 4, OP_FAIL,   -1 },
214      { 5, OP_PRUNE,  OP_PRUNE_ARG },
215      { 4, OP_SKIP,   OP_SKIP_ARG  },
216      { 4, OP_THEN,   OP_THEN_ARG  }
217  };  };
218    
219  static int verbcount = sizeof(verbs)/sizeof(verbitem);  static const int verbcount = sizeof(verbs)/sizeof(verbitem);
220    
221    
222  /* Tables of names of POSIX character classes and their lengths. The names are  /* Tables of names of POSIX character classes and their lengths. The names are
# Line 178  length entry. The first three must be al Line 226  length entry. The first three must be al
226  for handling case independence. */  for handling case independence. */
227    
228  static const char posix_names[] =  static const char posix_names[] =
229    "alpha\0"  "lower\0"  "upper\0"  "alnum\0"  "ascii\0"  "blank\0"    STRING_alpha0 STRING_lower0 STRING_upper0 STRING_alnum0
230    "cntrl\0"  "digit\0"  "graph\0"  "print\0"  "punct\0"  "space\0"    STRING_ascii0 STRING_blank0 STRING_cntrl0 STRING_digit0
231    "word\0"   "xdigit";    STRING_graph0 STRING_print0 STRING_punct0 STRING_space0
232      STRING_word0  STRING_xdigit;
233    
234  static const uschar posix_name_lengths[] = {  static const pcre_uint8 posix_name_lengths[] = {
235    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 };
236    
237  /* Table of class bit maps for each POSIX class. Each class is formed from a  /* Table of class bit maps for each POSIX class. Each class is formed from a
# Line 212  static const int posix_class_maps[] = { Line 261  static const int posix_class_maps[] = {
261    cbit_xdigit,-1,          0              /* xdigit */    cbit_xdigit,-1,          0              /* xdigit */
262  };  };
263    
264    /* Table of substitutes for \d etc when PCRE_UCP is set. The POSIX class
265    substitutes must be in the order of the names, defined above, and there are
266    both positive and negative cases. NULL means no substitute. */
267    
268    #ifdef SUPPORT_UCP
269    static const pcre_uchar literal_PNd[]  = { '\\', 'P', '{', 'N', 'd', '}', '\0' };
270    static const pcre_uchar literal_pNd[]  = { '\\', 'p', '{', 'N', 'd', '}', '\0' };
271    static const pcre_uchar literal_PXsp[] = { '\\', 'P', '{', 'X', 's', 'p', '}', '\0' };
272    static const pcre_uchar literal_pXsp[] = { '\\', 'p', '{', 'X', 's', 'p', '}', '\0' };
273    static const pcre_uchar literal_PXwd[] = { '\\', 'P', '{', 'X', 'w', 'd', '}', '\0' };
274    static const pcre_uchar literal_pXwd[] = { '\\', 'p', '{', 'X', 'w', 'd', '}', '\0' };
275    
276    static const pcre_uchar *substitutes[] = {
277      literal_PNd,           /* \D */
278      literal_pNd,           /* \d */
279      literal_PXsp,          /* \S */       /* NOTE: Xsp is Perl space */
280      literal_pXsp,          /* \s */
281      literal_PXwd,          /* \W */
282      literal_pXwd           /* \w */
283    };
284    
285    static const pcre_uchar literal_pL[] =   { '\\', 'p', '{', 'L', '}', '\0' };
286    static const pcre_uchar literal_pLl[] =  { '\\', 'p', '{', 'L', 'l', '}', '\0' };
287    static const pcre_uchar literal_pLu[] =  { '\\', 'p', '{', 'L', 'u', '}', '\0' };
288    static const pcre_uchar literal_pXan[] = { '\\', 'p', '{', 'X', 'a', 'n', '}', '\0' };
289    static const pcre_uchar literal_h[] =    { '\\', 'h', '\0' };
290    static const pcre_uchar literal_pXps[] = { '\\', 'p', '{', 'X', 'p', 's', '}', '\0' };
291    static const pcre_uchar literal_PL[] =   { '\\', 'P', '{', 'L', '}', '\0' };
292    static const pcre_uchar literal_PLl[] =  { '\\', 'P', '{', 'L', 'l', '}', '\0' };
293    static const pcre_uchar literal_PLu[] =  { '\\', 'P', '{', 'L', 'u', '}', '\0' };
294    static const pcre_uchar literal_PXan[] = { '\\', 'P', '{', 'X', 'a', 'n', '}', '\0' };
295    static const pcre_uchar literal_H[] =    { '\\', 'H', '\0' };
296    static const pcre_uchar literal_PXps[] = { '\\', 'P', '{', 'X', 'p', 's', '}', '\0' };
297    
298    static const pcre_uchar *posix_substitutes[] = {
299      literal_pL,            /* alpha */
300      literal_pLl,           /* lower */
301      literal_pLu,           /* upper */
302      literal_pXan,          /* alnum */
303      NULL,                  /* ascii */
304      literal_h,             /* blank */
305      NULL,                  /* cntrl */
306      literal_pNd,           /* digit */
307      NULL,                  /* graph */
308      NULL,                  /* print */
309      NULL,                  /* punct */
310      literal_pXps,          /* space */    /* NOTE: Xps is POSIX space */
311      literal_pXwd,          /* word */
312      NULL,                  /* xdigit */
313      /* Negated cases */
314      literal_PL,            /* ^alpha */
315      literal_PLl,           /* ^lower */
316      literal_PLu,           /* ^upper */
317      literal_PXan,          /* ^alnum */
318      NULL,                  /* ^ascii */
319      literal_H,             /* ^blank */
320      NULL,                  /* ^cntrl */
321      literal_PNd,           /* ^digit */
322      NULL,                  /* ^graph */
323      NULL,                  /* ^print */
324      NULL,                  /* ^punct */
325      literal_PXps,          /* ^space */   /* NOTE: Xps is POSIX space */
326      literal_PXwd,          /* ^word */
327      NULL                   /* ^xdigit */
328    };
329    #define POSIX_SUBSIZE (sizeof(posix_substitutes) / sizeof(pcre_uchar *))
330    #endif
331    
332  #define STRING(a)  # a  #define STRING(a)  # a
333  #define XSTRING(s) STRING(s)  #define XSTRING(s) STRING(s)
# Line 224  the number of relocations needed when a Line 340  the number of relocations needed when a
340  it is now one long string. We cannot use a table of offsets, because the  it is now one long string. We cannot use a table of offsets, because the
341  lengths of inserts such as XSTRING(MAX_NAME_SIZE) are not known. Instead, we  lengths of inserts such as XSTRING(MAX_NAME_SIZE) are not known. Instead, we
342  simply count through to the one we want - this isn't a performance issue  simply count through to the one we want - this isn't a performance issue
343  because these strings are used only when there is a compilation error. */  because these strings are used only when there is a compilation error.
344    
345    Each substring ends with \0 to insert a null character. This includes the final
346    substring, so that the whole string ends with \0\0, which can be detected when
347    counting through. */
348    
349  static const char error_texts[] =  static const char error_texts[] =
350    "no error\0"    "no error\0"
# Line 241  static const char error_texts[] = Line 361  static const char error_texts[] =
361    /* 10 */    /* 10 */
362    "operand of unlimited repeat could match the empty string\0"  /** DEAD **/    "operand of unlimited repeat could match the empty string\0"  /** DEAD **/
363    "internal error: unexpected repeat\0"    "internal error: unexpected repeat\0"
364    "unrecognized character after (?\0"    "unrecognized character after (? or (?-\0"
365    "POSIX named classes are supported only within a class\0"    "POSIX named classes are supported only within a class\0"
366    "missing )\0"    "missing )\0"
367    /* 15 */    /* 15 */
# Line 271  static const char error_texts[] = Line 391  static const char error_texts[] =
391    /* 35 */    /* 35 */
392    "invalid condition (?(0)\0"    "invalid condition (?(0)\0"
393    "\\C not allowed in lookbehind assertion\0"    "\\C not allowed in lookbehind assertion\0"
394    "PCRE does not support \\L, \\l, \\N, \\U, or \\u\0"    "PCRE does not support \\L, \\l, \\N{name}, \\U, or \\u\0"
395    "number after (?C is > 255\0"    "number after (?C is > 255\0"
396    "closing ) for (?C expected\0"    "closing ) for (?C expected\0"
397    /* 40 */    /* 40 */
# Line 293  static const char error_texts[] = Line 413  static const char error_texts[] =
413    "internal error: previously-checked referenced subpattern not found\0"    "internal error: previously-checked referenced subpattern not found\0"
414    "DEFINE group contains more than one branch\0"    "DEFINE group contains more than one branch\0"
415    /* 55 */    /* 55 */
416    "repeating a DEFINE group is not allowed\0"    "repeating a DEFINE group is not allowed\0"  /** DEAD **/
417    "inconsistent NEWLINE options\0"    "inconsistent NEWLINE options\0"
418    "\\g is not followed by a braced name or an optionally braced non-zero number\0"    "\\g is not followed by a braced, angle-bracketed, or quoted name/number or by a plain number\0"
419    "(?+ or (?- or (?(+ or (?(- must be followed by a non-zero number\0"    "a numbered reference must not be zero\0"
420    "(*VERB) with an argument is not supported\0"    "an argument is not allowed for (*ACCEPT), (*FAIL), or (*COMMIT)\0"
421    /* 60 */    /* 60 */
422    "(*VERB) not recognized\0"    "(*VERB) not recognized\0"
423    "number is too big";    "number is too big\0"
424      "subpattern name expected\0"
425      "digit expected after (?+\0"
426      "] is an invalid data character in JavaScript compatibility mode\0"
427      /* 65 */
428      "different names for subpatterns of the same number are not allowed\0"
429      "(*MARK) must have an argument\0"
430      "this version of PCRE is not compiled with PCRE_UCP support\0"
431      "\\c must be followed by an ASCII character\0"
432      "\\k is not followed by a braced, angle-bracketed, or quoted name\0"
433      /* 70 */
434      "internal error: unknown opcode in find_fixedlength()\0"
435      ;
436    
437  /* Table to identify digits and hex digits. This is used when compiling  /* Table to identify digits and hex digits. This is used when compiling
438  patterns. Note that the tables in chartables are dependent on the locale, and  patterns. Note that the tables in chartables are dependent on the locale, and
# Line 319  For convenience, we use the same bit def Line 450  For convenience, we use the same bit def
450    
451  Then we can use ctype_digit and ctype_xdigit in the code. */  Then we can use ctype_digit and ctype_xdigit in the code. */
452    
453  #ifndef EBCDIC  /* This is the "normal" case, for ASCII systems */  #ifndef EBCDIC
454    
455    /* This is the "normal" case, for ASCII systems, and EBCDIC systems running in
456    UTF-8 mode. */
457    
458  static const unsigned char digitab[] =  static const unsigned char digitab[] =
459    {    {
460    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*   0-  7 */    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*   0-  7 */
# Line 355  static const unsigned char digitab[] = Line 490  static const unsigned char digitab[] =
490    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 240-247 */    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 240-247 */
491    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};/* 248-255 */    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};/* 248-255 */
492    
493  #else           /* This is the "abnormal" case, for EBCDIC systems */  #else
494    
495    /* This is the "abnormal" case, for EBCDIC systems not running in UTF-8 mode. */
496    
497  static const unsigned char digitab[] =  static const unsigned char digitab[] =
498    {    {
499    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*   0-  7  0 */    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*   0-  7  0 */
# Line 430  static const unsigned char ebcdic_charta Line 568  static const unsigned char ebcdic_charta
568  /* Definition to allow mutual recursion */  /* Definition to allow mutual recursion */
569    
570  static BOOL  static BOOL
571    compile_regex(int, int, uschar **, const uschar **, int *, BOOL, BOOL, int,    compile_regex(int, pcre_uchar **, const pcre_uchar **, int *, BOOL, BOOL, int, int,
572      int *, int *, branch_chain *, compile_data *, int *);      int *, int *, branch_chain *, compile_data *, int *);
573    
574    
# Line 452  static const char * Line 590  static const char *
590  find_error_text(int n)  find_error_text(int n)
591  {  {
592  const char *s = error_texts;  const char *s = error_texts;
593  for (; n > 0; n--) while (*s++ != 0);  for (; n > 0; n--)
594      {
595      while (*s++ != 0) {};
596      if (*s == 0) return "Error text not found (please report)";
597      }
598  return s;  return s;
599  }  }
600    
601    
602  /*************************************************  /*************************************************
603    *            Check for counted repeat            *
604    *************************************************/
605    
606    /* This function is called when a '{' is encountered in a place where it might
607    start a quantifier. It looks ahead to see if it really is a quantifier or not.
608    It is only a quantifier if it is one of the forms {ddd} {ddd,} or {ddd,ddd}
609    where the ddds are digits.
610    
611    Arguments:
612      p         pointer to the first char after '{'
613    
614    Returns:    TRUE or FALSE
615    */
616    
617    static BOOL
618    is_counted_repeat(const pcre_uchar *p)
619    {
620    if ((digitab[*p++] & ctype_digit) == 0) return FALSE;
621    while ((digitab[*p] & ctype_digit) != 0) p++;
622    if (*p == CHAR_RIGHT_CURLY_BRACKET) return TRUE;
623    
624    if (*p++ != CHAR_COMMA) return FALSE;
625    if (*p == CHAR_RIGHT_CURLY_BRACKET) return TRUE;
626    
627    if ((digitab[*p++] & ctype_digit) == 0) return FALSE;
628    while ((digitab[*p] & ctype_digit) != 0) p++;
629    
630    return (*p == CHAR_RIGHT_CURLY_BRACKET);
631    }
632    
633    
634    
635    /*************************************************
636  *            Handle escapes                      *  *            Handle escapes                      *
637  *************************************************/  *************************************************/
638    
# Line 482  Returns:         zero or positive => a d Line 657  Returns:         zero or positive => a d
657  */  */
658    
659  static int  static int
660  check_escape(const uschar **ptrptr, int *errorcodeptr, int bracount,  check_escape(const pcre_uchar **ptrptr, int *errorcodeptr, int bracount,
661    int options, BOOL isclass)    int options, BOOL isclass)
662  {  {
663  BOOL utf8 = (options & PCRE_UTF8) != 0;  BOOL utf8 = (options & PCRE_UTF8) != 0;
664  const uschar *ptr = *ptrptr + 1;  const pcre_uchar *ptr = *ptrptr + 1;
665  int c, i;  int c, i;
666    
667  GETCHARINCTEST(c, ptr);           /* Get character value, increment pointer */  GETCHARINCTEST(c, ptr);           /* Get character value, increment pointer */
# Line 496  ptr--;                            /* Set Line 671  ptr--;                            /* Set
671    
672  if (c == 0) *errorcodeptr = ERR1;  if (c == 0) *errorcodeptr = ERR1;
673    
674  /* 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
675  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.
676  Otherwise further processing may be required. */  Otherwise further processing may be required. */
677    
678  #ifndef EBCDIC  /* ASCII coding */  #ifndef EBCDIC  /* ASCII/UTF-8 coding */
679  else if (c < '0' || c > 'z') {}                           /* Not alphameric */  else if (c < CHAR_0 || c > CHAR_z) {}                     /* Not alphanumeric */
680  else if ((i = escapes[c - '0']) != 0) c = i;  else if ((i = escapes[c - CHAR_0]) != 0) c = i;
681    
682  #else           /* EBCDIC coding */  #else           /* EBCDIC coding */
683  else if (c < 'a' || (ebcdic_chartab[c] & 0x0E) == 0) {}   /* Not alphameric */  else if (c < 'a' || (ebcdic_chartab[c] & 0x0E) == 0) {}   /* Not alphanumeric */
684  else if ((i = escapes[c - 0x48]) != 0)  c = i;  else if ((i = escapes[c - 0x48]) != 0)  c = i;
685  #endif  #endif
686    
# Line 513  else if ((i = escapes[c - 0x48]) != 0) Line 688  else if ((i = escapes[c - 0x48]) != 0)
688    
689  else  else
690    {    {
691    const uschar *oldptr;    const pcre_uchar *oldptr;
692    BOOL braced, negated;    BOOL braced, negated;
693    
694    switch (c)    switch (c)
# Line 521  else Line 696  else
696      /* A number of Perl escapes are not handled by PCRE. We give an explicit      /* A number of Perl escapes are not handled by PCRE. We give an explicit
697      error. */      error. */
698    
699      case 'l':      case CHAR_l:
700      case 'L':      case CHAR_L:
     case 'N':  
     case 'u':  
     case 'U':  
701      *errorcodeptr = ERR37;      *errorcodeptr = ERR37;
702      break;      break;
703    
704      /* \g must be followed by a number, either plain or braced. If positive, it      case CHAR_u:
705      is an absolute backreference. If negative, it is a relative backreference.      if ((options & PCRE_JAVASCRIPT_COMPAT) != 0)
706      This is a Perl 5.10 feature. Perl 5.10 also supports \g{name} as a        {
707      reference to a named group. This is part of Perl's movement towards a        /* In JavaScript, \u must be followed by four hexadecimal numbers.
708      unified syntax for back references. As this is synonymous with \k{name}, we        Otherwise it is a lowercase u letter. */
709      fudge it up by pretending it really was \k. */        if ((digitab[ptr[1]] & ctype_xdigit) != 0 && (digitab[ptr[2]] & ctype_xdigit) != 0
710               && (digitab[ptr[3]] & ctype_xdigit) != 0 && (digitab[ptr[4]] & ctype_xdigit) != 0)
711      case 'g':          {
712      if (ptr[1] == '{')          c = 0;
713        {          for (i = 0; i < 4; ++i)
714        const uschar *p;            {
715        for (p = ptr+2; *p != 0 && *p != '}'; p++)            register int cc = *(++ptr);
716          if (*p != '-' && (digitab[*p] & ctype_digit) == 0) break;  #ifndef EBCDIC  /* ASCII/UTF-8 coding */
717        if (*p != 0 && *p != '}')            if (cc >= CHAR_a) cc -= 32;               /* Convert to upper case */
718              c = (c << 4) + cc - ((cc < CHAR_A)? CHAR_0 : (CHAR_A - 10));
719    #else           /* EBCDIC coding */
720              if (cc >= CHAR_a && cc <= CHAR_z) cc += 64;  /* Convert to upper case */
721              c = (c << 4) + cc - ((cc >= CHAR_0)? CHAR_0 : (CHAR_A - 10));
722    #endif
723              }
724            }
725          }
726        else
727          *errorcodeptr = ERR37;
728        break;
729    
730        case CHAR_U:
731        /* In JavaScript, \U is an uppercase U letter. */
732        if ((options & PCRE_JAVASCRIPT_COMPAT) == 0) *errorcodeptr = ERR37;
733        break;
734    
735        /* In a character class, \g is just a literal "g". Outside a character
736        class, \g must be followed by one of a number of specific things:
737    
738        (1) A number, either plain or braced. If positive, it is an absolute
739        backreference. If negative, it is a relative backreference. This is a Perl
740        5.10 feature.
741    
742        (2) Perl 5.10 also supports \g{name} as a reference to a named group. This
743        is part of Perl's movement towards a unified syntax for back references. As
744        this is synonymous with \k{name}, we fudge it up by pretending it really
745        was \k.
746    
747        (3) For Oniguruma compatibility we also support \g followed by a name or a
748        number either in angle brackets or in single quotes. However, these are
749        (possibly recursive) subroutine calls, _not_ backreferences. Just return
750        the -ESC_g code (cf \k). */
751    
752        case CHAR_g:
753        if (isclass) break;
754        if (ptr[1] == CHAR_LESS_THAN_SIGN || ptr[1] == CHAR_APOSTROPHE)
755          {
756          c = -ESC_g;
757          break;
758          }
759    
760        /* Handle the Perl-compatible cases */
761    
762        if (ptr[1] == CHAR_LEFT_CURLY_BRACKET)
763          {
764          const pcre_uchar *p;
765          for (p = ptr+2; *p != 0 && *p != CHAR_RIGHT_CURLY_BRACKET; p++)
766            if (*p != CHAR_MINUS && (digitab[*p] & ctype_digit) == 0) break;
767          if (*p != 0 && *p != CHAR_RIGHT_CURLY_BRACKET)
768          {          {
769          c = -ESC_k;          c = -ESC_k;
770          break;          break;
# Line 552  else Line 774  else
774        }        }
775      else braced = FALSE;      else braced = FALSE;
776    
777      if (ptr[1] == '-')      if (ptr[1] == CHAR_MINUS)
778        {        {
779        negated = TRUE;        negated = TRUE;
780        ptr++;        ptr++;
# Line 561  else Line 783  else
783    
784      c = 0;      c = 0;
785      while ((digitab[ptr[1]] & ctype_digit) != 0)      while ((digitab[ptr[1]] & ctype_digit) != 0)
786        c = c * 10 + *(++ptr) - '0';        c = c * 10 + *(++ptr) - CHAR_0;
787    
788      if (c < 0)      if (c < 0)   /* Integer overflow */
789        {        {
790        *errorcodeptr = ERR61;        *errorcodeptr = ERR61;
791        break;        break;
792        }        }
793    
794      if (c == 0 || (braced && *(++ptr) != '}'))      if (braced && *(++ptr) != CHAR_RIGHT_CURLY_BRACKET)
795        {        {
796        *errorcodeptr = ERR57;        *errorcodeptr = ERR57;
797        break;        break;
798        }        }
799    
800        if (c == 0)
801          {
802          *errorcodeptr = ERR58;
803          break;
804          }
805    
806      if (negated)      if (negated)
807        {        {
808        if (c > bracount)        if (c > bracount)
# Line 600  else Line 828  else
828      value is greater than 377, the least significant 8 bits are taken. Inside a      value is greater than 377, the least significant 8 bits are taken. Inside a
829      character class, \ followed by a digit is always an octal number. */      character class, \ followed by a digit is always an octal number. */
830    
831      case '1': case '2': case '3': case '4': case '5':      case CHAR_1: case CHAR_2: case CHAR_3: case CHAR_4: case CHAR_5:
832      case '6': case '7': case '8': case '9':      case CHAR_6: case CHAR_7: case CHAR_8: case CHAR_9:
833    
834      if (!isclass)      if (!isclass)
835        {        {
836        oldptr = ptr;        oldptr = ptr;
837        c -= '0';        c -= CHAR_0;
838        while ((digitab[ptr[1]] & ctype_digit) != 0)        while ((digitab[ptr[1]] & ctype_digit) != 0)
839          c = c * 10 + *(++ptr) - '0';          c = c * 10 + *(++ptr) - CHAR_0;
840        if (c < 0)        if (c < 0)    /* Integer overflow */
841          {          {
842          *errorcodeptr = ERR61;          *errorcodeptr = ERR61;
843          break;          break;
# Line 626  else Line 854  else
854      generates a binary zero byte and treats the digit as a following literal.      generates a binary zero byte and treats the digit as a following literal.
855      Thus we have to pull back the pointer by one. */      Thus we have to pull back the pointer by one. */
856    
857      if ((c = *ptr) >= '8')      if ((c = *ptr) >= CHAR_8)
858        {        {
859        ptr--;        ptr--;
860        c = 0;        c = 0;
# Line 639  else Line 867  else
867      to do). Nowadays we allow for larger numbers in UTF-8 mode, but no more      to do). Nowadays we allow for larger numbers in UTF-8 mode, but no more
868      than 3 octal digits. */      than 3 octal digits. */
869    
870      case '0':      case CHAR_0:
871      c -= '0';      c -= CHAR_0;
872      while(i++ < 2 && ptr[1] >= '0' && ptr[1] <= '7')      while(i++ < 2 && ptr[1] >= CHAR_0 && ptr[1] <= CHAR_7)
873          c = c * 8 + *(++ptr) - '0';          c = c * 8 + *(++ptr) - CHAR_0;
874      if (!utf8 && c > 255) *errorcodeptr = ERR51;      if (!utf8 && c > 255) *errorcodeptr = ERR51;
875      break;      break;
876    
# Line 650  else Line 878  else
878      than 0xff in utf8 mode, but only if the ddd are hex digits. If not, { is      than 0xff in utf8 mode, but only if the ddd are hex digits. If not, { is
879      treated as a data character. */      treated as a data character. */
880    
881      case 'x':      case CHAR_x:
882      if (ptr[1] == '{')      if ((options & PCRE_JAVASCRIPT_COMPAT) != 0)
883          {
884          /* In JavaScript, \x must be followed by two hexadecimal numbers.
885          Otherwise it is a lowercase x letter. */
886          if ((digitab[ptr[1]] & ctype_xdigit) != 0 && (digitab[ptr[2]] & ctype_xdigit) != 0)
887            {
888            c = 0;
889            for (i = 0; i < 2; ++i)
890              {
891              register int cc = *(++ptr);
892    #ifndef EBCDIC  /* ASCII/UTF-8 coding */
893              if (cc >= CHAR_a) cc -= 32;               /* Convert to upper case */
894              c = (c << 4) + cc - ((cc < CHAR_A)? CHAR_0 : (CHAR_A - 10));
895    #else           /* EBCDIC coding */
896              if (cc >= CHAR_a && cc <= CHAR_z) cc += 64;  /* Convert to upper case */
897              c = (c << 4) + cc - ((cc >= CHAR_0)? CHAR_0 : (CHAR_A - 10));
898    #endif
899              }
900            }
901          break;
902          }
903    
904        if (ptr[1] == CHAR_LEFT_CURLY_BRACKET)
905        {        {
906        const uschar *pt = ptr + 2;        const pcre_uchar *pt = ptr + 2;
907        int count = 0;        int count = 0;
908    
909        c = 0;        c = 0;
910        while ((digitab[*pt] & ctype_xdigit) != 0)        while ((digitab[*pt] & ctype_xdigit) != 0)
911          {          {
912          register int cc = *pt++;          register int cc = *pt++;
913          if (c == 0 && cc == '0') continue;     /* Leading zeroes */          if (c == 0 && cc == CHAR_0) continue;     /* Leading zeroes */
914          count++;          count++;
915    
916  #ifndef EBCDIC  /* ASCII coding */  #ifndef EBCDIC  /* ASCII/UTF-8 coding */
917          if (cc >= 'a') cc -= 32;               /* Convert to upper case */          if (cc >= CHAR_a) cc -= 32;               /* Convert to upper case */
918          c = (c << 4) + cc - ((cc < 'A')? '0' : ('A' - 10));          c = (c << 4) + cc - ((cc < CHAR_A)? CHAR_0 : (CHAR_A - 10));
919  #else           /* EBCDIC coding */  #else           /* EBCDIC coding */
920          if (cc >= 'a' && cc <= 'z') cc += 64;  /* Convert to upper case */          if (cc >= CHAR_a && cc <= CHAR_z) cc += 64;  /* Convert to upper case */
921          c = (c << 4) + cc - ((cc >= '0')? '0' : ('A' - 10));          c = (c << 4) + cc - ((cc >= CHAR_0)? CHAR_0 : (CHAR_A - 10));
922  #endif  #endif
923          }          }
924    
925        if (*pt == '}')        if (*pt == CHAR_RIGHT_CURLY_BRACKET)
926          {          {
927          if (c < 0 || count > (utf8? 8 : 2)) *errorcodeptr = ERR34;          if (c < 0 || count > (utf8? 8 : 2)) *errorcodeptr = ERR34;
928          ptr = pt;          ptr = pt;
# Line 688  else Line 938  else
938      c = 0;      c = 0;
939      while (i++ < 2 && (digitab[ptr[1]] & ctype_xdigit) != 0)      while (i++ < 2 && (digitab[ptr[1]] & ctype_xdigit) != 0)
940        {        {
941        int cc;                               /* Some compilers don't like ++ */        int cc;                                  /* Some compilers don't like */
942        cc = *(++ptr);                        /* in initializers */        cc = *(++ptr);                           /* ++ in initializers */
943  #ifndef EBCDIC  /* ASCII coding */  #ifndef EBCDIC  /* ASCII/UTF-8 coding */
944        if (cc >= 'a') cc -= 32;              /* Convert to upper case */        if (cc >= CHAR_a) cc -= 32;              /* Convert to upper case */
945        c = c * 16 + cc - ((cc < 'A')? '0' : ('A' - 10));        c = c * 16 + cc - ((cc < CHAR_A)? CHAR_0 : (CHAR_A - 10));
946  #else           /* EBCDIC coding */  #else           /* EBCDIC coding */
947        if (cc <= 'z') cc += 64;              /* Convert to upper case */        if (cc <= CHAR_z) cc += 64;              /* Convert to upper case */
948        c = c * 16 + cc - ((cc >= '0')? '0' : ('A' - 10));        c = c * 16 + cc - ((cc >= CHAR_0)? CHAR_0 : (CHAR_A - 10));
949  #endif  #endif
950        }        }
951      break;      break;
952    
953      /* For \c, a following letter is upper-cased; then the 0x40 bit is flipped.      /* For \c, a following letter is upper-cased; then the 0x40 bit is flipped.
954      This coding is ASCII-specific, but then the whole concept of \cx is      An error is given if the byte following \c is not an ASCII character. This
955        coding is ASCII-specific, but then the whole concept of \cx is
956      ASCII-specific. (However, an EBCDIC equivalent has now been added.) */      ASCII-specific. (However, an EBCDIC equivalent has now been added.) */
957    
958      case 'c':      case CHAR_c:
959      c = *(++ptr);      c = *(++ptr);
960      if (c == 0)      if (c == 0)
961        {        {
962        *errorcodeptr = ERR2;        *errorcodeptr = ERR2;
963        break;        break;
964        }        }
965    #ifndef EBCDIC    /* ASCII/UTF-8 coding */
966  #ifndef EBCDIC  /* ASCII coding */      if (c > 127)  /* Excludes all non-ASCII in either mode */
967      if (c >= 'a' && c <= 'z') c -= 32;        {
968          *errorcodeptr = ERR68;
969          break;
970          }
971        if (c >= CHAR_a && c <= CHAR_z) c -= 32;
972      c ^= 0x40;      c ^= 0x40;
973  #else           /* EBCDIC coding */  #else             /* EBCDIC coding */
974      if (c >= 'a' && c <= 'z') c += 64;      if (c >= CHAR_a && c <= CHAR_z) c += 64;
975      c ^= 0xC0;      c ^= 0xC0;
976  #endif  #endif
977      break;      break;
978    
979      /* PCRE_EXTRA enables extensions to Perl in the matter of escapes. Any      /* PCRE_EXTRA enables extensions to Perl in the matter of escapes. Any
980      other alphameric following \ is an error if PCRE_EXTRA was set; otherwise,      other alphanumeric following \ is an error if PCRE_EXTRA was set;
981      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
982      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
983      in future, so I haven't "optimized" it. */      be again in future, so I haven't "optimized" it. */
984    
985      default:      default:
986      if ((options & PCRE_EXTRA) != 0) switch(c)      if ((options & PCRE_EXTRA) != 0) switch(c)
# Line 738  else Line 993  else
993      }      }
994    }    }
995    
996    /* Perl supports \N{name} for character names, as well as plain \N for "not
997    newline". PCRE does not support \N{name}. However, it does support
998    quantification such as \N{2,3}. */
999    
1000    if (c == -ESC_N && ptr[1] == CHAR_LEFT_CURLY_BRACKET &&
1001         !is_counted_repeat(ptr+2))
1002      *errorcodeptr = ERR37;
1003    
1004    /* If PCRE_UCP is set, we change the values for \d etc. */
1005    
1006    if ((options & PCRE_UCP) != 0 && c <= -ESC_D && c >= -ESC_w)
1007      c -= (ESC_DU - ESC_D);
1008    
1009    /* Set the pointer to the final character before returning. */
1010    
1011  *ptrptr = ptr;  *ptrptr = ptr;
1012  return c;  return c;
1013  }  }
# Line 764  Returns:         type value from ucp_typ Line 1034  Returns:         type value from ucp_typ
1034  */  */
1035    
1036  static int  static int
1037  get_ucp(const uschar **ptrptr, BOOL *negptr, int *dptr, int *errorcodeptr)  get_ucp(const pcre_uchar **ptrptr, BOOL *negptr, int *dptr, int *errorcodeptr)
1038  {  {
1039  int c, i, bot, top;  int c, i, bot, top;
1040  const uschar *ptr = *ptrptr;  const pcre_uchar *ptr = *ptrptr;
1041  char name[32];  char name[32];
1042    
1043  c = *(++ptr);  c = *(++ptr);
# Line 778  if (c == 0) goto ERROR_RETURN; Line 1048  if (c == 0) goto ERROR_RETURN;
1048  /* \P or \p can be followed by a name in {}, optionally preceded by ^ for  /* \P or \p can be followed by a name in {}, optionally preceded by ^ for
1049  negation. */  negation. */
1050    
1051  if (c == '{')  if (c == CHAR_LEFT_CURLY_BRACKET)
1052    {    {
1053    if (ptr[1] == '^')    if (ptr[1] == CHAR_CIRCUMFLEX_ACCENT)
1054      {      {
1055      *negptr = TRUE;      *negptr = TRUE;
1056      ptr++;      ptr++;
# Line 789  if (c == '{') Line 1059  if (c == '{')
1059      {      {
1060      c = *(++ptr);      c = *(++ptr);
1061      if (c == 0) goto ERROR_RETURN;      if (c == 0) goto ERROR_RETURN;
1062      if (c == '}') break;      if (c == CHAR_RIGHT_CURLY_BRACKET) break;
1063      name[i] = c;      name[i] = c;
1064      }      }
1065    if (c !='}') goto ERROR_RETURN;    if (c != CHAR_RIGHT_CURLY_BRACKET) goto ERROR_RETURN;
1066    name[i] = 0;    name[i] = 0;
1067    }    }
1068    
# Line 838  return -1; Line 1108  return -1;
1108    
1109    
1110  /*************************************************  /*************************************************
 *            Check for counted repeat            *  
 *************************************************/  
   
 /* This function is called when a '{' is encountered in a place where it might  
 start a quantifier. It looks ahead to see if it really is a quantifier or not.  
 It is only a quantifier if it is one of the forms {ddd} {ddd,} or {ddd,ddd}  
 where the ddds are digits.  
   
 Arguments:  
   p         pointer to the first char after '{'  
   
 Returns:    TRUE or FALSE  
 */  
   
 static BOOL  
 is_counted_repeat(const uschar *p)  
 {  
 if ((digitab[*p++] & ctype_digit) == 0) return FALSE;  
 while ((digitab[*p] & ctype_digit) != 0) p++;  
 if (*p == '}') return TRUE;  
   
 if (*p++ != ',') return FALSE;  
 if (*p == '}') return TRUE;  
   
 if ((digitab[*p++] & ctype_digit) == 0) return FALSE;  
 while ((digitab[*p] & ctype_digit) != 0) p++;  
   
 return (*p == '}');  
 }  
   
   
   
 /*************************************************  
1111  *         Read repeat counts                     *  *         Read repeat counts                     *
1112  *************************************************/  *************************************************/
1113    
# Line 889  Returns:         pointer to '}' on succe Line 1126  Returns:         pointer to '}' on succe
1126                   current ptr on error, with errorcodeptr set non-zero                   current ptr on error, with errorcodeptr set non-zero
1127  */  */
1128    
1129  static const uschar *  static const pcre_uchar *
1130  read_repeat_counts(const uschar *p, int *minp, int *maxp, int *errorcodeptr)  read_repeat_counts(const pcre_uchar *p, int *minp, int *maxp, int *errorcodeptr)
1131  {  {
1132  int min = 0;  int min = 0;
1133  int max = -1;  int max = -1;
# Line 898  int max = -1; Line 1135  int max = -1;
1135  /* Read the minimum value and do a paranoid check: a negative value indicates  /* Read the minimum value and do a paranoid check: a negative value indicates
1136  an integer overflow. */  an integer overflow. */
1137    
1138  while ((digitab[*p] & ctype_digit) != 0) min = min * 10 + *p++ - '0';  while ((digitab[*p] & ctype_digit) != 0) min = min * 10 + *p++ - CHAR_0;
1139  if (min < 0 || min > 65535)  if (min < 0 || min > 65535)
1140    {    {
1141    *errorcodeptr = ERR5;    *errorcodeptr = ERR5;
# Line 908  if (min < 0 || min > 65535) Line 1145  if (min < 0 || min > 65535)
1145  /* Read the maximum value if there is one, and again do a paranoid on its size.  /* Read the maximum value if there is one, and again do a paranoid on its size.
1146  Also, max must not be less than min. */  Also, max must not be less than min. */
1147    
1148  if (*p == '}') max = min; else  if (*p == CHAR_RIGHT_CURLY_BRACKET) max = min; else
1149    {    {
1150    if (*(++p) != '}')    if (*(++p) != CHAR_RIGHT_CURLY_BRACKET)
1151      {      {
1152      max = 0;      max = 0;
1153      while((digitab[*p] & ctype_digit) != 0) max = max * 10 + *p++ - '0';      while((digitab[*p] & ctype_digit) != 0) max = max * 10 + *p++ - CHAR_0;
1154      if (max < 0 || max > 65535)      if (max < 0 || max > 65535)
1155        {        {
1156        *errorcodeptr = ERR5;        *errorcodeptr = ERR5;
# Line 938  return p; Line 1175  return p;
1175    
1176    
1177  /*************************************************  /*************************************************
1178  *       Find forward referenced subpattern       *  *  Subroutine for finding forward reference      *
1179  *************************************************/  *************************************************/
1180    
1181  /* This function scans along a pattern's text looking for capturing  /* This recursive function is called only from find_parens() below. The
1182    top-level call starts at the beginning of the pattern. All other calls must
1183    start at a parenthesis. It scans along a pattern's text looking for capturing
1184  subpatterns, and counting them. If it finds a named pattern that matches the  subpatterns, and counting them. If it finds a named pattern that matches the
1185  name it is given, it returns its number. Alternatively, if the name is NULL, it  name it is given, it returns its number. Alternatively, if the name is NULL, it
1186  returns when it reaches a given numbered subpattern. This is used for forward  returns when it reaches a given numbered subpattern. Recursion is used to keep
1187  references to subpatterns. We know that if (?P< is encountered, the name will  track of subpatterns that reset the capturing group numbers - the (?| feature.
1188  be terminated by '>' because that is checked in the first pass.  
1189    This function was originally called only from the second pass, in which we know
1190    that if (?< or (?' or (?P< is encountered, the name will be correctly
1191    terminated because that is checked in the first pass. There is now one call to
1192    this function in the first pass, to check for a recursive back reference by
1193    name (so that we can make the whole group atomic). In this case, we need check
1194    only up to the current position in the pattern, and that is still OK because
1195    and previous occurrences will have been checked. To make this work, the test
1196    for "end of pattern" is a check against cd->end_pattern in the main loop,
1197    instead of looking for a binary zero. This means that the special first-pass
1198    call can adjust cd->end_pattern temporarily. (Checks for binary zero while
1199    processing items within the loop are OK, because afterwards the main loop will
1200    terminate.)
1201    
1202  Arguments:  Arguments:
1203    ptr          current position in the pattern    ptrptr       address of the current character pointer (updated)
1204    count        current count of capturing parens so far encountered    cd           compile background data
1205    name         name to seek, or NULL if seeking a numbered subpattern    name         name to seek, or NULL if seeking a numbered subpattern
1206    lorn         name length, or subpattern number if name is NULL    lorn         name length, or subpattern number if name is NULL
1207    xmode        TRUE if we are in /x mode    xmode        TRUE if we are in /x mode
1208      utf8         TRUE if we are in UTF-8 mode
1209      count        pointer to the current capturing subpattern number (updated)
1210    
1211  Returns:       the number of the named subpattern, or -1 if not found  Returns:       the number of the named subpattern, or -1 if not found
1212  */  */
1213    
1214  static int  static int
1215  find_parens(const uschar *ptr, int count, const uschar *name, int lorn,  find_parens_sub(pcre_uchar **ptrptr, compile_data *cd, const pcre_uchar *name, int lorn,
1216    BOOL xmode)    BOOL xmode, BOOL utf8, int *count)
1217  {  {
1218  const uschar *thisname;  pcre_uchar *ptr = *ptrptr;
1219    int start_count = *count;
1220    int hwm_count = start_count;
1221    BOOL dup_parens = FALSE;
1222    
1223  for (; *ptr != 0; ptr++)  /* If the first character is a parenthesis, check on the type of group we are
1224    dealing with. The very first call may not start with a parenthesis. */
1225    
1226    if (ptr[0] == CHAR_LEFT_PARENTHESIS)
1227    {    {
1228    int term;    /* Handle specials such as (*SKIP) or (*UTF8) etc. */
1229    
1230      if (ptr[1] == CHAR_ASTERISK) ptr += 2;
1231    
1232      /* Handle a normal, unnamed capturing parenthesis. */
1233    
1234      else if (ptr[1] != CHAR_QUESTION_MARK)
1235        {
1236        *count += 1;
1237        if (name == NULL && *count == lorn) return *count;
1238        ptr++;
1239        }
1240    
1241      /* All cases now have (? at the start. Remember when we are in a group
1242      where the parenthesis numbers are duplicated. */
1243    
1244      else if (ptr[2] == CHAR_VERTICAL_LINE)
1245        {
1246        ptr += 3;
1247        dup_parens = TRUE;
1248        }
1249    
1250      /* Handle comments; all characters are allowed until a ket is reached. */
1251    
1252      else if (ptr[2] == CHAR_NUMBER_SIGN)
1253        {
1254        for (ptr += 3; *ptr != 0; ptr++) if (*ptr == CHAR_RIGHT_PARENTHESIS) break;
1255        goto FAIL_EXIT;
1256        }
1257    
1258      /* Handle a condition. If it is an assertion, just carry on so that it
1259      is processed as normal. If not, skip to the closing parenthesis of the
1260      condition (there can't be any nested parens). */
1261    
1262      else if (ptr[2] == CHAR_LEFT_PARENTHESIS)
1263        {
1264        ptr += 2;
1265        if (ptr[1] != CHAR_QUESTION_MARK)
1266          {
1267          while (*ptr != 0 && *ptr != CHAR_RIGHT_PARENTHESIS) ptr++;
1268          if (*ptr != 0) ptr++;
1269          }
1270        }
1271    
1272      /* Start with (? but not a condition. */
1273    
1274      else
1275        {
1276        ptr += 2;
1277        if (*ptr == CHAR_P) ptr++;                      /* Allow optional P */
1278    
1279        /* We have to disambiguate (?<! and (?<= from (?<name> for named groups */
1280    
1281        if ((*ptr == CHAR_LESS_THAN_SIGN && ptr[1] != CHAR_EXCLAMATION_MARK &&
1282            ptr[1] != CHAR_EQUALS_SIGN) || *ptr == CHAR_APOSTROPHE)
1283          {
1284          int term;
1285          const pcre_uchar *thisname;
1286          *count += 1;
1287          if (name == NULL && *count == lorn) return *count;
1288          term = *ptr++;
1289          if (term == CHAR_LESS_THAN_SIGN) term = CHAR_GREATER_THAN_SIGN;
1290          thisname = ptr;
1291          while (*ptr != term) ptr++;
1292          if (name != NULL && lorn == ptr - thisname &&
1293              strncmp((const char *)name, (const char *)thisname, lorn) == 0)
1294            return *count;
1295          term++;
1296          }
1297        }
1298      }
1299    
1300    /* Past any initial parenthesis handling, scan for parentheses or vertical
1301    bars. Stop if we get to cd->end_pattern. Note that this is important for the
1302    first-pass call when this value is temporarily adjusted to stop at the current
1303    position. So DO NOT change this to a test for binary zero. */
1304    
1305    for (; ptr < cd->end_pattern; ptr++)
1306      {
1307    /* Skip over backslashed characters and also entire \Q...\E */    /* Skip over backslashed characters and also entire \Q...\E */
1308    
1309    if (*ptr == '\\')    if (*ptr == CHAR_BACKSLASH)
1310      {      {
1311      if (*(++ptr) == 0) return -1;      if (*(++ptr) == 0) goto FAIL_EXIT;
1312      if (*ptr == 'Q') for (;;)      if (*ptr == CHAR_Q) for (;;)
1313        {        {
1314        while (*(++ptr) != 0 && *ptr != '\\');        while (*(++ptr) != 0 && *ptr != CHAR_BACKSLASH) {};
1315        if (*ptr == 0) return -1;        if (*ptr == 0) goto FAIL_EXIT;
1316        if (*(++ptr) == 'E') break;        if (*(++ptr) == CHAR_E) break;
1317        }        }
1318      continue;      continue;
1319      }      }
1320    
1321    /* Skip over character classes */    /* Skip over character classes; this logic must be similar to the way they
1322      are handled for real. If the first character is '^', skip it. Also, if the
1323      first few characters (either before or after ^) are \Q\E or \E we skip them
1324      too. This makes for compatibility with Perl. Note the use of STR macros to
1325      encode "Q\\E" so that it works in UTF-8 on EBCDIC platforms. */
1326    
1327    if (*ptr == '[')    if (*ptr == CHAR_LEFT_SQUARE_BRACKET)
1328      {      {
1329      while (*(++ptr) != ']')      BOOL negate_class = FALSE;
1330        for (;;)
1331          {
1332          if (ptr[1] == CHAR_BACKSLASH)
1333            {
1334            if (ptr[2] == CHAR_E)
1335              ptr+= 2;
1336            else if (strncmp((const char *)ptr+2,
1337                     STR_Q STR_BACKSLASH STR_E, 3) == 0)
1338              ptr += 4;
1339            else
1340              break;
1341            }
1342          else if (!negate_class && ptr[1] == CHAR_CIRCUMFLEX_ACCENT)
1343            {
1344            negate_class = TRUE;
1345            ptr++;
1346            }
1347          else break;
1348          }
1349    
1350        /* If the next character is ']', it is a data character that must be
1351        skipped, except in JavaScript compatibility mode. */
1352    
1353        if (ptr[1] == CHAR_RIGHT_SQUARE_BRACKET &&
1354            (cd->external_options & PCRE_JAVASCRIPT_COMPAT) == 0)
1355          ptr++;
1356    
1357        while (*(++ptr) != CHAR_RIGHT_SQUARE_BRACKET)
1358        {        {
1359        if (*ptr == 0) return -1;        if (*ptr == 0) return -1;
1360        if (*ptr == '\\')        if (*ptr == CHAR_BACKSLASH)
1361          {          {
1362          if (*(++ptr) == 0) return -1;          if (*(++ptr) == 0) goto FAIL_EXIT;
1363          if (*ptr == 'Q') for (;;)          if (*ptr == CHAR_Q) for (;;)
1364            {            {
1365            while (*(++ptr) != 0 && *ptr != '\\');            while (*(++ptr) != 0 && *ptr != CHAR_BACKSLASH) {};
1366            if (*ptr == 0) return -1;            if (*ptr == 0) goto FAIL_EXIT;
1367            if (*(++ptr) == 'E') break;            if (*(++ptr) == CHAR_E) break;
1368            }            }
1369          continue;          continue;
1370          }          }
# Line 1006  for (; *ptr != 0; ptr++) Line 1374  for (; *ptr != 0; ptr++)
1374    
1375    /* Skip comments in /x mode */    /* Skip comments in /x mode */
1376    
1377    if (xmode && *ptr == '#')    if (xmode && *ptr == CHAR_NUMBER_SIGN)
1378      {      {
1379      while (*(++ptr) != 0 && *ptr != '\n');      ptr++;
1380      if (*ptr == 0) return -1;      while (*ptr != 0)
1381          {
1382          if (IS_NEWLINE(ptr)) { ptr += cd->nllen - 1; break; }
1383          ptr++;
1384    #ifdef SUPPORT_UTF8
1385          if (utf8) while ((*ptr & 0xc0) == 0x80) ptr++;
1386    #endif
1387          }
1388        if (*ptr == 0) goto FAIL_EXIT;
1389      continue;      continue;
1390      }      }
1391    
1392    /* An opening parens must now be a real metacharacter */    /* Check for the special metacharacters */
1393    
1394    if (*ptr != '(') continue;    if (*ptr == CHAR_LEFT_PARENTHESIS)
   if (ptr[1] != '?' && ptr[1] != '*')  
1395      {      {
1396      count++;      int rc = find_parens_sub(&ptr, cd, name, lorn, xmode, utf8, count);
1397      if (name == NULL && count == lorn) return count;      if (rc > 0) return rc;
1398      continue;      if (*ptr == 0) goto FAIL_EXIT;
1399        }
1400    
1401      else if (*ptr == CHAR_RIGHT_PARENTHESIS)
1402        {
1403        if (dup_parens && *count < hwm_count) *count = hwm_count;
1404        goto FAIL_EXIT;
1405        }
1406    
1407      else if (*ptr == CHAR_VERTICAL_LINE && dup_parens)
1408        {
1409        if (*count > hwm_count) hwm_count = *count;
1410        *count = start_count;
1411      }      }
1412      }
1413    
1414    ptr += 2;  FAIL_EXIT:
1415    if (*ptr == 'P') ptr++;                      /* Allow optional P */  *ptrptr = ptr;
1416    return -1;
1417    }
1418    
   /* We have to disambiguate (?<! and (?<= from (?<name> */  
1419    
   if ((*ptr != '<' || ptr[1] == '!' || ptr[1] == '=') &&  
        *ptr != '\'')  
     continue;  
1420    
   count++;  
1421    
1422    if (name == NULL && count == lorn) return count;  /*************************************************
1423    term = *ptr++;  *       Find forward referenced subpattern       *
1424    if (term == '<') term = '>';  *************************************************/
1425    thisname = ptr;  
1426    while (*ptr != term) ptr++;  /* This function scans along a pattern's text looking for capturing
1427    if (name != NULL && lorn == ptr - thisname &&  subpatterns, and counting them. If it finds a named pattern that matches the
1428        strncmp((const char *)name, (const char *)thisname, lorn) == 0)  name it is given, it returns its number. Alternatively, if the name is NULL, it
1429      return count;  returns when it reaches a given numbered subpattern. This is used for forward
1430    references to subpatterns. We used to be able to start this scan from the
1431    current compiling point, using the current count value from cd->bracount, and
1432    do it all in a single loop, but the addition of the possibility of duplicate
1433    subpattern numbers means that we have to scan from the very start, in order to
1434    take account of such duplicates, and to use a recursive function to keep track
1435    of the different types of group.
1436    
1437    Arguments:
1438      cd           compile background data
1439      name         name to seek, or NULL if seeking a numbered subpattern
1440      lorn         name length, or subpattern number if name is NULL
1441      xmode        TRUE if we are in /x mode
1442      utf8         TRUE if we are in UTF-8 mode
1443    
1444    Returns:       the number of the found subpattern, or -1 if not found
1445    */
1446    
1447    static int
1448    find_parens(compile_data *cd, const pcre_uchar *name, int lorn, BOOL xmode,
1449      BOOL utf8)
1450    {
1451    pcre_uchar *ptr = (pcre_uchar *)cd->start_pattern;
1452    int count = 0;
1453    int rc;
1454    
1455    /* If the pattern does not start with an opening parenthesis, the first call
1456    to find_parens_sub() will scan right to the end (if necessary). However, if it
1457    does start with a parenthesis, find_parens_sub() will return when it hits the
1458    matching closing parens. That is why we have to have a loop. */
1459    
1460    for (;;)
1461      {
1462      rc = find_parens_sub(&ptr, cd, name, lorn, xmode, utf8, &count);
1463      if (rc > 0 || *ptr++ == 0) break;
1464    }    }
1465    
1466  return -1;  return rc;
1467  }  }
1468    
1469    
1470    
1471    
1472  /*************************************************  /*************************************************
1473  *      Find first significant op code            *  *      Find first significant op code            *
1474  *************************************************/  *************************************************/
1475    
1476  /* This is called by several functions that scan a compiled expression looking  /* This is called by several functions that scan a compiled expression looking
1477  for a fixed first character, or an anchoring op code etc. It skips over things  for a fixed first character, or an anchoring op code etc. It skips over things
1478  that do not influence this. For some calls, a change of option is important.  that do not influence this. For some calls, it makes sense to skip negative
1479  For some calls, it makes sense to skip negative forward and all backward  forward and all backward assertions, and also the \b assertion; for others it
1480  assertions, and also the \b assertion; for others it does not.  does not.
1481    
1482  Arguments:  Arguments:
1483    code         pointer to the start of the group    code         pointer to the start of the group
   options      pointer to external options  
   optbit       the option bit whose changing is significant, or  
                  zero if none are  
1484    skipassert   TRUE if certain assertions are to be skipped    skipassert   TRUE if certain assertions are to be skipped
1485    
1486  Returns:       pointer to the first significant opcode  Returns:       pointer to the first significant opcode
1487  */  */
1488    
1489  static const uschar*  static const pcre_uchar*
1490  first_significant_code(const uschar *code, int *options, int optbit,  first_significant_code(const pcre_uchar *code, BOOL skipassert)
   BOOL skipassert)  
1491  {  {
1492  for (;;)  for (;;)
1493    {    {
1494    switch ((int)*code)    switch ((int)*code)
1495      {      {
     case OP_OPT:  
     if (optbit > 0 && ((int)code[1] & optbit) != (*options & optbit))  
       *options = (int)code[1];  
     code += 2;  
     break;  
   
1496      case OP_ASSERT_NOT:      case OP_ASSERT_NOT:
1497      case OP_ASSERTBACK:      case OP_ASSERTBACK:
1498      case OP_ASSERTBACK_NOT:      case OP_ASSERTBACK_NOT:
# Line 1098  for (;;) Line 1508  for (;;)
1508    
1509      case OP_CALLOUT:      case OP_CALLOUT:
1510      case OP_CREF:      case OP_CREF:
1511        case OP_NCREF:
1512      case OP_RREF:      case OP_RREF:
1513        case OP_NRREF:
1514      case OP_DEF:      case OP_DEF:
1515      code += _pcre_OP_lengths[*code];      code += _pcre_OP_lengths[*code];
1516      break;      break;
# Line 1114  for (;;) Line 1526  for (;;)
1526    
1527    
1528  /*************************************************  /*************************************************
1529  *        Find the fixed length of a pattern      *  *        Find the fixed length of a branch       *
1530  *************************************************/  *************************************************/
1531    
1532  /* Scan a pattern and compute the fixed length of subject that will match it,  /* Scan a branch and compute the fixed length of subject that will match it,
1533  if the length is fixed. This is needed for dealing with backward assertions.  if the length is fixed. This is needed for dealing with backward assertions.
1534  In UTF8 mode, the result is in characters rather than bytes.  In UTF8 mode, the result is in characters rather than bytes. The branch is
1535    temporarily terminated with OP_END when this function is called.
1536    
1537    This function is called when a backward assertion is encountered, so that if it
1538    fails, the error message can point to the correct place in the pattern.
1539    However, we cannot do this when the assertion contains subroutine calls,
1540    because they can be forward references. We solve this by remembering this case
1541    and doing the check at the end; a flag specifies which mode we are running in.
1542    
1543  Arguments:  Arguments:
1544    code     points to the start of the pattern (the bracket)    code     points to the start of the pattern (the bracket)
1545    options  the compiling options    utf8     TRUE in UTF-8 mode
1546      atend    TRUE if called when the pattern is complete
1547  Returns:   the fixed length, or -1 if there is no fixed length,    cd       the "compile data" structure
1548               or -2 if \C was encountered  
1549    Returns:   the fixed length,
1550                 or -1 if there is no fixed length,
1551                 or -2 if \C was encountered (in UTF-8 mode only)
1552                 or -3 if an OP_RECURSE item was encountered and atend is FALSE
1553                 or -4 if an unknown opcode was encountered (internal error)
1554  */  */
1555    
1556  static int  static int
1557  find_fixedlength(uschar *code, int options)  find_fixedlength(pcre_uchar *code, BOOL utf8, BOOL atend, compile_data *cd)
1558  {  {
1559  int length = -1;  int length = -1;
1560    
1561  register int branchlength = 0;  register int branchlength = 0;
1562  register uschar *cc = code + 1 + LINK_SIZE;  register pcre_uchar *cc = code + 1 + LINK_SIZE;
1563    
1564  /* Scan along the opcodes for this branch. If we get to the end of the  /* Scan along the opcodes for this branch. If we get to the end of the
1565  branch, check the length against that of the other branches. */  branch, check the length against that of the other branches. */
# Line 1143  branch, check the length against that of Line 1567  branch, check the length against that of
1567  for (;;)  for (;;)
1568    {    {
1569    int d;    int d;
1570      pcre_uchar *ce, *cs;
1571    register int op = *cc;    register int op = *cc;
1572    switch (op)    switch (op)
1573      {      {
1574        /* We only need to continue for OP_CBRA (normal capturing bracket) and
1575        OP_BRA (normal non-capturing bracket) because the other variants of these
1576        opcodes are all concerned with unlimited repeated groups, which of course
1577        are not of fixed length. */
1578    
1579      case OP_CBRA:      case OP_CBRA:
1580      case OP_BRA:      case OP_BRA:
1581      case OP_ONCE:      case OP_ONCE:
1582        case OP_ONCE_NC:
1583      case OP_COND:      case OP_COND:
1584      d = find_fixedlength(cc + ((op == OP_CBRA)? 2:0), options);      d = find_fixedlength(cc + ((op == OP_CBRA)? 2:0), utf8, atend, cd);
1585      if (d < 0) return d;      if (d < 0) return d;
1586      branchlength += d;      branchlength += d;
1587      do cc += GET(cc, 1); while (*cc == OP_ALT);      do cc += GET(cc, 1); while (*cc == OP_ALT);
1588      cc += 1 + LINK_SIZE;      cc += 1 + LINK_SIZE;
1589      break;      break;
1590    
1591      /* Reached end of a branch; if it's a ket it is the end of a nested      /* Reached end of a branch; if it's a ket it is the end of a nested call.
1592      call. If it's ALT it is an alternation in a nested call. If it is      If it's ALT it is an alternation in a nested call. An ACCEPT is effectively
1593      END it's the end of the outer call. All can be handled by the same code. */      an ALT. If it is END it's the end of the outer call. All can be handled by
1594        the same code. Note that we must not include the OP_KETRxxx opcodes here,
1595        because they all imply an unlimited repeat. */
1596    
1597      case OP_ALT:      case OP_ALT:
1598      case OP_KET:      case OP_KET:
     case OP_KETRMAX:  
     case OP_KETRMIN:  
1599      case OP_END:      case OP_END:
1600        case OP_ACCEPT:
1601        case OP_ASSERT_ACCEPT:
1602      if (length < 0) length = branchlength;      if (length < 0) length = branchlength;
1603        else if (length != branchlength) return -1;        else if (length != branchlength) return -1;
1604      if (*cc != OP_ALT) return length;      if (*cc != OP_ALT) return length;
# Line 1173  for (;;) Line 1606  for (;;)
1606      branchlength = 0;      branchlength = 0;
1607      break;      break;
1608    
1609        /* A true recursion implies not fixed length, but a subroutine call may
1610        be OK. If the subroutine is a forward reference, we can't deal with
1611        it until the end of the pattern, so return -3. */
1612    
1613        case OP_RECURSE:
1614        if (!atend) return -3;
1615        cs = ce = (pcre_uchar *)cd->start_code + GET(cc, 1);  /* Start subpattern */
1616        do ce += GET(ce, 1); while (*ce == OP_ALT);           /* End subpattern */
1617        if (cc > cs && cc < ce) return -1;                    /* Recursion */
1618        d = find_fixedlength(cs + 2, utf8, atend, cd);
1619        if (d < 0) return d;
1620        branchlength += d;
1621        cc += 1 + LINK_SIZE;
1622        break;
1623    
1624      /* Skip over assertive subpatterns */      /* Skip over assertive subpatterns */
1625    
1626      case OP_ASSERT:      case OP_ASSERT:
# Line 1184  for (;;) Line 1632  for (;;)
1632    
1633      /* Skip over things that don't match chars */      /* Skip over things that don't match chars */
1634    
1635      case OP_REVERSE:      case OP_MARK:
1636        case OP_PRUNE_ARG:
1637        case OP_SKIP_ARG:
1638        case OP_THEN_ARG:
1639        cc += cc[1] + _pcre_OP_lengths[*cc];
1640        break;
1641    
1642        case OP_CALLOUT:
1643        case OP_CIRC:
1644        case OP_CIRCM:
1645        case OP_CLOSE:
1646        case OP_COMMIT:
1647      case OP_CREF:      case OP_CREF:
     case OP_RREF:  
1648      case OP_DEF:      case OP_DEF:
1649      case OP_OPT:      case OP_DOLL:
1650      case OP_CALLOUT:      case OP_DOLLM:
     case OP_SOD:  
     case OP_SOM:  
1651      case OP_EOD:      case OP_EOD:
1652      case OP_EODN:      case OP_EODN:
1653      case OP_CIRC:      case OP_FAIL:
1654      case OP_DOLL:      case OP_NCREF:
1655        case OP_NRREF:
1656      case OP_NOT_WORD_BOUNDARY:      case OP_NOT_WORD_BOUNDARY:
1657        case OP_PRUNE:
1658        case OP_REVERSE:
1659        case OP_RREF:
1660        case OP_SET_SOM:
1661        case OP_SKIP:
1662        case OP_SOD:
1663        case OP_SOM:
1664        case OP_THEN:
1665      case OP_WORD_BOUNDARY:      case OP_WORD_BOUNDARY:
1666      cc += _pcre_OP_lengths[*cc];      cc += _pcre_OP_lengths[*cc];
1667      break;      break;
# Line 1204  for (;;) Line 1669  for (;;)
1669      /* Handle literal characters */      /* Handle literal characters */
1670    
1671      case OP_CHAR:      case OP_CHAR:
1672      case OP_CHARNC:      case OP_CHARI:
1673      case OP_NOT:      case OP_NOT:
1674        case OP_NOTI:
1675      branchlength++;      branchlength++;
1676      cc += 2;      cc += 2;
1677  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF8
1678      if ((options & PCRE_UTF8) != 0)      if (utf8 && cc[-1] >= 0xc0) cc += _pcre_utf8_table4[cc[-1] & 0x3f];
       {  
       while ((*cc & 0xc0) == 0x80) cc++;  
       }  
1679  #endif  #endif
1680      break;      break;
1681    
# Line 1220  for (;;) Line 1683  for (;;)
1683      need to skip over a multibyte character in UTF8 mode.  */      need to skip over a multibyte character in UTF8 mode.  */
1684    
1685      case OP_EXACT:      case OP_EXACT:
1686        case OP_EXACTI:
1687        case OP_NOTEXACT:
1688        case OP_NOTEXACTI:
1689      branchlength += GET2(cc,1);      branchlength += GET2(cc,1);
1690      cc += 4;      cc += 4;
1691  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF8
1692      if ((options & PCRE_UTF8) != 0)      if (utf8 && cc[-1] >= 0xc0) cc += _pcre_utf8_table4[cc[-1] & 0x3f];
       {  
       while((*cc & 0x80) == 0x80) cc++;  
       }  
1693  #endif  #endif
1694      break;      break;
1695    
# Line 1243  for (;;) Line 1706  for (;;)
1706      cc += 2;      cc += 2;
1707      /* Fall through */      /* Fall through */
1708    
1709        case OP_HSPACE:
1710        case OP_VSPACE:
1711        case OP_NOT_HSPACE:
1712        case OP_NOT_VSPACE:
1713      case OP_NOT_DIGIT:      case OP_NOT_DIGIT:
1714      case OP_DIGIT:      case OP_DIGIT:
1715      case OP_NOT_WHITESPACE:      case OP_NOT_WHITESPACE:
# Line 1250  for (;;) Line 1717  for (;;)
1717      case OP_NOT_WORDCHAR:      case OP_NOT_WORDCHAR:
1718      case OP_WORDCHAR:      case OP_WORDCHAR:
1719      case OP_ANY:      case OP_ANY:
1720        case OP_ALLANY:
1721      branchlength++;      branchlength++;
1722      cc++;      cc++;
1723      break;      break;
1724    
1725      /* The single-byte matcher isn't allowed */      /* The single-byte matcher isn't allowed. This only happens in UTF-8 mode;
1726        otherwise \C is coded as OP_ALLANY. */
1727    
1728      case OP_ANYBYTE:      case OP_ANYBYTE:
1729      return -2;      return -2;
# Line 1273  for (;;) Line 1742  for (;;)
1742    
1743      switch (*cc)      switch (*cc)
1744        {        {
1745          case OP_CRPLUS:
1746          case OP_CRMINPLUS:
1747        case OP_CRSTAR:        case OP_CRSTAR:
1748        case OP_CRMINSTAR:        case OP_CRMINSTAR:
1749        case OP_CRQUERY:        case OP_CRQUERY:
# Line 1293  for (;;) Line 1764  for (;;)
1764    
1765      /* Anything else is variable length */      /* Anything else is variable length */
1766    
1767      default:      case OP_ANYNL:
1768        case OP_BRAMINZERO:
1769        case OP_BRAPOS:
1770        case OP_BRAPOSZERO:
1771        case OP_BRAZERO:
1772        case OP_CBRAPOS:
1773        case OP_EXTUNI:
1774        case OP_KETRMAX:
1775        case OP_KETRMIN:
1776        case OP_KETRPOS:
1777        case OP_MINPLUS:
1778        case OP_MINPLUSI:
1779        case OP_MINQUERY:
1780        case OP_MINQUERYI:
1781        case OP_MINSTAR:
1782        case OP_MINSTARI:
1783        case OP_MINUPTO:
1784        case OP_MINUPTOI:
1785        case OP_NOTMINPLUS:
1786        case OP_NOTMINPLUSI:
1787        case OP_NOTMINQUERY:
1788        case OP_NOTMINQUERYI:
1789        case OP_NOTMINSTAR:
1790        case OP_NOTMINSTARI:
1791        case OP_NOTMINUPTO:
1792        case OP_NOTMINUPTOI:
1793        case OP_NOTPLUS:
1794        case OP_NOTPLUSI:
1795        case OP_NOTPOSPLUS:
1796        case OP_NOTPOSPLUSI:
1797        case OP_NOTPOSQUERY:
1798        case OP_NOTPOSQUERYI:
1799        case OP_NOTPOSSTAR:
1800        case OP_NOTPOSSTARI:
1801        case OP_NOTPOSUPTO:
1802        case OP_NOTPOSUPTOI:
1803        case OP_NOTQUERY:
1804        case OP_NOTQUERYI:
1805        case OP_NOTSTAR:
1806        case OP_NOTSTARI:
1807        case OP_NOTUPTO:
1808        case OP_NOTUPTOI:
1809        case OP_PLUS:
1810        case OP_PLUSI:
1811        case OP_POSPLUS:
1812        case OP_POSPLUSI:
1813        case OP_POSQUERY:
1814        case OP_POSQUERYI:
1815        case OP_POSSTAR:
1816        case OP_POSSTARI:
1817        case OP_POSUPTO:
1818        case OP_POSUPTOI:
1819        case OP_QUERY:
1820        case OP_QUERYI:
1821        case OP_REF:
1822        case OP_REFI:
1823        case OP_SBRA:
1824        case OP_SBRAPOS:
1825        case OP_SCBRA:
1826        case OP_SCBRAPOS:
1827        case OP_SCOND:
1828        case OP_SKIPZERO:
1829        case OP_STAR:
1830        case OP_STARI:
1831        case OP_TYPEMINPLUS:
1832        case OP_TYPEMINQUERY:
1833        case OP_TYPEMINSTAR:
1834        case OP_TYPEMINUPTO:
1835        case OP_TYPEPLUS:
1836        case OP_TYPEPOSPLUS:
1837        case OP_TYPEPOSQUERY:
1838        case OP_TYPEPOSSTAR:
1839        case OP_TYPEPOSUPTO:
1840        case OP_TYPEQUERY:
1841        case OP_TYPESTAR:
1842        case OP_TYPEUPTO:
1843        case OP_UPTO:
1844        case OP_UPTOI:
1845      return -1;      return -1;
1846    
1847        /* Catch unrecognized opcodes so that when new ones are added they
1848        are not forgotten, as has happened in the past. */
1849    
1850        default:
1851        return -4;
1852      }      }
1853    }    }
1854  /* Control never gets here */  /* Control never gets here */
# Line 1304  for (;;) Line 1858  for (;;)
1858    
1859    
1860  /*************************************************  /*************************************************
1861  *    Scan compiled regex for numbered bracket    *  *    Scan compiled regex for specific bracket    *
1862  *************************************************/  *************************************************/
1863    
1864  /* This little function scans through a compiled pattern until it finds a  /* This little function scans through a compiled pattern until it finds a
1865  capturing bracket with the given number.  capturing bracket with the given number, or, if the number is negative, an
1866    instance of OP_REVERSE for a lookbehind. The function is global in the C sense
1867    so that it can be called from pcre_study() when finding the minimum matching
1868    length.
1869    
1870  Arguments:  Arguments:
1871    code        points to start of expression    code        points to start of expression
1872    utf8        TRUE in UTF-8 mode    utf8        TRUE in UTF-8 mode
1873    number      the required bracket number    number      the required bracket number or negative to find a lookbehind
1874    
1875  Returns:      pointer to the opcode for the bracket, or NULL if not found  Returns:      pointer to the opcode for the bracket, or NULL if not found
1876  */  */
1877    
1878  static const uschar *  const pcre_uchar *
1879  find_bracket(const uschar *code, BOOL utf8, int number)  _pcre_find_bracket(const pcre_uchar *code, BOOL utf8, int number)
1880  {  {
1881  for (;;)  for (;;)
1882    {    {
1883    register int c = *code;    register int c = *code;
1884    
1885    if (c == OP_END) return NULL;    if (c == OP_END) return NULL;
1886    
1887    /* XCLASS is used for classes that cannot be represented just by a bit    /* XCLASS is used for classes that cannot be represented just by a bit
# Line 1332  for (;;) Line 1890  for (;;)
1890    
1891    if (c == OP_XCLASS) code += GET(code, 1);    if (c == OP_XCLASS) code += GET(code, 1);
1892    
1893      /* Handle recursion */
1894    
1895      else if (c == OP_REVERSE)
1896        {
1897        if (number < 0) return (pcre_uchar *)code;
1898        code += _pcre_OP_lengths[c];
1899        }
1900    
1901    /* Handle capturing bracket */    /* Handle capturing bracket */
1902    
1903    else if (c == OP_CBRA)    else if (c == OP_CBRA || c == OP_SCBRA ||
1904               c == OP_CBRAPOS || c == OP_SCBRAPOS)
1905      {      {
1906      int n = GET2(code, 1+LINK_SIZE);      int n = GET2(code, 1+LINK_SIZE);
1907      if (n == number) return (uschar *)code;      if (n == number) return (pcre_uchar *)code;
1908      code += _pcre_OP_lengths[c];      code += _pcre_OP_lengths[c];
1909      }      }
1910    
1911    /* Otherwise, we can get the item's length from the table, except that for    /* Otherwise, we can get the item's length from the table, except that for
1912    repeated character types, we have to test for \p and \P, which have an extra    repeated character types, we have to test for \p and \P, which have an extra
1913    two bytes of parameters. */    two bytes of parameters, and for MARK/PRUNE/SKIP/THEN with an argument, we
1914      must add in its length. */
1915    
1916    else    else
1917      {      {
# Line 1367  for (;;) Line 1935  for (;;)
1935        case OP_TYPEPOSUPTO:        case OP_TYPEPOSUPTO:
1936        if (code[3] == OP_PROP || code[3] == OP_NOTPROP) code += 2;        if (code[3] == OP_PROP || code[3] == OP_NOTPROP) code += 2;
1937        break;        break;
1938    
1939          case OP_MARK:
1940          case OP_PRUNE_ARG:
1941          case OP_SKIP_ARG:
1942          code += code[1];
1943          break;
1944    
1945          case OP_THEN_ARG:
1946          code += code[1];
1947          break;
1948        }        }
1949    
1950      /* Add in the fixed length from the table */      /* Add in the fixed length from the table */
# Line 1381  for (;;) Line 1959  for (;;)
1959      if (utf8) switch(c)      if (utf8) switch(c)
1960        {        {
1961        case OP_CHAR:        case OP_CHAR:
1962        case OP_CHARNC:        case OP_CHARI:
1963        case OP_EXACT:        case OP_EXACT:
1964          case OP_EXACTI:
1965        case OP_UPTO:        case OP_UPTO:
1966          case OP_UPTOI:
1967        case OP_MINUPTO:        case OP_MINUPTO:
1968          case OP_MINUPTOI:
1969        case OP_POSUPTO:        case OP_POSUPTO:
1970          case OP_POSUPTOI:
1971        case OP_STAR:        case OP_STAR:
1972          case OP_STARI:
1973        case OP_MINSTAR:        case OP_MINSTAR:
1974          case OP_MINSTARI:
1975        case OP_POSSTAR:        case OP_POSSTAR:
1976          case OP_POSSTARI:
1977        case OP_PLUS:        case OP_PLUS:
1978          case OP_PLUSI:
1979        case OP_MINPLUS:        case OP_MINPLUS:
1980          case OP_MINPLUSI:
1981        case OP_POSPLUS:        case OP_POSPLUS:
1982          case OP_POSPLUSI:
1983        case OP_QUERY:        case OP_QUERY:
1984          case OP_QUERYI:
1985        case OP_MINQUERY:        case OP_MINQUERY:
1986          case OP_MINQUERYI:
1987        case OP_POSQUERY:        case OP_POSQUERY:
1988          case OP_POSQUERYI:
1989        if (code[-1] >= 0xc0) code += _pcre_utf8_table4[code[-1] & 0x3f];        if (code[-1] >= 0xc0) code += _pcre_utf8_table4[code[-1] & 0x3f];
1990        break;        break;
1991        }        }
1992    #else
1993        (void)(utf8);  /* Keep compiler happy by referencing function argument */
1994  #endif  #endif
1995      }      }
1996    }    }
# Line 1419  Arguments: Line 2012  Arguments:
2012  Returns:      pointer to the opcode for OP_RECURSE, or NULL if not found  Returns:      pointer to the opcode for OP_RECURSE, or NULL if not found
2013  */  */
2014    
2015  static const uschar *  static const pcre_uchar *
2016  find_recurse(const uschar *code, BOOL utf8)  find_recurse(const pcre_uchar *code, BOOL utf8)
2017  {  {
2018  for (;;)  for (;;)
2019    {    {
# Line 1436  for (;;) Line 2029  for (;;)
2029    
2030    /* Otherwise, we can get the item's length from the table, except that for    /* Otherwise, we can get the item's length from the table, except that for
2031    repeated character types, we have to test for \p and \P, which have an extra    repeated character types, we have to test for \p and \P, which have an extra
2032    two bytes of parameters. */    two bytes of parameters, and for MARK/PRUNE/SKIP/THEN with an argument, we
2033      must add in its length. */
2034    
2035    else    else
2036      {      {
# Line 1460  for (;;) Line 2054  for (;;)
2054        case OP_TYPEEXACT:        case OP_TYPEEXACT:
2055        if (code[3] == OP_PROP || code[3] == OP_NOTPROP) code += 2;        if (code[3] == OP_PROP || code[3] == OP_NOTPROP) code += 2;
2056        break;        break;
2057    
2058          case OP_MARK:
2059          case OP_PRUNE_ARG:
2060          case OP_SKIP_ARG:
2061          code += code[1];
2062          break;
2063    
2064          case OP_THEN_ARG:
2065          code += code[1];
2066          break;
2067        }        }
2068    
2069      /* Add in the fixed length from the table */      /* Add in the fixed length from the table */
# Line 1474  for (;;) Line 2078  for (;;)
2078      if (utf8) switch(c)      if (utf8) switch(c)
2079        {        {
2080        case OP_CHAR:        case OP_CHAR:
2081        case OP_CHARNC:        case OP_CHARI:
2082        case OP_EXACT:        case OP_EXACT:
2083          case OP_EXACTI:
2084        case OP_UPTO:        case OP_UPTO:
2085          case OP_UPTOI:
2086        case OP_MINUPTO:        case OP_MINUPTO:
2087          case OP_MINUPTOI:
2088        case OP_POSUPTO:        case OP_POSUPTO:
2089          case OP_POSUPTOI:
2090        case OP_STAR:        case OP_STAR:
2091          case OP_STARI:
2092        case OP_MINSTAR:        case OP_MINSTAR:
2093          case OP_MINSTARI:
2094        case OP_POSSTAR:        case OP_POSSTAR:
2095          case OP_POSSTARI:
2096        case OP_PLUS:        case OP_PLUS:
2097          case OP_PLUSI:
2098        case OP_MINPLUS:        case OP_MINPLUS:
2099          case OP_MINPLUSI:
2100        case OP_POSPLUS:        case OP_POSPLUS:
2101          case OP_POSPLUSI:
2102        case OP_QUERY:        case OP_QUERY:
2103          case OP_QUERYI:
2104        case OP_MINQUERY:        case OP_MINQUERY:
2105          case OP_MINQUERYI:
2106        case OP_POSQUERY:        case OP_POSQUERY:
2107          case OP_POSQUERYI:
2108        if (code[-1] >= 0xc0) code += _pcre_utf8_table4[code[-1] & 0x3f];        if (code[-1] >= 0xc0) code += _pcre_utf8_table4[code[-1] & 0x3f];
2109        break;        break;
2110        }        }
2111    #else
2112        (void)(utf8);  /* Keep compiler happy by referencing function argument */
2113  #endif  #endif
2114      }      }
2115    }    }
# Line 1506  for (;;) Line 2125  for (;;)
2125  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()
2126  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
2127  group that can match nothing. Note that first_significant_code() skips over  group that can match nothing. Note that first_significant_code() skips over
2128  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
2129  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
2130    bracket whose current branch will already have been scanned.
2131    
2132    Arguments:
2133      code        points to start of search
2134      endcode     points to where to stop
2135      utf8        TRUE if in UTF8 mode
2136      cd          contains pointers to tables etc.
2137    
2138    Returns:      TRUE if what is matched could be empty
2139    */
2140    
2141    static BOOL
2142    could_be_empty_branch(const pcre_uchar *code, const pcre_uchar *endcode,
2143      BOOL utf8, compile_data *cd)
2144    {
2145    register int c;
2146    for (code = first_significant_code(code + _pcre_OP_lengths[*code], TRUE);
2147         code < endcode;
2148         code = first_significant_code(code + _pcre_OP_lengths[c], TRUE))
2149      {
2150      const pcre_uchar *ccode;
2151    
2152      c = *code;
2153    
2154      /* Skip over forward assertions; the other assertions are skipped by
2155      first_significant_code() with a TRUE final argument. */
2156    
2157      if (c == OP_ASSERT)
2158        {
2159        do code += GET(code, 1); while (*code == OP_ALT);
2160        c = *code;
2161        continue;
2162        }
2163    
2164      /* For a recursion/subroutine call, if its end has been reached, which
2165      implies a backward reference subroutine call, we can scan it. If it's a
2166      forward reference subroutine call, we can't. To detect forward reference
2167      we have to scan up the list that is kept in the workspace. This function is
2168      called only when doing the real compile, not during the pre-compile that
2169      measures the size of the compiled pattern. */
2170    
2171      if (c == OP_RECURSE)
2172        {
2173        const pcre_uchar *scode;
2174        BOOL empty_branch;
2175    
2176        /* Test for forward reference */
2177    
2178        for (scode = cd->start_workspace; scode < cd->hwm; scode += LINK_SIZE)
2179          if (GET(scode, 0) == code + 1 - cd->start_code) return TRUE;
2180    
2181        /* Not a forward reference, test for completed backward reference */
2182    
2183  Arguments:      empty_branch = FALSE;
2184    code        points to start of search      scode = cd->start_code + GET(code, 1);
2185    endcode     points to where to stop      if (GET(scode, 1) == 0) return TRUE;    /* Unclosed */
   utf8        TRUE if in UTF8 mode  
2186    
2187  Returns:      TRUE if what is matched could be empty      /* Completed backwards reference */
 */  
2188    
2189  static BOOL      do
2190  could_be_empty_branch(const uschar *code, const uschar *endcode, BOOL utf8)        {
2191  {        if (could_be_empty_branch(scode, endcode, utf8, cd))
2192  register int c;          {
2193  for (code = first_significant_code(code + _pcre_OP_lengths[*code], NULL, 0, TRUE);          empty_branch = TRUE;
2194       code < endcode;          break;
2195       code = first_significant_code(code + _pcre_OP_lengths[c], NULL, 0, TRUE))          }
2196    {        scode += GET(scode, 1);
2197    const uschar *ccode;        }
2198        while (*scode == OP_ALT);
2199    
2200    c = *code;      if (!empty_branch) return FALSE;  /* All branches are non-empty */
2201        continue;
2202        }
2203    
2204    /* Groups with zero repeats can of course be empty; skip them. */    /* Groups with zero repeats can of course be empty; skip them. */
2205    
2206    if (c == OP_BRAZERO || c == OP_BRAMINZERO)    if (c == OP_BRAZERO || c == OP_BRAMINZERO || c == OP_SKIPZERO ||
2207          c == OP_BRAPOSZERO)
2208      {      {
2209      code += _pcre_OP_lengths[c];      code += _pcre_OP_lengths[c];
2210      do code += GET(code, 1); while (*code == OP_ALT);      do code += GET(code, 1); while (*code == OP_ALT);
# Line 1539  for (code = first_significant_code(code Line 2212  for (code = first_significant_code(code
2212      continue;      continue;
2213      }      }
2214    
2215      /* A nested group that is already marked as "could be empty" can just be
2216      skipped. */
2217    
2218      if (c == OP_SBRA  || c == OP_SBRAPOS ||
2219          c == OP_SCBRA || c == OP_SCBRAPOS)
2220        {
2221        do code += GET(code, 1); while (*code == OP_ALT);
2222        c = *code;
2223        continue;
2224        }
2225    
2226    /* For other groups, scan the branches. */    /* For other groups, scan the branches. */
2227    
2228    if (c == OP_BRA || c == OP_CBRA || c == OP_ONCE || c == OP_COND)    if (c == OP_BRA  || c == OP_BRAPOS ||
2229          c == OP_CBRA || c == OP_CBRAPOS ||
2230          c == OP_ONCE || c == OP_ONCE_NC ||
2231          c == OP_COND)
2232      {      {
2233      BOOL empty_branch;      BOOL empty_branch;
2234      if (GET(code, 1) == 0) return TRUE;    /* Hit unclosed bracket */      if (GET(code, 1) == 0) return TRUE;    /* Hit unclosed bracket */
2235    
2236      /* Scan a closed bracket */      /* If a conditional group has only one branch, there is a second, implied,
2237        empty branch, so just skip over the conditional, because it could be empty.
2238        Otherwise, scan the individual branches of the group. */
2239    
2240      empty_branch = FALSE;      if (c == OP_COND && code[GET(code, 1)] != OP_ALT)
     do  
       {  
       if (!empty_branch && could_be_empty_branch(code, endcode, utf8))  
         empty_branch = TRUE;  
2241        code += GET(code, 1);        code += GET(code, 1);
2242        else
2243          {
2244          empty_branch = FALSE;
2245          do
2246            {
2247            if (!empty_branch && could_be_empty_branch(code, endcode, utf8, cd))
2248              empty_branch = TRUE;
2249            code += GET(code, 1);
2250            }
2251          while (*code == OP_ALT);
2252          if (!empty_branch) return FALSE;   /* All branches are non-empty */
2253        }        }
2254      while (*code == OP_ALT);  
     if (!empty_branch) return FALSE;   /* All branches are non-empty */  
2255      c = *code;      c = *code;
2256      continue;      continue;
2257      }      }
# Line 1617  for (code = first_significant_code(code Line 2312  for (code = first_significant_code(code
2312      case OP_NOT_WORDCHAR:      case OP_NOT_WORDCHAR:
2313      case OP_WORDCHAR:      case OP_WORDCHAR:
2314      case OP_ANY:      case OP_ANY:
2315        case OP_ALLANY:
2316      case OP_ANYBYTE:      case OP_ANYBYTE:
2317      case OP_CHAR:      case OP_CHAR:
2318      case OP_CHARNC:      case OP_CHARI:
2319      case OP_NOT:      case OP_NOT:
2320        case OP_NOTI:
2321      case OP_PLUS:      case OP_PLUS:
2322      case OP_MINPLUS:      case OP_MINPLUS:
2323      case OP_POSPLUS:      case OP_POSPLUS:
# Line 1660  for (code = first_significant_code(code Line 2357  for (code = first_significant_code(code
2357      case OP_KET:      case OP_KET:
2358      case OP_KETRMAX:      case OP_KETRMAX:
2359      case OP_KETRMIN:      case OP_KETRMIN:
2360        case OP_KETRPOS:
2361      case OP_ALT:      case OP_ALT:
2362      return TRUE;      return TRUE;
2363    
# Line 1668  for (code = first_significant_code(code Line 2366  for (code = first_significant_code(code
2366    
2367  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF8
2368      case OP_STAR:      case OP_STAR:
2369        case OP_STARI:
2370      case OP_MINSTAR:      case OP_MINSTAR:
2371        case OP_MINSTARI:
2372      case OP_POSSTAR:      case OP_POSSTAR:
2373        case OP_POSSTARI:
2374      case OP_QUERY:      case OP_QUERY:
2375        case OP_QUERYI:
2376      case OP_MINQUERY:      case OP_MINQUERY:
2377        case OP_MINQUERYI:
2378      case OP_POSQUERY:      case OP_POSQUERY:
2379        case OP_POSQUERYI:
2380        if (utf8 && code[1] >= 0xc0) code += _pcre_utf8_table4[code[1] & 0x3f];
2381        break;
2382    
2383      case OP_UPTO:      case OP_UPTO:
2384        case OP_UPTOI:
2385      case OP_MINUPTO:      case OP_MINUPTO:
2386        case OP_MINUPTOI:
2387      case OP_POSUPTO:      case OP_POSUPTO:
2388      if (utf8) while ((code[2] & 0xc0) == 0x80) code++;      case OP_POSUPTOI:
2389        if (utf8 && code[3] >= 0xc0) code += _pcre_utf8_table4[code[3] & 0x3f];
2390      break;      break;
2391  #endif  #endif
2392    
2393        /* MARK, and PRUNE/SKIP/THEN with an argument must skip over the argument
2394        string. */
2395    
2396        case OP_MARK:
2397        case OP_PRUNE_ARG:
2398        case OP_SKIP_ARG:
2399        code += code[1];
2400        break;
2401    
2402        case OP_THEN_ARG:
2403        code += code[1];
2404        break;
2405    
2406        /* None of the remaining opcodes are required to match a character. */
2407    
2408        default:
2409        break;
2410      }      }
2411    }    }
2412    
# Line 1695  return TRUE; Line 2423  return TRUE;
2423  the current branch of the current pattern to see if it could match the empty  the current branch of the current pattern to see if it could match the empty
2424  string. If it could, we must look outwards for branches at other levels,  string. If it could, we must look outwards for branches at other levels,
2425  stopping when we pass beyond the bracket which is the subject of the recursion.  stopping when we pass beyond the bracket which is the subject of the recursion.
2426    This function is called only during the real compile, not during the
2427    pre-compile.
2428    
2429  Arguments:  Arguments:
2430    code        points to start of the recursion    code        points to start of the recursion
2431    endcode     points to where to stop (current RECURSE item)    endcode     points to where to stop (current RECURSE item)
2432    bcptr       points to the chain of current (unclosed) branch starts    bcptr       points to the chain of current (unclosed) branch starts
2433    utf8        TRUE if in UTF-8 mode    utf8        TRUE if in UTF-8 mode
2434      cd          pointers to tables etc
2435    
2436  Returns:      TRUE if what is matched could be empty  Returns:      TRUE if what is matched could be empty
2437  */  */
2438    
2439  static BOOL  static BOOL
2440  could_be_empty(const uschar *code, const uschar *endcode, branch_chain *bcptr,  could_be_empty(const pcre_uchar *code, const pcre_uchar *endcode,
2441    BOOL utf8)    branch_chain *bcptr, BOOL utf8, compile_data *cd)
2442  {  {
2443  while (bcptr != NULL && bcptr->current >= code)  while (bcptr != NULL && bcptr->current_branch >= code)
2444    {    {
2445    if (!could_be_empty_branch(bcptr->current, endcode, utf8)) return FALSE;    if (!could_be_empty_branch(bcptr->current_branch, endcode, utf8, cd))
2446        return FALSE;
2447    bcptr = bcptr->outer;    bcptr = bcptr->outer;
2448    }    }
2449  return TRUE;  return TRUE;
# Line 1724  return TRUE; Line 2456  return TRUE;
2456  *************************************************/  *************************************************/
2457    
2458  /* This function is called when the sequence "[:" or "[." or "[=" is  /* This function is called when the sequence "[:" or "[." or "[=" is
2459  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
2460  optional ^ and then a sequence of letters, terminated by a matching ":]" or  sequence of characters terminated by a matching ":]" or ".]" or "=]". If we
2461  ".]" or "=]".  reach an unescaped ']' without the special preceding character, return FALSE.
2462    
2463    Originally, this function only recognized a sequence of letters between the
2464    terminators, but it seems that Perl recognizes any sequence of characters,
2465    though of course unknown POSIX names are subsequently rejected. Perl gives an
2466    "Unknown POSIX class" error for [:f\oo:] for example, where previously PCRE
2467    didn't consider this to be a POSIX class. Likewise for [:1234:].
2468    
2469    The problem in trying to be exactly like Perl is in the handling of escapes. We
2470    have to be sure that [abc[:x\]pqr] is *not* treated as containing a POSIX
2471    class, but [abc[:x\]pqr:]] is (so that an error can be generated). The code
2472    below handles the special case of \], but does not try to do any other escape
2473    processing. This makes it different from Perl for cases such as [:l\ower:]
2474    where Perl recognizes it as the POSIX class "lower" but PCRE does not recognize
2475    "l\ower". This is a lesser evil that not diagnosing bad classes when Perl does,
2476    I think.
2477    
2478    A user pointed out that PCRE was rejecting [:a[:digit:]] whereas Perl was not.
2479    It seems that the appearance of a nested POSIX class supersedes an apparent
2480    external class. For example, [:a[:digit:]b:] matches "a", "b", ":", or
2481    a digit.
2482    
2483    In Perl, unescaped square brackets may also appear as part of class names. For
2484    example, [:a[:abc]b:] gives unknown POSIX class "[:abc]b:]". However, for
2485    [:a[:abc]b][b:] it gives unknown POSIX class "[:abc]b][b:]", which does not
2486    seem right at all. PCRE does not allow closing square brackets in POSIX class
2487    names.
2488    
2489  Argument:  Arguments:
2490    ptr      pointer to the initial [    ptr      pointer to the initial [
2491    endptr   where to return the end pointer    endptr   where to return the end pointer
   cd       pointer to compile data  
2492    
2493  Returns:   TRUE or FALSE  Returns:   TRUE or FALSE
2494  */  */
2495    
2496  static BOOL  static BOOL
2497  check_posix_syntax(const uschar *ptr, const uschar **endptr, compile_data *cd)  check_posix_syntax(const pcre_uchar *ptr, const pcre_uchar **endptr)
2498  {  {
2499  int terminator;          /* Don't combine these lines; the Solaris cc */  int terminator;          /* Don't combine these lines; the Solaris cc */
2500  terminator = *(++ptr);   /* compiler warns about "non-constant" initializer. */  terminator = *(++ptr);   /* compiler warns about "non-constant" initializer. */
2501  if (*(++ptr) == '^') ptr++;  for (++ptr; *ptr != 0; ptr++)
 while ((cd->ctypes[*ptr] & ctype_letter) != 0) ptr++;  
 if (*ptr == terminator && ptr[1] == ']')  
2502    {    {
2503    *endptr = ptr;    if (*ptr == CHAR_BACKSLASH && ptr[1] == CHAR_RIGHT_SQUARE_BRACKET)
2504    return TRUE;      ptr++;
2505      else if (*ptr == CHAR_RIGHT_SQUARE_BRACKET) return FALSE;
2506      else
2507        {
2508        if (*ptr == terminator && ptr[1] == CHAR_RIGHT_SQUARE_BRACKET)
2509          {
2510          *endptr = ptr;
2511          return TRUE;
2512          }
2513        if (*ptr == CHAR_LEFT_SQUARE_BRACKET &&
2514             (ptr[1] == CHAR_COLON || ptr[1] == CHAR_DOT ||
2515              ptr[1] == CHAR_EQUALS_SIGN) &&
2516            check_posix_syntax(ptr, endptr))
2517          return FALSE;
2518        }
2519    }    }
2520  return FALSE;  return FALSE;
2521  }  }
# Line 1769  Returns:     a value representing the na Line 2538  Returns:     a value representing the na
2538  */  */
2539    
2540  static int  static int
2541  check_posix_name(const uschar *ptr, int len)  check_posix_name(const pcre_uchar *ptr, int len)
2542  {  {
2543  const char *pn = posix_names;  const char *pn = posix_names;
2544  register int yield = 0;  register int yield = 0;
# Line 1792  return -1; Line 2561  return -1;
2561  that is referenced. This means that groups can be replicated for fixed  that is referenced. This means that groups can be replicated for fixed
2562  repetition simply by copying (because the recursion is allowed to refer to  repetition simply by copying (because the recursion is allowed to refer to
2563  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
2564  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
2565  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
2566  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
2567  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
2568  the partially compiled regex must be temporarily terminated with OP_END.  is called, the partially compiled regex must be temporarily terminated with
2569    OP_END.
2570    
2571  This function has been extended with the possibility of forward references for  This function has been extended with the possibility of forward references for
2572  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 1815  Returns:     nothing Line 2585  Returns:     nothing
2585  */  */
2586    
2587  static void  static void
2588  adjust_recurse(uschar *group, int adjust, BOOL utf8, compile_data *cd,  adjust_recurse(pcre_uchar *group, int adjust, BOOL utf8, compile_data *cd,
2589    uschar *save_hwm)    pcre_uchar *save_hwm)
2590  {  {
2591  uschar *ptr = group;  pcre_uchar *ptr = group;
2592    
2593  while ((ptr = (uschar *)find_recurse(ptr, utf8)) != NULL)  while ((ptr = (pcre_uchar *)find_recurse(ptr, utf8)) != NULL)
2594    {    {
2595    int offset;    int offset;
2596    uschar *hc;    pcre_uchar *hc;
2597    
2598    /* See if this recursion is on the forward reference list. If so, adjust the    /* See if this recursion is on the forward reference list. If so, adjust the
2599    reference. */    reference. */
# Line 1868  Arguments: Line 2638  Arguments:
2638  Returns:         new code pointer  Returns:         new code pointer
2639  */  */
2640    
2641  static uschar *  static pcre_uchar *
2642  auto_callout(uschar *code, const uschar *ptr, compile_data *cd)  auto_callout(pcre_uchar *code, const pcre_uchar *ptr, compile_data *cd)
2643  {  {
2644  *code++ = OP_CALLOUT;  *code++ = OP_CALLOUT;
2645  *code++ = 255;  *code++ = 255;
2646  PUT(code, 0, ptr - cd->start_pattern);  /* Pattern offset */  PUT(code, 0, (int)(ptr - cd->start_pattern));  /* Pattern offset */
2647  PUT(code, LINK_SIZE, 0);                /* Default length */  PUT(code, LINK_SIZE, 0);                       /* Default length */
2648  return code + 2*LINK_SIZE;  return code + 2 * LINK_SIZE;
2649  }  }
2650    
2651    
# Line 1897  Returns:             nothing Line 2667  Returns:             nothing
2667  */  */
2668    
2669  static void  static void
2670  complete_callout(uschar *previous_callout, const uschar *ptr, compile_data *cd)  complete_callout(pcre_uchar *previous_callout, const pcre_uchar *ptr, compile_data *cd)
2671  {  {
2672  int length = ptr - cd->start_pattern - GET(previous_callout, 2);  int length = (int)(ptr - cd->start_pattern - GET(previous_callout, 2));
2673  PUT(previous_callout, 2 + LINK_SIZE, length);  PUT(previous_callout, 2 + LINK_SIZE, length);
2674  }  }
2675    
# Line 1931  get_othercase_range(unsigned int *cptr, Line 2701  get_othercase_range(unsigned int *cptr,
2701  unsigned int c, othercase, next;  unsigned int c, othercase, next;
2702    
2703  for (c = *cptr; c <= d; c++)  for (c = *cptr; c <= d; c++)
2704    { if ((othercase = _pcre_ucp_othercase(c)) != NOTACHAR) break; }    { if ((othercase = UCD_OTHERCASE(c)) != c) break; }
2705    
2706  if (c > d) return FALSE;  if (c > d) return FALSE;
2707    
# Line 1940  next = othercase + 1; Line 2710  next = othercase + 1;
2710    
2711  for (++c; c <= d; c++)  for (++c; c <= d; c++)
2712    {    {
2713    if (_pcre_ucp_othercase(c) != next) break;    if (UCD_OTHERCASE(c) != next) break;
2714    next++;    next++;
2715    }    }
2716    
# Line 1949  for (++c; c <= d; c++) Line 2719  for (++c; c <= d; c++)
2719    
2720  return TRUE;  return TRUE;
2721  }  }
2722    
2723    
2724    
2725    /*************************************************
2726    *        Check a character and a property        *
2727    *************************************************/
2728    
2729    /* This function is called by check_auto_possessive() when a property item
2730    is adjacent to a fixed character.
2731    
2732    Arguments:
2733      c            the character
2734      ptype        the property type
2735      pdata        the data for the type
2736      negated      TRUE if it's a negated property (\P or \p{^)
2737    
2738    Returns:       TRUE if auto-possessifying is OK
2739    */
2740    
2741    static BOOL
2742    check_char_prop(int c, int ptype, int pdata, BOOL negated)
2743    {
2744    const ucd_record *prop = GET_UCD(c);
2745    switch(ptype)
2746      {
2747      case PT_LAMP:
2748      return (prop->chartype == ucp_Lu ||
2749              prop->chartype == ucp_Ll ||
2750              prop->chartype == ucp_Lt) == negated;
2751    
2752      case PT_GC:
2753      return (pdata == _pcre_ucp_gentype[prop->chartype]) == negated;
2754    
2755      case PT_PC:
2756      return (pdata == prop->chartype) == negated;
2757    
2758      case PT_SC:
2759      return (pdata == prop->script) == negated;
2760    
2761      /* These are specials */
2762    
2763      case PT_ALNUM:
2764      return (_pcre_ucp_gentype[prop->chartype] == ucp_L ||
2765              _pcre_ucp_gentype[prop->chartype] == ucp_N) == negated;
2766    
2767      case PT_SPACE:    /* Perl space */
2768      return (_pcre_ucp_gentype[prop->chartype] == ucp_Z ||
2769              c == CHAR_HT || c == CHAR_NL || c == CHAR_FF || c == CHAR_CR)
2770              == negated;
2771    
2772      case PT_PXSPACE:  /* POSIX space */
2773      return (_pcre_ucp_gentype[prop->chartype] == ucp_Z ||
2774              c == CHAR_HT || c == CHAR_NL || c == CHAR_VT ||
2775              c == CHAR_FF || c == CHAR_CR)
2776              == negated;
2777    
2778      case PT_WORD:
2779      return (_pcre_ucp_gentype[prop->chartype] == ucp_L ||
2780              _pcre_ucp_gentype[prop->chartype] == ucp_N ||
2781              c == CHAR_UNDERSCORE) == negated;
2782      }
2783    return FALSE;
2784    }
2785  #endif  /* SUPPORT_UCP */  #endif  /* SUPPORT_UCP */
2786    
2787    
# Line 1962  whether the next thing could possibly ma Line 2795  whether the next thing could possibly ma
2795  sense to automatically possessify the repeated item.  sense to automatically possessify the repeated item.
2796    
2797  Arguments:  Arguments:
2798    op_code       the repeated op code    previous      pointer to the repeated opcode
   this          data for this item, depends on the opcode  
2799    utf8          TRUE in UTF-8 mode    utf8          TRUE in UTF-8 mode
   utf8_char     used for utf8 character bytes, NULL if not relevant  
2800    ptr           next character in pattern    ptr           next character in pattern
2801    options       options bits    options       options bits
2802    cd            contains pointers to tables etc.    cd            contains pointers to tables etc.
# Line 1974  Returns:        TRUE if possessifying is Line 2805  Returns:        TRUE if possessifying is
2805  */  */
2806    
2807  static BOOL  static BOOL
2808  check_auto_possessive(int op_code, int item, BOOL utf8, uschar *utf8_char,  check_auto_possessive(const pcre_uchar *previous, BOOL utf8,
2809    const uschar *ptr, int options, compile_data *cd)    const pcre_uchar *ptr, int options, compile_data *cd)
2810  {  {
2811  int next;  int c, next;
2812    int op_code = *previous++;
2813    
2814  /* Skip whitespace and comments in extended mode */  /* Skip whitespace and comments in extended mode */
2815    
# Line 1986  if ((options & PCRE_EXTENDED) != 0) Line 2818  if ((options & PCRE_EXTENDED) != 0)
2818    for (;;)    for (;;)
2819      {      {
2820      while ((cd->ctypes[*ptr] & ctype_space) != 0) ptr++;      while ((cd->ctypes[*ptr] & ctype_space) != 0) ptr++;
2821      if (*ptr == '#')      if (*ptr == CHAR_NUMBER_SIGN)
2822        {        {
2823        while (*(++ptr) != 0)        ptr++;
2824          while (*ptr != 0)
2825            {
2826          if (IS_NEWLINE(ptr)) { ptr += cd->nllen; break; }          if (IS_NEWLINE(ptr)) { ptr += cd->nllen; break; }
2827            ptr++;
2828    #ifdef SUPPORT_UTF8
2829            if (utf8) while ((*ptr & 0xc0) == 0x80) ptr++;
2830    #endif
2831            }
2832        }        }
2833      else break;      else break;
2834      }      }
# Line 1998  if ((options & PCRE_EXTENDED) != 0) Line 2837  if ((options & PCRE_EXTENDED) != 0)
2837  /* If the next item is one that we can handle, get its value. A non-negative  /* If the next item is one that we can handle, get its value. A non-negative
2838  value is a character, a negative value is an escape value. */  value is a character, a negative value is an escape value. */
2839    
2840  if (*ptr == '\\')  if (*ptr == CHAR_BACKSLASH)
2841    {    {
2842    int temperrorcode = 0;    int temperrorcode = 0;
2843    next = check_escape(&ptr, &temperrorcode, cd->bracount, options, FALSE);    next = check_escape(&ptr, &temperrorcode, cd->bracount, options, FALSE);
# Line 2023  if ((options & PCRE_EXTENDED) != 0) Line 2862  if ((options & PCRE_EXTENDED) != 0)
2862    for (;;)    for (;;)
2863      {      {
2864      while ((cd->ctypes[*ptr] & ctype_space) != 0) ptr++;      while ((cd->ctypes[*ptr] & ctype_space) != 0) ptr++;
2865      if (*ptr == '#')      if (*ptr == CHAR_NUMBER_SIGN)
2866        {        {
2867        while (*(++ptr) != 0)        ptr++;
2868          while (*ptr != 0)
2869            {
2870          if (IS_NEWLINE(ptr)) { ptr += cd->nllen; break; }          if (IS_NEWLINE(ptr)) { ptr += cd->nllen; break; }
2871            ptr++;
2872    #ifdef SUPPORT_UTF8
2873            if (utf8) while ((*ptr & 0xc0) == 0x80) ptr++;
2874    #endif
2875            }
2876        }        }
2877      else break;      else break;
2878      }      }
# Line 2034  if ((options & PCRE_EXTENDED) != 0) Line 2880  if ((options & PCRE_EXTENDED) != 0)
2880    
2881  /* If the next thing is itself optional, we have to give up. */  /* If the next thing is itself optional, we have to give up. */
2882    
2883  if (*ptr == '*' || *ptr == '?' || strncmp((char *)ptr, "{0,", 3) == 0)  if (*ptr == CHAR_ASTERISK || *ptr == CHAR_QUESTION_MARK ||
2884    return FALSE;    strncmp((char *)ptr, STR_LEFT_CURLY_BRACKET STR_0 STR_COMMA, 3) == 0)
2885        return FALSE;
 /* Now compare the next item with the previous opcode. If the previous is a  
 positive single character match, "item" either contains the character or, if  
 "item" is greater than 127 in utf8 mode, the character's bytes are in  
 utf8_char. */  
   
2886    
2887  /* Handle cases when the next item is a character. */  /* Now compare the next item with the previous opcode. First, handle cases when
2888    the next item is a character. */
2889    
2890  if (next >= 0) switch(op_code)  if (next >= 0) switch(op_code)
2891    {    {
2892    case OP_CHAR:    case OP_CHAR:
2893  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF8
2894    if (utf8 && item > 127) { GETCHAR(item, utf8_char); }    GETCHARTEST(c, previous);
2895    #else
2896      c = *previous;
2897  #endif  #endif
2898    return item != next;    return c != next;
2899    
2900    /* For CHARNC (caseless character) we must check the other case. If we have    /* For CHARI (caseless character) we must check the other case. If we have
2901    Unicode property support, we can use it to test the other case of    Unicode property support, we can use it to test the other case of
2902    high-valued characters. */    high-valued characters. */
2903    
2904    case OP_CHARNC:    case OP_CHARI:
2905  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF8
2906    if (utf8 && item > 127) { GETCHAR(item, utf8_char); }    GETCHARTEST(c, previous);
2907    #else
2908      c = *previous;
2909  #endif  #endif
2910    if (item == next) return FALSE;    if (c == next) return FALSE;
2911  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF8
2912    if (utf8)    if (utf8)
2913      {      {
2914      unsigned int othercase;      unsigned int othercase;
2915      if (next < 128) othercase = cd->fcc[next]; else      if (next < 128) othercase = cd->fcc[next]; else
2916  #ifdef SUPPORT_UCP  #ifdef SUPPORT_UCP
2917      othercase = _pcre_ucp_othercase((unsigned int)next);      othercase = UCD_OTHERCASE((unsigned int)next);
2918  #else  #else
2919      othercase = NOTACHAR;      othercase = NOTACHAR;
2920  #endif  #endif
2921      return (unsigned int)item != othercase;      return (unsigned int)c != othercase;
2922      }      }
2923    else    else
2924  #endif  /* SUPPORT_UTF8 */  #endif  /* SUPPORT_UTF8 */
2925    return (item != cd->fcc[next]);  /* Non-UTF-8 mode */    return (c != cd->fcc[next]);  /* Non-UTF-8 mode */
2926    
2927    /* For OP_NOT, "item" must be a single-byte character. */    /* For OP_NOT and OP_NOTI, the data is always a single-byte character. These
2928      opcodes are not used for multi-byte characters, because they are coded using
2929      an XCLASS instead. */
2930    
2931    case OP_NOT:    case OP_NOT:
2932    if (next < 0) return FALSE;  /* Not a character */    return (c = *previous) == next;
2933    if (item == next) return TRUE;  
2934    if ((options & PCRE_CASELESS) == 0) return FALSE;    case OP_NOTI:
2935      if ((c = *previous) == next) return TRUE;
2936  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF8
2937    if (utf8)    if (utf8)
2938      {      {
2939      unsigned int othercase;      unsigned int othercase;
2940      if (next < 128) othercase = cd->fcc[next]; else      if (next < 128) othercase = cd->fcc[next]; else
2941  #ifdef SUPPORT_UCP  #ifdef SUPPORT_UCP
2942      othercase = _pcre_ucp_othercase(next);      othercase = UCD_OTHERCASE(next);
2943  #else  #else
2944      othercase = NOTACHAR;      othercase = NOTACHAR;
2945  #endif  #endif
2946      return (unsigned int)item == othercase;      return (unsigned int)c == othercase;
2947      }      }
2948    else    else
2949  #endif  /* SUPPORT_UTF8 */  #endif  /* SUPPORT_UTF8 */
2950    return (item == cd->fcc[next]);  /* Non-UTF-8 mode */    return (c == cd->fcc[next]);  /* Non-UTF-8 mode */
2951    
2952      /* Note that OP_DIGIT etc. are generated only when PCRE_UCP is *not* set.
2953      When it is set, \d etc. are converted into OP_(NOT_)PROP codes. */
2954    
2955    case OP_DIGIT:    case OP_DIGIT:
2956    return next > 127 || (cd->ctypes[next] & ctype_digit) == 0;    return next > 127 || (cd->ctypes[next] & ctype_digit) == 0;
# Line 2141  if (next >= 0) switch(op_code) Line 2993  if (next >= 0) switch(op_code)
2993      case 0x202f:      case 0x202f:
2994      case 0x205f:      case 0x205f:
2995      case 0x3000:      case 0x3000:
2996      return op_code != OP_HSPACE;      return op_code == OP_NOT_HSPACE;
2997      default:      default:
2998      return op_code == OP_HSPACE;      return op_code != OP_NOT_HSPACE;
2999      }      }
3000    
3001      case OP_ANYNL:
3002    case OP_VSPACE:    case OP_VSPACE:
3003    case OP_NOT_VSPACE:    case OP_NOT_VSPACE:
3004    switch(next)    switch(next)
# Line 2157  if (next >= 0) switch(op_code) Line 3010  if (next >= 0) switch(op_code)
3010      case 0x85:      case 0x85:
3011      case 0x2028:      case 0x2028:
3012      case 0x2029:      case 0x2029:
3013      return op_code != OP_VSPACE;      return op_code == OP_NOT_VSPACE;
3014      default:      default:
3015      return op_code == OP_VSPACE;      return op_code != OP_NOT_VSPACE;
3016      }      }
3017    
3018    #ifdef SUPPORT_UCP
3019      case OP_PROP:
3020      return check_char_prop(next, previous[0], previous[1], FALSE);
3021    
3022      case OP_NOTPROP:
3023      return check_char_prop(next, previous[0], previous[1], TRUE);
3024    #endif
3025    
3026    default:    default:
3027    return FALSE;    return FALSE;
3028    }    }
3029    
3030    
3031  /* Handle the case when the next item is \d, \s, etc. */  /* Handle the case when the next item is \d, \s, etc. Note that when PCRE_UCP
3032    is set, \d turns into ESC_du rather than ESC_d, etc., so ESC_d etc. are
3033    generated only when PCRE_UCP is *not* set, that is, when only ASCII
3034    characteristics are recognized. Similarly, the opcodes OP_DIGIT etc. are
3035    replaced by OP_PROP codes when PCRE_UCP is set. */
3036    
3037  switch(op_code)  switch(op_code)
3038    {    {
3039    case OP_CHAR:    case OP_CHAR:
3040    case OP_CHARNC:    case OP_CHARI:
3041  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF8
3042    if (utf8 && item > 127) { GETCHAR(item, utf8_char); }    GETCHARTEST(c, previous);
3043    #else
3044      c = *previous;
3045  #endif  #endif
3046    switch(-next)    switch(-next)
3047      {      {
3048      case ESC_d:      case ESC_d:
3049      return item > 127 || (cd->ctypes[item] & ctype_digit) == 0;      return c > 127 || (cd->ctypes[c] & ctype_digit) == 0;
3050    
3051      case ESC_D:      case ESC_D:
3052      return item <= 127 && (cd->ctypes[item] & ctype_digit) != 0;      return c <= 127 && (cd->ctypes[c] & ctype_digit) != 0;
3053    
3054      case ESC_s:      case ESC_s:
3055      return item > 127 || (cd->ctypes[item] & ctype_space) == 0;      return c > 127 || (cd->ctypes[c] & ctype_space) == 0;
3056    
3057      case ESC_S:      case ESC_S:
3058      return item <= 127 && (cd->ctypes[item] & ctype_space) != 0;      return c <= 127 && (cd->ctypes[c] & ctype_space) != 0;
3059    
3060      case ESC_w:      case ESC_w:
3061      return item > 127 || (cd->ctypes[item] & ctype_word) == 0;      return c > 127 || (cd->ctypes[c] & ctype_word) == 0;
3062    
3063      case ESC_W:      case ESC_W:
3064      return item <= 127 && (cd->ctypes[item] & ctype_word) != 0;      return c <= 127 && (cd->ctypes[c] & ctype_word) != 0;
3065    
3066      case ESC_h:      case ESC_h:
3067      case ESC_H:      case ESC_H:
3068      switch(item)      switch(c)
3069        {        {
3070        case 0x09:        case 0x09:
3071        case 0x20:        case 0x20:
# Line 2226  switch(op_code) Line 3093  switch(op_code)
3093    
3094      case ESC_v:      case ESC_v:
3095      case ESC_V:      case ESC_V:
3096      switch(item)      switch(c)
3097        {        {
3098        case 0x0a:        case 0x0a:
3099        case 0x0b:        case 0x0b:
# Line 2240  switch(op_code) Line 3107  switch(op_code)
3107        return -next == ESC_v;        return -next == ESC_v;
3108        }        }
3109    
3110        /* When PCRE_UCP is set, these values get generated for \d etc. Find
3111        their substitutions and process them. The result will always be either
3112        -ESC_p or -ESC_P. Then fall through to process those values. */
3113    
3114    #ifdef SUPPORT_UCP
3115        case ESC_du:
3116        case ESC_DU:
3117        case ESC_wu:
3118        case ESC_WU:
3119        case ESC_su:
3120        case ESC_SU:
3121          {
3122          int temperrorcode = 0;
3123          ptr = substitutes[-next - ESC_DU];
3124          next = check_escape(&ptr, &temperrorcode, 0, options, FALSE);
3125          if (temperrorcode != 0) return FALSE;
3126          ptr++;    /* For compatibility */
3127          }
3128        /* Fall through */
3129    
3130        case ESC_p:
3131        case ESC_P:
3132          {
3133          int ptype, pdata, errorcodeptr;
3134          BOOL negated;
3135    
3136          ptr--;      /* Make ptr point at the p or P */
3137          ptype = get_ucp(&ptr, &negated, &pdata, &errorcodeptr);
3138          if (ptype < 0) return FALSE;
3139          ptr++;      /* Point past the final curly ket */
3140    
3141          /* If the property item is optional, we have to give up. (When generated
3142          from \d etc by PCRE_UCP, this test will have been applied much earlier,
3143          to the original \d etc. At this point, ptr will point to a zero byte. */
3144    
3145          if (*ptr == CHAR_ASTERISK || *ptr == CHAR_QUESTION_MARK ||
3146            strncmp((char *)ptr, STR_LEFT_CURLY_BRACKET STR_0 STR_COMMA, 3) == 0)
3147              return FALSE;
3148    
3149          /* Do the property check. */
3150    
3151          return check_char_prop(c, ptype, pdata, (next == -ESC_P) != negated);
3152          }
3153    #endif
3154    
3155      default:      default:
3156      return FALSE;      return FALSE;
3157      }      }
3158    
3159      /* In principle, support for Unicode properties should be integrated here as
3160      well. It means re-organizing the above code so as to get hold of the property
3161      values before switching on the op-code. However, I wonder how many patterns
3162      combine ASCII \d etc with Unicode properties? (Note that if PCRE_UCP is set,
3163      these op-codes are never generated.) */
3164    
3165    case OP_DIGIT:    case OP_DIGIT:
3166    return next == -ESC_D || next == -ESC_s || next == -ESC_W ||    return next == -ESC_D || next == -ESC_s || next == -ESC_W ||
3167           next == -ESC_h || next == -ESC_v;           next == -ESC_h || next == -ESC_v || next == -ESC_R;
3168    
3169    case OP_NOT_DIGIT:    case OP_NOT_DIGIT:
3170    return next == -ESC_d;    return next == -ESC_d;
3171    
3172    case OP_WHITESPACE:    case OP_WHITESPACE:
3173    return next == -ESC_S || next == -ESC_d || next == -ESC_w;    return next == -ESC_S || next == -ESC_d || next == -ESC_w || next == -ESC_R;
3174    
3175    case OP_NOT_WHITESPACE:    case OP_NOT_WHITESPACE:
3176    return next == -ESC_s || next == -ESC_h || next == -ESC_v;    return next == -ESC_s || next == -ESC_h || next == -ESC_v;
3177    
3178    case OP_HSPACE:    case OP_HSPACE:
3179    return next == -ESC_S || next == -ESC_H || next == -ESC_d || next == -ESC_w;    return next == -ESC_S || next == -ESC_H || next == -ESC_d ||
3180             next == -ESC_w || next == -ESC_v || next == -ESC_R;
3181    
3182    case OP_NOT_HSPACE:    case OP_NOT_HSPACE:
3183    return next == -ESC_h;    return next == -ESC_h;
3184    
3185    /* Can't have \S in here because VT matches \S (Perl anomaly) */    /* Can't have \S in here because VT matches \S (Perl anomaly) */
3186      case OP_ANYNL:
3187    case OP_VSPACE:    case OP_VSPACE:
3188    return next == -ESC_V || next == -ESC_d || next == -ESC_w;    return next == -ESC_V || next == -ESC_d || next == -ESC_w;
3189    
3190    case OP_NOT_VSPACE:    case OP_NOT_VSPACE:
3191    return next == -ESC_v;    return next == -ESC_v || next == -ESC_R;
3192    
3193    case OP_WORDCHAR:    case OP_WORDCHAR:
3194    return next == -ESC_W || next == -ESC_s || next == -ESC_h || next == -ESC_v;    return next == -ESC_W || next == -ESC_s || next == -ESC_h ||
3195             next == -ESC_v || next == -ESC_R;
3196    
3197    case OP_NOT_WORDCHAR:    case OP_NOT_WORDCHAR:
3198    return next == -ESC_w || next == -ESC_d;    return next == -ESC_w || next == -ESC_d;
# Line 2303  Arguments: Line 3224  Arguments:
3224    firstbyteptr   set to initial literal character, or < 0 (REQ_UNSET, REQ_NONE)    firstbyteptr   set to initial literal character, or < 0 (REQ_UNSET, REQ_NONE)
3225    reqbyteptr     set to the last literal character required, else < 0    reqbyteptr     set to the last literal character required, else < 0
3226    bcptr          points to current branch chain    bcptr          points to current branch chain
3227      cond_depth     conditional nesting depth
3228    cd             contains pointers to tables etc.    cd             contains pointers to tables etc.
3229    lengthptr      NULL during the real compile phase    lengthptr      NULL during the real compile phase
3230                   points to length accumulator during pre-compile phase                   points to length accumulator during pre-compile phase
# Line 2312  Returns:         TRUE on success Line 3234  Returns:         TRUE on success
3234  */  */
3235    
3236  static BOOL  static BOOL
3237  compile_branch(int *optionsptr, uschar **codeptr, const uschar **ptrptr,  compile_branch(int *optionsptr, pcre_uchar **codeptr,
3238    int *errorcodeptr, int *firstbyteptr, int *reqbyteptr, branch_chain *bcptr,    const pcre_uchar **ptrptr, int *errorcodeptr, int *firstbyteptr,
3239    compile_data *cd, int *lengthptr)    int *reqbyteptr, branch_chain *bcptr, int cond_depth, compile_data *cd,
3240      int *lengthptr)
3241  {  {
3242  int repeat_type, op_type;  int repeat_type, op_type;
3243  int repeat_min = 0, repeat_max = 0;      /* To please picky compilers */  int repeat_min = 0, repeat_max = 0;      /* To please picky compilers */
# Line 2323  int greedy_default, greedy_non_default; Line 3246  int greedy_default, greedy_non_default;
3246  int firstbyte, reqbyte;  int firstbyte, reqbyte;
3247  int zeroreqbyte, zerofirstbyte;  int zeroreqbyte, zerofirstbyte;
3248  int req_caseopt, reqvary, tempreqvary;  int req_caseopt, reqvary, tempreqvary;
3249  int options = *optionsptr;  int options = *optionsptr;               /* May change dynamically */
3250  int after_manual_callout = 0;  int after_manual_callout = 0;
3251  int length_prevgroup = 0;  int length_prevgroup = 0;
3252  register int c;  register int c;
3253  register uschar *code = *codeptr;  register pcre_uchar *code = *codeptr;
3254  uschar *last_code = code;  pcre_uchar *last_code = code;
3255  uschar *orig_code = code;  pcre_uchar *orig_code = code;
3256  uschar *tempcode;  pcre_uchar *tempcode;
3257  BOOL inescq = FALSE;  BOOL inescq = FALSE;
3258  BOOL groupsetfirstbyte = FALSE;  BOOL groupsetfirstbyte = FALSE;
3259  const uschar *ptr = *ptrptr;  const pcre_uchar *ptr = *ptrptr;
3260  const uschar *tempptr;  const pcre_uchar *tempptr;
3261  uschar *previous = NULL;  const pcre_uchar *nestptr = NULL;
3262  uschar *previous_callout = NULL;  pcre_uchar *previous = NULL;
3263  uschar *save_hwm = NULL;  pcre_uchar *previous_callout = NULL;
3264  uschar classbits[32];  pcre_uchar *save_hwm = NULL;
3265    pcre_uchar classbits[32];
3266    
3267    /* We can fish out the UTF-8 setting once and for all into a BOOL, but we
3268    must not do this for other options (e.g. PCRE_EXTENDED) because they may change
3269    dynamically as we process the pattern. */
3270    
3271  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF8
3272  BOOL class_utf8;  BOOL class_utf8;
3273  BOOL utf8 = (options & PCRE_UTF8) != 0;  BOOL utf8 = (options & PCRE_UTF8) != 0;
3274  uschar *class_utf8data;  pcre_uint8 *class_utf8data;
3275  uschar utf8_char[6];  pcre_uint8 *class_utf8data_base;
3276    pcre_uint8 utf8_char[6];
3277  #else  #else
3278  BOOL utf8 = FALSE;  BOOL utf8 = FALSE;
 uschar *utf8_char = NULL;  
3279  #endif  #endif
3280    
3281  #ifdef DEBUG  #ifdef PCRE_DEBUG
3282  if (lengthptr != NULL) DPRINTF((">> start branch\n"));  if (lengthptr != NULL) DPRINTF((">> start branch\n"));
3283  #endif  #endif
3284    
# Line 2383  req_caseopt = ((options & PCRE_CASELESS) Line 3311  req_caseopt = ((options & PCRE_CASELESS)
3311  for (;; ptr++)  for (;; ptr++)
3312    {    {
3313    BOOL negate_class;    BOOL negate_class;
3314    BOOL should_flip_negation;    BOOL should_flip_negation;
3315    BOOL possessive_quantifier;    BOOL possessive_quantifier;
3316    BOOL is_quantifier;    BOOL is_quantifier;
3317    BOOL is_recurse;    BOOL is_recurse;
# Line 2398  for (;; ptr++) Line 3326  for (;; ptr++)
3326    int subfirstbyte;    int subfirstbyte;
3327    int terminator;    int terminator;
3328    int mclength;    int mclength;
3329    uschar mcbuffer[8];    int tempbracount;
3330      pcre_uchar mcbuffer[8];
3331    
3332    /* Get next byte in the pattern */    /* Get next byte in the pattern */
3333    
3334    c = *ptr;    c = *ptr;
3335    
3336      /* If we are at the end of a nested substitution, revert to the outer level
3337      string. Nesting only happens one level deep. */
3338    
3339      if (c == 0 && nestptr != NULL)
3340        {
3341        ptr = nestptr;
3342        nestptr = NULL;
3343        c = *ptr;
3344        }
3345    
3346    /* If we are in the pre-compile phase, accumulate the length used for the    /* If we are in the pre-compile phase, accumulate the length used for the
3347    previous cycle of this loop. */    previous cycle of this loop. */
3348    
3349    if (lengthptr != NULL)    if (lengthptr != NULL)
3350      {      {
3351  #ifdef DEBUG  #ifdef PCRE_DEBUG
3352      if (code > cd->hwm) cd->hwm = code;                 /* High water info */      if (code > cd->hwm) cd->hwm = code;                 /* High water info */
3353  #endif  #endif
3354      if (code > cd->start_workspace + COMPILE_WORK_SIZE) /* Check for overrun */      if (code > cd->start_workspace + WORK_SIZE_CHECK)   /* Check for overrun */
3355        {        {
3356        *errorcodeptr = ERR52;        *errorcodeptr = ERR52;
3357        goto FAILED;        goto FAILED;
# Line 2434  for (;; ptr++) Line 3373  for (;; ptr++)
3373        goto FAILED;        goto FAILED;
3374        }        }
3375    
3376      *lengthptr += code - last_code;      *lengthptr += (int)(code - last_code);
3377      DPRINTF(("length=%d added %d c=%c\n", *lengthptr, code - last_code, c));      DPRINTF(("length=%d added %d c=%c\n", *lengthptr, (int)(code - last_code),
3378          c));
3379    
3380      /* If "previous" is set and it is not at the start of the work space, move      /* If "previous" is set and it is not at the start of the work space, move
3381      it back to there, in order to avoid filling up the work space. Otherwise,      it back to there, in order to avoid filling up the work space. Otherwise,
# Line 2461  for (;; ptr++) Line 3401  for (;; ptr++)
3401    /* In the real compile phase, just check the workspace used by the forward    /* In the real compile phase, just check the workspace used by the forward
3402    reference list. */    reference list. */
3403    
3404    else if (cd->hwm > cd->start_workspace + COMPILE_WORK_SIZE)    else if (cd->hwm > cd->start_workspace + WORK_SIZE_CHECK)
3405      {      {
3406      *errorcodeptr = ERR52;      *errorcodeptr = ERR52;
3407      goto FAILED;      goto FAILED;
# Line 2471  for (;; ptr++) Line 3411  for (;; ptr++)
3411    
3412    if (inescq && c != 0)    if (inescq && c != 0)
3413      {      {
3414      if (c == '\\' && ptr[1] == 'E')      if (c == CHAR_BACKSLASH && ptr[1] == CHAR_E)
3415        {        {
3416        inescq = FALSE;        inescq = FALSE;
3417        ptr++;        ptr++;
# Line 2497  for (;; ptr++) Line 3437  for (;; ptr++)
3437    /* Fill in length of a previous callout, except when the next thing is    /* Fill in length of a previous callout, except when the next thing is
3438    a quantifier. */    a quantifier. */
3439    
3440    is_quantifier = c == '*' || c == '+' || c == '?' ||    is_quantifier =
3441      (c == '{' && is_counted_repeat(ptr+1));      c == CHAR_ASTERISK || c == CHAR_PLUS || c == CHAR_QUESTION_MARK ||
3442        (c == CHAR_LEFT_CURLY_BRACKET && is_counted_repeat(ptr+1));
3443    
3444    if (!is_quantifier && previous_callout != NULL &&    if (!is_quantifier && previous_callout != NULL &&
3445         after_manual_callout-- <= 0)         after_manual_callout-- <= 0)
# Line 2508  for (;; ptr++) Line 3449  for (;; ptr++)
3449      previous_callout = NULL;      previous_callout = NULL;
3450      }      }
3451    
3452    /* In extended mode, skip white space and comments */    /* In extended mode, skip white space and comments. */
3453    
3454    if ((options & PCRE_EXTENDED) != 0)    if ((options & PCRE_EXTENDED) != 0)
3455      {      {
3456      if ((cd->ctypes[c] & ctype_space) != 0) continue;      if ((cd->ctypes[c] & ctype_space) != 0) continue;
3457      if (c == '#')      if (c == CHAR_NUMBER_SIGN)
3458        {        {
3459        while (*(++ptr) != 0)        ptr++;
3460          while (*ptr != 0)
3461          {          {
3462          if (IS_NEWLINE(ptr)) { ptr += cd->nllen - 1; break; }          if (IS_NEWLINE(ptr)) { ptr += cd->nllen - 1; break; }
3463            ptr++;
3464    #ifdef SUPPORT_UTF8
3465            if (utf8) while ((*ptr & 0xc0) == 0x80) ptr++;
3466    #endif
3467          }          }
3468        if (*ptr != 0) continue;        if (*ptr != 0) continue;
3469    
# Line 2538  for (;; ptr++) Line 3484  for (;; ptr++)
3484      {      {
3485      /* ===================================================================*/      /* ===================================================================*/
3486      case 0:                        /* The branch terminates at string end */      case 0:                        /* The branch terminates at string end */
3487      case '|':                      /* or | or ) */      case CHAR_VERTICAL_LINE:       /* or | or ) */
3488      case ')':      case CHAR_RIGHT_PARENTHESIS:
3489      *firstbyteptr = firstbyte;      *firstbyteptr = firstbyte;
3490      *reqbyteptr = reqbyte;      *reqbyteptr = reqbyte;
3491      *codeptr = code;      *codeptr = code;
# Line 2551  for (;; ptr++) Line 3497  for (;; ptr++)
3497          *errorcodeptr = ERR20;          *errorcodeptr = ERR20;
3498          goto FAILED;          goto FAILED;
3499          }          }
3500        *lengthptr += code - last_code;   /* To include callout length */        *lengthptr += (int)(code - last_code);   /* To include callout length */
3501        DPRINTF((">> end branch\n"));        DPRINTF((">> end branch\n"));
3502        }        }
3503      return TRUE;      return TRUE;
# Line 2561  for (;; ptr++) Line 3507  for (;; ptr++)
3507      /* Handle single-character metacharacters. In multiline mode, ^ disables      /* Handle single-character metacharacters. In multiline mode, ^ disables
3508      the setting of any following char as a first character. */      the setting of any following char as a first character. */
3509    
3510      case '^':      case CHAR_CIRCUMFLEX_ACCENT:
3511        previous = NULL;
3512      if ((options & PCRE_MULTILINE) != 0)      if ((options & PCRE_MULTILINE) != 0)
3513        {        {
3514        if (firstbyte == REQ_UNSET) firstbyte = REQ_NONE;        if (firstbyte == REQ_UNSET) firstbyte = REQ_NONE;
3515          *code++ = OP_CIRCM;
3516        }        }
3517      previous = NULL;      else *code++ = OP_CIRC;
     *code++ = OP_CIRC;  
3518      break;      break;
3519    
3520      case '$':      case CHAR_DOLLAR_SIGN:
3521      previous = NULL;      previous = NULL;
3522      *code++ = OP_DOLL;      *code++ = ((options & PCRE_MULTILINE) != 0)? OP_DOLLM : OP_DOLL;
3523      break;      break;
3524    
3525      /* There can never be a first char if '.' is first, whatever happens about      /* There can never be a first char if '.' is first, whatever happens about
3526      repeats. The value of reqbyte doesn't change either. */      repeats. The value of reqbyte doesn't change either. */
3527    
3528      case '.':      case CHAR_DOT:
3529      if (firstbyte == REQ_UNSET) firstbyte = REQ_NONE;      if (firstbyte == REQ_UNSET) firstbyte = REQ_NONE;
3530      zerofirstbyte = firstbyte;      zerofirstbyte = firstbyte;
3531      zeroreqbyte = reqbyte;      zeroreqbyte = reqbyte;
3532      previous = code;      previous = code;
3533      *code++ = OP_ANY;      *code++ = ((options & PCRE_DOTALL) != 0)? OP_ALLANY: OP_ANY;
3534      break;      break;
3535    
3536    
# Line 2598  for (;; ptr++) Line 3545  for (;; ptr++)
3545      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,
3546      but those above are are explicitly listed afterwards. A flag byte tells      but those above are are explicitly listed afterwards. A flag byte tells
3547      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.
     */  
3548    
3549      case '[':      In JavaScript compatibility mode, an isolated ']' causes an error. In
3550        default (Perl) mode, it is treated as a data character. */
3551    
3552        case CHAR_RIGHT_SQUARE_BRACKET:
3553        if ((cd->external_options & PCRE_JAVASCRIPT_COMPAT) != 0)
3554          {
3555          *errorcodeptr = ERR64;
3556          goto FAILED;
3557          }
3558        goto NORMAL_CHAR;
3559    
3560        case CHAR_LEFT_SQUARE_BRACKET:
3561      previous = code;      previous = code;
3562    
3563      /* PCRE supports POSIX class stuff inside a class. Perl gives an error if      /* PCRE supports POSIX class stuff inside a class. Perl gives an error if
3564      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. */
3565    
3566      if ((ptr[1] == ':' || ptr[1] == '.' || ptr[1] == '=') &&      if ((ptr[1] == CHAR_COLON || ptr[1] == CHAR_DOT ||
3567          check_posix_syntax(ptr, &tempptr, cd))           ptr[1] == CHAR_EQUALS_SIGN) &&
3568            check_posix_syntax(ptr, &tempptr))
3569        {        {
3570        *errorcodeptr = (ptr[1] == ':')? ERR13 : ERR31;        *errorcodeptr = (ptr[1] == CHAR_COLON)? ERR13 : ERR31;
3571        goto FAILED;        goto FAILED;
3572        }        }
3573    
# Line 2621  for (;; ptr++) Line 3579  for (;; ptr++)
3579      for (;;)      for (;;)
3580        {        {
3581        c = *(++ptr);        c = *(++ptr);
3582        if (c == '\\')        if (c == CHAR_BACKSLASH)
3583          {          {
3584          if (ptr[1] == 'E') ptr++;          if (ptr[1] == CHAR_E)
3585            else if (strncmp((const char *)ptr+1, "Q\\E", 3) == 0) ptr += 3;            ptr++;
3586              else break;          else if (strncmp((const char *)ptr+1,
3587                              STR_Q STR_BACKSLASH STR_E, 3) == 0)
3588              ptr += 3;
3589            else
3590              break;
3591          }          }
3592        else if (!negate_class && c == '^')        else if (!negate_class && c == CHAR_CIRCUMFLEX_ACCENT)
3593          negate_class = TRUE;          negate_class = TRUE;
3594        else break;        else break;
3595        }        }
3596    
3597      /* If a class contains a negative special such as \S, we need to flip the      /* Empty classes are allowed in JavaScript compatibility mode. Otherwise,
3598      negation flag at the end, so that support for characters > 255 works      an initial ']' is taken as a data character -- the code below handles
3599        that. In JS mode, [] must always fail, so generate OP_FAIL, whereas
3600        [^] must match any character, so generate OP_ALLANY. */
3601    
3602        if (c == CHAR_RIGHT_SQUARE_BRACKET &&
3603            (cd->external_options & PCRE_JAVASCRIPT_COMPAT) != 0)
3604          {
3605          *code++ = negate_class? OP_ALLANY : OP_FAIL;
3606          if (firstbyte == REQ_UNSET) firstbyte = REQ_NONE;
3607          zerofirstbyte = firstbyte;
3608          break;
3609          }
3610    
3611        /* If a class contains a negative special such as \S, we need to flip the
3612        negation flag at the end, so that support for characters > 255 works
3613      correctly (they are all included in the class). */      correctly (they are all included in the class). */
3614    
3615      should_flip_negation = FALSE;      should_flip_negation = FALSE;
# Line 2650  for (;; ptr++) Line 3626  for (;; ptr++)
3626      than 256), because in that case the compiled code doesn't use the bit map.      than 256), because in that case the compiled code doesn't use the bit map.
3627      */      */
3628    
3629      memset(classbits, 0, 32 * sizeof(uschar));      memset(classbits, 0, 32 * sizeof(pcre_uint8));
3630    
3631  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF8
3632      class_utf8 = FALSE;                       /* No chars >= 256 */      class_utf8 = FALSE;                       /* No chars >= 256 */
3633      class_utf8data = code + LINK_SIZE + 2;    /* For UTF-8 items */      class_utf8data = code + LINK_SIZE + 2;    /* For UTF-8 items */
3634        class_utf8data_base = class_utf8data;     /* For resetting in pass 1 */
3635  #endif  #endif
3636    
3637      /* 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 2663  for (;; ptr++) Line 3640  for (;; ptr++)
3640    
3641      if (c != 0) do      if (c != 0) do
3642        {        {
3643        const uschar *oldptr;        const pcre_uchar *oldptr;
3644    
3645  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF8
3646        if (utf8 && c > 127)        if (utf8 && c > 127)
3647          {                           /* Braces are required because the */          {                           /* Braces are required because the */
3648          GETCHARLEN(c, ptr, ptr);    /* macro generates multiple statements */          GETCHARLEN(c, ptr, ptr);    /* macro generates multiple statements */
3649          }          }
3650    
3651          /* In the pre-compile phase, accumulate the length of any UTF-8 extra
3652          data and reset the pointer. This is so that very large classes that
3653          contain a zillion UTF-8 characters no longer overwrite the work space
3654          (which is on the stack). */
3655    
3656          if (lengthptr != NULL)
3657            {
3658            *lengthptr += class_utf8data - class_utf8data_base;
3659            class_utf8data = class_utf8data_base;
3660            }
3661    
3662  #endif  #endif
3663    
3664        /* Inside \Q...\E everything is literal except \E */        /* Inside \Q...\E everything is literal except \E */
3665    
3666        if (inescq)        if (inescq)
3667          {          {
3668          if (c == '\\' && ptr[1] == 'E')     /* If we are at \E */          if (c == CHAR_BACKSLASH && ptr[1] == CHAR_E)  /* If we are at \E */
3669            {            {
3670            inescq = FALSE;                   /* Reset literal state */            inescq = FALSE;                   /* Reset literal state */
3671            ptr++;                            /* Skip the 'E' */            ptr++;                            /* Skip the 'E' */
# Line 2691  for (;; ptr++) Line 3680  for (;; ptr++)
3680        [.ch.] and [=ch=] ("collating elements") and fault them, as Perl        [.ch.] and [=ch=] ("collating elements") and fault them, as Perl
3681        5.6 and 5.8 do. */        5.6 and 5.8 do. */
3682    
3683        if (c == '[' &&        if (c == CHAR_LEFT_SQUARE_BRACKET &&
3684            (ptr[1] == ':' || ptr[1] == '.' || ptr[1] == '=') &&            (ptr[1] == CHAR_COLON || ptr[1] == CHAR_DOT ||
3685            check_posix_syntax(ptr, &tempptr, cd))             ptr[1] == CHAR_EQUALS_SIGN) && check_posix_syntax(ptr, &tempptr))
3686          {          {
3687          BOOL local_negate = FALSE;          BOOL local_negate = FALSE;
3688          int posix_class, taboffset, tabopt;          int posix_class, taboffset, tabopt;
3689          register const uschar *cbits = cd->cbits;          register const pcre_uint8 *cbits = cd->cbits;
3690          uschar pbits[32];          pcre_uint8 pbits[32];
3691    
3692          if (ptr[1] != ':')          if (ptr[1] != CHAR_COLON)
3693            {            {
3694            *errorcodeptr = ERR31;            *errorcodeptr = ERR31;
3695            goto FAILED;            goto FAILED;
3696            }            }
3697    
3698          ptr += 2;          ptr += 2;
3699          if (*ptr == '^')          if (*ptr == CHAR_CIRCUMFLEX_ACCENT)
3700            {            {
3701            local_negate = TRUE;            local_negate = TRUE;
3702              should_flip_negation = TRUE;  /* Note negative special */
3703            ptr++;            ptr++;
3704            }            }
3705    
3706          posix_class = check_posix_name(ptr, tempptr - ptr);          posix_class = check_posix_name(ptr, (int)(tempptr - ptr));
3707          if (posix_class < 0)          if (posix_class < 0)
3708            {            {
3709            *errorcodeptr = ERR30;            *errorcodeptr = ERR30;
# Line 2727  for (;; ptr++) Line 3717  for (;; ptr++)
3717          if ((options & PCRE_CASELESS) != 0 && posix_class <= 2)          if ((options & PCRE_CASELESS) != 0 && posix_class <= 2)
3718            posix_class = 0;            posix_class = 0;
3719    
3720          /* We build the bit map for the POSIX class in a chunk of local store          /* When PCRE_UCP is set, some of the POSIX classes are converted to
3721          because we may be adding and subtracting from it, and we don't want to          different escape sequences that use Unicode properties. */
3722          subtract bits that may be in the main map already. At the end we or the  
3723          result into the bit map that is being built. */  #ifdef SUPPORT_UCP
3724            if ((options & PCRE_UCP) != 0)
3725              {
3726              int pc = posix_class + ((local_negate)? POSIX_SUBSIZE/2 : 0);
3727              if (posix_substitutes[pc] != NULL)
3728                {
3729                nestptr = tempptr + 1;
3730                ptr = posix_substitutes[pc] - 1;
3731                continue;
3732                }
3733              }
3734    #endif
3735            /* In the non-UCP case, we build the bit map for the POSIX class in a
3736            chunk of local store because we may be adding and subtracting from it,
3737            and we don't want to subtract bits that may be in the main map already.
3738            At the end we or the result into the bit map that is being built. */
3739    
3740          posix_class *= 3;          posix_class *= 3;
3741    
3742          /* Copy in the first table (always present) */          /* Copy in the first table (always present) */
3743    
3744          memcpy(pbits, cbits + posix_class_maps[posix_class],          memcpy(pbits, cbits + posix_class_maps[posix_class],
3745            32 * sizeof(uschar));            32 * sizeof(pcre_uint8));
3746    
3747          /* If there is a second table, add or remove it as required. */          /* If there is a second table, add or remove it as required. */
3748    
# Line 2774  for (;; ptr++) Line 3779  for (;; ptr++)
3779    
3780        /* Backslash may introduce a single character, or it may introduce one        /* Backslash may introduce a single character, or it may introduce one
3781        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
3782        case. Inside a class (and only there) it is treated as backspace.        case. Inside a class (and only there) it is treated as backspace. We
3783        Elsewhere it marks a word boundary. Other escapes have preset maps ready        assume that other escapes have more than one character in them, so set
3784        to 'or' into the one we are building. We assume they have more than one        class_charcount bigger than one. Unrecognized escapes fall through and
3785        character in them, so set class_charcount bigger than one. */        are either treated as literal characters (by default), or are faulted if
3786          PCRE_EXTRA is set. */
3787    
3788        if (c == '\\')        if (c == CHAR_BACKSLASH)
3789          {          {
3790          c = check_escape(&ptr, errorcodeptr, cd->bracount, options, TRUE);          c = check_escape(&ptr, errorcodeptr, cd->bracount, options, TRUE);
3791          if (*errorcodeptr != 0) goto FAILED;          if (*errorcodeptr != 0) goto FAILED;
3792    
3793          if (-c == ESC_b) c = '\b';       /* \b is backslash in a class */          if (-c == ESC_b) c = CHAR_BS;    /* \b is backspace in a class */
         else if (-c == ESC_X) c = 'X';   /* \X is literal X in a class */  
         else if (-c == ESC_R) c = 'R';   /* \R is literal R in a class */  
3794          else if (-c == ESC_Q)            /* Handle start of quoted string */          else if (-c == ESC_Q)            /* Handle start of quoted string */
3795            {            {
3796            if (ptr[1] == '\\' && ptr[2] == 'E')            if (ptr[1] == CHAR_BACKSLASH && ptr[2] == CHAR_E)
3797              {              {
3798              ptr += 2; /* avoid empty string */              ptr += 2; /* avoid empty string */
3799              }              }
# Line 2800  for (;; ptr++) Line 3804  for (;; ptr++)
3804    
3805          if (c < 0)          if (c < 0)
3806            {            {
3807            register const uschar *cbits = cd->cbits;            register const pcre_uint8 *cbits = cd->cbits;
3808            class_charcount += 2;     /* Greater than 1 is what matters */            class_charcount += 2;     /* Greater than 1 is what matters */
3809    
3810            /* Save time by not doing this in the pre-compile phase. */            switch (-c)
   
           if (lengthptr == NULL) switch (-c)  
3811              {              {
3812    #ifdef SUPPORT_UCP
3813                case ESC_du:     /* These are the values given for \d etc */
3814                case ESC_DU:     /* when PCRE_UCP is set. We replace the */
3815                case ESC_wu:     /* escape sequence with an appropriate \p */
3816                case ESC_WU:     /* or \P to test Unicode properties instead */
3817                case ESC_su:     /* of the default ASCII testing. */
3818                case ESC_SU:
3819                nestptr = ptr;
3820                ptr = substitutes[-c - ESC_DU] - 1;  /* Just before substitute */
3821                class_charcount -= 2;                /* Undo! */
3822                continue;
3823    #endif
3824              case ESC_d:              case ESC_d:
3825              for (c = 0; c < 32; c++) classbits[c] |= cbits[c+cbit_digit];              for (c = 0; c < 32; c++) classbits[c] |= cbits[c+cbit_digit];
3826              continue;              continue;
3827    
3828              case ESC_D:              case ESC_D:
3829              should_flip_negation = TRUE;              should_flip_negation = TRUE;
3830              for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_digit];              for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_digit];
3831              continue;              continue;
3832    
# Line 2821  for (;; ptr++) Line 3835  for (;; ptr++)
3835              continue;              continue;
3836    
3837              case ESC_W:              case ESC_W:
3838              should_flip_negation = TRUE;              should_flip_negation = TRUE;
3839              for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_word];              for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_word];
3840              continue;              continue;
3841    
3842                /* Perl 5.004 onwards omits VT from \s, but we must preserve it
3843                if it was previously set by something earlier in the character
3844                class. */
3845    
3846              case ESC_s:              case ESC_s:
3847              for (c = 0; c < 32; c++) classbits[c] |= cbits[c+cbit_space];              classbits[0] |= cbits[cbit_space];
3848              classbits[1] &= ~0x08;   /* Perl 5.004 onwards omits VT from \s */              classbits[1] |= cbits[cbit_space+1] & ~0x08;
3849                for (c = 2; c < 32; c++) classbits[c] |= cbits[c+cbit_space];
3850              continue;              continue;
3851    
3852              case ESC_S:              case ESC_S:
3853              should_flip_negation = TRUE;              should_flip_negation = TRUE;
3854              for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_space];              for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_space];
3855              classbits[1] |= 0x08;    /* Perl 5.004 onwards omits VT from \s */              classbits[1] |= 0x08;    /* Perl 5.004 onwards omits VT from \s */
3856              continue;              continue;
3857    
3858              case ESC_E: /* Perl ignores an orphan \E */              case ESC_h:
             continue;  
   
             default:    /* Not recognized; fall through */  
             break;      /* Need "default" setting to stop compiler warning. */  
             }  
   
           /* In the pre-compile phase, just do the recognition. */  
   
           else if (c == -ESC_d || c == -ESC_D || c == -ESC_w ||  
                    c == -ESC_W || c == -ESC_s || c == -ESC_S) continue;  
   
           /* We need to deal with \H, \h, \V, and \v in both phases because  
           they use extra memory. */  
   
           if (-c == ESC_h)  
             {  
3859              SETBIT(classbits, 0x09); /* VT */              SETBIT(classbits, 0x09); /* VT */
3860              SETBIT(classbits, 0x20); /* SPACE */              SETBIT(classbits, 0x20); /* SPACE */
3861              SETBIT(classbits, 0xa0); /* NSBP */              SETBIT(classbits, 0xa0); /* NSBP */
# Line 2876  for (;; ptr++) Line 3879  for (;; ptr++)
3879                }                }
3880  #endif  #endif
3881              continue;              continue;
             }  
3882    
3883            if (-c == ESC_H)              case ESC_H:
             {  
3884              for (c = 0; c < 32; c++)              for (c = 0; c < 32; c++)
3885                {                {
3886                int x = 0xff;                int x = 0xff;
# Line 2921  for (;; ptr++) Line 3922  for (;; ptr++)
3922                }                }
3923  #endif  #endif
3924              continue;              continue;
             }  
3925    
3926            if (-c == ESC_v)              case ESC_v:
             {  
3927              SETBIT(classbits, 0x0a); /* LF */              SETBIT(classbits, 0x0a); /* LF */
3928              SETBIT(classbits, 0x0b); /* VT */              SETBIT(classbits, 0x0b); /* VT */
3929              SETBIT(classbits, 0x0c); /* FF */              SETBIT(classbits, 0x0c); /* FF */
# Line 2940  for (;; ptr++) Line 3939  for (;; ptr++)
3939                }                }
3940  #endif  #endif
3941              continue;              continue;
             }  
3942    
3943            if (-c == ESC_V)              case ESC_V:
             {  
3944              for (c = 0; c < 32; c++)              for (c = 0; c < 32; c++)
3945                {                {
3946                int x = 0xff;                int x = 0xff;
# Line 2973  for (;; ptr++) Line 3970  for (;; ptr++)
3970                }                }
3971  #endif  #endif
3972              continue;              continue;
             }  
   
           /* We need to deal with \P and \p in both phases. */  
3973    
3974  #ifdef SUPPORT_UCP  #ifdef SUPPORT_UCP
3975            if (-c == ESC_p || -c == ESC_P)              case ESC_p:
3976              {              case ESC_P:
3977              BOOL negated;                {
3978              int pdata;                BOOL negated;
3979              int ptype = get_ucp(&ptr, &negated, &pdata, errorcodeptr);                int pdata;
3980              if (ptype < 0) goto FAILED;                int ptype = get_ucp(&ptr, &negated, &pdata, errorcodeptr);
3981              class_utf8 = TRUE;                if (ptype < 0) goto FAILED;
3982              *class_utf8data++ = ((-c == ESC_p) != negated)?                class_utf8 = TRUE;
3983                XCL_PROP : XCL_NOTPROP;                *class_utf8data++ = ((-c == ESC_p) != negated)?
3984              *class_utf8data++ = ptype;                  XCL_PROP : XCL_NOTPROP;
3985              *class_utf8data++ = pdata;                *class_utf8data++ = ptype;
3986              class_charcount -= 2;   /* Not a < 256 character */                *class_utf8data++ = pdata;
3987              continue;                class_charcount -= 2;   /* Not a < 256 character */
3988              }                continue;
3989                  }
3990  #endif  #endif
3991            /* Unrecognized escapes are faulted if PCRE is running in its              /* Unrecognized escapes are faulted if PCRE is running in its
3992            strict mode. By default, for compatibility with Perl, they are              strict mode. By default, for compatibility with Perl, they are
3993            treated as literals. */              treated as literals. */
3994    
3995            if ((options & PCRE_EXTRA) != 0)              default:
3996              {              if ((options & PCRE_EXTRA) != 0)
3997              *errorcodeptr = ERR7;                {
3998              goto FAILED;                *errorcodeptr = ERR7;
3999                  goto FAILED;
4000                  }
4001                class_charcount -= 2;  /* Undo the default count from above */
4002                c = *ptr;              /* Get the final character and fall through */
4003                break;
4004              }              }
   
           class_charcount -= 2;  /* Undo the default count from above */  
           c = *ptr;              /* Get the final character and fall through */  
4005            }            }
4006    
4007          /* Fall through if we have a single character (c >= 0). This may be          /* Fall through if we have a single character (c >= 0). This may be
# Line 3018  for (;; ptr++) Line 4015  for (;; ptr++)
4015        entirely. The code for handling \Q and \E is messy. */        entirely. The code for handling \Q and \E is messy. */
4016    
4017        CHECK_RANGE:        CHECK_RANGE:
4018        while (ptr[1] == '\\' && ptr[2] == 'E')        while (ptr[1] == CHAR_BACKSLASH && ptr[2] == CHAR_E)
4019          {          {
4020          inescq = FALSE;          inescq = FALSE;
4021          ptr += 2;          ptr += 2;
# Line 3028  for (;; ptr++) Line 4025  for (;; ptr++)
4025    
4026        /* Remember \r or \n */        /* Remember \r or \n */
4027    
4028        if (c == '\r' || c == '\n') cd->external_flags |= PCRE_HASCRORLF;        if (c == CHAR_CR || c == CHAR_NL) cd->external_flags |= PCRE_HASCRORLF;
4029    
4030        /* Check for range */        /* Check for range */
4031    
4032        if (!inescq && ptr[1] == '-')        if (!inescq && ptr[1] == CHAR_MINUS)
4033          {          {
4034          int d;          int d;
4035          ptr += 2;          ptr += 2;
4036          while (*ptr == '\\' && ptr[1] == 'E') ptr += 2;          while (*ptr == CHAR_BACKSLASH && ptr[1] == CHAR_E) ptr += 2;
4037    
4038          /* If we hit \Q (not followed by \E) at this point, go into escaped          /* If we hit \Q (not followed by \E) at this point, go into escaped
4039          mode. */          mode. */
4040    
4041          while (*ptr == '\\' && ptr[1] == 'Q')          while (*ptr == CHAR_BACKSLASH && ptr[1] == CHAR_Q)
4042            {            {
4043            ptr += 2;            ptr += 2;
4044            if (*ptr == '\\' && ptr[1] == 'E') { ptr += 2; continue; }            if (*ptr == CHAR_BACKSLASH && ptr[1] == CHAR_E)
4045                { ptr += 2; continue; }
4046            inescq = TRUE;            inescq = TRUE;
4047            break;            break;
4048            }            }
4049    
4050          if (*ptr == 0 || (!inescq && *ptr == ']'))          if (*ptr == 0 || (!inescq && *ptr == CHAR_RIGHT_SQUARE_BRACKET))
4051            {            {
4052            ptr = oldptr;            ptr = oldptr;
4053            goto LONE_SINGLE_CHARACTER;            goto LONE_SINGLE_CHARACTER;
# Line 3068  for (;; ptr++) Line 4066  for (;; ptr++)
4066          not any of the other escapes. Perl 5.6 treats a hyphen as a literal          not any of the other escapes. Perl 5.6 treats a hyphen as a literal
4067          in such circumstances. */          in such circumstances. */
4068    
4069          if (!inescq && d == '\\')          if (!inescq && d == CHAR_BACKSLASH)
4070            {            {
4071            d = check_escape(&ptr, errorcodeptr, cd->bracount, options, TRUE);            d = check_escape(&ptr, errorcodeptr, cd->bracount, options, TRUE);
4072            if (*errorcodeptr != 0) goto FAILED;            if (*errorcodeptr != 0) goto FAILED;
4073    
4074            /* \b is backslash; \X is literal X; \R is literal R; any other            /* \b is backspace; any other special means the '-' was literal */
           special means the '-' was literal */  
4075    
4076            if (d < 0)            if (d < 0)
4077              {              {
4078              if (d == -ESC_b) d = '\b';              if (d == -ESC_b) d = CHAR_BS; else
             else if (d == -ESC_X) d = 'X';  
             else if (d == -ESC_R) d = 'R'; else  
4079                {                {
4080                ptr = oldptr;                ptr = oldptr;
4081                goto LONE_SINGLE_CHARACTER;  /* A few lines below */                goto LONE_SINGLE_CHARACTER;  /* A few lines below */
# Line 3101  for (;; ptr++) Line 4096  for (;; ptr++)
4096    
4097          /* Remember \r or \n */          /* Remember \r or \n */
4098    
4099          if (d == '\r' || d == '\n') cd->external_flags |= PCRE_HASCRORLF;          if (d == CHAR_CR || d == CHAR_NL) cd->external_flags |= PCRE_HASCRORLF;
4100    
4101          /* 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
4102          matching, we have to use an XCLASS with extra data items. Caseless          matching, we have to use an XCLASS with extra data items. Caseless
# Line 3221  for (;; ptr++) Line 4216  for (;; ptr++)
4216          if ((options & PCRE_CASELESS) != 0)          if ((options & PCRE_CASELESS) != 0)
4217            {            {
4218            unsigned int othercase;            unsigned int othercase;
4219            if ((othercase = _pcre_ucp_othercase(c)) != NOTACHAR)            if ((othercase = UCD_OTHERCASE(c)) != c)
4220              {              {
4221              *class_utf8data++ = XCL_SINGLE;              *class_utf8data++ = XCL_SINGLE;
4222              class_utf8data += _pcre_ord2utf8(othercase, class_utf8data);              class_utf8data += _pcre_ord2utf8(othercase, class_utf8data);
# Line 3246  for (;; ptr++) Line 4241  for (;; ptr++)
4241          }          }
4242        }        }
4243    
4244      /* Loop until ']' reached. This "while" is the end of the "do" above. */      /* Loop until ']' reached. This "while" is the end of the "do" far above.
4245        If we are at the end of an internal nested string, revert to the outer
4246        string. */
4247    
4248        while (((c = *(++ptr)) != 0 ||
4249               (nestptr != NULL &&
4250                 (ptr = nestptr, nestptr = NULL, c = *(++ptr)) != 0)) &&
4251               (c != CHAR_RIGHT_SQUARE_BRACKET || inescq));
4252    
4253      while ((c = *(++ptr)) != 0 && (c != ']' || inescq));      /* Check for missing terminating ']' */
4254    
4255      if (c == 0)                          /* Missing terminating ']' */      if (c == 0)
4256        {        {
4257        *errorcodeptr = ERR6;        *errorcodeptr = ERR6;
4258        goto FAILED;        goto FAILED;
4259        }        }
4260    
   
 /* This code has been disabled because it would mean that \s counts as  
 an explicit \r or \n reference, and that's not really what is wanted. Now  
 we set the flag only if there is a literal "\r" or "\n" in the class. */  
   
 #if 0  
     /* Remember whether \r or \n are in this class */  
   
     if (negate_class)  
       {  
       if ((classbits[1] & 0x24) != 0x24) cd->external_flags |= PCRE_HASCRORLF;  
       }  
     else  
       {  
       if ((classbits[1] & 0x24) != 0) cd->external_flags |= PCRE_HASCRORLF;  
       }  
 #endif  
   
   
4261      /* 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
4262      less than 256. As long as there were no characters >= 128 and there was no      less than 256. As long as there were no characters >= 128 and there was no
4263      use of \p or \P, in other words, no use of any XCLASS features, we can      use of \p or \P, in other words, no use of any XCLASS features, we can
# Line 3282  we set the flag only if there is a liter Line 4265  we set the flag only if there is a liter
4265    
4266      In UTF-8 mode, we can optimize the negative case only if there were no      In UTF-8 mode, we can optimize the negative case only if there were no
4267      characters >= 128 because OP_NOT and the related opcodes like OP_NOTSTAR      characters >= 128 because OP_NOT and the related opcodes like OP_NOTSTAR
4268      operate on single-bytes only. This is an historical hangover. Maybe one day      operate on single-bytes characters only. This is an historical hangover.
4269      we can tidy these opcodes to handle multi-byte characters.      Maybe one day we can tidy these opcodes to handle multi-byte characters.
4270    
4271      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
4272      1-character OP_CHAR[NC] if it's positive, or OP_NOT if it's negative. Note      1-character OP_CHAR[I] if it's positive, or OP_NOT[I] if it's negative.
4273      that OP_NOT does not support multibyte characters. In the positive case, it      Note that OP_NOT[I] does not support multibyte characters. In the positive
4274      can cause firstbyte to be set. Otherwise, there can be no first char if      case, it can cause firstbyte to be set. Otherwise, there can be no first
4275      this item is first, whatever repeat count may follow. In the case of      char if this item is first, whatever repeat count may follow. In the case
4276      reqbyte, save the previous value for reinstating. */      of reqbyte, save the previous value for reinstating. */
4277    
4278  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF8
4279      if (class_charcount == 1 && !class_utf8 &&      if (class_charcount == 1 && !class_utf8 &&
# Line 3301  we set the flag only if there is a liter Line 4284  we set the flag only if there is a liter
4284        {        {
4285        zeroreqbyte = reqbyte;        zeroreqbyte = reqbyte;
4286    
4287        /* The OP_NOT opcode works on one-byte characters only. */        /* The OP_NOT[I] opcodes work on one-byte characters only. */
4288    
4289        if (negate_class)        if (negate_class)
4290          {          {
4291          if (firstbyte == REQ_UNSET) firstbyte = REQ_NONE;          if (firstbyte == REQ_UNSET) firstbyte = REQ_NONE;
4292          zerofirstbyte = firstbyte;          zerofirstbyte = firstbyte;
4293          *code++ = OP_NOT;          *code++ = ((options & PCRE_CASELESS) != 0)? OP_NOTI: OP_NOT;
4294          *code++ = class_lastchar;          *code++ = class_lastchar;
4295          break;          break;
4296          }          }
# Line 3337  we set the flag only if there is a liter Line 4320  we set the flag only if there is a liter
4320      zeroreqbyte = reqbyte;      zeroreqbyte = reqbyte;
4321    
4322      /* If there are characters with values > 255, we have to compile an      /* If there are characters with values > 255, we have to compile an
4323      extended class, with its own opcode, unless there was a negated special      extended class, with its own opcode, unless there was a negated special
4324      such as \S in the class, because in that case all characters > 255 are in      such as \S in the class, and PCRE_UCP is not set, because in that case all
4325      the class, so any that were explicitly given as well can be ignored. If      characters > 255 are in the class, so any that were explicitly given as
4326      (when there are explicit characters > 255 that must be listed) there are no      well can be ignored. If (when there are explicit characters > 255 that must
4327      characters < 256, we can omit the bitmap in the actual compiled code. */      be listed) there are no characters < 256, we can omit the bitmap in the
4328        actual compiled code. */
4329    
4330  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF8
4331      if (class_utf8 && !should_flip_negation)      if (class_utf8 && (!should_flip_negation || (options & PCRE_UCP) != 0))
4332        {        {
4333        *class_utf8data++ = XCL_END;    /* Marks the end of extra data */        *class_utf8data++ = XCL_END;    /* Marks the end of extra data */
4334        *code++ = OP_XCLASS;        *code++ = OP_XCLASS;
# Line 3370  we set the flag only if there is a liter Line 4354  we set the flag only if there is a liter
4354        }        }
4355  #endif  #endif
4356    
4357      /* If there are no characters > 255, set the opcode to OP_CLASS or      /* If there are no characters > 255, or they are all to be included or
4358      OP_NCLASS, depending on whether the whole class was negated and whether      excluded, set the opcode to OP_CLASS or OP_NCLASS, depending on whether the
4359      there were negative specials such as \S in the class. Then copy the 32-byte      whole class was negated and whether there were negative specials such as \S
4360      map into the code vector, negating it if necessary. */      (non-UCP) in the class. Then copy the 32-byte map into the code vector,
4361        negating it if necessary. */
4362    
4363      *code++ = (negate_class == should_flip_negation) ? OP_CLASS : OP_NCLASS;      *code++ = (negate_class == should_flip_negation) ? OP_CLASS : OP_NCLASS;
4364      if (negate_class)      if (negate_class)
4365        {        {
# Line 3393  we set the flag only if there is a liter Line 4378  we set the flag only if there is a liter
4378      /* Various kinds of repeat; '{' is not necessarily a quantifier, but this      /* Various kinds of repeat; '{' is not necessarily a quantifier, but this
4379      has been tested above. */      has been tested above. */
4380    
4381      case '{':      case CHAR_LEFT_CURLY_BRACKET:
4382      if (!is_quantifier) goto NORMAL_CHAR;      if (!is_quantifier) goto NORMAL_CHAR;
4383      ptr = read_repeat_counts(ptr+1, &repeat_min, &repeat_max, errorcodeptr);      ptr = read_repeat_counts(ptr+1, &repeat_min, &repeat_max, errorcodeptr);
4384      if (*errorcodeptr != 0) goto FAILED;      if (*errorcodeptr != 0) goto FAILED;
4385      goto REPEAT;      goto REPEAT;
4386    
4387      case '*':      case CHAR_ASTERISK:
4388      repeat_min = 0;      repeat_min = 0;
4389      repeat_max = -1;      repeat_max = -1;
4390      goto REPEAT;      goto REPEAT;
4391    
4392      case '+':      case CHAR_PLUS:
4393      repeat_min = 1;      repeat_min = 1;
4394      repeat_max = -1;      repeat_max = -1;
4395      goto REPEAT;      goto REPEAT;
4396    
4397      case '?':      case CHAR_QUESTION_MARK:
4398      repeat_min = 0;      repeat_min = 0;
4399      repeat_max = 1;      repeat_max = 1;
4400    
# Line 3433  we set the flag only if there is a liter Line 4418  we set the flag only if there is a liter
4418      op_type = 0;                    /* Default single-char op codes */      op_type = 0;                    /* Default single-char op codes */
4419      possessive_quantifier = FALSE;  /* Default not possessive quantifier */      possessive_quantifier = FALSE;  /* Default not possessive quantifier */
4420    
4421      /* Save start of previous item, in case we have to move it up to make space      /* Save start of previous item, in case we have to move it up in order to
4422      for an inserted OP_ONCE for the additional '+' extension. */      insert something before it. */
4423    
4424      tempcode = previous;      tempcode = previous;
4425    
# Line 3444  we set the flag only if there is a liter Line 4429  we set the flag only if there is a liter
4429      but if PCRE_UNGREEDY is set, it works the other way round. We change the      but if PCRE_UNGREEDY is set, it works the other way round. We change the
4430      repeat type to the non-default. */      repeat type to the non-default. */
4431    
4432      if (ptr[1] == '+')      if (ptr[1] == CHAR_PLUS)
4433        {        {
4434        repeat_type = 0;                  /* Force greedy */        repeat_type = 0;                  /* Force greedy */
4435        possessive_quantifier = TRUE;        possessive_quantifier = TRUE;
4436        ptr++;        ptr++;
4437        }        }
4438      else if (ptr[1] == '?')      else if (ptr[1] == CHAR_QUESTION_MARK)
4439        {        {
4440        repeat_type = greedy_non_default;        repeat_type = greedy_non_default;
4441        ptr++;        ptr++;
4442        }        }
4443      else repeat_type = greedy_default;      else repeat_type = greedy_default;
4444    
4445        /* If previous was a recursion call, wrap it in atomic brackets so that
4446        previous becomes the atomic group. All recursions were so wrapped in the
4447        past, but it no longer happens for non-repeated recursions. In fact, the
4448        repeated ones could be re-implemented independently so as not to need this,
4449        but for the moment we rely on the code for repeating groups. */
4450    
4451        if (*previous == OP_RECURSE)
4452          {
4453          memmove(previous + 1 + LINK_SIZE, previous, 1 + LINK_SIZE);
4454          *previous = OP_ONCE;
4455          PUT(previous, 1, 2 + 2*LINK_SIZE);
4456          previous[2 + 2*LINK_SIZE] = OP_KET;
4457          PUT(previous, 3 + 2*LINK_SIZE, 2 + 2*LINK_SIZE);
4458          code += 2 + 2 * LINK_SIZE;
4459          length_prevgroup = 3 + 3*LINK_SIZE;
4460    
4461          /* When actually compiling, we need to check whether this was a forward
4462          reference, and if so, adjust the offset. */
4463    
4464          if (lengthptr == NULL && cd->hwm >= cd->start_workspace + LINK_SIZE)
4465            {
4466            int offset = GET(cd->hwm, -LINK_SIZE);
4467            if (offset == previous + 1 - cd->start_code)
4468              PUT(cd->hwm, -LINK_SIZE, offset + 1 + LINK_SIZE);
4469            }
4470          }
4471    
4472        /* Now handle repetition for the different types of item. */
4473    
4474      /* If previous was a character match, abolish the item and generate a      /* If previous was a character match, abolish the item and generate a
4475      repeat item instead. If a char item has a minumum of more than one, ensure      repeat item instead. If a char item has a minumum of more than one, ensure
4476      that it is set in reqbyte - it might not be if a sequence such as x{3} is      that it is set in reqbyte - it might not be if a sequence such as x{3} is
4477      the first thing in a branch because the x will have gone into firstbyte      the first thing in a branch because the x will have gone into firstbyte
4478      instead.  */      instead.  */
4479    
4480      if (*previous == OP_CHAR || *previous == OP_CHARNC)      if (*previous == OP_CHAR || *previous == OP_CHARI)
4481        {        {
4482          op_type = (*previous == OP_CHAR)? 0 : OP_STARI - OP_STAR;
4483    
4484        /* Deal with UTF-8 characters that take up more than one byte. It's        /* Deal with UTF-8 characters that take up more than one byte. It's
4485        easier to write this out separately than try to macrify it. Use c to        easier to write this out separately than try to macrify it. Use c to
4486        hold the length of the character in bytes, plus 0x80 to flag that it's a        hold the length o