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