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

Diff of /code/trunk/pcre_compile.c

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

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