/[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 85 by nigel, Sat Feb 24 21:41:13 2007 UTC code/branches/pcre16/pcre_compile.c revision 786 by zherczeg, Tue Dec 6 11:33:41 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-2005 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 42  POSSIBILITY OF SUCH DAMAGE. Line 42  POSSIBILITY OF SUCH DAMAGE.
42  supporting internal functions that are not used by other modules. */  supporting internal functions that are not used by other modules. */
43    
44    
45    #ifdef HAVE_CONFIG_H
46    #include "config.h"
47    #endif
48    
49    #define NLBLOCK cd             /* Block containing newline information */
50    #define PSSTART start_pattern  /* Field containing processed string start */
51    #define PSEND   end_pattern    /* Field containing processed string end */
52    
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    
64    
65    /* Macro for setting individual bits in class bitmaps. */
66    
67    #define SETBIT(a,b) a[b/8] |= (1 << (b%8))
68    
69    /* Maximum length value to check against when making sure that the integer that
70    holds the compiled pattern length does not overflow. We make it a bit less than
71    INT_MAX to allow for adding in group terminating bytes, so that we don't have
72    to check them every time. */
73    
74    #define OFLOW_MAX (INT_MAX - 20)
75    
76    
77  /*************************************************  /*************************************************
78  *      Code parameters and static tables         *  *      Code parameters and static tables         *
79  *************************************************/  *************************************************/
80    
81  /* Maximum number of items on the nested bracket stacks at compile time. This  /* This value specifies the size of stack workspace that is used during the
82  applies to the nesting of all kinds of parentheses. It does not limit  first pre-compile phase that determines how much memory is required. The regex
83  un-nested, non-capturing parentheses. This number can be made bigger if  is partly compiled into this space, but the compiled parts are discarded as
84  necessary - it is used to dimension one int and one unsigned char vector at  soon as they can be, so that hopefully there will never be an overrun. The code
85  compile time. */  does, however, check for an overrun. The largest amount I've seen used is 218,
86    so this number is very generous.
87    
88    The same workspace is used during the second, actual compile phase for
89    remembering forward references to groups so that they can be filled in at the
90    end. Each entry in this list occupies LINK_SIZE bytes, so even when LINK_SIZE
91    is 4 there is plenty of room. */
92    
93  #define BRASTACK_SIZE 200  #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    /* Private flags added to firstchar and reqchar. */
101    
102    #define REQ_CASELESS   0x10000000l      /* Indicates caselessness */
103    #define REQ_VARY       0x20000000l      /* Reqchar followed non-literal item */
104    
105    /* Repeated character flags. */
106    
107    #define UTF_LENGTH     0x10000000l      /* The char contains its length. */
108    
109  /* Table for handling escaped characters in the range '0'-'z'. Positive returns  /* Table for handling escaped characters in the range '0'-'z'. Positive returns
110  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
111  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
112  is invalid. */  is invalid. */
113    
114  #if !EBCDIC   /* This is the "normal" table for ASCII systems */  #ifndef EBCDIC
115    
116    /* This is the "normal" table for ASCII systems or for EBCDIC systems running
117    in UTF-8 mode. */
118    
119  static const short int escapes[] = {  static const short int escapes[] = {
120       0,      0,      0,      0,      0,      0,      0,      0,   /* 0 - 7 */       0,                       0,
121       0,      0,    ':',    ';',    '<',    '=',    '>',    '?',   /* 8 - ? */       0,                       0,
122     '@', -ESC_A, -ESC_B, -ESC_C, -ESC_D, -ESC_E,      0, -ESC_G,   /* @ - G */       0,                       0,
123       0,      0,      0,      0,      0,      0,      0,      0,   /* H - O */       0,                       0,
124  -ESC_P, -ESC_Q,      0, -ESC_S,      0,      0,      0, -ESC_W,   /* P - W */       0,                       0,
125  -ESC_X,      0, -ESC_Z,    '[',   '\\',    ']',    '^',    '_',   /* X - _ */       CHAR_COLON,              CHAR_SEMICOLON,
126     '`',      7, -ESC_b,      0, -ESC_d,  ESC_e,  ESC_f,      0,   /* ` - g */       CHAR_LESS_THAN_SIGN,     CHAR_EQUALS_SIGN,
127       0,      0,      0,      0,      0,      0,  ESC_n,      0,   /* h - o */       CHAR_GREATER_THAN_SIGN,  CHAR_QUESTION_MARK,
128  -ESC_p,      0,  ESC_r, -ESC_s,  ESC_tee,    0,      0, -ESC_w,   /* p - w */       CHAR_COMMERCIAL_AT,      -ESC_A,
129       0,      0, -ESC_z                                            /* x - z */       -ESC_B,                  -ESC_C,
130         -ESC_D,                  -ESC_E,
131         0,                       -ESC_G,
132         -ESC_H,                  0,
133         0,                       -ESC_K,
134         0,                       0,
135         -ESC_N,                  0,
136         -ESC_P,                  -ESC_Q,
137         -ESC_R,                  -ESC_S,
138         0,                       0,
139         -ESC_V,                  -ESC_W,
140         -ESC_X,                  0,
141         -ESC_Z,                  CHAR_LEFT_SQUARE_BRACKET,
142         CHAR_BACKSLASH,          CHAR_RIGHT_SQUARE_BRACKET,
143         CHAR_CIRCUMFLEX_ACCENT,  CHAR_UNDERSCORE,
144         CHAR_GRAVE_ACCENT,       7,
145         -ESC_b,                  0,
146         -ESC_d,                  ESC_e,
147         ESC_f,                   0,
148         -ESC_h,                  0,
149         0,                       -ESC_k,
150         0,                       0,
151         ESC_n,                   0,
152         -ESC_p,                  0,
153         ESC_r,                   -ESC_s,
154         ESC_tee,                 0,
155         -ESC_v,                  -ESC_w,
156         0,                       0,
157         -ESC_z
158  };  };
159    
160  #else         /* This is the "abnormal" table for EBCDIC systems */  #else
161    
162    /* This is the "abnormal" table for EBCDIC systems without UTF-8 support. */
163    
164  static const short int escapes[] = {  static const short int escapes[] = {
165  /*  48 */     0,     0,      0,     '.',    '<',   '(',    '+',    '|',  /*  48 */     0,     0,      0,     '.',    '<',   '(',    '+',    '|',
166  /*  50 */   '&',     0,      0,       0,      0,     0,      0,      0,  /*  50 */   '&',     0,      0,       0,      0,     0,      0,      0,
# Line 96  static const short int escapes[] = { Line 170  static const short int escapes[] = {
170  /*  70 */     0,     0,      0,       0,      0,     0,      0,      0,  /*  70 */     0,     0,      0,       0,      0,     0,      0,      0,
171  /*  78 */     0,   '`',    ':',     '#',    '@',  '\'',    '=',    '"',  /*  78 */     0,   '`',    ':',     '#',    '@',  '\'',    '=',    '"',
172  /*  80 */     0,     7, -ESC_b,       0, -ESC_d, ESC_e,  ESC_f,      0,  /*  80 */     0,     7, -ESC_b,       0, -ESC_d, ESC_e,  ESC_f,      0,
173  /*  88 */     0,     0,      0,     '{',      0,     0,      0,      0,  /*  88 */-ESC_h,     0,      0,     '{',      0,     0,      0,      0,
174  /*  90 */     0,     0,      0,     'l',      0, ESC_n,      0, -ESC_p,  /*  90 */     0,     0, -ESC_k,     'l',      0, ESC_n,      0, -ESC_p,
175  /*  98 */     0, ESC_r,      0,     '}',      0,     0,      0,      0,  /*  98 */     0, ESC_r,      0,     '}',      0,     0,      0,      0,
176  /*  A0 */     0,   '~', -ESC_s, ESC_tee,      0,     0, -ESC_w,      0,  /*  A0 */     0,   '~', -ESC_s, ESC_tee,      0,-ESC_v, -ESC_w,      0,
177  /*  A8 */     0,-ESC_z,      0,       0,      0,   '[',      0,      0,  /*  A8 */     0,-ESC_z,      0,       0,      0,   '[',      0,      0,
178  /*  B0 */     0,     0,      0,       0,      0,     0,      0,      0,  /*  B0 */     0,     0,      0,       0,      0,     0,      0,      0,
179  /*  B8 */     0,     0,      0,       0,      0,   ']',    '=',    '-',  /*  B8 */     0,     0,      0,       0,      0,   ']',    '=',    '-',
180  /*  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,
181  /*  C8 */     0,     0,      0,       0,      0,     0,      0,      0,  /*  C8 */-ESC_H,     0,      0,       0,      0,     0,      0,      0,
182  /*  D0 */   '}',     0,      0,       0,      0,     0,      0, -ESC_P,  /*  D0 */   '}',     0, -ESC_K,       0,      0,-ESC_N,      0, -ESC_P,
183  /*  D8 */-ESC_Q,     0,      0,       0,      0,     0,      0,      0,  /*  D8 */-ESC_Q,-ESC_R,      0,       0,      0,     0,      0,      0,
184  /*  E0 */  '\\',     0, -ESC_S,       0,      0,     0, -ESC_W, -ESC_X,  /*  E0 */  '\\',     0, -ESC_S,       0,      0,-ESC_V, -ESC_W, -ESC_X,
185  /*  E8 */     0,-ESC_Z,      0,       0,      0,     0,      0,      0,  /*  E8 */     0,-ESC_Z,      0,       0,      0,     0,      0,      0,
186  /*  F0 */     0,     0,      0,       0,      0,     0,      0,      0,  /*  F0 */     0,     0,      0,       0,      0,     0,      0,      0,
187  /*  F8 */     0,     0,      0,       0,      0,     0,      0,      0  /*  F8 */     0,     0,      0,       0,      0,     0,      0,      0
# Line 115  static const short int escapes[] = { Line 189  static const short int escapes[] = {
189  #endif  #endif
190    
191    
192  /* Tables of names of POSIX character classes and their lengths. The list is  /* Table of special "verbs" like (*PRUNE). This is a short table, so it is
193  terminated by a zero length entry. The first three must be alpha, upper, lower,  searched linearly. Put all the names into a single string, in order to reduce
194  as this is assumed for handling case independence. */  the number of relocations when a shared library is dynamically linked. The
195    string is built from string macros so that it works in UTF-8 mode on EBCDIC
196  static const char *const posix_names[] = {  platforms. */
197    "alpha", "lower", "upper",  
198    "alnum", "ascii", "blank", "cntrl", "digit", "graph",  typedef struct verbitem {
199    "print", "punct", "space", "word",  "xdigit" };    int   len;                 /* Length of verb name */
200      int   op;                  /* Op when no arg, or -1 if arg mandatory */
201      int   op_arg;              /* Op when arg present, or -1 if not allowed */
202    } verbitem;
203    
204    static const char verbnames[] =
205      "\0"                       /* Empty name is a shorthand for MARK */
206      STRING_MARK0
207      STRING_ACCEPT0
208      STRING_COMMIT0
209      STRING_F0
210      STRING_FAIL0
211      STRING_PRUNE0
212      STRING_SKIP0
213      STRING_THEN;
214    
215    static const verbitem verbs[] = {
216      { 0, -1,        OP_MARK },
217      { 4, -1,        OP_MARK },
218      { 6, OP_ACCEPT, -1 },
219      { 6, OP_COMMIT, -1 },
220      { 1, OP_FAIL,   -1 },
221      { 4, OP_FAIL,   -1 },
222      { 5, OP_PRUNE,  OP_PRUNE_ARG },
223      { 4, OP_SKIP,   OP_SKIP_ARG  },
224      { 4, OP_THEN,   OP_THEN_ARG  }
225    };
226    
227    static const int verbcount = sizeof(verbs)/sizeof(verbitem);
228    
229    
230    /* Tables of names of POSIX character classes and their lengths. The names are
231    now all in a single string, to reduce the number of relocations when a shared
232    library is dynamically loaded. The list of lengths is terminated by a zero
233    length entry. The first three must be alpha, lower, upper, as this is assumed
234    for handling case independence. */
235    
236    static const char posix_names[] =
237      STRING_alpha0 STRING_lower0 STRING_upper0 STRING_alnum0
238      STRING_ascii0 STRING_blank0 STRING_cntrl0 STRING_digit0
239      STRING_graph0 STRING_print0 STRING_punct0 STRING_space0
240      STRING_word0  STRING_xdigit;
241    
242  static const uschar posix_name_lengths[] = {  static const pcre_uint8 posix_name_lengths[] = {
243    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 };
244    
245  /* Table of class bit maps for each POSIX class; up to three may be combined  /* Table of class bit maps for each POSIX class. Each class is formed from a
246  to form the class. The table for [:blank:] is dynamically modified to remove  base map, with an optional addition or removal of another map. Then, for some
247  the vertical space characters. */  classes, there is some additional tweaking: for [:blank:] the vertical space
248    characters are removed, and for [:alpha:] and [:alnum:] the underscore
249    character is removed. The triples in the table consist of the base map offset,
250    second map offset or -1 if no second map, and a non-negative value for map
251    addition or a negative value for map subtraction (if there are two maps). The
252    absolute value of the third field has these meanings: 0 => no tweaking, 1 =>
253    remove vertical space characters, 2 => remove underscore. */
254    
255  static const int posix_class_maps[] = {  static const int posix_class_maps[] = {
256    cbit_lower, cbit_upper, -1,             /* alpha */    cbit_word,  cbit_digit, -2,             /* alpha */
257    cbit_lower, -1,         -1,             /* lower */    cbit_lower, -1,          0,             /* lower */
258    cbit_upper, -1,         -1,             /* upper */    cbit_upper, -1,          0,             /* upper */
259    cbit_digit, cbit_lower, cbit_upper,     /* alnum */    cbit_word,  -1,          2,             /* alnum - word without underscore */
260    cbit_print, cbit_cntrl, -1,             /* ascii */    cbit_print, cbit_cntrl,  0,             /* ascii */
261    cbit_space, -1,         -1,             /* blank - a GNU extension */    cbit_space, -1,          1,             /* blank - a GNU extension */
262    cbit_cntrl, -1,         -1,             /* cntrl */    cbit_cntrl, -1,          0,             /* cntrl */
263    cbit_digit, -1,         -1,             /* digit */    cbit_digit, -1,          0,             /* digit */
264    cbit_graph, -1,         -1,             /* graph */    cbit_graph, -1,          0,             /* graph */
265    cbit_print, -1,         -1,             /* print */    cbit_print, -1,          0,             /* print */
266    cbit_punct, -1,         -1,             /* punct */    cbit_punct, -1,          0,             /* punct */
267    cbit_space, -1,         -1,             /* space */    cbit_space, -1,          0,             /* space */
268    cbit_word,  -1,         -1,             /* word - a Perl extension */    cbit_word,  -1,          0,             /* word - a Perl extension */
269    cbit_xdigit,-1,         -1              /* xdigit */    cbit_xdigit,-1,          0              /* xdigit */
270  };  };
271    
272    /* Table of substitutes for \d etc when PCRE_UCP is set. The POSIX class
273    substitutes must be in the order of the names, defined above, and there are
274    both positive and negative cases. NULL means no substitute. */
275    
276  /* The texts of compile-time error messages. These are "char *" because they  #ifdef SUPPORT_UCP
277  are passed to the outside world. */  static const pcre_uchar string_PNd[]  = {
278      CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET,
279      CHAR_N, CHAR_d, CHAR_RIGHT_CURLY_BRACKET, '\0' };
280    static const pcre_uchar string_pNd[]  = {
281      CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET,
282      CHAR_N, CHAR_d, CHAR_RIGHT_CURLY_BRACKET, '\0' };
283    static const pcre_uchar string_PXsp[] = {
284      CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET,
285      CHAR_X, CHAR_s, CHAR_p, CHAR_RIGHT_CURLY_BRACKET, '\0' };
286    static const pcre_uchar string_pXsp[] = {
287      CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET,
288      CHAR_X, CHAR_s, CHAR_p, CHAR_RIGHT_CURLY_BRACKET, '\0' };
289    static const pcre_uchar string_PXwd[] = {
290      CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET,
291      CHAR_X, CHAR_w, CHAR_d, CHAR_RIGHT_CURLY_BRACKET, '\0' };
292    static const pcre_uchar string_pXwd[] = {
293      CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET,
294      CHAR_X, CHAR_w, CHAR_d, CHAR_RIGHT_CURLY_BRACKET, '\0' };
295    
296    static const pcre_uchar *substitutes[] = {
297      string_PNd,           /* \D */
298      string_pNd,           /* \d */
299      string_PXsp,          /* \S */       /* NOTE: Xsp is Perl space */
300      string_pXsp,          /* \s */
301      string_PXwd,          /* \W */
302      string_pXwd           /* \w */
303    };
304    
305    static const pcre_uchar string_pL[] =   {
306      CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET,
307      CHAR_L, CHAR_RIGHT_CURLY_BRACKET, '\0' };
308    static const pcre_uchar string_pLl[] =  {
309      CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET,
310      CHAR_L, CHAR_l, CHAR_RIGHT_CURLY_BRACKET, '\0' };
311    static const pcre_uchar string_pLu[] =  {
312      CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET,
313      CHAR_L, CHAR_u, CHAR_RIGHT_CURLY_BRACKET, '\0' };
314    static const pcre_uchar string_pXan[] = {
315      CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET,
316      CHAR_X, CHAR_a, CHAR_n, CHAR_RIGHT_CURLY_BRACKET, '\0' };
317    static const pcre_uchar string_h[] =    {
318      CHAR_BACKSLASH, CHAR_h, '\0' };
319    static const pcre_uchar string_pXps[] = {
320      CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET,
321      CHAR_X, CHAR_p, CHAR_s, CHAR_RIGHT_CURLY_BRACKET, '\0' };
322    static const pcre_uchar string_PL[] =   {
323      CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET,
324      CHAR_L, CHAR_RIGHT_CURLY_BRACKET, '\0' };
325    static const pcre_uchar string_PLl[] =  {
326      CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET,
327      CHAR_L, CHAR_l, CHAR_RIGHT_CURLY_BRACKET, '\0' };
328    static const pcre_uchar string_PLu[] =  {
329      CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET,
330      CHAR_L, CHAR_u, CHAR_RIGHT_CURLY_BRACKET, '\0' };
331    static const pcre_uchar string_PXan[] = {
332      CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET,
333      CHAR_X, CHAR_a, CHAR_n, CHAR_RIGHT_CURLY_BRACKET, '\0' };
334    static const pcre_uchar string_H[] =    {
335      CHAR_BACKSLASH, CHAR_H, '\0' };
336    static const pcre_uchar string_PXps[] = {
337      CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET,
338      CHAR_X, CHAR_p, CHAR_s, CHAR_RIGHT_CURLY_BRACKET, '\0' };
339    
340    static const pcre_uchar *posix_substitutes[] = {
341      string_pL,            /* alpha */
342      string_pLl,           /* lower */
343      string_pLu,           /* upper */
344      string_pXan,          /* alnum */
345      NULL,                 /* ascii */
346      string_h,             /* blank */
347      NULL,                 /* cntrl */
348      string_pNd,           /* digit */
349      NULL,                 /* graph */
350      NULL,                 /* print */
351      NULL,                 /* punct */
352      string_pXps,          /* space */    /* NOTE: Xps is POSIX space */
353      string_pXwd,          /* word */
354      NULL,                 /* xdigit */
355      /* Negated cases */
356      string_PL,            /* ^alpha */
357      string_PLl,           /* ^lower */
358      string_PLu,           /* ^upper */
359      string_PXan,          /* ^alnum */
360      NULL,                 /* ^ascii */
361      string_H,             /* ^blank */
362      NULL,                 /* ^cntrl */
363      string_PNd,           /* ^digit */
364      NULL,                 /* ^graph */
365      NULL,                 /* ^print */
366      NULL,                 /* ^punct */
367      string_PXps,          /* ^space */   /* NOTE: Xps is POSIX space */
368      string_PXwd,          /* ^word */
369      NULL                  /* ^xdigit */
370    };
371    #define POSIX_SUBSIZE (sizeof(posix_substitutes) / sizeof(pcre_uchar *))
372    #endif
373    
374  static const char *error_texts[] = {  #define STRING(a)  # a
375    "no error",  #define XSTRING(s) STRING(s)
376    "\\ at end of pattern",  
377    "\\c at end of pattern",  /* The texts of compile-time error messages. These are "char *" because they
378    "unrecognized character follows \\",  are passed to the outside world. Do not ever re-use any error number, because
379    "numbers out of order in {} quantifier",  they are documented. Always add a new error instead. Messages marked DEAD below
380    are no longer used. This used to be a table of strings, but in order to reduce
381    the number of relocations needed when a shared library is loaded dynamically,
382    it is now one long string. We cannot use a table of offsets, because the
383    lengths of inserts such as XSTRING(MAX_NAME_SIZE) are not known. Instead, we
384    simply count through to the one we want - this isn't a performance issue
385    because these strings are used only when there is a compilation error.
386    
387    Each substring ends with \0 to insert a null character. This includes the final
388    substring, so that the whole string ends with \0\0, which can be detected when
389    counting through. */
390    
391    static const char error_texts[] =
392      "no error\0"
393      "\\ at end of pattern\0"
394      "\\c at end of pattern\0"
395      "unrecognized character follows \\\0"
396      "numbers out of order in {} quantifier\0"
397    /* 5 */    /* 5 */
398    "number too big in {} quantifier",    "number too big in {} quantifier\0"
399    "missing terminating ] for character class",    "missing terminating ] for character class\0"
400    "invalid escape sequence in character class",    "invalid escape sequence in character class\0"
401    "range out of order in character class",    "range out of order in character class\0"
402    "nothing to repeat",    "nothing to repeat\0"
403    /* 10 */    /* 10 */
404    "operand of unlimited repeat could match the empty string",    "operand of unlimited repeat could match the empty string\0"  /** DEAD **/
405    "internal error: unexpected repeat",    "internal error: unexpected repeat\0"
406    "unrecognized character after (?",    "unrecognized character after (? or (?-\0"
407    "POSIX named classes are supported only within a class",    "POSIX named classes are supported only within a class\0"
408    "missing )",    "missing )\0"
409    /* 15 */    /* 15 */
410    "reference to non-existent subpattern",    "reference to non-existent subpattern\0"
411    "erroffset passed as NULL",    "erroffset passed as NULL\0"
412    "unknown option bit(s) set",    "unknown option bit(s) set\0"
413    "missing ) after comment",    "missing ) after comment\0"
414    "parentheses nested too deeply",    "parentheses nested too deeply\0"  /** DEAD **/
415    /* 20 */    /* 20 */
416    "regular expression too large",    "regular expression is too large\0"
417    "failed to get memory",    "failed to get memory\0"
418    "unmatched parentheses",    "unmatched parentheses\0"
419    "internal error: code overflow",    "internal error: code overflow\0"
420    "unrecognized character after (?<",    "unrecognized character after (?<\0"
421    /* 25 */    /* 25 */
422    "lookbehind assertion is not fixed length",    "lookbehind assertion is not fixed length\0"
423    "malformed number after (?(",    "malformed number or name after (?(\0"
424    "conditional group contains more than two branches",    "conditional group contains more than two branches\0"
425    "assertion expected after (?(",    "assertion expected after (?(\0"
426    "(?R or (?digits must be followed by )",    "(?R or (?[+-]digits must be followed by )\0"
427    /* 30 */    /* 30 */
428    "unknown POSIX class name",    "unknown POSIX class name\0"
429    "POSIX collating elements are not supported",    "POSIX collating elements are not supported\0"
430    "this version of PCRE is not compiled with PCRE_UTF8 support",    "this version of PCRE is not compiled with PCRE_UTF8 support\0"
431    "spare error",    "spare error\0"  /** DEAD **/
432    "character value in \\x{...} sequence is too large",    "character value in \\x{...} sequence is too large\0"
433    /* 35 */    /* 35 */
434    "invalid condition (?(0)",    "invalid condition (?(0)\0"
435    "\\C not allowed in lookbehind assertion",    "\\C not allowed in lookbehind assertion\0"
436    "PCRE does not support \\L, \\l, \\N, \\U, or \\u",    "PCRE does not support \\L, \\l, \\N{name}, \\U, or \\u\0"
437    "number after (?C is > 255",    "number after (?C is > 255\0"
438    "closing ) for (?C expected",    "closing ) for (?C expected\0"
439    /* 40 */    /* 40 */
440    "recursive call could loop indefinitely",    "recursive call could loop indefinitely\0"
441    "unrecognized character after (?P",    "unrecognized character after (?P\0"
442    "syntax error after (?P",    "syntax error in subpattern name (missing terminator)\0"
443    "two named groups have the same name",    "two named subpatterns have the same name\0"
444    "invalid UTF-8 string",    "invalid UTF-8 string\0"
445    /* 45 */    /* 45 */
446    "support for \\P, \\p, and \\X has not been compiled",    "support for \\P, \\p, and \\X has not been compiled\0"
447    "malformed \\P or \\p sequence",    "malformed \\P or \\p sequence\0"
448    "unknown property name after \\P or \\p"    "unknown property name after \\P or \\p\0"
449  };    "subpattern name is too long (maximum " XSTRING(MAX_NAME_SIZE) " characters)\0"
450      "too many named subpatterns (maximum " XSTRING(MAX_NAME_COUNT) ")\0"
451      /* 50 */
452      "repeated subpattern is too long\0"    /** DEAD **/
453      "octal value is greater than \\377 (not in UTF-8 mode)\0"
454      "internal error: overran compiling workspace\0"
455      "internal error: previously-checked referenced subpattern not found\0"
456      "DEFINE group contains more than one branch\0"
457      /* 55 */
458      "repeating a DEFINE group is not allowed\0"  /** DEAD **/
459      "inconsistent NEWLINE options\0"
460      "\\g is not followed by a braced, angle-bracketed, or quoted name/number or by a plain number\0"
461      "a numbered reference must not be zero\0"
462      "an argument is not allowed for (*ACCEPT), (*FAIL), or (*COMMIT)\0"
463      /* 60 */
464      "(*VERB) not recognized\0"
465      "number is too big\0"
466      "subpattern name expected\0"
467      "digit expected after (?+\0"
468      "] is an invalid data character in JavaScript compatibility mode\0"
469      /* 65 */
470      "different names for subpatterns of the same number are not allowed\0"
471      "(*MARK) must have an argument\0"
472      "this version of PCRE is not compiled with PCRE_UCP support\0"
473      "\\c must be followed by an ASCII character\0"
474      "\\k is not followed by a braced, angle-bracketed, or quoted name\0"
475      /* 70 */
476      "internal error: unknown opcode in find_fixedlength()\0"
477      "Not allowed UTF-8 / UTF-16 code point (>= 0xd800 && <= 0xdfff)\0"
478      ;
479    
480  /* Table to identify digits and hex digits. This is used when compiling  /* Table to identify digits and hex digits. This is used when compiling
481  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 229  For convenience, we use the same bit def Line 493  For convenience, we use the same bit def
493    
494  Then we can use ctype_digit and ctype_xdigit in the code. */  Then we can use ctype_digit and ctype_xdigit in the code. */
495    
496  #if !EBCDIC    /* This is the "normal" case, for ASCII systems */  /* Using a simple comparison for decimal numbers rather than a memory read
497  static const unsigned char digitab[] =  is much faster, and the resulting code is simpler (the compiler turns it
498    into a subtraction and unsigned comparison). */
499    
500    #define IS_DIGIT(x) ((x) >= CHAR_0 && (x) <= CHAR_9)
501    
502    #ifndef EBCDIC
503    
504    /* This is the "normal" case, for ASCII systems, and EBCDIC systems running in
505    UTF-8 mode. */
506    
507    static const pcre_uint8 digitab[] =
508    {    {
509    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*   0-  7 */    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*   0-  7 */
510    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*   8- 15 */    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*   8- 15 */
# Line 265  static const unsigned char digitab[] = Line 539  static const unsigned char digitab[] =
539    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 240-247 */    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 240-247 */
540    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};/* 248-255 */    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};/* 248-255 */
541    
542  #else          /* This is the "abnormal" case, for EBCDIC systems */  #else
543  static const unsigned char digitab[] =  
544    /* This is the "abnormal" case, for EBCDIC systems not running in UTF-8 mode. */
545    
546    static const pcre_uint8 digitab[] =
547    {    {
548    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*   0-  7  0 */    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*   0-  7  0 */
549    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*   8- 15    */    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*   8- 15    */
# Line 279  static const unsigned char digitab[] = Line 556  static const unsigned char digitab[] =
556    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*    - 71 40 */    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*    - 71 40 */
557    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  72- |     */    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  72- |     */
558    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  & - 87 50 */    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  & - 87 50 */
559    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  88-     */    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  88- 95    */
560    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  - -103 60 */    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  - -103 60 */
561    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 104- ?     */    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 104- ?     */
562    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 112-119 70 */    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 112-119 70 */
# Line 301  static const unsigned char digitab[] = Line 578  static const unsigned char digitab[] =
578    0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c, /*  0 - 7  F0 */    0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c, /*  0 - 7  F0 */
579    0x0c,0x0c,0x00,0x00,0x00,0x00,0x00,0x00};/*  8 -255    */    0x0c,0x0c,0x00,0x00,0x00,0x00,0x00,0x00};/*  8 -255    */
580    
581  static const unsigned char ebcdic_chartab[] = { /* chartable partial dup */  static const pcre_uint8 ebcdic_chartab[] = { /* chartable partial dup */
582    0x80,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /*   0-  7 */    0x80,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /*   0-  7 */
583    0x00,0x00,0x00,0x00,0x01,0x01,0x00,0x00, /*   8- 15 */    0x00,0x00,0x00,0x00,0x01,0x01,0x00,0x00, /*   8- 15 */
584    0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /*  16- 23 */    0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /*  16- 23 */
# Line 313  static const unsigned char ebcdic_charta Line 590  static const unsigned char ebcdic_charta
590    0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*    - 71 */    0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*    - 71 */
591    0x00,0x00,0x00,0x80,0x00,0x80,0x80,0x80, /*  72- |  */    0x00,0x00,0x00,0x80,0x00,0x80,0x80,0x80, /*  72- |  */
592    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  & - 87 */    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  & - 87 */
593    0x00,0x00,0x00,0x80,0x80,0x80,0x00,0x00, /*  88-  */    0x00,0x00,0x00,0x80,0x80,0x80,0x00,0x00, /*  88- 95 */
594    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  - -103 */    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  - -103 */
595    0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x80, /* 104- ?  */    0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x80, /* 104- ?  */
596    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 112-119 */    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 112-119 */
# Line 340  static const unsigned char ebcdic_charta Line 617  static const unsigned char ebcdic_charta
617  /* Definition to allow mutual recursion */  /* Definition to allow mutual recursion */
618    
619  static BOOL  static BOOL
620    compile_regex(int, int, int *, uschar **, const uschar **, int *, BOOL, int,    compile_regex(int, pcre_uchar **, const pcre_uchar **, int *, BOOL, BOOL, int, int,
621      int *, int *, branch_chain *, compile_data *);      int *, int *, branch_chain *, compile_data *, int *);
622    
623    
624    
625    /*************************************************
626    *            Find an error text                  *
627    *************************************************/
628    
629    /* The error texts are now all in one long string, to save on relocations. As
630    some of the text is of unknown length, we can't use a table of offsets.
631    Instead, just count through the strings. This is not a performance issue
632    because it happens only when there has been a compilation error.
633    
634    Argument:   the error number
635    Returns:    pointer to the error string
636    */
637    
638    static const char *
639    find_error_text(int n)
640    {
641    const char *s = error_texts;
642    for (; n > 0; n--)
643      {
644      while (*s++ != 0) {};
645      if (*s == 0) return "Error text not found (please report)";
646      }
647    return s;
648    }
649    
650    
651    /*************************************************
652    *            Check for counted repeat            *
653    *************************************************/
654    
655    /* This function is called when a '{' is encountered in a place where it might
656    start a quantifier. It looks ahead to see if it really is a quantifier or not.
657    It is only a quantifier if it is one of the forms {ddd} {ddd,} or {ddd,ddd}
658    where the ddds are digits.
659    
660    Arguments:
661      p         pointer to the first char after '{'
662    
663    Returns:    TRUE or FALSE
664    */
665    
666    static BOOL
667    is_counted_repeat(const pcre_uchar *p)
668    {
669    if (!IS_DIGIT(*p)) return FALSE;
670    p++;
671    while (IS_DIGIT(*p)) p++;
672    if (*p == CHAR_RIGHT_CURLY_BRACKET) return TRUE;
673    
674    if (*p++ != CHAR_COMMA) return FALSE;
675    if (*p == CHAR_RIGHT_CURLY_BRACKET) return TRUE;
676    
677    if (!IS_DIGIT(*p)) return FALSE;
678    p++;
679    while (IS_DIGIT(*p)) p++;
680    
681    return (*p == CHAR_RIGHT_CURLY_BRACKET);
682    }
683    
684    
685    
# Line 351  static BOOL Line 689  static BOOL
689    
690  /* This function is called when a \ has been encountered. It either returns a  /* This function is called when a \ has been encountered. It either returns a
691  positive value for a simple escape such as \n, or a negative value which  positive value for a simple escape such as \n, or a negative value which
692  encodes one of the more complicated things such as \d. When UTF-8 is enabled,  encodes one of the more complicated things such as \d. A backreference to group
693  a positive value greater than 255 may be returned. On entry, ptr is pointing at  n is returned as -(ESC_REF + n); ESC_REF is the highest ESC_xxx macro. When
694  the \. On exit, it is on the final character of the escape sequence.  UTF-8 is enabled, a positive value greater than 255 may be returned. On entry,
695    ptr is pointing at the \. On exit, it is on the final character of the escape
696    sequence.
697    
698  Arguments:  Arguments:
699    ptrptr         points to the pattern position pointer    ptrptr         points to the pattern position pointer
# Line 364  Arguments: Line 704  Arguments:
704    
705  Returns:         zero or positive => a data character  Returns:         zero or positive => a data character
706                   negative => a special escape sequence                   negative => a special escape sequence
707                   on error, errorptr is set                   on error, errorcodeptr is set
708  */  */
709    
710  static int  static int
711  check_escape(const uschar **ptrptr, int *errorcodeptr, int bracount,  check_escape(const pcre_uchar **ptrptr, int *errorcodeptr, int bracount,
712    int options, BOOL isclass)    int options, BOOL isclass)
713  {  {
714  const uschar *ptr = *ptrptr;  /* PCRE_UTF16 has the same value as PCRE_UTF8. */
715  int c, i;  BOOL utf = (options & PCRE_UTF8) != 0;
716    const pcre_uchar *ptr = *ptrptr + 1;
717    pcre_int32 c;
718    int i;
719    
720    GETCHARINCTEST(c, ptr);           /* Get character value, increment pointer */
721    ptr--;                            /* Set pointer back to the last byte */
722    
723  /* If backslash is at the end of the pattern, it's an error. */  /* If backslash is at the end of the pattern, it's an error. */
724    
 c = *(++ptr);  
725  if (c == 0) *errorcodeptr = ERR1;  if (c == 0) *errorcodeptr = ERR1;
726    
727  /* 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
728  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.
729  Otherwise further processing may be required. */  Otherwise further processing may be required. */
730    
731  #if !EBCDIC    /* ASCII coding */  #ifndef EBCDIC  /* ASCII/UTF-8 coding */
732  else if (c < '0' || c > 'z') {}                           /* Not alphameric */  /* Not alphanumeric */
733  else if ((i = escapes[c - '0']) != 0) c = i;  else if (c < CHAR_0 || c > CHAR_z) {}
734    else if ((i = escapes[c - CHAR_0]) != 0) c = i;
735  #else          /* EBCDIC coding */  
736  else if (c < 'a' || (ebcdic_chartab[c] & 0x0E) == 0) {}   /* Not alphameric */  #else           /* EBCDIC coding */
737    /* Not alphanumeric */
738    else if (c < 'a' || (!MAX_255(c) || (ebcdic_chartab[c] & 0x0E) == 0)) {}
739  else if ((i = escapes[c - 0x48]) != 0)  c = i;  else if ((i = escapes[c - 0x48]) != 0)  c = i;
740  #endif  #endif
741    
# Line 396  else if ((i = escapes[c - 0x48]) != 0) Line 743  else if ((i = escapes[c - 0x48]) != 0)
743    
744  else  else
745    {    {
746    const uschar *oldptr;    const pcre_uchar *oldptr;
747      BOOL braced, negated;
748    
749    switch (c)    switch (c)
750      {      {
751      /* 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
752      error. */      error. */
753    
754      case 'l':      case CHAR_l:
755      case 'L':      case CHAR_L:
     case 'N':  
     case 'u':  
     case 'U':  
756      *errorcodeptr = ERR37;      *errorcodeptr = ERR37;
757      break;      break;
758    
759        case CHAR_u:
760        if ((options & PCRE_JAVASCRIPT_COMPAT) != 0)
761          {
762          /* In JavaScript, \u must be followed by four hexadecimal numbers.
763          Otherwise it is a lowercase u letter. */
764          if (MAX_255(ptr[1]) && (digitab[ptr[1]] & ctype_xdigit) != 0
765            && MAX_255(ptr[2]) && (digitab[ptr[2]] & ctype_xdigit) != 0
766            && MAX_255(ptr[3]) && (digitab[ptr[3]] & ctype_xdigit) != 0
767            && MAX_255(ptr[4]) && (digitab[ptr[4]] & ctype_xdigit) != 0)
768            {
769            c = 0;
770            for (i = 0; i < 4; ++i)
771              {
772              register int cc = *(++ptr);
773    #ifndef EBCDIC  /* ASCII/UTF-8 coding */
774              if (cc >= CHAR_a) cc -= 32;               /* Convert to upper case */
775              c = (c << 4) + cc - ((cc < CHAR_A)? CHAR_0 : (CHAR_A - 10));
776    #else           /* EBCDIC coding */
777              if (cc >= CHAR_a && cc <= CHAR_z) cc += 64;  /* Convert to upper case */
778              c = (c << 4) + cc - ((cc >= CHAR_0)? CHAR_0 : (CHAR_A - 10));
779    #endif
780              }
781            }
782          }
783        else
784          *errorcodeptr = ERR37;
785        break;
786    
787        case CHAR_U:
788        /* In JavaScript, \U is an uppercase U letter. */
789        if ((options & PCRE_JAVASCRIPT_COMPAT) == 0) *errorcodeptr = ERR37;
790        break;
791    
792        /* In a character class, \g is just a literal "g". Outside a character
793        class, \g must be followed by one of a number of specific things:
794    
795        (1) A number, either plain or braced. If positive, it is an absolute
796        backreference. If negative, it is a relative backreference. This is a Perl
797        5.10 feature.
798    
799        (2) Perl 5.10 also supports \g{name} as a reference to a named group. This
800        is part of Perl's movement towards a unified syntax for back references. As
801        this is synonymous with \k{name}, we fudge it up by pretending it really
802        was \k.
803    
804        (3) For Oniguruma compatibility we also support \g followed by a name or a
805        number either in angle brackets or in single quotes. However, these are
806        (possibly recursive) subroutine calls, _not_ backreferences. Just return
807        the -ESC_g code (cf \k). */
808    
809        case CHAR_g:
810        if (isclass) break;
811        if (ptr[1] == CHAR_LESS_THAN_SIGN || ptr[1] == CHAR_APOSTROPHE)
812          {
813          c = -ESC_g;
814          break;
815          }
816    
817        /* Handle the Perl-compatible cases */
818    
819        if (ptr[1] == CHAR_LEFT_CURLY_BRACKET)
820          {
821          const pcre_uchar *p;
822          for (p = ptr+2; *p != 0 && *p != CHAR_RIGHT_CURLY_BRACKET; p++)
823            if (*p != CHAR_MINUS && !IS_DIGIT(*p)) break;
824          if (*p != 0 && *p != CHAR_RIGHT_CURLY_BRACKET)
825            {
826            c = -ESC_k;
827            break;
828            }
829          braced = TRUE;
830          ptr++;
831          }
832        else braced = FALSE;
833    
834        if (ptr[1] == CHAR_MINUS)
835          {
836          negated = TRUE;
837          ptr++;
838          }
839        else negated = FALSE;
840    
841        /* The integer range is limited by the machine's int representation. */
842        c = 0;
843        while (IS_DIGIT(ptr[1]))
844          {
845          if (((unsigned int)c) > INT_MAX / 10) /* Integer overflow */
846            {
847            c = -1;
848            break;
849            }
850          c = c * 10 + *(++ptr) - CHAR_0;
851          }
852        if (((unsigned int)c) > INT_MAX) /* Integer overflow */
853          {
854          while (IS_DIGIT(ptr[1]))
855            ptr++;
856          *errorcodeptr = ERR61;
857          break;
858          }
859    
860        if (braced && *(++ptr) != CHAR_RIGHT_CURLY_BRACKET)
861          {
862          *errorcodeptr = ERR57;
863          break;
864          }
865    
866        if (c == 0)
867          {
868          *errorcodeptr = ERR58;
869          break;
870          }
871    
872        if (negated)
873          {
874          if (c > bracount)
875            {
876            *errorcodeptr = ERR15;
877            break;
878            }
879          c = bracount - (c - 1);
880          }
881    
882        c = -(ESC_REF + c);
883        break;
884    
885      /* The handling of escape sequences consisting of a string of digits      /* The handling of escape sequences consisting of a string of digits
886      starting with one that is not zero is not straightforward. By experiment,      starting with one that is not zero is not straightforward. By experiment,
887      the way Perl works seems to be as follows:      the way Perl works seems to be as follows:
# Line 422  else Line 894  else
894      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
895      character class, \ followed by a digit is always an octal number. */      character class, \ followed by a digit is always an octal number. */
896    
897      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:
898      case '6': case '7': case '8': case '9':      case CHAR_6: case CHAR_7: case CHAR_8: case CHAR_9:
899    
900      if (!isclass)      if (!isclass)
901        {        {
902        oldptr = ptr;        oldptr = ptr;
903        c -= '0';        /* The integer range is limited by the machine's int representation. */
904        while ((digitab[ptr[1]] & ctype_digit) != 0)        c -= CHAR_0;
905          c = c * 10 + *(++ptr) - '0';        while (IS_DIGIT(ptr[1]))
906            {
907            if (((unsigned int)c) > INT_MAX / 10) /* Integer overflow */
908              {
909              c = -1;
910              break;
911              }
912            c = c * 10 + *(++ptr) - CHAR_0;
913            }
914          if (((unsigned int)c) > INT_MAX) /* Integer overflow */
915            {
916            while (IS_DIGIT(ptr[1]))
917              ptr++;
918            *errorcodeptr = ERR61;
919            break;
920            }
921        if (c < 10 || c <= bracount)        if (c < 10 || c <= bracount)
922          {          {
923          c = -(ESC_REF + c);          c = -(ESC_REF + c);
# Line 443  else Line 930  else
930      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.
931      Thus we have to pull back the pointer by one. */      Thus we have to pull back the pointer by one. */
932    
933      if ((c = *ptr) >= '8')      if ((c = *ptr) >= CHAR_8)
934        {        {
935        ptr--;        ptr--;
936        c = 0;        c = 0;
# Line 451  else Line 938  else
938        }        }
939    
940      /* \0 always starts an octal number, but we may drop through to here with a      /* \0 always starts an octal number, but we may drop through to here with a
941      larger first octal digit. */      larger first octal digit. The original code used just to take the least
942        significant 8 bits of octal numbers (I think this is what early Perls used
943      case '0':      to do). Nowadays we allow for larger numbers in UTF-8 mode, but no more
944      c -= '0';      than 3 octal digits. */
945      while(i++ < 2 && ptr[1] >= '0' && ptr[1] <= '7')  
946          c = c * 8 + *(++ptr) - '0';      case CHAR_0:
947      c &= 255;     /* Take least significant 8 bits */      c -= CHAR_0;
948        while(i++ < 2 && ptr[1] >= CHAR_0 && ptr[1] <= CHAR_7)
949            c = c * 8 + *(++ptr) - CHAR_0;
950        if (!utf && c > 0xff) *errorcodeptr = ERR51;
951      break;      break;
952    
953      /* \x is complicated when UTF-8 is enabled. \x{ddd} is a character number      /* \x is complicated. \x{ddd} is a character number which can be greater
954      which can be greater than 0xff, but only if the ddd are hex digits. */      than 0xff in utf or non-8bit mode, but only if the ddd are hex digits.
955        If not, { is treated as a data character. */
956    
957        case CHAR_x:
958        if ((options & PCRE_JAVASCRIPT_COMPAT) != 0)
959          {
960          /* In JavaScript, \x must be followed by two hexadecimal numbers.
961          Otherwise it is a lowercase x letter. */
962          if (MAX_255(ptr[1]) && (digitab[ptr[1]] & ctype_xdigit) != 0
963            && MAX_255(ptr[2]) && (digitab[ptr[2]] & ctype_xdigit) != 0)
964            {
965            c = 0;
966            for (i = 0; i < 2; ++i)
967              {
968              register int cc = *(++ptr);
969    #ifndef EBCDIC  /* ASCII/UTF-8 coding */
970              if (cc >= CHAR_a) cc -= 32;               /* Convert to upper case */
971              c = (c << 4) + cc - ((cc < CHAR_A)? CHAR_0 : (CHAR_A - 10));
972    #else           /* EBCDIC coding */
973              if (cc >= CHAR_a && cc <= CHAR_z) cc += 64;  /* Convert to upper case */
974              c = (c << 4) + cc - ((cc >= CHAR_0)? CHAR_0 : (CHAR_A - 10));
975    #endif
976              }
977            }
978          break;
979          }
980    
981      case 'x':      if (ptr[1] == CHAR_LEFT_CURLY_BRACKET)
 #ifdef SUPPORT_UTF8  
     if (ptr[1] == '{' && (options & PCRE_UTF8) != 0)  
982        {        {
983        const uschar *pt = ptr + 2;        const pcre_uchar *pt = ptr + 2;
984        register int count = 0;  
985        c = 0;        c = 0;
986        while ((digitab[*pt] & ctype_xdigit) != 0)        while (MAX_255(*pt) && (digitab[*pt] & ctype_xdigit) != 0)
987          {          {
988          int cc = *pt++;          register int cc = *pt++;
989          count++;          if (c == 0 && cc == CHAR_0) continue;     /* Leading zeroes */
990  #if !EBCDIC    /* ASCII coding */  
991          if (cc >= 'a') cc -= 32;               /* Convert to upper case */  #ifndef EBCDIC  /* ASCII/UTF-8 coding */
992          c = c * 16 + cc - ((cc < 'A')? '0' : ('A' - 10));          if (cc >= CHAR_a) cc -= 32;               /* Convert to upper case */
993  #else          /* EBCDIC coding */          c = (c << 4) + cc - ((cc < CHAR_A)? CHAR_0 : (CHAR_A - 10));
994          if (cc >= 'a' && cc <= 'z') cc += 64;  /* Convert to upper case */  #else           /* EBCDIC coding */
995          c = c * 16 + cc - ((cc >= '0')? '0' : ('A' - 10));          if (cc >= CHAR_a && cc <= CHAR_z) cc += 64;  /* Convert to upper case */
996            c = (c << 4) + cc - ((cc >= CHAR_0)? CHAR_0 : (CHAR_A - 10));
997    #endif
998    
999    #ifdef COMPILE_PCRE8
1000            if (c > (utf ? 0x10ffff : 0xff)) { c = -1; break; }
1001    #else
1002    #ifdef COMPILE_PCRE16
1003            if (c > (utf ? 0x10ffff : 0xffff)) { c = -1; break; }
1004    #endif
1005  #endif  #endif
1006          }          }
1007        if (*pt == '}')  
1008          if (c < 0)
1009            {
1010            while (MAX_255(*pt) && (digitab[*pt] & ctype_xdigit) != 0) pt++;
1011            *errorcodeptr = ERR34;
1012            }
1013    
1014          if (*pt == CHAR_RIGHT_CURLY_BRACKET)
1015          {          {
1016          if (c < 0 || count > 8) *errorcodeptr = ERR34;          if (utf && c >= 0xd800 && c <= 0xdfff) *errorcodeptr = ERR71;
1017          ptr = pt;          ptr = pt;
1018          break;          break;
1019          }          }
1020    
1021        /* If the sequence of hex digits does not end with '}', then we don't        /* If the sequence of hex digits does not end with '}', then we don't
1022        recognize this construct; fall through to the normal \x handling. */        recognize this construct; fall through to the normal \x handling. */
1023        }        }
 #endif  
1024    
1025      /* Read just a single hex char */      /* Read just a single-byte hex-defined char */
1026    
1027      c = 0;      c = 0;
1028      while (i++ < 2 && (digitab[ptr[1]] & ctype_xdigit) != 0)      while (i++ < 2 && MAX_255(ptr[1]) && (digitab[ptr[1]] & ctype_xdigit) != 0)
1029        {        {
1030        int cc;                               /* Some compilers don't like ++ */        int cc;                                  /* Some compilers don't like */
1031        cc = *(++ptr);                        /* in initializers */        cc = *(++ptr);                           /* ++ in initializers */
1032  #if !EBCDIC    /* ASCII coding */  #ifndef EBCDIC  /* ASCII/UTF-8 coding */
1033        if (cc >= 'a') cc -= 32;              /* Convert to upper case */        if (cc >= CHAR_a) cc -= 32;              /* Convert to upper case */
1034        c = c * 16 + cc - ((cc < 'A')? '0' : ('A' - 10));        c = c * 16 + cc - ((cc < CHAR_A)? CHAR_0 : (CHAR_A - 10));
1035  #else          /* EBCDIC coding */  #else           /* EBCDIC coding */
1036        if (cc <= 'z') cc += 64;              /* Convert to upper case */        if (cc <= CHAR_z) cc += 64;              /* Convert to upper case */
1037        c = c * 16 + cc - ((cc >= '0')? '0' : ('A' - 10));        c = c * 16 + cc - ((cc >= CHAR_0)? CHAR_0 : (CHAR_A - 10));
1038  #endif  #endif
1039        }        }
1040      break;      break;
1041    
1042      /* Other special escapes not starting with a digit are straightforward */      /* For \c, a following letter is upper-cased; then the 0x40 bit is flipped.
1043        An error is given if the byte following \c is not an ASCII character. This
1044        coding is ASCII-specific, but then the whole concept of \cx is
1045        ASCII-specific. (However, an EBCDIC equivalent has now been added.) */
1046    
1047      case 'c':      case CHAR_c:
1048      c = *(++ptr);      c = *(++ptr);
1049      if (c == 0)      if (c == 0)
1050        {        {
1051        *errorcodeptr = ERR2;        *errorcodeptr = ERR2;
1052        return 0;        break;
1053        }        }
1054    #ifndef EBCDIC    /* ASCII/UTF-8 coding */
1055      /* A letter is upper-cased; then the 0x40 bit is flipped. This coding      if (c > 127)  /* Excludes all non-ASCII in either mode */
1056      is ASCII-specific, but then the whole concept of \cx is ASCII-specific.        {
1057      (However, an EBCDIC equivalent has now been added.) */        *errorcodeptr = ERR68;
1058          break;
1059  #if !EBCDIC    /* ASCII coding */        }
1060      if (c >= 'a' && c <= 'z') c -= 32;      if (c >= CHAR_a && c <= CHAR_z) c -= 32;
1061      c ^= 0x40;      c ^= 0x40;
1062  #else          /* EBCDIC coding */  #else             /* EBCDIC coding */
1063      if (c >= 'a' && c <= 'z') c += 64;      if (c >= CHAR_a && c <= CHAR_z) c += 64;
1064      c ^= 0xC0;      c ^= 0xC0;
1065  #endif  #endif
1066      break;      break;
1067    
1068      /* PCRE_EXTRA enables extensions to Perl in the matter of escapes. Any      /* PCRE_EXTRA enables extensions to Perl in the matter of escapes. Any
1069      other alphameric following \ is an error if PCRE_EXTRA was set; otherwise,      other alphanumeric following \ is an error if PCRE_EXTRA was set;
1070      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
1071      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
1072      in future, so I haven't "optimized" it. */      be again in future, so I haven't "optimized" it. */
1073    
1074      default:      default:
1075      if ((options & PCRE_EXTRA) != 0) switch(c)      if ((options & PCRE_EXTRA) != 0) switch(c)
# Line 550  else Line 1082  else
1082      }      }
1083    }    }
1084    
1085    /* Perl supports \N{name} for character names, as well as plain \N for "not
1086    newline". PCRE does not support \N{name}. However, it does support
1087    quantification such as \N{2,3}. */
1088    
1089    if (c == -ESC_N && ptr[1] == CHAR_LEFT_CURLY_BRACKET &&
1090         !is_counted_repeat(ptr+2))
1091      *errorcodeptr = ERR37;
1092    
1093    /* If PCRE_UCP is set, we change the values for \d etc. */
1094    
1095    if ((options & PCRE_UCP) != 0 && c <= -ESC_D && c >= -ESC_w)
1096      c -= (ESC_DU - ESC_D);
1097    
1098    /* Set the pointer to the final character before returning. */
1099    
1100  *ptrptr = ptr;  *ptrptr = ptr;
1101  return c;  return c;
1102  }  }
# Line 569  escape sequence. Line 1116  escape sequence.
1116  Argument:  Argument:
1117    ptrptr         points to the pattern position pointer    ptrptr         points to the pattern position pointer
1118    negptr         points to a boolean that is set TRUE for negation else FALSE    negptr         points to a boolean that is set TRUE for negation else FALSE
1119      dptr           points to an int that is set to the detailed property value
1120    errorcodeptr   points to the error code variable    errorcodeptr   points to the error code variable
1121    
1122  Returns:     value from ucp_type_table, or -1 for an invalid type  Returns:         type value from ucp_type_table, or -1 for an invalid type
1123  */  */
1124    
1125  static int  static int
1126  get_ucp(const uschar **ptrptr, BOOL *negptr, int *errorcodeptr)  get_ucp(const pcre_uchar **ptrptr, BOOL *negptr, int *dptr, int *errorcodeptr)
1127  {  {
1128  int c, i, bot, top;  int c, i, bot, top;
1129  const uschar *ptr = *ptrptr;  const pcre_uchar *ptr = *ptrptr;
1130  char name[4];  pcre_uchar name[32];
1131    
1132  c = *(++ptr);  c = *(++ptr);
1133  if (c == 0) goto ERROR_RETURN;  if (c == 0) goto ERROR_RETURN;
1134    
1135  *negptr = FALSE;  *negptr = FALSE;
1136    
1137  /* \P or \p can be followed by a one- or two-character name in {}, optionally  /* \P or \p can be followed by a name in {}, optionally preceded by ^ for
1138  preceded by ^ for negation. */  negation. */
1139    
1140  if (c == '{')  if (c == CHAR_LEFT_CURLY_BRACKET)
1141    {    {
1142    if (ptr[1] == '^')    if (ptr[1] == CHAR_CIRCUMFLEX_ACCENT)
1143      {      {
1144      *negptr = TRUE;      *negptr = TRUE;
1145      ptr++;      ptr++;
1146      }      }
1147    for (i = 0; i <= 2; i++)    for (i = 0; i < (int)sizeof(name) - 1; i++)
1148      {      {
1149      c = *(++ptr);      c = *(++ptr);
1150      if (c == 0) goto ERROR_RETURN;      if (c == 0) goto ERROR_RETURN;
1151      if (c == '}') break;      if (c == CHAR_RIGHT_CURLY_BRACKET) break;
1152      name[i] = c;      name[i] = c;
1153      }      }
1154    if (c !='}')   /* Try to distinguish error cases */    if (c != CHAR_RIGHT_CURLY_BRACKET) goto ERROR_RETURN;
     {  
     while (*(++ptr) != 0 && *ptr != '}');  
     if (*ptr == '}') goto UNKNOWN_RETURN; else goto ERROR_RETURN;  
     }  
1155    name[i] = 0;    name[i] = 0;
1156    }    }
1157    
# Line 624  else Line 1168  else
1168  /* Search for a recognized property name using binary chop */  /* Search for a recognized property name using binary chop */
1169    
1170  bot = 0;  bot = 0;
1171  top = _pcre_utt_size;  top = PRIV(utt_size);
1172    
1173  while (bot < top)  while (bot < top)
1174    {    {
1175    i = (bot + top)/2;    i = (bot + top) >> 1;
1176    c = strcmp(name, _pcre_utt[i].name);    c = STRCMP_UC_C8(name, PRIV(utt_names) + PRIV(utt)[i].name_offset);
1177    if (c == 0) return _pcre_utt[i].value;    if (c == 0)
1178        {
1179        *dptr = PRIV(utt)[i].value;
1180        return PRIV(utt)[i].type;
1181        }
1182    if (c > 0) bot = i + 1; else top = i;    if (c > 0) bot = i + 1; else top = i;
1183    }    }
1184    
 UNKNOWN_RETURN:  
1185  *errorcodeptr = ERR47;  *errorcodeptr = ERR47;
1186  *ptrptr = ptr;  *ptrptr = ptr;
1187  return -1;  return -1;
# Line 650  return -1; Line 1197  return -1;
1197    
1198    
1199  /*************************************************  /*************************************************
 *            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 == '}');  
 }  
   
   
   
 /*************************************************  
1200  *         Read repeat counts                     *  *         Read repeat counts                     *
1201  *************************************************/  *************************************************/
1202    
# Line 701  Returns:         pointer to '}' on succe Line 1215  Returns:         pointer to '}' on succe
1215                   current ptr on error, with errorcodeptr set non-zero                   current ptr on error, with errorcodeptr set non-zero
1216  */  */
1217    
1218  static const uschar *  static const pcre_uchar *
1219  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)
1220  {  {
1221  int min = 0;  int min = 0;
1222  int max = -1;  int max = -1;
# Line 710  int max = -1; Line 1224  int max = -1;
1224  /* 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
1225  an integer overflow. */  an integer overflow. */
1226    
1227  while ((digitab[*p] & ctype_digit) != 0) min = min * 10 + *p++ - '0';  while (IS_DIGIT(*p)) min = min * 10 + *p++ - CHAR_0;
1228  if (min < 0 || min > 65535)  if (min < 0 || min > 65535)
1229    {    {
1230    *errorcodeptr = ERR5;    *errorcodeptr = ERR5;
# Line 720  if (min < 0 || min > 65535) Line 1234  if (min < 0 || min > 65535)
1234  /* 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.
1235  Also, max must not be less than min. */  Also, max must not be less than min. */
1236    
1237  if (*p == '}') max = min; else  if (*p == CHAR_RIGHT_CURLY_BRACKET) max = min; else
1238    {    {
1239    if (*(++p) != '}')    if (*(++p) != CHAR_RIGHT_CURLY_BRACKET)
1240      {      {
1241      max = 0;      max = 0;
1242      while((digitab[*p] & ctype_digit) != 0) max = max * 10 + *p++ - '0';      while(IS_DIGIT(*p)) max = max * 10 + *p++ - CHAR_0;
1243      if (max < 0 || max > 65535)      if (max < 0 || max > 65535)
1244        {        {
1245        *errorcodeptr = ERR5;        *errorcodeptr = ERR5;
# Line 750  return p; Line 1264  return p;
1264    
1265    
1266  /*************************************************  /*************************************************
1267  *      Find first significant op code            *  *  Subroutine for finding forward reference      *
1268  *************************************************/  *************************************************/
1269    
1270  /* This is called by several functions that scan a compiled expression looking  /* This recursive function is called only from find_parens() below. The
1271  for a fixed first character, or an anchoring op code etc. It skips over things  top-level call starts at the beginning of the pattern. All other calls must
1272  that do not influence this. For some calls, a change of option is important.  start at a parenthesis. It scans along a pattern's text looking for capturing
1273  For some calls, it makes sense to skip negative forward and all backward  subpatterns, and counting them. If it finds a named pattern that matches the
1274  assertions, and also the \b assertion; for others it does not.  name it is given, it returns its number. Alternatively, if the name is NULL, it
1275    returns when it reaches a given numbered subpattern. Recursion is used to keep
1276    track of subpatterns that reset the capturing group numbers - the (?| feature.
1277    
1278    This function was originally called only from the second pass, in which we know
1279    that if (?< or (?' or (?P< is encountered, the name will be correctly
1280    terminated because that is checked in the first pass. There is now one call to
1281    this function in the first pass, to check for a recursive back reference by
1282    name (so that we can make the whole group atomic). In this case, we need check
1283    only up to the current position in the pattern, and that is still OK because
1284    and previous occurrences will have been checked. To make this work, the test
1285    for "end of pattern" is a check against cd->end_pattern in the main loop,
1286    instead of looking for a binary zero. This means that the special first-pass
1287    call can adjust cd->end_pattern temporarily. (Checks for binary zero while
1288    processing items within the loop are OK, because afterwards the main loop will
1289    terminate.)
1290    
1291  Arguments:  Arguments:
1292    code         pointer to the start of the group    ptrptr       address of the current character pointer (updated)
1293    options      pointer to external options    cd           compile background data
1294    optbit       the option bit whose changing is significant, or    name         name to seek, or NULL if seeking a numbered subpattern
1295                   zero if none are    lorn         name length, or subpattern number if name is NULL
1296    skipassert   TRUE if certain assertions are to be skipped    xmode        TRUE if we are in /x mode
1297      utf          TRUE if we are in UTF-8 / UTF-16 mode
1298      count        pointer to the current capturing subpattern number (updated)
1299    
1300  Returns:       pointer to the first significant opcode  Returns:       the number of the named subpattern, or -1 if not found
1301  */  */
1302    
1303  static const uschar*  static int
1304  first_significant_code(const uschar *code, int *options, int optbit,  find_parens_sub(pcre_uchar **ptrptr, compile_data *cd, const pcre_uchar *name, int lorn,
1305    BOOL skipassert)    BOOL xmode, BOOL utf, int *count)
1306  {  {
1307  for (;;)  pcre_uchar *ptr = *ptrptr;
1308    {  int start_count = *count;
1309    switch ((int)*code)  int hwm_count = start_count;
1310      {  BOOL dup_parens = FALSE;
     case OP_OPT:  
     if (optbit > 0 && ((int)code[1] & optbit) != (*options & optbit))  
       *options = (int)code[1];  
     code += 2;  
     break;  
1311    
1312      case OP_ASSERT_NOT:  /* If the first character is a parenthesis, check on the type of group we are
1313      case OP_ASSERTBACK:  dealing with. The very first call may not start with a parenthesis. */
     case OP_ASSERTBACK_NOT:  
     if (!skipassert) return code;  
     do code += GET(code, 1); while (*code == OP_ALT);  
     code += _pcre_OP_lengths[*code];  
     break;  
1314    
1315      case OP_WORD_BOUNDARY:  if (ptr[0] == CHAR_LEFT_PARENTHESIS)
1316      case OP_NOT_WORD_BOUNDARY:    {
1317      if (!skipassert) return code;    /* Handle specials such as (*SKIP) or (*UTF8) etc. */
     /* Fall through */  
1318    
1319      case OP_CALLOUT:    if (ptr[1] == CHAR_ASTERISK) ptr += 2;
     case OP_CREF:  
     case OP_BRANUMBER:  
     code += _pcre_OP_lengths[*code];  
     break;  
1320    
1321      default:    /* Handle a normal, unnamed capturing parenthesis. */
     return code;  
     }  
   }  
 /* Control never reaches here */  
 }  
1322    
1323      else if (ptr[1] != CHAR_QUESTION_MARK)
1324        {
1325        *count += 1;
1326        if (name == NULL && *count == lorn) return *count;
1327        ptr++;
1328        }
1329    
1330      /* All cases now have (? at the start. Remember when we are in a group
1331      where the parenthesis numbers are duplicated. */
1332    
1333      else if (ptr[2] == CHAR_VERTICAL_LINE)
1334        {
1335        ptr += 3;
1336        dup_parens = TRUE;
1337        }
1338    
1339  /*************************************************    /* Handle comments; all characters are allowed until a ket is reached. */
 *        Find the fixed length of a pattern      *  
 *************************************************/  
1340    
1341  /* Scan a pattern and compute the fixed length of subject that will match it,    else if (ptr[2] == CHAR_NUMBER_SIGN)
1342  if the length is fixed. This is needed for dealing with backward assertions.      {
1343  In UTF8 mode, the result is in characters rather than bytes.      for (ptr += 3; *ptr != 0; ptr++) if (*ptr == CHAR_RIGHT_PARENTHESIS) break;
1344        goto FAIL_EXIT;
1345        }
1346    
1347  Arguments:    /* Handle a condition. If it is an assertion, just carry on so that it
1348    code     points to the start of the pattern (the bracket)    is processed as normal. If not, skip to the closing parenthesis of the
1349    options  the compiling options    condition (there can't be any nested parens). */
1350    
1351  Returns:   the fixed length, or -1 if there is no fixed length,    else if (ptr[2] == CHAR_LEFT_PARENTHESIS)
1352               or -2 if \C was encountered      {
1353  */      ptr += 2;
1354        if (ptr[1] != CHAR_QUESTION_MARK)
1355          {
1356          while (*ptr != 0 && *ptr != CHAR_RIGHT_PARENTHESIS) ptr++;
1357          if (*ptr != 0) ptr++;
1358          }
1359        }
1360    
1361  static int    /* Start with (? but not a condition. */
 find_fixedlength(uschar *code, int options)  
 {  
 int length = -1;  
1362    
1363  register int branchlength = 0;    else
1364  register uschar *cc = code + 1 + LINK_SIZE;      {
1365        ptr += 2;
1366        if (*ptr == CHAR_P) ptr++;                      /* Allow optional P */
1367    
1368  /* Scan along the opcodes for this branch. If we get to the end of the      /* We have to disambiguate (?<! and (?<= from (?<name> for named groups */
1369  branch, check the length against that of the other branches. */  
1370        if ((*ptr == CHAR_LESS_THAN_SIGN && ptr[1] != CHAR_EXCLAMATION_MARK &&
1371            ptr[1] != CHAR_EQUALS_SIGN) || *ptr == CHAR_APOSTROPHE)
1372          {
1373          int term;
1374          const pcre_uchar *thisname;
1375          *count += 1;
1376          if (name == NULL && *count == lorn) return *count;
1377          term = *ptr++;
1378          if (term == CHAR_LESS_THAN_SIGN) term = CHAR_GREATER_THAN_SIGN;
1379          thisname = ptr;
1380          while (*ptr != term) ptr++;
1381          if (name != NULL && lorn == ptr - thisname &&
1382              STRNCMP_UC_UC(name, thisname, lorn) == 0)
1383            return *count;
1384          term++;
1385          }
1386        }
1387      }
1388    
1389    /* Past any initial parenthesis handling, scan for parentheses or vertical
1390    bars. Stop if we get to cd->end_pattern. Note that this is important for the
1391    first-pass call when this value is temporarily adjusted to stop at the current
1392    position. So DO NOT change this to a test for binary zero. */
1393    
1394    for (; ptr < cd->end_pattern; ptr++)
1395      {
1396      /* Skip over backslashed characters and also entire \Q...\E */
1397    
1398      if (*ptr == CHAR_BACKSLASH)
1399        {
1400        if (*(++ptr) == 0) goto FAIL_EXIT;
1401        if (*ptr == CHAR_Q) for (;;)
1402          {
1403          while (*(++ptr) != 0 && *ptr != CHAR_BACKSLASH) {};
1404          if (*ptr == 0) goto FAIL_EXIT;
1405          if (*(++ptr) == CHAR_E) break;
1406          }
1407        continue;
1408        }
1409    
1410      /* Skip over character classes; this logic must be similar to the way they
1411      are handled for real. If the first character is '^', skip it. Also, if the
1412      first few characters (either before or after ^) are \Q\E or \E we skip them
1413      too. This makes for compatibility with Perl. Note the use of STR macros to
1414      encode "Q\\E" so that it works in UTF-8 on EBCDIC platforms. */
1415    
1416      if (*ptr == CHAR_LEFT_SQUARE_BRACKET)
1417        {
1418        BOOL negate_class = FALSE;
1419        for (;;)
1420          {
1421          if (ptr[1] == CHAR_BACKSLASH)
1422            {
1423            if (ptr[2] == CHAR_E)
1424              ptr+= 2;
1425            else if (STRNCMP_UC_C8(ptr + 2,
1426                     STR_Q STR_BACKSLASH STR_E, 3) == 0)
1427              ptr += 4;
1428            else
1429              break;
1430            }
1431          else if (!negate_class && ptr[1] == CHAR_CIRCUMFLEX_ACCENT)
1432            {
1433            negate_class = TRUE;
1434            ptr++;
1435            }
1436          else break;
1437          }
1438    
1439        /* If the next character is ']', it is a data character that must be
1440        skipped, except in JavaScript compatibility mode. */
1441    
1442        if (ptr[1] == CHAR_RIGHT_SQUARE_BRACKET &&
1443            (cd->external_options & PCRE_JAVASCRIPT_COMPAT) == 0)
1444          ptr++;
1445    
1446        while (*(++ptr) != CHAR_RIGHT_SQUARE_BRACKET)
1447          {
1448          if (*ptr == 0) return -1;
1449          if (*ptr == CHAR_BACKSLASH)
1450            {
1451            if (*(++ptr) == 0) goto FAIL_EXIT;
1452            if (*ptr == CHAR_Q) for (;;)
1453              {
1454              while (*(++ptr) != 0 && *ptr != CHAR_BACKSLASH) {};
1455              if (*ptr == 0) goto FAIL_EXIT;
1456              if (*(++ptr) == CHAR_E) break;
1457              }
1458            continue;
1459            }
1460          }
1461        continue;
1462        }
1463    
1464      /* Skip comments in /x mode */
1465    
1466      if (xmode && *ptr == CHAR_NUMBER_SIGN)
1467        {
1468        ptr++;
1469        while (*ptr != 0)
1470          {
1471          if (IS_NEWLINE(ptr)) { ptr += cd->nllen - 1; break; }
1472          ptr++;
1473    #ifdef SUPPORT_UTF
1474          if (utf) FORWARDCHAR(ptr);
1475    #endif
1476          }
1477        if (*ptr == 0) goto FAIL_EXIT;
1478        continue;
1479        }
1480    
1481      /* Check for the special metacharacters */
1482    
1483      if (*ptr == CHAR_LEFT_PARENTHESIS)
1484        {
1485        int rc = find_parens_sub(&ptr, cd, name, lorn, xmode, utf, count);
1486        if (rc > 0) return rc;
1487        if (*ptr == 0) goto FAIL_EXIT;
1488        }
1489    
1490      else if (*ptr == CHAR_RIGHT_PARENTHESIS)
1491        {
1492        if (dup_parens && *count < hwm_count) *count = hwm_count;
1493        goto FAIL_EXIT;
1494        }
1495    
1496      else if (*ptr == CHAR_VERTICAL_LINE && dup_parens)
1497        {
1498        if (*count > hwm_count) hwm_count = *count;
1499        *count = start_count;
1500        }
1501      }
1502    
1503    FAIL_EXIT:
1504    *ptrptr = ptr;
1505    return -1;
1506    }
1507    
1508    
1509    
1510    
1511    /*************************************************
1512    *       Find forward referenced subpattern       *
1513    *************************************************/
1514    
1515    /* This function scans along a pattern's text looking for capturing
1516    subpatterns, and counting them. If it finds a named pattern that matches the
1517    name it is given, it returns its number. Alternatively, if the name is NULL, it
1518    returns when it reaches a given numbered subpattern. This is used for forward
1519    references to subpatterns. We used to be able to start this scan from the
1520    current compiling point, using the current count value from cd->bracount, and
1521    do it all in a single loop, but the addition of the possibility of duplicate
1522    subpattern numbers means that we have to scan from the very start, in order to
1523    take account of such duplicates, and to use a recursive function to keep track
1524    of the different types of group.
1525    
1526    Arguments:
1527      cd           compile background data
1528      name         name to seek, or NULL if seeking a numbered subpattern
1529      lorn         name length, or subpattern number if name is NULL
1530      xmode        TRUE if we are in /x mode
1531      utf          TRUE if we are in UTF-8 / UTF-16 mode
1532    
1533    Returns:       the number of the found subpattern, or -1 if not found
1534    */
1535    
1536    static int
1537    find_parens(compile_data *cd, const pcre_uchar *name, int lorn, BOOL xmode,
1538      BOOL utf)
1539    {
1540    pcre_uchar *ptr = (pcre_uchar *)cd->start_pattern;
1541    int count = 0;
1542    int rc;
1543    
1544    /* If the pattern does not start with an opening parenthesis, the first call
1545    to find_parens_sub() will scan right to the end (if necessary). However, if it
1546    does start with a parenthesis, find_parens_sub() will return when it hits the
1547    matching closing parens. That is why we have to have a loop. */
1548    
1549    for (;;)
1550      {
1551      rc = find_parens_sub(&ptr, cd, name, lorn, xmode, utf, &count);
1552      if (rc > 0 || *ptr++ == 0) break;
1553      }
1554    
1555    return rc;
1556    }
1557    
1558    
1559    
1560    
1561    /*************************************************
1562    *      Find first significant op code            *
1563    *************************************************/
1564    
1565    /* This is called by several functions that scan a compiled expression looking
1566    for a fixed first character, or an anchoring op code etc. It skips over things
1567    that do not influence this. For some calls, it makes sense to skip negative
1568    forward and all backward assertions, and also the \b assertion; for others it
1569    does not.
1570    
1571    Arguments:
1572      code         pointer to the start of the group
1573      skipassert   TRUE if certain assertions are to be skipped
1574    
1575    Returns:       pointer to the first significant opcode
1576    */
1577    
1578    static const pcre_uchar*
1579    first_significant_code(const pcre_uchar *code, BOOL skipassert)
1580    {
1581    for (;;)
1582      {
1583      switch ((int)*code)
1584        {
1585        case OP_ASSERT_NOT:
1586        case OP_ASSERTBACK:
1587        case OP_ASSERTBACK_NOT:
1588        if (!skipassert) return code;
1589        do code += GET(code, 1); while (*code == OP_ALT);
1590        code += PRIV(OP_lengths)[*code];
1591        break;
1592    
1593        case OP_WORD_BOUNDARY:
1594        case OP_NOT_WORD_BOUNDARY:
1595        if (!skipassert) return code;
1596        /* Fall through */
1597    
1598        case OP_CALLOUT:
1599        case OP_CREF:
1600        case OP_NCREF:
1601        case OP_RREF:
1602        case OP_NRREF:
1603        case OP_DEF:
1604        code += PRIV(OP_lengths)[*code];
1605        break;
1606    
1607        default:
1608        return code;
1609        }
1610      }
1611    /* Control never reaches here */
1612    }
1613    
1614    
1615    
1616    
1617    /*************************************************
1618    *        Find the fixed length of a branch       *
1619    *************************************************/
1620    
1621    /* Scan a branch and compute the fixed length of subject that will match it,
1622    if the length is fixed. This is needed for dealing with backward assertions.
1623    In UTF8 mode, the result is in characters rather than bytes. The branch is
1624    temporarily terminated with OP_END when this function is called.
1625    
1626    This function is called when a backward assertion is encountered, so that if it
1627    fails, the error message can point to the correct place in the pattern.
1628    However, we cannot do this when the assertion contains subroutine calls,
1629    because they can be forward references. We solve this by remembering this case
1630    and doing the check at the end; a flag specifies which mode we are running in.
1631    
1632    Arguments:
1633      code     points to the start of the pattern (the bracket)
1634      utf      TRUE in UTF-8 / UTF-16 mode
1635      atend    TRUE if called when the pattern is complete
1636      cd       the "compile data" structure
1637    
1638    Returns:   the fixed length,
1639                 or -1 if there is no fixed length,
1640                 or -2 if \C was encountered (in UTF-8 mode only)
1641                 or -3 if an OP_RECURSE item was encountered and atend is FALSE
1642                 or -4 if an unknown opcode was encountered (internal error)
1643    */
1644    
1645    static int
1646    find_fixedlength(pcre_uchar *code, BOOL utf, BOOL atend, compile_data *cd)
1647    {
1648    int length = -1;
1649    
1650    register int branchlength = 0;
1651    register pcre_uchar *cc = code + 1 + LINK_SIZE;
1652    
1653    /* Scan along the opcodes for this branch. If we get to the end of the
1654    branch, check the length against that of the other branches. */
1655    
1656  for (;;)  for (;;)
1657    {    {
1658    int d;    int d;
1659      pcre_uchar *ce, *cs;
1660    register int op = *cc;    register int op = *cc;
   if (op >= OP_BRA) op = OP_BRA;  
   
1661    switch (op)    switch (op)
1662      {      {
1663        /* We only need to continue for OP_CBRA (normal capturing bracket) and
1664        OP_BRA (normal non-capturing bracket) because the other variants of these
1665        opcodes are all concerned with unlimited repeated groups, which of course
1666        are not of fixed length. */
1667    
1668        case OP_CBRA:
1669      case OP_BRA:      case OP_BRA:
1670      case OP_ONCE:      case OP_ONCE:
1671        case OP_ONCE_NC:
1672      case OP_COND:      case OP_COND:
1673      d = find_fixedlength(cc, options);      d = find_fixedlength(cc + ((op == OP_CBRA)? IMM2_SIZE : 0), utf, atend, cd);
1674      if (d < 0) return d;      if (d < 0) return d;
1675      branchlength += d;      branchlength += d;
1676      do cc += GET(cc, 1); while (*cc == OP_ALT);      do cc += GET(cc, 1); while (*cc == OP_ALT);
1677      cc += 1 + LINK_SIZE;      cc += 1 + LINK_SIZE;
1678      break;      break;
1679    
1680      /* 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.
1681      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
1682      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
1683        the same code. Note that we must not include the OP_KETRxxx opcodes here,
1684        because they all imply an unlimited repeat. */
1685    
1686      case OP_ALT:      case OP_ALT:
1687      case OP_KET:      case OP_KET:
     case OP_KETRMAX:  
     case OP_KETRMIN:  
1688      case OP_END:      case OP_END:
1689        case OP_ACCEPT:
1690        case OP_ASSERT_ACCEPT:
1691      if (length < 0) length = branchlength;      if (length < 0) length = branchlength;
1692        else if (length != branchlength) return -1;        else if (length != branchlength) return -1;
1693      if (*cc != OP_ALT) return length;      if (*cc != OP_ALT) return length;
# Line 873  for (;;) Line 1695  for (;;)
1695      branchlength = 0;      branchlength = 0;
1696      break;      break;
1697    
1698        /* A true recursion implies not fixed length, but a subroutine call may
1699        be OK. If the subroutine is a forward reference, we can't deal with
1700        it until the end of the pattern, so return -3. */
1701    
1702        case OP_RECURSE:
1703        if (!atend) return -3;
1704        cs = ce = (pcre_uchar *)cd->start_code + GET(cc, 1);  /* Start subpattern */
1705        do ce += GET(ce, 1); while (*ce == OP_ALT);           /* End subpattern */
1706        if (cc > cs && cc < ce) return -1;                    /* Recursion */
1707        d = find_fixedlength(cs + 2, utf, atend, cd);
1708        if (d < 0) return d;
1709        branchlength += d;
1710        cc += 1 + LINK_SIZE;
1711        break;
1712    
1713      /* Skip over assertive subpatterns */      /* Skip over assertive subpatterns */
1714    
1715      case OP_ASSERT:      case OP_ASSERT:
# Line 884  for (;;) Line 1721  for (;;)
1721    
1722      /* Skip over things that don't match chars */      /* Skip over things that don't match chars */
1723    
1724      case OP_REVERSE:      case OP_MARK:
1725      case OP_BRANUMBER:      case OP_PRUNE_ARG:
1726      case OP_CREF:      case OP_SKIP_ARG:
1727      case OP_OPT:      case OP_THEN_ARG:
1728        cc += cc[1] + PRIV(OP_lengths)[*cc];
1729        break;
1730    
1731      case OP_CALLOUT:      case OP_CALLOUT:
     case OP_SOD:  
     case OP_SOM:  
     case OP_EOD:  
     case OP_EODN:  
1732      case OP_CIRC:      case OP_CIRC:
1733        case OP_CIRCM:
1734        case OP_CLOSE:
1735        case OP_COMMIT:
1736        case OP_CREF:
1737        case OP_DEF:
1738      case OP_DOLL:      case OP_DOLL:
1739        case OP_DOLLM:
1740        case OP_EOD:
1741        case OP_EODN:
1742        case OP_FAIL:
1743        case OP_NCREF:
1744        case OP_NRREF:
1745      case OP_NOT_WORD_BOUNDARY:      case OP_NOT_WORD_BOUNDARY:
1746        case OP_PRUNE:
1747        case OP_REVERSE:
1748        case OP_RREF:
1749        case OP_SET_SOM:
1750        case OP_SKIP:
1751        case OP_SOD:
1752        case OP_SOM:
1753        case OP_THEN:
1754      case OP_WORD_BOUNDARY:      case OP_WORD_BOUNDARY:
1755      cc += _pcre_OP_lengths[*cc];      cc += PRIV(OP_lengths)[*cc];
1756      break;      break;
1757    
1758      /* Handle literal characters */      /* Handle literal characters */
1759    
1760      case OP_CHAR:      case OP_CHAR:
1761      case OP_CHARNC:      case OP_CHARI:
1762        case OP_NOT:
1763        case OP_NOTI:
1764      branchlength++;      branchlength++;
1765      cc += 2;      cc += 2;
1766  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF
1767      if ((options & PCRE_UTF8) != 0)      if (utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);
       {  
       while ((*cc & 0xc0) == 0x80) cc++;  
       }  
1768  #endif  #endif
1769      break;      break;
1770    
# Line 918  for (;;) Line 1772  for (;;)
1772      need to skip over a multibyte character in UTF8 mode.  */      need to skip over a multibyte character in UTF8 mode.  */
1773    
1774      case OP_EXACT:      case OP_EXACT:
1775        case OP_EXACTI:
1776        case OP_NOTEXACT:
1777        case OP_NOTEXACTI:
1778      branchlength += GET2(cc,1);      branchlength += GET2(cc,1);
1779      cc += 4;      cc += 2 + IMM2_SIZE;
1780  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF
1781      if ((options & PCRE_UTF8) != 0)      if (utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);
       {  
       while((*cc & 0x80) == 0x80) cc++;  
       }  
1782  #endif  #endif
1783      break;      break;
1784    
1785      case OP_TYPEEXACT:      case OP_TYPEEXACT:
1786      branchlength += GET2(cc,1);      branchlength += GET2(cc,1);
1787      cc += 4;      if (cc[1 + IMM2_SIZE] == OP_PROP || cc[1 + IMM2_SIZE] == OP_NOTPROP) cc += 2;
1788        cc += 1 + IMM2_SIZE + 1;
1789      break;      break;
1790    
1791      /* Handle single-char matchers */      /* Handle single-char matchers */
1792    
1793      case OP_PROP:      case OP_PROP:
1794      case OP_NOTPROP:      case OP_NOTPROP:
1795      cc++;      cc += 2;
1796      /* Fall through */      /* Fall through */
1797    
1798        case OP_HSPACE:
1799        case OP_VSPACE:
1800        case OP_NOT_HSPACE:
1801        case OP_NOT_VSPACE:
1802      case OP_NOT_DIGIT:      case OP_NOT_DIGIT:
1803      case OP_DIGIT:      case OP_DIGIT:
1804      case OP_NOT_WHITESPACE:      case OP_NOT_WHITESPACE:
# Line 947  for (;;) Line 1806  for (;;)
1806      case OP_NOT_WORDCHAR:      case OP_NOT_WORDCHAR:
1807      case OP_WORDCHAR:      case OP_WORDCHAR:
1808      case OP_ANY:      case OP_ANY:
1809        case OP_ALLANY:
1810      branchlength++;      branchlength++;
1811      cc++;      cc++;
1812      break;      break;
1813    
1814      /* The single-byte matcher isn't allowed */      /* The single-byte matcher isn't allowed. This only happens in UTF-8 mode;
1815        otherwise \C is coded as OP_ALLANY. */
1816    
1817      case OP_ANYBYTE:      case OP_ANYBYTE:
1818      return -2;      return -2;
1819    
1820      /* Check a class for variable quantification */      /* Check a class for variable quantification */
1821    
1822  #ifdef SUPPORT_UTF8  #if defined SUPPORT_UTF || defined COMPILE_PCRE16
1823      case OP_XCLASS:      case OP_XCLASS:
1824      cc += GET(cc, 1) - 33;      cc += GET(cc, 1) - PRIV(OP_lengths)[OP_CLASS];
1825      /* Fall through */      /* Fall through */
1826  #endif  #endif
1827    
1828      case OP_CLASS:      case OP_CLASS:
1829      case OP_NCLASS:      case OP_NCLASS:
1830      cc += 33;      cc += PRIV(OP_lengths)[OP_CLASS];
1831    
1832      switch (*cc)      switch (*cc)
1833        {        {
1834          case OP_CRPLUS:
1835          case OP_CRMINPLUS:
1836        case OP_CRSTAR:        case OP_CRSTAR:
1837        case OP_CRMINSTAR:        case OP_CRMINSTAR:
1838        case OP_CRQUERY:        case OP_CRQUERY:
# Line 978  for (;;) Line 1841  for (;;)
1841    
1842        case OP_CRRANGE:        case OP_CRRANGE:
1843        case OP_CRMINRANGE:        case OP_CRMINRANGE:
1844        if (GET2(cc,1) != GET2(cc,3)) return -1;        if (GET2(cc,1) != GET2(cc,1+IMM2_SIZE)) return -1;
1845        branchlength += GET2(cc,1);        branchlength += GET2(cc,1);
1846        cc += 5;        cc += 1 + 2 * IMM2_SIZE;
1847        break;        break;
1848    
1849        default:        default:
# Line 990  for (;;) Line 1853  for (;;)
1853    
1854      /* Anything else is variable length */      /* Anything else is variable length */
1855    
1856      default:      case OP_ANYNL:
1857        case OP_BRAMINZERO:
1858        case OP_BRAPOS:
1859        case OP_BRAPOSZERO:
1860        case OP_BRAZERO:
1861        case OP_CBRAPOS:
1862        case OP_EXTUNI:
1863        case OP_KETRMAX:
1864        case OP_KETRMIN:
1865        case OP_KETRPOS:
1866        case OP_MINPLUS:
1867        case OP_MINPLUSI:
1868        case OP_MINQUERY:
1869        case OP_MINQUERYI:
1870        case OP_MINSTAR:
1871        case OP_MINSTARI:
1872        case OP_MINUPTO:
1873        case OP_MINUPTOI:
1874        case OP_NOTMINPLUS:
1875        case OP_NOTMINPLUSI:
1876        case OP_NOTMINQUERY:
1877        case OP_NOTMINQUERYI:
1878        case OP_NOTMINSTAR:
1879        case OP_NOTMINSTARI:
1880        case OP_NOTMINUPTO:
1881        case OP_NOTMINUPTOI:
1882        case OP_NOTPLUS:
1883        case OP_NOTPLUSI:
1884        case OP_NOTPOSPLUS:
1885        case OP_NOTPOSPLUSI:
1886        case OP_NOTPOSQUERY:
1887        case OP_NOTPOSQUERYI:
1888        case OP_NOTPOSSTAR:
1889        case OP_NOTPOSSTARI:
1890        case OP_NOTPOSUPTO:
1891        case OP_NOTPOSUPTOI:
1892        case OP_NOTQUERY:
1893        case OP_NOTQUERYI:
1894        case OP_NOTSTAR:
1895        case OP_NOTSTARI:
1896        case OP_NOTUPTO:
1897        case OP_NOTUPTOI:
1898        case OP_PLUS:
1899        case OP_PLUSI:
1900        case OP_POSPLUS:
1901        case OP_POSPLUSI:
1902        case OP_POSQUERY:
1903        case OP_POSQUERYI:
1904        case OP_POSSTAR:
1905        case OP_POSSTARI:
1906        case OP_POSUPTO:
1907        case OP_POSUPTOI:
1908        case OP_QUERY:
1909        case OP_QUERYI:
1910        case OP_REF:
1911        case OP_REFI:
1912        case OP_SBRA:
1913        case OP_SBRAPOS:
1914        case OP_SCBRA:
1915        case OP_SCBRAPOS:
1916        case OP_SCOND:
1917        case OP_SKIPZERO:
1918        case OP_STAR:
1919        case OP_STARI:
1920        case OP_TYPEMINPLUS:
1921        case OP_TYPEMINQUERY:
1922        case OP_TYPEMINSTAR:
1923        case OP_TYPEMINUPTO:
1924        case OP_TYPEPLUS:
1925        case OP_TYPEPOSPLUS:
1926        case OP_TYPEPOSQUERY:
1927        case OP_TYPEPOSSTAR:
1928        case OP_TYPEPOSUPTO:
1929        case OP_TYPEQUERY:
1930        case OP_TYPESTAR:
1931        case OP_TYPEUPTO:
1932        case OP_UPTO:
1933        case OP_UPTOI:
1934      return -1;      return -1;
1935    
1936        /* Catch unrecognized opcodes so that when new ones are added they
1937        are not forgotten, as has happened in the past. */
1938    
1939        default:
1940        return -4;
1941      }      }
1942    }    }
1943  /* Control never gets here */  /* Control never gets here */
# Line 1001  for (;;) Line 1947  for (;;)
1947    
1948    
1949  /*************************************************  /*************************************************
1950  *    Scan compiled regex for numbered bracket    *  *    Scan compiled regex for specific bracket    *
1951  *************************************************/  *************************************************/
1952    
1953  /* This little function scans through a compiled pattern until it finds a  /* This little function scans through a compiled pattern until it finds a
1954  capturing bracket with the given number.  capturing bracket with the given number, or, if the number is negative, an
1955    instance of OP_REVERSE for a lookbehind. The function is global in the C sense
1956    so that it can be called from pcre_study() when finding the minimum matching
1957    length.
1958    
1959  Arguments:  Arguments:
1960    code        points to start of expression    code        points to start of expression
1961    utf8        TRUE in UTF-8 mode    utf         TRUE in UTF-8 / UTF-16 mode
1962    number      the required bracket number    number      the required bracket number or negative to find a lookbehind
1963    
1964  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
1965  */  */
1966    
1967  static const uschar *  const pcre_uchar *
1968  find_bracket(const uschar *code, BOOL utf8, int number)  PRIV(find_bracket)(const pcre_uchar *code, BOOL utf, int number)
1969  {  {
 #ifndef SUPPORT_UTF8  
 utf8 = utf8;               /* Stop pedantic compilers complaining */  
 #endif  
   
1970  for (;;)  for (;;)
1971    {    {
1972    register int c = *code;    register int c = *code;
1973    
1974    if (c == OP_END) return NULL;    if (c == OP_END) return NULL;
1975    else if (c > OP_BRA)  
1976      /* XCLASS is used for classes that cannot be represented just by a bit
1977      map. This includes negated single high-valued characters. The length in
1978      the table is zero; the actual length is stored in the compiled code. */
1979    
1980      if (c == OP_XCLASS) code += GET(code, 1);
1981    
1982      /* Handle recursion */
1983    
1984      else if (c == OP_REVERSE)
1985        {
1986        if (number < 0) return (pcre_uchar *)code;
1987        code += PRIV(OP_lengths)[c];
1988        }
1989    
1990      /* Handle capturing bracket */
1991    
1992      else if (c == OP_CBRA || c == OP_SCBRA ||
1993               c == OP_CBRAPOS || c == OP_SCBRAPOS)
1994      {      {
1995      int n = c - OP_BRA;      int n = GET2(code, 1+LINK_SIZE);
1996      if (n > EXTRACT_BASIC_MAX) n = GET2(code, 2+LINK_SIZE);      if (n == number) return (pcre_uchar *)code;
1997      if (n == number) return (uschar *)code;      code += PRIV(OP_lengths)[c];
     code += _pcre_OP_lengths[OP_BRA];  
1998      }      }
1999    
2000      /* Otherwise, we can get the item's length from the table, except that for
2001      repeated character types, we have to test for \p and \P, which have an extra
2002      two bytes of parameters, and for MARK/PRUNE/SKIP/THEN with an argument, we
2003      must add in its length. */
2004    
2005    else    else
2006      {      {
2007      code += _pcre_OP_lengths[c];      switch(c)
2008          {
2009          case OP_TYPESTAR:
2010          case OP_TYPEMINSTAR:
2011          case OP_TYPEPLUS:
2012          case OP_TYPEMINPLUS:
2013          case OP_TYPEQUERY:
2014          case OP_TYPEMINQUERY:
2015          case OP_TYPEPOSSTAR:
2016          case OP_TYPEPOSPLUS:
2017          case OP_TYPEPOSQUERY:
2018          if (code[1] == OP_PROP || code[1] == OP_NOTPROP) code += 2;
2019          break;
2020    
2021  #ifdef SUPPORT_UTF8        case OP_TYPEUPTO:
2022          case OP_TYPEMINUPTO:
2023          case OP_TYPEEXACT:
2024          case OP_TYPEPOSUPTO:
2025          if (code[1 + IMM2_SIZE] == OP_PROP
2026            || code[1 + IMM2_SIZE] == OP_NOTPROP) code += 2;
2027          break;
2028    
2029      /* In UTF-8 mode, opcodes that are followed by a character may be followed        case OP_MARK:
2030      by a multi-byte character. The length in the table is a minimum, so we have        case OP_PRUNE_ARG:
2031      to scan along to skip the extra bytes. All opcodes are less than 128, so we        case OP_SKIP_ARG:
2032      can use relatively efficient code. */        code += code[1];
2033          break;
2034    
2035          case OP_THEN_ARG:
2036          code += code[1];
2037          break;
2038          }
2039    
2040        /* Add in the fixed length from the table */
2041    
2042        code += PRIV(OP_lengths)[c];
2043    
2044      /* In UTF-8 mode, opcodes that are followed by a character may be followed by
2045      a multi-byte character. The length in the table is a minimum, so we have to
2046      arrange to skip the extra bytes. */
2047    
2048      if (utf8) switch(c)  #ifdef SUPPORT_UTF
2049        if (utf) switch(c)
2050        {        {
2051        case OP_CHAR:        case OP_CHAR:
2052        case OP_CHARNC:        case OP_CHARI:
2053        case OP_EXACT:        case OP_EXACT:
2054          case OP_EXACTI:
2055        case OP_UPTO:        case OP_UPTO:
2056          case OP_UPTOI:
2057        case OP_MINUPTO:        case OP_MINUPTO:
2058          case OP_MINUPTOI:
2059          case OP_POSUPTO:
2060          case OP_POSUPTOI:
2061        case OP_STAR:        case OP_STAR:
2062          case OP_STARI:
2063        case OP_MINSTAR:        case OP_MINSTAR:
2064          case OP_MINSTARI:
2065          case OP_POSSTAR:
2066          case OP_POSSTARI:
2067        case OP_PLUS:        case OP_PLUS:
2068          case OP_PLUSI:
2069        case OP_MINPLUS:        case OP_MINPLUS:
2070          case OP_MINPLUSI:
2071          case OP_POSPLUS:
2072          case OP_POSPLUSI:
2073        case OP_QUERY:        case OP_QUERY:
2074          case OP_QUERYI:
2075        case OP_MINQUERY:        case OP_MINQUERY:
2076        while ((*code & 0xc0) == 0x80) code++;        case OP_MINQUERYI:
2077        break;        case OP_POSQUERY:
2078          case OP_POSQUERYI:
2079        /* XCLASS is used for classes that cannot be represented just by a bit        if (HAS_EXTRALEN(code[-1])) code += GET_EXTRALEN(code[-1]);
       map. This includes negated single high-valued characters. The length in  
       the table is zero; the actual length is stored in the compiled code. */  
   
       case OP_XCLASS:  
       code += GET(code, 1) + 1;  
2080        break;        break;
2081        }        }
2082    #else
2083        (void)(utf);  /* Keep compiler happy by referencing function argument */
2084  #endif  #endif
2085      }      }
2086    }    }
# Line 1084  instance of OP_RECURSE. Line 2097  instance of OP_RECURSE.
2097    
2098  Arguments:  Arguments:
2099    code        points to start of expression    code        points to start of expression
2100    utf8        TRUE in UTF-8 mode    utf         TRUE in UTF-8 / UTF-16 mode
2101    
2102  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
2103  */  */
2104    
2105  static const uschar *  static const pcre_uchar *
2106  find_recurse(const uschar *code, BOOL utf8)  find_recurse(const pcre_uchar *code, BOOL utf)
2107  {  {
 #ifndef SUPPORT_UTF8  
 utf8 = utf8;               /* Stop pedantic compilers complaining */  
 #endif  
   
2108  for (;;)  for (;;)
2109    {    {
2110    register int c = *code;    register int c = *code;
2111    if (c == OP_END) return NULL;    if (c == OP_END) return NULL;
2112    else if (c == OP_RECURSE) return code;    if (c == OP_RECURSE) return code;
2113    else if (c > OP_BRA)  
2114      {    /* XCLASS is used for classes that cannot be represented just by a bit
2115      code += _pcre_OP_lengths[OP_BRA];    map. This includes negated single high-valued characters. The length in
2116      }    the table is zero; the actual length is stored in the compiled code. */
2117    
2118      if (c == OP_XCLASS) code += GET(code, 1);
2119    
2120      /* Otherwise, we can get the item's length from the table, except that for
2121      repeated character types, we have to test for \p and \P, which have an extra
2122      two bytes of parameters, and for MARK/PRUNE/SKIP/THEN with an argument, we
2123      must add in its length. */
2124    
2125    else    else
2126      {      {
2127      code += _pcre_OP_lengths[c];      switch(c)
2128          {
2129          case OP_TYPESTAR:
2130          case OP_TYPEMINSTAR:
2131          case OP_TYPEPLUS:
2132          case OP_TYPEMINPLUS:
2133          case OP_TYPEQUERY:
2134          case OP_TYPEMINQUERY:
2135          case OP_TYPEPOSSTAR:
2136          case OP_TYPEPOSPLUS:
2137          case OP_TYPEPOSQUERY:
2138          if (code[1] == OP_PROP || code[1] == OP_NOTPROP) code += 2;
2139          break;
2140    
2141  #ifdef SUPPORT_UTF8        case OP_TYPEPOSUPTO:
2142          case OP_TYPEUPTO:
2143          case OP_TYPEMINUPTO:
2144          case OP_TYPEEXACT:
2145          if (code[1 + IMM2_SIZE] == OP_PROP
2146            || code[1 + IMM2_SIZE] == OP_NOTPROP) code += 2;
2147          break;
2148    
2149          case OP_MARK:
2150          case OP_PRUNE_ARG:
2151          case OP_SKIP_ARG:
2152          code += code[1];
2153          break;
2154    
2155          case OP_THEN_ARG:
2156          code += code[1];
2157          break;
2158          }
2159    
2160        /* Add in the fixed length from the table */
2161    
2162        code += PRIV(OP_lengths)[c];
2163    
2164      /* In UTF-8 mode, opcodes that are followed by a character may be followed      /* In UTF-8 mode, opcodes that are followed by a character may be followed
2165      by a multi-byte character. The length in the table is a minimum, so we have      by a multi-byte character. The length in the table is a minimum, so we have
2166      to scan along to skip the extra bytes. All opcodes are less than 128, so we      to arrange to skip the extra bytes. */
     can use relatively efficient code. */  
2167    
2168      if (utf8) switch(c)  #ifdef SUPPORT_UTF
2169        if (utf) switch(c)
2170        {        {
2171        case OP_CHAR:        case OP_CHAR:
2172        case OP_CHARNC:        case OP_CHARI:
2173        case OP_EXACT:        case OP_EXACT:
2174          case OP_EXACTI:
2175        case OP_UPTO:        case OP_UPTO:
2176          case OP_UPTOI:
2177        case OP_MINUPTO:        case OP_MINUPTO:
2178          case OP_MINUPTOI:
2179          case OP_POSUPTO:
2180          case OP_POSUPTOI:
2181        case OP_STAR:        case OP_STAR:
2182          case OP_STARI:
2183        case OP_MINSTAR:        case OP_MINSTAR:
2184          case OP_MINSTARI:
2185          case OP_POSSTAR:
2186          case OP_POSSTARI:
2187        case OP_PLUS:        case OP_PLUS:
2188          case OP_PLUSI:
2189        case OP_MINPLUS:        case OP_MINPLUS:
2190          case OP_MINPLUSI:
2191          case OP_POSPLUS:
2192          case OP_POSPLUSI:
2193        case OP_QUERY:        case OP_QUERY:
2194          case OP_QUERYI:
2195        case OP_MINQUERY:        case OP_MINQUERY:
2196        while ((*code & 0xc0) == 0x80) code++;        case OP_MINQUERYI:
2197        break;        case OP_POSQUERY:
2198          case OP_POSQUERYI:
2199        /* XCLASS is used for classes that cannot be represented just by a bit        if (HAS_EXTRALEN(code[-1])) code += GET_EXTRALEN(code[-1]);
       map. This includes negated single high-valued characters. The length in  
       the table is zero; the actual length is stored in the compiled code. */  
   
       case OP_XCLASS:  
       code += GET(code, 1) + 1;  
2200        break;        break;
2201        }        }
2202    #else
2203        (void)(utf);  /* Keep compiler happy by referencing function argument */
2204  #endif  #endif
2205      }      }
2206    }    }
# Line 1152  for (;;) Line 2213  for (;;)
2213  *************************************************/  *************************************************/
2214    
2215  /* This function scans through a branch of a compiled pattern to see whether it  /* This function scans through a branch of a compiled pattern to see whether it
2216  can match the empty string or not. It is called only from could_be_empty()  can match the empty string or not. It is called from could_be_empty()
2217  below. Note that first_significant_code() skips over assertions. If we hit an  below and from compile_branch() when checking for an unlimited repeat of a
2218  unclosed bracket, we return "empty" - this means we've struck an inner bracket  group that can match nothing. Note that first_significant_code() skips over
2219  whose current branch will already have been scanned.  backward and negative forward assertions when its final argument is TRUE. If we
2220    hit an unclosed bracket, we return "empty" - this means we've struck an inner
2221    bracket whose current branch will already have been scanned.
2222    
2223  Arguments:  Arguments:
2224    code        points to start of search    code        points to start of search
2225    endcode     points to where to stop    endcode     points to where to stop
2226    utf8        TRUE if in UTF8 mode    utf         TRUE if in UTF-8 / UTF-16 mode
2227      cd          contains pointers to tables etc.
2228    
2229  Returns:      TRUE if what is matched could be empty  Returns:      TRUE if what is matched could be empty
2230  */  */
2231    
2232  static BOOL  static BOOL
2233  could_be_empty_branch(const uschar *code, const uschar *endcode, BOOL utf8)  could_be_empty_branch(const pcre_uchar *code, const pcre_uchar *endcode,
2234      BOOL utf, compile_data *cd)
2235  {  {
2236  register int c;  register int c;
2237  for (code = first_significant_code(code + 1 + LINK_SIZE, NULL, 0, TRUE);  for (code = first_significant_code(code + PRIV(OP_lengths)[*code], TRUE);
2238       code < endcode;       code < endcode;
2239       code = first_significant_code(code + _pcre_OP_lengths[c], NULL, 0, TRUE))       code = first_significant_code(code + PRIV(OP_lengths)[c], TRUE))
2240    {    {
2241    const uschar *ccode;    const pcre_uchar *ccode;
2242    
2243    c = *code;    c = *code;
2244    
2245    if (c >= OP_BRA)    /* Skip over forward assertions; the other assertions are skipped by
2246      first_significant_code() with a TRUE final argument. */
2247    
2248      if (c == OP_ASSERT)
2249        {
2250        do code += GET(code, 1); while (*code == OP_ALT);
2251        c = *code;
2252        continue;
2253        }
2254    
2255      /* For a recursion/subroutine call, if its end has been reached, which
2256      implies a backward reference subroutine call, we can scan it. If it's a
2257      forward reference subroutine call, we can't. To detect forward reference
2258      we have to scan up the list that is kept in the workspace. This function is
2259      called only when doing the real compile, not during the pre-compile that
2260      measures the size of the compiled pattern. */
2261    
2262      if (c == OP_RECURSE)
2263      {      {
2264        const pcre_uchar *scode;
2265      BOOL empty_branch;      BOOL empty_branch;
     if (GET(code, 1) == 0) return TRUE;    /* Hit unclosed bracket */  
2266    
2267      /* Scan a closed bracket */      /* Test for forward reference */
2268    
2269        for (scode = cd->start_workspace; scode < cd->hwm; scode += LINK_SIZE)
2270          if (GET(scode, 0) == code + 1 - cd->start_code) return TRUE;
2271    
2272        /* Not a forward reference, test for completed backward reference */
2273    
2274      empty_branch = FALSE;      empty_branch = FALSE;
2275        scode = cd->start_code + GET(code, 1);
2276        if (GET(scode, 1) == 0) return TRUE;    /* Unclosed */
2277    
2278        /* Completed backwards reference */
2279    
2280      do      do
2281        {        {
2282        if (!empty_branch && could_be_empty_branch(code, endcode, utf8))        if (could_be_empty_branch(scode, endcode, utf, cd))
2283            {
2284          empty_branch = TRUE;          empty_branch = TRUE;
2285            break;
2286            }
2287          scode += GET(scode, 1);
2288          }
2289        while (*scode == OP_ALT);
2290    
2291        if (!empty_branch) return FALSE;  /* All branches are non-empty */
2292        continue;
2293        }
2294    
2295      /* Groups with zero repeats can of course be empty; skip them. */
2296    
2297      if (c == OP_BRAZERO || c == OP_BRAMINZERO || c == OP_SKIPZERO ||
2298          c == OP_BRAPOSZERO)
2299        {
2300        code += PRIV(OP_lengths)[c];
2301        do code += GET(code, 1); while (*code == OP_ALT);
2302        c = *code;
2303        continue;
2304        }
2305    
2306      /* A nested group that is already marked as "could be empty" can just be
2307      skipped. */
2308    
2309      if (c == OP_SBRA  || c == OP_SBRAPOS ||
2310          c == OP_SCBRA || c == OP_SCBRAPOS)
2311        {
2312        do code += GET(code, 1); while (*code == OP_ALT);
2313        c = *code;
2314        continue;
2315        }
2316    
2317      /* For other groups, scan the branches. */
2318    
2319      if (c == OP_BRA  || c == OP_BRAPOS ||
2320          c == OP_CBRA || c == OP_CBRAPOS ||
2321          c == OP_ONCE || c == OP_ONCE_NC ||
2322          c == OP_COND)
2323        {
2324        BOOL empty_branch;
2325        if (GET(code, 1) == 0) return TRUE;    /* Hit unclosed bracket */
2326    
2327        /* If a conditional group has only one branch, there is a second, implied,
2328        empty branch, so just skip over the conditional, because it could be empty.
2329        Otherwise, scan the individual branches of the group. */
2330    
2331        if (c == OP_COND && code[GET(code, 1)] != OP_ALT)
2332        code += GET(code, 1);        code += GET(code, 1);
2333        else
2334          {
2335          empty_branch = FALSE;
2336          do
2337            {
2338            if (!empty_branch && could_be_empty_branch(code, endcode, utf, cd))
2339              empty_branch = TRUE;
2340            code += GET(code, 1);
2341            }
2342          while (*code == OP_ALT);
2343          if (!empty_branch) return FALSE;   /* All branches are non-empty */
2344        }        }
2345      while (*code == OP_ALT);  
     if (!empty_branch) return FALSE;   /* All branches are non-empty */  
     code += 1 + LINK_SIZE;  
2346      c = *code;      c = *code;
2347        continue;
2348      }      }
2349    
2350    else switch (c)    /* Handle the other opcodes */
2351    
2352      switch (c)
2353      {      {
2354      /* Check for quantifiers after a class */      /* Check for quantifiers after a class. XCLASS is used for classes that
2355        cannot be represented just by a bit map. This includes negated single
2356        high-valued characters. The length in PRIV(OP_lengths)[] is zero; the
2357        actual length is stored in the compiled code, so we must update "code"
2358        here. */
2359    
2360  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF8
2361      case OP_XCLASS:      case OP_XCLASS:
2362      ccode = code + GET(code, 1);      ccode = code += GET(code, 1);
2363      goto CHECK_CLASS_REPEAT;      goto CHECK_CLASS_REPEAT;
2364  #endif  #endif
2365    
2366      case OP_CLASS:      case OP_CLASS:
2367      case OP_NCLASS:      case OP_NCLASS:
2368      ccode = code + 33;      ccode = code + PRIV(OP_lengths)[OP_CLASS];
2369    
2370  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF8
2371      CHECK_CLASS_REPEAT:      CHECK_CLASS_REPEAT:
# Line 1247  for (code = first_significant_code(code Line 2403  for (code = first_significant_code(code
2403      case OP_NOT_WORDCHAR:      case OP_NOT_WORDCHAR:
2404      case OP_WORDCHAR:      case OP_WORDCHAR:
2405      case OP_ANY:      case OP_ANY:
2406        case OP_ALLANY:
2407      case OP_ANYBYTE:      case OP_ANYBYTE:
2408      case OP_CHAR:      case OP_CHAR:
2409      case OP_CHARNC:      case OP_CHARI:
2410      case OP_NOT:      case OP_NOT:
2411        case OP_NOTI:
2412      case OP_PLUS:      case OP_PLUS:
2413      case OP_MINPLUS:      case OP_MINPLUS:
2414        case OP_POSPLUS:
2415      case OP_EXACT:      case OP_EXACT:
2416      case OP_NOTPLUS:      case OP_NOTPLUS:
2417      case OP_NOTMINPLUS:      case OP_NOTMINPLUS:
2418        case OP_NOTPOSPLUS:
2419      case OP_NOTEXACT:      case OP_NOTEXACT:
2420      case OP_TYPEPLUS:      case OP_TYPEPLUS:
2421      case OP_TYPEMINPLUS:      case OP_TYPEMINPLUS:
2422        case OP_TYPEPOSPLUS:
2423      case OP_TYPEEXACT:      case OP_TYPEEXACT:
2424      return FALSE;      return FALSE;
2425    
2426        /* These are going to continue, as they may be empty, but we have to
2427        fudge the length for the \p and \P cases. */
2428    
2429        case OP_TYPESTAR:
2430        case OP_TYPEMINSTAR:
2431        case OP_TYPEPOSSTAR:
2432        case OP_TYPEQUERY:
2433        case OP_TYPEMINQUERY:
2434        case OP_TYPEPOSQUERY:
2435        if (code[1] == OP_PROP || code[1] == OP_NOTPROP) code += 2;
2436        break;
2437    
2438        /* Same for these */
2439    
2440        case OP_TYPEUPTO:
2441        case OP_TYPEMINUPTO:
2442        case OP_TYPEPOSUPTO:
2443        if (code[1 + IMM2_SIZE] == OP_PROP
2444          || code[1 + IMM2_SIZE] == OP_NOTPROP) code += 2;
2445        break;
2446    
2447      /* End of branch */      /* End of branch */
2448    
2449      case OP_KET:      case OP_KET:
2450      case OP_KETRMAX:      case OP_KETRMAX:
2451      case OP_KETRMIN:      case OP_KETRMIN:
2452        case OP_KETRPOS:
2453      case OP_ALT:      case OP_ALT:
2454      return TRUE;      return TRUE;
2455    
2456      /* In UTF-8 mode, STAR, MINSTAR, QUERY, MINQUERY, UPTO, and MINUPTO  may be      /* In UTF-8 mode, STAR, MINSTAR, POSSTAR, QUERY, MINQUERY, POSQUERY, UPTO,
2457      followed by a multibyte character */      MINUPTO, and POSUPTO may be followed by a multibyte character */
2458    
2459  #ifdef SUPPORT_UTF8  #ifdef SUPPORT_UTF
2460      case OP_STAR:      case OP_STAR:
2461        case OP_STARI:
2462      case OP_MINSTAR:      case OP_MINSTAR:
2463        case OP_MINSTARI:
2464        case OP_POSSTAR:
2465        case OP_POSSTARI:
2466      case OP_QUERY:      case OP_QUERY:
2467        case OP_QUERYI:
2468      case OP_MINQUERY:      case OP_MINQUERY:
2469        case OP_MINQUERYI:
2470        case OP_POSQUERY:
2471        case OP_POSQUERYI:
2472        if (utf && HAS_EXTRALEN(code[1])) code += GET_EXTRALEN(code[1]);
2473        break;
2474    
2475      case OP_UPTO:      case OP_UPTO:
2476        case OP_UPTOI:
2477      case OP_MINUPTO:      case OP_MINUPTO:
2478      if (utf8) while ((code[2] & 0xc0) == 0x80) code++;      case OP_MINUPTOI:
2479        case OP_POSUPTO:
2480        case OP_POSUPTOI:
2481        if (utf && HAS_EXTRALEN(code[1 + IMM2_SIZE])) code += GET_EXTRALEN(code[1 + IMM2_SIZE]);
2482      break;      break;
2483  #endif  #endif
2484    
2485        /* MARK, and PRUNE/SKIP/THEN with an argument must skip over the argument
2486        string. */
2487    
2488        case OP_MARK:
2489        case OP_PRUNE_ARG:
2490        case OP_SKIP_ARG:
2491        code += code[1];
2492        break;
2493    
2494        case OP_THEN_ARG:
2495        code += code[1];
2496        break;
2497    
2498        /* None of the remaining opcodes are required to match a character. */
2499    
2500        default:
2501        break;
2502      }      }
2503    }    }
2504    
# Line 1299  return TRUE; Line 2515  return TRUE;
2515  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
2516  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,
2517  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.
2518    This function is called only during the real compile, not during the
2519    pre-compile.
2520    
2521  Arguments:  Arguments:
2522    code        points to start of the recursion    code        points to start of the recursion
2523    endcode     points to where to stop (current RECURSE item)    endcode     points to where to stop (current RECURSE item)
2524    bcptr       points to the chain of current (unclosed) branch starts    bcptr       points to the chain of current (unclosed) branch starts
2525    utf8        TRUE if in UTF-8 mode    utf         TRUE if in UTF-8 / UTF-16 mode
2526      cd          pointers to tables etc
2527    
2528  Returns:      TRUE if what is matched could be empty  Returns:      TRUE if what is matched could be empty
2529  */  */
2530    
2531  static BOOL  static BOOL
2532  could_be_empty(const uschar *code, const uschar *endcode, branch_chain *bcptr,  could_be_empty(const pcre_uchar *code, const pcre_uchar *endcode,
2533    BOOL utf8)    branch_chain *bcptr, BOOL utf, compile_data *cd)
2534  {  {
2535  while (bcptr != NULL && bcptr->current >= code)  while (bcptr != NULL && bcptr->current_branch >= code)
2536    {    {
2537    if (!could_be_empty_branch(bcptr->current, endcode, utf8)) return FALSE;    if (!could_be_empty_branch(bcptr->current_branch, endcode, utf, cd))
2538        return FALSE;
2539    bcptr = bcptr->outer;    bcptr = bcptr->outer;
2540    }    }
2541  return TRUE;  return TRUE;
# Line 1328  return TRUE; Line 2548  return TRUE;
2548  *************************************************/  *************************************************/
2549    
2550  /* This function is called when the sequence "[:" or "[." or "[=" is  /* This function is called when the sequence "[:" or "[." or "[=" is
2551  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
2552  optional ^ and then a sequence of letters, terminated by a matching ":]" or  sequence of characters terminated by a matching ":]" or ".]" or "=]". If we
2553  ".]" or "=]".  reach an unescaped ']' without the special preceding character, return FALSE.
2554    
2555    Originally, this function only recognized a sequence of letters between the
2556    terminators, but it seems that Perl recognizes any sequence of characters,
2557    though of course unknown POSIX names are subsequently rejected. Perl gives an
2558    "Unknown POSIX class" error for [:f\oo:] for example, where previously PCRE
2559    didn't consider this to be a POSIX class. Likewise for [:1234:].
2560    
2561    The problem in trying to be exactly like Perl is in the handling of escapes. We
2562    have to be sure that [abc[:x\]pqr] is *not* treated as containing a POSIX
2563    class, but [abc[:x\]pqr:]] is (so that an error can be generated). The code
2564    below handles the special case of \], but does not try to do any other escape
2565    processing. This makes it different from Perl for cases such as [:l\ower:]
2566    where Perl recognizes it as the POSIX class "lower" but PCRE does not recognize
2567    "l\ower". This is a lesser evil that not diagnosing bad classes when Perl does,
2568    I think.
2569    
2570    A user pointed out that PCRE was rejecting [:a[:digit:]] whereas Perl was not.
2571    It seems that the appearance of a nested POSIX class supersedes an apparent
2572    external class. For example, [:a[:digit:]b:] matches "a", "b", ":", or
2573    a digit.
2574    
2575    In Perl, unescaped square brackets may also appear as part of class names. For
2576    example, [:a[:abc]b:] gives unknown POSIX class "[:abc]b:]". However, for
2577    [:a[:abc]b][b:] it gives unknown POSIX class "[:abc]b][b:]", which does not
2578    seem right at all. PCRE does not allow closing square brackets in POSIX class
2579    names.
2580    
2581  Argument:  Arguments:
2582    ptr      pointer to the initial [    ptr      pointer to the initial [
2583    endptr   where to return the end pointer    endptr   where to return the end pointer
   cd       pointer to compile data  
2584    
2585  Returns:   TRUE or FALSE  Returns:   TRUE or FALSE
2586  */  */
2587    
2588  static BOOL  static BOOL
2589  check_posix_syntax(const uschar *ptr, const uschar **endptr, compile_data *cd)  check_posix_syntax(const pcre_uchar *ptr, const pcre_uchar **endptr)
2590  {  {
2591  int terminator;          /* Don't combine these lines; the Solaris cc */  int terminator;          /* Don't combine these lines; the Solaris cc */
2592  terminator = *(++ptr);   /* compiler warns about "non-constant" initializer. */  terminator = *(++ptr);   /* compiler warns about "non-constant" initializer. */
2593  if (*(++ptr) == '^') ptr++;  for (++ptr; *ptr != 0; ptr++)
 while ((cd->ctypes[*ptr] & ctype_letter) != 0) ptr++;  
 if (*ptr == terminator && ptr[1] == ']')  
2594    {    {
2595    *endptr = ptr;    if (*ptr == CHAR_BACKSLASH && ptr[1] == CHAR_RIGHT_SQUARE_BRACKET)
2596    return TRUE;      ptr++;
2597      else if (*ptr == CHAR_RIGHT_SQUARE_BRACKET) return FALSE;
2598      else
2599        {
2600        if (*ptr == terminator && ptr[1] == CHAR_RIGHT_SQUARE_BRACKET)
2601          {
2602          *endptr = ptr;
2603          return TRUE;
2604          }
2605        if (*ptr == CHAR_LEFT_SQUARE_BRACKET &&
2606             (ptr[1] == CHAR_COLON || ptr[1] == CHAR_DOT ||
2607              ptr[1] == CHAR_EQUALS_SIGN) &&
2608            check_posix_syntax(ptr, endptr))
2609          return FALSE;
2610        }
2611    }    }
2612  return FALSE;  return FALSE;
2613  }  }
# Line 1373  Returns:     a value representing the na Line 2630  Returns:     a value representing the na
2630  */  */
2631    
2632  static int  static int
2633  check_posix_name(const uschar *ptr, int len)  check_posix_name(const pcre_uchar *ptr, int len)
2634  {  {
2635    const char *pn = posix_names;
2636  register int yield = 0;  register int yield = 0;
2637  while (posix_name_lengths[yield] != 0)  while (posix_name_lengths[yield] != 0)
2638    {    {
2639    if (len == posix_name_lengths[yield] &&    if (len == posix_name_lengths[yield] &&
2640      strncmp((const char *)ptr, posix_names[yield], len) == 0) return yield;      STRNCMP_UC_C8(ptr, pn, len) == 0) return yield;
2641      pn += posix_name_lengths[yield] + 1;
2642    yield++;    yield++;
2643    }    }
2644  return -1;  return -1;
# Line 1394  return -1; Line 2653  return -1;
2653  that is referenced. This means that groups can be replicated for fixed  that is referenced. This means that groups can be replicated for fixed
2654  repetition simply by copying (because the recursion is allowed to refer to  repetition simply by copying (because the recursion is allowed to refer to
2655  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
2656  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
2657  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
2658  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
2659  offsets adjusted. That is the job of this function. Before it is called, the  have their offsets adjusted. That one of the jobs of this function. Before it
2660  partially compiled regex must be temporarily terminated with OP_END.  is called, the partially compiled regex must be temporarily terminated with
2661    OP_END.
2662    
2663    This function has been extended with the possibility of forward references for
2664    recursions and subroutine calls. It must also check the list of such references
2665    for the group we are dealing with. If it finds that one of the recursions in
2666    the current group is on this list, it adjusts the offset in the list, not the
2667    value in the reference (which is a group number).
2668    
2669  Arguments:  Arguments:
2670    group      points to the start of the group    group      points to the start of the group
2671    adjust     the amount by which the group is to be moved    adjust     the amount by which the group is to be moved
2672    utf8       TRUE in UTF-8 mode    utf        TRUE in UTF-8 / UTF-16 mode
2673    cd         contains pointers to tables etc.    cd         contains pointers to tables etc.
2674      save_hwm   the hwm forward reference pointer at the start of the group
2675    
2676  Returns:     nothing  Returns:     nothing
2677  */  */
2678    
2679  static void  static void
2680  adjust_recurse(uschar *group, int adjust, BOOL utf8, compile_data *cd)  adjust_recurse(pcre_uchar *group, int adjust, BOOL utf, compile_data *cd,
2681      pcre_uchar *save_hwm)
2682  {  {
2683  uschar *ptr = group;  pcre_uchar *ptr = group;
2684  while ((ptr = (uschar *)find_recurse(ptr, utf8)) != NULL)  
2685    while ((ptr = (pcre_uchar *)find_recurse(ptr, utf)) != NULL)
2686    {    {
2687    int offset = GET(ptr, 1);    int offset;
2688    if (cd->start_code + offset >= group) PUT(ptr, 1, offset + adjust);    pcre_uchar *hc;
2689    
2690      /* See if this recursion is on the forward reference list. If so, adjust the
2691      reference. */
2692    
2693      for (hc = save_hwm; hc < cd->hwm; hc += LINK_SIZE)
2694        {
2695        offset = GET(hc, 0);
2696        if (cd->start_code + offset == ptr + 1)
2697          {
2698          PUT(hc, 0, offset + adjust);
2699          break;
2700          }
2701        }
2702    
2703      /* Otherwise, adjust the recursion offset if it's after the start of this
2704      group. */
2705    
2706      if (hc >= cd->hwm)
2707        {
2708        offset = GET(ptr, 1);
2709        if (cd->start_code + offset >= group) PUT(ptr, 1, offset + adjust);
2710        }
2711    
2712    ptr += 1 + LINK_SIZE;    ptr += 1 + LINK_SIZE;
2713    }    }
2714  }  }
# Line 1438  Arguments: Line 2730  Arguments:
2730  Returns:         new code pointer  Returns:         new code pointer
2731  */  */
2732    
2733  static uschar *  static pcre_uchar *
2734  auto_callout(uschar *code, const uschar *ptr, compile_data *cd)  auto_callout(pcre_uchar *code, const pcre_uchar *ptr, compile_data *cd)
2735  {  {
2736  *code++ = OP_CALLOUT;  *code++ = OP_CALLOUT;
2737  *code++ = 255;  *code++ = 255;
2738  PUT(code, 0, ptr - cd->start_pattern);  /* Pattern offset */  PUT(code, 0, (int)(ptr - cd->start_pattern));  /* Pattern offset */
2739  PUT(code, LINK_SIZE, 0);                /* Default length */  PUT(code, LINK_SIZE, 0);                       /* Default length */
2740  return code + 2*LINK_SIZE;  return code + 2 * LINK_SIZE;
2741  }  }
2742    
2743    
# Line 1467  Returns:             nothing Line 2759  Returns:             nothing
2759  */  */
2760    
2761  static void  static void
2762  complete_callout(uschar *previous_callout, const uschar *ptr, compile_data *cd)  complete_callout(pcre_uchar *previous_callout, const pcre_uchar *ptr, compile_data *cd)
2763  {  {
2764  int length = ptr - cd->start_pattern - GET(previous_callout, 2);  int length = (int)(ptr - cd->start_pattern - GET(previous_callout, 2));
2765  PUT(previous_callout, 2 + LINK_SIZE, length);  PUT(previous_callout, 2 + LINK_SIZE, length);
2766  }  }
2767    
# Line 1495  Yield:        TRUE when range returned; Line 2787  Yield:        TRUE when range returned;
2787  */  */
2788    
2789  static BOOL  static BOOL
2790  get_othercase_range(int *cptr, int d, int *ocptr, int *odptr)  get_othercase_range(unsigned int *cptr, unsigned int d, unsigned int *ocptr,
2791      unsigned int *odptr)
2792  {  {
2793  int c, chartype, othercase, next;  unsigned int c, othercase, next;
2794    
2795  for (c = *cptr; c <= d; c++)  for (c = *cptr; c <= d; c++)
2796    {    { if ((othercase = UCD_OTHERCASE(c)) != c) break; }
   if (_pcre_ucp_findchar(c, &chartype, &othercase) == ucp_L && othercase != 0)  
     break;  
   }  
2797    
2798  if (c > d) return FALSE;  if (c > d) return FALSE;
2799    
# Line 1512  next = othercase + 1; Line 2802  next = othercase + 1;
2802    
2803  for (++c; c <= d; c++)  for (++c; c <= d; c++)
2804    {    {
2805    if (_pcre_ucp_findchar(c, &chartype, &othercase) != ucp_L ||    if (UCD_OTHERCASE(c) != next) break;
         othercase != next)  
     break;  
2806    next++;    next++;
2807    }    }
2808    
# Line 1523  for (++c; c <= d; c++) Line 2811  for (++c; c <= d; c++)
2811    
2812  return TRUE;  return TRUE;
2813  }  }
2814  #endif  /* SUPPORT_UCP */  
2815    
2816    
2817  /*************************************************  /*************************************************
2818  *           Compile one branch                   *  *        Check a character and a property        *
2819  *************************************************/  *************************************************/
2820    
2821  /* Scan the pattern, compiling it into the code vector. If the options are  /* This function is called by check_auto_possessive() when a property item
2822  changed during the branch, the pointer is used to change the external options  is adjacent to a fixed character.
 bits.  
2823    
2824  Arguments:  Arguments:
2825    optionsptr     pointer to the option bits    c            the character
2826    brackets       points to number of extracting brackets used    ptype        the property type
2827    codeptr        points to the pointer to the current code point    pdata        the data for the type
2828    ptrptr         points to the current pattern pointer    negated      TRUE if it's a negated property (\P or \p{^)
   errorcodeptr   points to error code variable  
   firstbyteptr   set to initial literal character, or < 0 (REQ_UNSET, REQ_NONE)  
   reqbyteptr     set to the last literal character required, else < 0  
   bcptr          points to current branch chain  
   cd             contains pointers to tables etc.  
2829    
2830  Returns:         TRUE on success  Returns:       TRUE if auto-possessifying is OK
                  FALSE, with *errorcodeptr set non-zero on error  
2831  */  */
2832    
2833  static BOOL  static BOOL
2834  compile_branch(int *optionsptr, int *brackets, uschar **codeptr,  check_char_prop(int c, int ptype, int pdata, BOOL negated)
   const uschar **ptrptr, int *errorcodeptr, int *firstbyteptr,  
   int *reqbyteptr, branch_chain *bcptr, compile_data *cd)  
2835  {  {
2836  int repeat_type, op_type;  const ucd_record *prop = GET_UCD(c);
2837  int repeat_min = 0, repeat_max = 0;      /* To please picky compilers */  switch(ptype)
2838  int bravalue = 0;    {
2839  int greedy_default, greedy_non_default;    case PT_LAMP:
2840  int firstbyte, reqbyte;    return (prop->chartype == ucp_Lu ||
2841  int zeroreqbyte, zerofirstbyte;            prop->chartype == ucp_Ll ||
2842  int req_caseopt, reqvary, tempreqvary;            prop->chartype == ucp_Lt) == negated;
2843  int condcount = 0;  
2844  int options = *optionsptr;    case PT_GC:
2845  int after_manual_callout = 0;    return (pdata == PRIV(ucp_gentype)[prop->chartype]) == negated;
2846  register int c;  
2847  register uschar *code = *codeptr;    case PT_PC:
2848  uschar *tempcode;    return (pdata == prop->chartype) == negated;
2849  BOOL inescq = FALSE;  
2850  BOOL groupsetfirstbyte = FALSE;    case PT_SC:
2851  const uschar *ptr = *ptrptr;    return (pdata == prop->script) == negated;
2852  const uschar *tempptr;  
2853  uschar *previous = NULL;    /* These are specials */
2854  uschar *previous_callout = NULL;  
2855  uschar classbits[32];    case PT_ALNUM:
2856      return (PRIV(ucp_gentype)[prop->chartype] == ucp_L ||
2857  #ifdef SUPPORT_UTF8            PRIV(ucp_gentype)[prop->chartype] == ucp_N) == negated;
2858  BOOL class_utf8;  
2859  BOOL utf8 = (options & PCRE_UTF8) != 0;    case PT_SPACE:    /* Perl space */
2860  uschar *class_utf8data;    return (PRIV(ucp_gentype)[prop->chartype] == ucp_Z ||
2861  uschar utf8_char[6];            c == CHAR_HT || c == CHAR_NL || c == CHAR_FF || c == CHAR_CR)
2862  #else            == negated;
2863  BOOL utf8 = FALSE;  
2864  #endif    case PT_PXSPACE:  /* POSIX space */
2865      return (PRIV(ucp_gentype)[prop->chartype] == ucp_Z ||
2866              c == CHAR_HT || c == CHAR_NL || c == CHAR_VT ||
2867              c == CHAR_FF || c == CHAR_CR)
2868              == negated;
2869    
2870      case PT_WORD:
2871      return (PRIV(ucp_gentype)[prop->chartype] == ucp_L ||
2872              PRIV(ucp_gentype)[prop->chartype] == ucp_N ||
2873              c == CHAR_UNDERSCORE) == negated;
2874      }
2875    return FALSE;
2876    }
2877    #endif  /* SUPPORT_UCP */
2878    
 /* Set up the default and non-default settings for greediness */  
2879    
 greedy_default = ((options & PCRE_UNGREEDY) != 0);  
 greedy_non_default = greedy_default ^ 1;  
2880    
2881  /* Initialize no first byte, no required byte. REQ_UNSET means "no char  /*************************************************
2882  matching encountered yet". It gets changed to REQ_NONE if we hit something that  *     Check if auto-possessifying is possible    *
2883  matches a non-fixed char first char; reqbyte just remains unset if we never  *************************************************/
 find one.  
2884    
2885  When we hit a repeat whose minimum is zero, we may have to adjust these values  /* This function is called for unlimited repeats of certain items, to see
2886  to take the zero repeat into account. This is implemented by setting them to  whether the next thing could possibly match the repeated item. If not, it makes
2887  zerofirstbyte and zeroreqbyte when such a repeat is encountered. The individual  sense to automatically possessify the repeated item.
 item types that can be repeated set these backoff variables appropriately. */  
2888    
2889  firstbyte = reqbyte = zerofirstbyte = zeroreqbyte = REQ_UNSET;  Arguments:
2890      previous      pointer to the repeated opcode
2891      utf           TRUE in UTF-8 / UTF-16 mode
2892      ptr           next character in pattern
2893      options       options bits
2894      cd            contains pointers to tables etc.
2895    
2896  /* The variable req_caseopt contains either the REQ_CASELESS value or zero,  Returns:        TRUE if possessifying is wanted
2897  according to the current setting of the caseless flag. REQ_CASELESS is a bit  */
 value > 255. It is added into the firstbyte or reqbyte variables to record the  
 case status of the value. This is used only for ASCII characters. */  
2898    
2899  req_caseopt = ((options & PCRE_CASELESS) != 0)? REQ_CASELESS : 0;  static BOOL
2900    check_auto_possessive(const pcre_uchar *previous, BOOL utf,
2901      const pcre_uchar *ptr, int options, compile_data *cd)
2902    {
2903    pcre_int32 c, next;
2904    int op_code = *previous++;
2905    
2906  /* Switch on next character until the end of the branch */  /* Skip whitespace and comments in extended mode */
2907    
2908  for (;; ptr++)  if ((options & PCRE_EXTENDED) != 0)
2909    {    {
2910    BOOL negate_class;    for (;;)
2911    BOOL possessive_quantifier;      {
2912    BOOL is_quantifier;      while ((cd->ctypes[*ptr] & ctype_space) != 0) ptr++;
2913    int class_charcount;      if (*ptr == CHAR_NUMBER_SIGN)
2914    int class_lastchar;        {
2915    int newoptions;        ptr++;
2916    int recno;        while (*ptr != 0)
2917    int skipbytes;          {
2918    int subreqbyte;          if (IS_NEWLINE(ptr)) { ptr += cd->nllen; break; }
2919    int subfirstbyte;          ptr++;
2920    int mclength;  #ifdef SUPPORT_UTF
2921    uschar mcbuffer[8];          if (utf) FORWARDCHAR(ptr);
2922    #endif
2923            }
2924          }
2925        else break;
2926        }
2927      }
2928    
2929    /* Next byte in the pattern */  /* If the next item is one that we can handle, get its value. A non-negative
2930    value is a character, a negative value is an escape value. */
2931    
2932    c = *ptr;  if (*ptr == CHAR_BACKSLASH)
2933      {
2934      int temperrorcode = 0;
2935      next = check_escape(&ptr, &temperrorcode, cd->bracount, options, FALSE);
2936      if (temperrorcode != 0) return FALSE;
2937      ptr++;    /* Point after the escape sequence */
2938      }
2939    else if (!MAX_255(*ptr) || (cd->ctypes[*ptr] & ctype_meta) == 0)
2940      {
2941    #ifdef SUPPORT_UTF
2942      if (utf) { GETCHARINC(next, ptr); } else
2943    #endif
2944      next = *ptr++;
2945      }
2946    else return FALSE;
2947    
2948    /* If in \Q...\E, check for the end; if not, we have a literal */  /* Skip whitespace and comments in extended mode */
2949    
2950    if (inescq && c != 0)  if ((options & PCRE_EXTENDED) != 0)
2951      {
2952      for (;;)
2953      {      {
2954      if (c == '\\' && ptr[1] == 'E')      while ((cd->ctypes[*ptr] & ctype_space) != 0) ptr++;
2955        if (*ptr == CHAR_NUMBER_SIGN)
2956        {        {
       inescq = FALSE;  
2957        ptr++;        ptr++;
2958        continue;        while (*ptr != 0)
       }  
     else  
       {  
       if (previous_callout != NULL)  
         {  
         complete_callout(previous_callout, ptr, cd);  
         previous_callout = NULL;  
         }  
       if ((options & PCRE_AUTO_CALLOUT) != 0)  
2959          {          {
2960          previous_callout = code;          if (IS_NEWLINE(ptr)) { ptr += cd->nllen; break; }
2961          code = auto_callout(code, ptr, cd);          ptr++;
2962    #ifdef SUPPORT_UTF
2963            if (utf) FORWARDCHAR(ptr);
2964    #endif
2965          }          }
       goto NORMAL_CHAR;  
2966        }        }
2967        else break;
2968      }      }
2969      }
2970    
2971    /* Fill in length of a previous callout, except when the next thing is  /* If the next thing is itself optional, we have to give up. */
   a quantifier. */  
2972    
2973    is_quantifier = c == '*' || c == '+' || c == '?' ||  if (*ptr == CHAR_ASTERISK || *ptr == CHAR_QUESTION_MARK ||
2974      (c == '{' && is_counted_repeat(ptr+1));    STRNCMP_UC_C8(ptr, STR_LEFT_CURLY_BRACKET STR_0 STR_COMMA, 3) == 0)
2975        return FALSE;
2976    
2977    if (!is_quantifier && previous_callout != NULL &&  /* Now compare the next item with the previous opcode. First, handle cases when
2978         after_manual_callout-- <= 0)  the next item is a character. */
2979      {  
2980      complete_callout(previous_callout, ptr, cd);  if (next >= 0) switch(op_code)
2981      previous_callout = NULL;    {
2982      }    case OP_CHAR:
2983    #ifdef SUPPORT_UTF8
2984      GETCHARTEST(c, previous);
2985    #else
2986      c = *previous;
2987    #endif
2988      return c != next;
2989    
2990    /* In extended mode, skip white space and comments */    /* For CHARI (caseless character) we must check the other case. If we have
2991      Unicode property support, we can use it to test the other case of
2992      high-valued characters. */
2993    
2994    if ((options & PCRE_EXTENDED) != 0)    case OP_CHARI:
2995    #ifdef SUPPORT_UTF8
2996      GETCHARTEST(c, previous);
2997    #else
2998      c = *previous;
2999    #endif
3000      if (c == next) return FALSE;
3001    #ifdef SUPPORT_UTF8
3002      if (utf)
3003      {      {
3004      if ((cd->ctypes[c] & ctype_space) != 0) continue;      unsigned int othercase;
3005      if (c == '#')      if (next < 128) othercase = cd->fcc[next]; else
3006        {  #ifdef SUPPORT_UCP
3007        /* The space before the ; is to avoid a warning on a silly compiler      othercase = UCD_OTHERCASE((unsigned int)next);
3008        on the Macintosh. */  #else
3009        while ((c = *(++ptr)) != 0 && c != NEWLINE) ;      othercase = NOTACHAR;
3010        if (c != 0) continue;   /* Else fall through to handle end of string */  #endif
3011        }      return (unsigned int)c != othercase;
3012      }      }
3013      else
3014    #endif  /* SUPPORT_UTF8 */
3015      return (c != cd->fcc[next]);  /* Non-UTF-8 mode */
3016    
3017    /* No auto callout for quantifiers. */    /* For OP_NOT and OP_NOTI, the data is always a single-byte character. These
3018      opcodes are not used for multi-byte characters, because they are coded using
3019      an XCLASS instead. */
3020    
3021    if ((options & PCRE_AUTO_CALLOUT) != 0 && !is_quantifier)    case OP_NOT:
3022      return (c = *previous) == next;
3023    
3024      case OP_NOTI:
3025      if ((c = *previous) == next) return TRUE;
3026    #ifdef SUPPORT_UTF8
3027      if (utf)
3028      {      {
3029      previous_callout = code;      unsigned int othercase;
3030      code = auto_callout(code, ptr, cd);      if (next < 128) othercase = cd->fcc[next]; else
3031    #ifdef SUPPORT_UCP
3032        othercase = UCD_OTHERCASE(next);
3033    #else
3034        othercase = NOTACHAR;
3035    #endif
3036        return (unsigned int)c == othercase;
3037      }      }
3038      else
3039    #endif  /* SUPPORT_UTF8 */
3040      return (c == cd->fcc[next]);  /* Non-UTF-8 mode */
3041    
3042    switch(c)    /* Note that OP_DIGIT etc. are generated only when PCRE_UCP is *not* set.
3043      {    When it is set, \d etc. are converted into OP_(NOT_)PROP codes. */
     /* The branch terminates at end of string, |, or ). */  
3044    
3045      case 0:    case OP_DIGIT:
3046      case '|':    return next > 127 || (cd->ctypes[next] & ctype_digit) == 0;
     case ')':  
     *firstbyteptr = firstbyte;  
     *reqbyteptr = reqbyte;  
     *codeptr = code;  
     *ptrptr = ptr;  
     return TRUE;  
3047    
3048      /* Handle single-character metacharacters. In multiline mode, ^ disables    case OP_NOT_DIGIT:
3049      the setting of any following char as a first character. */    return next <= 127 && (cd->ctypes[next] & ctype_digit) != 0;
3050    
3051      case '^':    case OP_WHITESPACE:
3052      if ((options & PCRE_MULTILINE) != 0)    return next > 127 || (cd->ctypes[next] & ctype_space) == 0;
       {  
       if (firstbyte == REQ_UNSET) firstbyte = REQ_NONE;  
       }  
     previous = NULL;  
     *code++ = OP_CIRC;  
     break;  
3053    
3054      case '$':    case OP_NOT_WHITESPACE:
3055      previous = NULL;    return next <= 127 && (cd->ctypes[next] & ctype_space) != 0;
     *code++ = OP_DOLL;  
     break;  
3056    
3057      /* There can never be a first char if '.' is first, whatever happens about    case OP_WORDCHAR:
3058      repeats. The value of reqbyte doesn't change either. */    return next > 127 || (cd->ctypes[next] & ctype_word) == 0;
3059    
3060      case '.':    case OP_NOT_WORDCHAR:
3061      if (firstbyte == REQ_UNSET) firstbyte = REQ_NONE;    return next <= 127 && (cd->ctypes[next] & ctype_word) != 0;
     zerofirstbyte = firstbyte;  
     zeroreqbyte = reqbyte;  
     previous = code;  
     *code++ = OP_ANY;  
     break;  
3062    
3063      /* Character classes. If the included characters are all < 255 in value, we    case OP_HSPACE:
3064      build a 32-byte bitmap of the permitted characters, except in the special    case OP_NOT_HSPACE:
3065      case where there is only one such character. For negated classes, we build    switch(next)
3066      the map as usual, then invert it at the end. However, we use a different      {
3067      opcode so that data characters > 255 can be handled correctly.      case 0x09:
3068        case 0x20:
3069        case 0xa0:
3070        case 0x1680:
3071        case 0x180e:
3072        case 0x2000:
3073        case 0x2001:
3074        case 0x2002:
3075        case 0x2003:
3076        case 0x2004:
3077        case 0x2005:
3078        case 0x2006:
3079        case 0x2007:
3080        case 0x2008:
3081        case 0x2009:
3082        case 0x200A:
3083        case 0x202f:
3084        case 0x205f:
3085        case 0x3000:
3086        return op_code == OP_NOT_HSPACE;
3087        default:
3088        return op_code != OP_NOT_HSPACE;
3089        }
3090    
3091      If the class contains characters outside the 0-255 range, a different    case OP_ANYNL:
3092      opcode is compiled. It may optionally have a bit map for characters < 256,    case OP_VSPACE:
3093      but those above are are explicitly listed afterwards. A flag byte tells    case OP_NOT_VSPACE:
3094      whether the bitmap is present, and whether this is a negated class or not.    switch(next)
3095      */      {
3096        case 0x0a:
3097        case 0x0b:
3098        case 0x0c:
3099        case 0x0d:
3100        case 0x85:
3101        case 0x2028:
3102        case 0x2029:
3103        return op_code == OP_NOT_VSPACE;
3104        default:
3105        return op_code != OP_NOT_VSPACE;
3106        }
3107    
3108      case '[':  #ifdef SUPPORT_UCP
3109      previous = code;    case OP_PROP:
3110      return check_char_prop(next, previous[0], previous[1], FALSE);
3111    
3112      /* PCRE supports POSIX class stuff inside a class. Perl gives an error if    case OP_NOTPROP:
3113      they are encountered at the top level, so we'll do that too. */    return check_char_prop(next, previous[0], previous[1], TRUE);
3114    #endif
3115    
3116      if ((ptr[1] == ':' || ptr[1] == '.' || ptr[1] == '=') &&    default:
3117          check_posix_syntax(ptr, &tempptr, cd))    return FALSE;
3118        {    }
3119        *errorcodeptr = (ptr[1] == ':')? ERR13 : ERR31;  
3120    
3121    /* Handle the case when the next item is \d, \s, etc. Note that when PCRE_UCP
3122    is set, \d turns into ESC_du rather than ESC_d, etc., so ESC_d etc. are
3123    generated only when PCRE_UCP is *not* set, that is, when only ASCII
3124    characteristics are recognized. Similarly, the opcodes OP_DIGIT etc. are
3125    replaced by OP_PROP codes when PCRE_UCP is set. */
3126    
3127    switch(op_code)
3128      {
3129      case OP_CHAR:
3130      case OP_CHARI:
3131    #ifdef SUPPORT_UTF8
3132      GETCHARTEST(c, previous);
3133    #else
3134      c = *previous;
3135    #endif
3136      switch(-next)
3137        {
3138        case ESC_d:
3139        return c > 127 || (cd->ctypes[c] & ctype_digit) == 0;
3140    
3141        case ESC_D:
3142        return c <= 127 && (cd->ctypes[c] & ctype_digit) != 0;
3143    
3144        case ESC_s:
3145        return c > 127 || (cd->ctypes[c] & ctype_space) == 0;
3146    
3147        case ESC_S:
3148        return c <= 127 && (cd->ctypes[c] & ctype_space) != 0;
3149    
3150        case ESC_w:
3151        return c > 127 || (cd->ctypes[c] & ctype_word) == 0;
3152    
3153        case ESC_W:
3154        return c <= 127 && (cd->ctypes[c] & ctype_word) != 0;
3155    
3156        case ESC_h:
3157        case ESC_H:
3158        switch(c)
3159          {
3160          case 0x09:
3161          case 0x20:
3162          case 0xa0:
3163          case 0x1680:
3164          case 0x180e:
3165          case 0x2000:
3166          case 0x2001:
3167          case 0x2002:
3168          case 0x2003:
3169          case 0x2004:
3170          case 0x2005:
3171          case 0x2006:
3172          case 0x2007:
3173          case 0x2008:
3174          case 0x2009:
3175          case 0x200A:
3176          case 0x202f:
3177          case 0x205f:
3178          case 0x3000:
3179          return -next != ESC_h;
3180          default:
3181          return -next == ESC_h;
3182          }
3183    
3184        case ESC_v:
3185        case ESC_V:
3186        switch(c)
3187          {
3188          case 0x0a:
3189          case 0x0b:
3190          case 0x0c:
3191          case 0x0d:
3192          case 0x85:
3193          case 0x2028:
3194          case 0x2029:
3195          return -next != ESC_v;
3196          default:
3197          return -next == ESC_v;
3198          }
3199    
3200        /* When PCRE_UCP is set, these values get generated for \d etc. Find
3201        their substitutions and process them. The result will always be either
3202        -ESC_p or -ESC_P. Then fall through to process those values. */
3203    
3204    #ifdef SUPPORT_UCP
3205        case ESC_du:
3206        case ESC_DU:
3207        case ESC_wu:
3208        case ESC_WU:
3209        case ESC_su:
3210        case ESC_SU:
3211          {
3212          int temperrorcode = 0;
3213          ptr = substitutes[-next - ESC_DU];
3214          next = check_escape(&ptr, &temperrorcode, 0, options, FALSE);
3215          if (temperrorcode != 0) return FALSE;
3216          ptr++;    /* For compatibility */
3217          }
3218        /* Fall through */
3219    
3220        case ESC_p:
3221        case ESC_P:
3222          {
3223          int ptype, pdata, errorcodeptr;
3224          BOOL negated;
3225    
3226          ptr--;      /* Make ptr point at the p or P */
3227          ptype = get_ucp(&ptr, &negated, &pdata, &errorcodeptr);
3228          if (ptype < 0) return FALSE;
3229          ptr++;      /* Point past the final curly ket */
3230    
3231          /* If the property item is optional, we have to give up. (When generated
3232          from \d etc by PCRE_UCP, this test will have been applied much earlier,
3233          to the original \d etc. At this point, ptr will point to a zero byte. */
3234    
3235          if (*ptr == CHAR_ASTERISK || *ptr == CHAR_QUESTION_MARK ||
3236            STRNCMP_UC_C8(ptr, STR_LEFT_CURLY_BRACKET STR_0 STR_COMMA, 3) == 0)
3237              return FALSE;
3238    
3239          /* Do the property check. */
3240    
3241          return check_char_prop(c, ptype, pdata, (next == -ESC_P) != negated);
3242          }
3243    #endif
3244    
3245        default:
3246        return FALSE;
3247        }
3248    
3249      /* In principle, support for Unicode properties should be integrated here as
3250      well. It means re-organizing the above code so as to get hold of the property
3251      values before switching on the op-code. However, I wonder how many patterns
3252      combine ASCII \d etc with Unicode properties? (Note that if PCRE_UCP is set,
3253      these op-codes are never generated.) */
3254    
3255      case OP_DIGIT:
3256      return next == -ESC_D || next == -ESC_s || next == -ESC_W ||
3257             next == -ESC_h || next == -ESC_v || next == -ESC_R;
3258    
3259      case OP_NOT_DIGIT:
3260      return next == -ESC_d;
3261    
3262      case OP_WHITESPACE:
3263      return next == -ESC_S || next == -ESC_d || next == -ESC_w || next == -ESC_R;
3264    
3265      case OP_NOT_WHITESPACE:
3266      return next == -ESC_s || next == -ESC_h || next == -ESC_v;
3267    
3268      case OP_HSPACE:
3269      return next == -ESC_S || next == -ESC_H || next == -ESC_d ||
3270             next == -ESC_w || next == -ESC_v || next == -ESC_R;
3271    
3272      case OP_NOT_HSPACE:
3273      return next == -ESC_h;
3274    
3275      /* Can't have \S in here because VT matches \S (Perl anomaly) */
3276      case OP_ANYNL:
3277      case OP_VSPACE:
3278      return next == -ESC_V || next == -ESC_d || next == -ESC_w;
3279    
3280      case OP_NOT_VSPACE:
3281      return next == -ESC_v || next == -ESC_R;
3282    
3283      case OP_WORDCHAR:
3284      return next == -ESC_W || next == -ESC_s || next == -ESC_h ||
3285             next == -ESC_v || next == -ESC_R;
3286    
3287      case OP_NOT_WORDCHAR:
3288      return next == -ESC_w || next == -ESC_d;
3289    
3290      default:
3291      return FALSE;
3292      }
3293    
3294    /* Control does not reach here */
3295    }
3296    
3297    
3298    
3299    /*************************************************
3300    *           Compile one branch                   *
3301    *************************************************/
3302    
3303    /* Scan the pattern, compiling it into the a vector. If the options are
3304    changed during the branch, the pointer is used to change the external options
3305    bits. This function is used during the pre-compile phase when we are trying
3306    to find out the amount of memory needed, as well as during the real compile
3307    phase. The value of lengthptr distinguishes the two phases.
3308    
3309    Arguments:
3310      optionsptr     pointer to the option bits
3311      codeptr        points to the pointer to the current code point
3312      ptrptr         points to the current pattern pointer
3313      errorcodeptr   points to error code variable
3314      firstcharptr   set to initial literal character, or < 0 (REQ_UNSET, REQ_NONE)
3315      reqcharptr     set to the last literal character required, else < 0
3316      bcptr          points to current branch chain
3317      cond_depth     conditional nesting depth
3318      cd             contains pointers to tables etc.
3319      lengthptr      NULL during the real compile phase
3320                     points to length accumulator during pre-compile phase
3321    
3322    Returns:         TRUE on success
3323                     FALSE, with *errorcodeptr set non-zero on error
3324    */
3325    
3326    static BOOL
3327    compile_branch(int *optionsptr, pcre_uchar **codeptr,
3328      const pcre_uchar **ptrptr, int *errorcodeptr, pcre_int32 *firstcharptr,
3329      pcre_int32 *reqcharptr, branch_chain *bcptr, int cond_depth,
3330      compile_data *cd, int *lengthptr)
3331    {
3332    int repeat_type, op_type;
3333    int repeat_min = 0, repeat_max = 0;      /* To please picky compilers */
3334    int bravalue = 0;
3335    int greedy_default, greedy_non_default;
3336    pcre_int32 firstchar, reqchar;
3337    pcre_int32 zeroreqchar, zerofirstchar;
3338    pcre_int32 req_caseopt, reqvary, tempreqvary;
3339    int options = *optionsptr;               /* May change dynamically */
3340    int after_manual_callout = 0;
3341    int length_prevgroup = 0;
3342    register int c;
3343    register pcre_uchar *code = *codeptr;
3344    pcre_uchar *last_code = code;
3345    pcre_uchar *orig_code = code;
3346    pcre_uchar *tempcode;
3347    BOOL inescq = FALSE;
3348    BOOL groupsetfirstchar = FALSE;
3349    const pcre_uchar *ptr = *ptrptr;
3350    const pcre_uchar *tempptr;
3351    const pcre_uchar *nestptr = NULL;
3352    pcre_uchar *previous = NULL;
3353    pcre_uchar *previous_callout = NULL;
3354    pcre_uchar *save_hwm = NULL;
3355    pcre_uint8 classbits[32];
3356    
3357    /* We can fish out the UTF-8 setting once and for all into a BOOL, but we
3358    must not do this for other options (e.g. PCRE_EXTENDED) because they may change
3359    dynamically as we process the pattern. */
3360    
3361    #ifdef SUPPORT_UTF8
3362    /* PCRE_UTF16 has the same value as PCRE_UTF8. */
3363    BOOL utf = (options & PCRE_UTF8) != 0;
3364    pcre_uchar utf_chars[6];
3365    #else
3366    BOOL utf = FALSE;
3367    #endif
3368    
3369    /* Helper variables for OP_XCLASS opcode (for characters > 255). */
3370    
3371    #if defined SUPPORT_UTF || !defined COMPILE_PCRE8
3372    BOOL xclass;
3373    pcre_uchar *class_uchardata;
3374    pcre_uchar *class_uchardata_base;
3375    #endif
3376    
3377    #ifdef PCRE_DEBUG
3378    if (lengthptr != NULL) DPRINTF((">> start branch\n"));
3379    #endif
3380    
3381    /* Set up the default and non-default settings for greediness */
3382    
3383    greedy_default = ((options & PCRE_UNGREEDY) != 0);
3384    greedy_non_default = greedy_default ^ 1;
3385    
3386    /* Initialize no first byte, no required byte. REQ_UNSET means "no char
3387    matching encountered yet". It gets changed to REQ_NONE if we hit something that
3388    matches a non-fixed char first char; reqchar just remains unset if we never
3389    find one.
3390    
3391    When we hit a repeat whose minimum is zero, we may have to adjust these values
3392    to take the zero repeat into account. This is implemented by setting them to
3393    zerofirstbyte and zeroreqchar when such a repeat is encountered. The individual
3394    item types that can be repeated set these backoff variables appropriately. */
3395    
3396    firstchar = reqchar = zerofirstchar = zeroreqchar = REQ_UNSET;
3397    
3398    /* The variable req_caseopt contains either the REQ_CASELESS value
3399    or zero, according to the current setting of the caseless flag. The
3400    REQ_CASELESS leaves the lower 28 bit empty. It is added into the
3401    firstchar or reqchar variables to record the case status of the
3402    value. This is used only for ASCII characters. */
3403    
3404    req_caseopt = ((options & PCRE_CASELESS) != 0)? REQ_CASELESS:0;
3405    
3406    /* Switch on next character until the end of the branch */
3407    
3408    for (;; ptr++)
3409      {
3410      BOOL negate_class;
3411      BOOL should_flip_negation;
3412      BOOL possessive_quantifier;
3413      BOOL is_quantifier;
3414      BOOL is_recurse;
3415      BOOL reset_bracount;
3416      int class_charcount;
3417      int class_lastchar;
3418      int newoptions;
3419      int recno;
3420      int refsign;
3421      int skipbytes;
3422      int subreqchar;
3423      int subfirstchar;
3424      int terminator;
3425      int mclength;
3426      int tempbracount;
3427      pcre_uchar mcbuffer[8];
3428    
3429      /* Get next character in the pattern */
3430    
3431      c = *ptr;
3432    
3433      /* If we are at the end of a nested substitution, revert to the outer level
3434      string. Nesting only happens one level deep. */
3435    
3436      if (c == 0 && nestptr != NULL)
3437        {
3438        ptr = nestptr;
3439        nestptr = NULL;
3440        c = *ptr;
3441        }
3442    
3443      /* If we are in the pre-compile phase, accumulate the length used for the
3444      previous cycle of this loop. */
3445    
3446      if (lengthptr != NULL)
3447        {
3448    #ifdef PCRE_DEBUG
3449        if (code > cd->hwm) cd->hwm = code;                 /* High water info */
3450    #endif
3451        if (code > cd->start_workspace + WORK_SIZE_CHECK)   /* Check for overrun */
3452          {
3453          *errorcodeptr = ERR52;
3454        goto FAILED;        goto FAILED;
3455        }        }
3456    
3457      /* If the first character is '^', set the negation flag and skip it. */      /* There is at least one situation where code goes backwards: this is the
3458        case of a zero quantifier after a class (e.g. [ab]{0}). At compile time,
3459        the class is simply eliminated. However, it is created first, so we have to
3460        allow memory for it. Therefore, don't ever reduce the length at this point.
3461        */
3462    
3463        if (code < last_code) code = last_code;
3464    
3465        /* Paranoid check for integer overflow */
3466    
3467      if ((c = *(++ptr)) == '^')      if (OFLOW_MAX - *lengthptr < code - last_code)
3468        {        {
3469        negate_class = TRUE;        *errorcodeptr = ERR20;
3470        c = *(++ptr);        goto FAILED;
3471          }
3472    
3473        *lengthptr += (int)(code - last_code);
3474        DPRINTF(("length=%d added %d c=%c (0x%x)\n", *lengthptr,
3475          (int)(code - last_code), c, c));
3476    
3477        /* If "previous" is set and it is not at the start of the work space, move
3478        it back to there, in order to avoid filling up the work space. Otherwise,
3479        if "previous" is NULL, reset the current code pointer to the start. */
3480    
3481        if (previous != NULL)
3482          {
3483          if (previous > orig_code)
3484            {
3485            memmove(orig_code, previous, IN_UCHARS(code - previous));
3486            code -= previous - orig_code;
3487            previous = orig_code;
3488            }
3489          }
3490        else code = orig_code;
3491    
3492        /* Remember where this code item starts so we can pick up the length
3493        next time round. */
3494    
3495        last_code = code;
3496        }
3497    
3498      /* In the real compile phase, just check the workspace used by the forward
3499      reference list. */
3500    
3501      else if (cd->hwm > cd->start_workspace + WORK_SIZE_CHECK)
3502        {
3503        *errorcodeptr = ERR52;