GDesktopAppInfo: fix default app logic
[platform/upstream/glib.git] / glib / pcre / pcre_compile.c
1 /*************************************************
2 *      Perl-Compatible Regular Expressions       *
3 *************************************************/
4
5 /* PCRE is a library of functions to support regular expressions whose syntax
6 and semantics are as close as possible to those of the Perl 5 language.
7
8                        Written by Philip Hazel
9            Copyright (c) 1997-2012 University of Cambridge
10
11 -----------------------------------------------------------------------------
12 Redistribution and use in source and binary forms, with or without
13 modification, are permitted provided that the following conditions are met:
14
15     * Redistributions of source code must retain the above copyright notice,
16       this list of conditions and the following disclaimer.
17
18     * Redistributions in binary form must reproduce the above copyright
19       notice, this list of conditions and the following disclaimer in the
20       documentation and/or other materials provided with the distribution.
21
22     * Neither the name of the University of Cambridge nor the names of its
23       contributors may be used to endorse or promote products derived from
24       this software without specific prior written permission.
25
26 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
27 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
30 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 POSSIBILITY OF SUCH DAMAGE.
37 -----------------------------------------------------------------------------
38 */
39
40
41 /* This module contains the external function pcre_compile(), along with
42 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"
54
55 #ifdef GLIB_COMPILATION
56 #include "gstrfuncs.h"
57 #else
58 #include <glib.h>
59 #endif
60
61 /* When PCRE_DEBUG is defined, we need the pcre(16)_printint() function, which
62 is also used by pcretest. PCRE_DEBUG is not defined when building a production
63 library. We do not need to select pcre16_printint.c specially, because the
64 COMPILE_PCREx macro will already be appropriately set. */
65
66 #ifdef PCRE_DEBUG
67 /* pcre_printint.c should not include any headers */
68 #define PCRE_INCLUDED
69 #include "pcre_printint.c"
70 #undef PCRE_INCLUDED
71 #endif
72
73
74 /* Macro for setting individual bits in class bitmaps. */
75
76 #define SETBIT(a,b) a[b/8] |= (1 << (b%8))
77
78 /* Maximum length value to check against when making sure that the integer that
79 holds the compiled pattern length does not overflow. We make it a bit less than
80 INT_MAX to allow for adding in group terminating bytes, so that we don't have
81 to check them every time. */
82
83 #define OFLOW_MAX (INT_MAX - 20)
84
85
86 /*************************************************
87 *      Code parameters and static tables         *
88 *************************************************/
89
90 /* This value specifies the size of stack workspace that is used during the
91 first pre-compile phase that determines how much memory is required. The regex
92 is partly compiled into this space, but the compiled parts are discarded as
93 soon as they can be, so that hopefully there will never be an overrun. The code
94 does, however, check for an overrun. The largest amount I've seen used is 218,
95 so this number is very generous.
96
97 The same workspace is used during the second, actual compile phase for
98 remembering forward references to groups so that they can be filled in at the
99 end. Each entry in this list occupies LINK_SIZE bytes, so even when LINK_SIZE
100 is 4 there is plenty of room for most patterns. However, the memory can get
101 filled up by repetitions of forward references, for example patterns like
102 /(?1){0,1999}(b)/, and one user did hit the limit. The code has been changed so
103 that the workspace is expanded using malloc() in this situation. The value
104 below is therefore a minimum, and we put a maximum on it for safety. The
105 minimum is now also defined in terms of LINK_SIZE so that the use of malloc()
106 kicks in at the same number of forward references in all cases. */
107
108 #define COMPILE_WORK_SIZE (2048*LINK_SIZE)
109 #define COMPILE_WORK_SIZE_MAX (100*COMPILE_WORK_SIZE)
110
111 /* The overrun tests check for a slightly smaller size so that they detect the
112 overrun before it actually does run off the end of the data block. */
113
114 #define WORK_SIZE_SAFETY_MARGIN (100)
115
116 /* Private flags added to firstchar and reqchar. */
117
118 #define REQ_CASELESS   0x10000000l      /* Indicates caselessness */
119 #define REQ_VARY       0x20000000l      /* Reqchar followed non-literal item */
120
121 /* Repeated character flags. */
122
123 #define UTF_LENGTH     0x10000000l      /* The char contains its length. */
124
125 /* Table for handling escaped characters in the range '0'-'z'. Positive returns
126 are simple data values; negative values are for special things like \d and so
127 on. Zero means further processing is needed (for things like \x), or the escape
128 is invalid. */
129
130 #ifndef EBCDIC
131
132 /* This is the "normal" table for ASCII systems or for EBCDIC systems running
133 in UTF-8 mode. */
134
135 static const short int escapes[] = {
136      0,                       0,
137      0,                       0,
138      0,                       0,
139      0,                       0,
140      0,                       0,
141      CHAR_COLON,              CHAR_SEMICOLON,
142      CHAR_LESS_THAN_SIGN,     CHAR_EQUALS_SIGN,
143      CHAR_GREATER_THAN_SIGN,  CHAR_QUESTION_MARK,
144      CHAR_COMMERCIAL_AT,      -ESC_A,
145      -ESC_B,                  -ESC_C,
146      -ESC_D,                  -ESC_E,
147      0,                       -ESC_G,
148      -ESC_H,                  0,
149      0,                       -ESC_K,
150      0,                       0,
151      -ESC_N,                  0,
152      -ESC_P,                  -ESC_Q,
153      -ESC_R,                  -ESC_S,
154      0,                       0,
155      -ESC_V,                  -ESC_W,
156      -ESC_X,                  0,
157      -ESC_Z,                  CHAR_LEFT_SQUARE_BRACKET,
158      CHAR_BACKSLASH,          CHAR_RIGHT_SQUARE_BRACKET,
159      CHAR_CIRCUMFLEX_ACCENT,  CHAR_UNDERSCORE,
160      CHAR_GRAVE_ACCENT,       7,
161      -ESC_b,                  0,
162      -ESC_d,                  ESC_e,
163      ESC_f,                   0,
164      -ESC_h,                  0,
165      0,                       -ESC_k,
166      0,                       0,
167      ESC_n,                   0,
168      -ESC_p,                  0,
169      ESC_r,                   -ESC_s,
170      ESC_tee,                 0,
171      -ESC_v,                  -ESC_w,
172      0,                       0,
173      -ESC_z
174 };
175
176 #else
177
178 /* This is the "abnormal" table for EBCDIC systems without UTF-8 support. */
179
180 static const short int escapes[] = {
181 /*  48 */     0,     0,      0,     '.',    '<',   '(',    '+',    '|',
182 /*  50 */   '&',     0,      0,       0,      0,     0,      0,      0,
183 /*  58 */     0,     0,    '!',     '$',    '*',   ')',    ';',    '~',
184 /*  60 */   '-',   '/',      0,       0,      0,     0,      0,      0,
185 /*  68 */     0,     0,    '|',     ',',    '%',   '_',    '>',    '?',
186 /*  70 */     0,     0,      0,       0,      0,     0,      0,      0,
187 /*  78 */     0,   '`',    ':',     '#',    '@',  '\'',    '=',    '"',
188 /*  80 */     0,     7, -ESC_b,       0, -ESC_d, ESC_e,  ESC_f,      0,
189 /*  88 */-ESC_h,     0,      0,     '{',      0,     0,      0,      0,
190 /*  90 */     0,     0, -ESC_k,     'l',      0, ESC_n,      0, -ESC_p,
191 /*  98 */     0, ESC_r,      0,     '}',      0,     0,      0,      0,
192 /*  A0 */     0,   '~', -ESC_s, ESC_tee,      0,-ESC_v, -ESC_w,      0,
193 /*  A8 */     0,-ESC_z,      0,       0,      0,   '[',      0,      0,
194 /*  B0 */     0,     0,      0,       0,      0,     0,      0,      0,
195 /*  B8 */     0,     0,      0,       0,      0,   ']',    '=',    '-',
196 /*  C0 */   '{',-ESC_A, -ESC_B,  -ESC_C, -ESC_D,-ESC_E,      0, -ESC_G,
197 /*  C8 */-ESC_H,     0,      0,       0,      0,     0,      0,      0,
198 /*  D0 */   '}',     0, -ESC_K,       0,      0,-ESC_N,      0, -ESC_P,
199 /*  D8 */-ESC_Q,-ESC_R,      0,       0,      0,     0,      0,      0,
200 /*  E0 */  '\\',     0, -ESC_S,       0,      0,-ESC_V, -ESC_W, -ESC_X,
201 /*  E8 */     0,-ESC_Z,      0,       0,      0,     0,      0,      0,
202 /*  F0 */     0,     0,      0,       0,      0,     0,      0,      0,
203 /*  F8 */     0,     0,      0,       0,      0,     0,      0,      0
204 };
205 #endif
206
207
208 /* Table of special "verbs" like (*PRUNE). This is a short table, so it is
209 searched linearly. Put all the names into a single string, in order to reduce
210 the number of relocations when a shared library is dynamically linked. The
211 string is built from string macros so that it works in UTF-8 mode on EBCDIC
212 platforms. */
213
214 typedef struct verbitem {
215   int   len;                 /* Length of verb name */
216   int   op;                  /* Op when no arg, or -1 if arg mandatory */
217   int   op_arg;              /* Op when arg present, or -1 if not allowed */
218 } verbitem;
219
220 static const char verbnames[] =
221   "\0"                       /* Empty name is a shorthand for MARK */
222   STRING_MARK0
223   STRING_ACCEPT0
224   STRING_COMMIT0
225   STRING_F0
226   STRING_FAIL0
227   STRING_PRUNE0
228   STRING_SKIP0
229   STRING_THEN;
230
231 static const verbitem verbs[] = {
232   { 0, -1,        OP_MARK },
233   { 4, -1,        OP_MARK },
234   { 6, OP_ACCEPT, -1 },
235   { 6, OP_COMMIT, -1 },
236   { 1, OP_FAIL,   -1 },
237   { 4, OP_FAIL,   -1 },
238   { 5, OP_PRUNE,  OP_PRUNE_ARG },
239   { 4, OP_SKIP,   OP_SKIP_ARG  },
240   { 4, OP_THEN,   OP_THEN_ARG  }
241 };
242
243 static const int verbcount = sizeof(verbs)/sizeof(verbitem);
244
245
246 /* Tables of names of POSIX character classes and their lengths. The names are
247 now all in a single string, to reduce the number of relocations when a shared
248 library is dynamically loaded. The list of lengths is terminated by a zero
249 length entry. The first three must be alpha, lower, upper, as this is assumed
250 for handling case independence. */
251
252 static const char posix_names[] =
253   STRING_alpha0 STRING_lower0 STRING_upper0 STRING_alnum0
254   STRING_ascii0 STRING_blank0 STRING_cntrl0 STRING_digit0
255   STRING_graph0 STRING_print0 STRING_punct0 STRING_space0
256   STRING_word0  STRING_xdigit;
257
258 static const pcre_uint8 posix_name_lengths[] = {
259   5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 6, 0 };
260
261 /* Table of class bit maps for each POSIX class. Each class is formed from a
262 base map, with an optional addition or removal of another map. Then, for some
263 classes, there is some additional tweaking: for [:blank:] the vertical space
264 characters are removed, and for [:alpha:] and [:alnum:] the underscore
265 character is removed. The triples in the table consist of the base map offset,
266 second map offset or -1 if no second map, and a non-negative value for map
267 addition or a negative value for map subtraction (if there are two maps). The
268 absolute value of the third field has these meanings: 0 => no tweaking, 1 =>
269 remove vertical space characters, 2 => remove underscore. */
270
271 static const int posix_class_maps[] = {
272   cbit_word,  cbit_digit, -2,             /* alpha */
273   cbit_lower, -1,          0,             /* lower */
274   cbit_upper, -1,          0,             /* upper */
275   cbit_word,  -1,          2,             /* alnum - word without underscore */
276   cbit_print, cbit_cntrl,  0,             /* ascii */
277   cbit_space, -1,          1,             /* blank - a GNU extension */
278   cbit_cntrl, -1,          0,             /* cntrl */
279   cbit_digit, -1,          0,             /* digit */
280   cbit_graph, -1,          0,             /* graph */
281   cbit_print, -1,          0,             /* print */
282   cbit_punct, -1,          0,             /* punct */
283   cbit_space, -1,          0,             /* space */
284   cbit_word,  -1,          0,             /* word - a Perl extension */
285   cbit_xdigit,-1,          0              /* xdigit */
286 };
287
288 /* Table of substitutes for \d etc when PCRE_UCP is set. The POSIX class
289 substitutes must be in the order of the names, defined above, and there are
290 both positive and negative cases. NULL means no substitute. */
291
292 #ifdef SUPPORT_UCP
293 static const pcre_uchar string_PNd[]  = {
294   CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET,
295   CHAR_N, CHAR_d, CHAR_RIGHT_CURLY_BRACKET, '\0' };
296 static const pcre_uchar string_pNd[]  = {
297   CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET,
298   CHAR_N, CHAR_d, CHAR_RIGHT_CURLY_BRACKET, '\0' };
299 static const pcre_uchar string_PXsp[] = {
300   CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET,
301   CHAR_X, CHAR_s, CHAR_p, CHAR_RIGHT_CURLY_BRACKET, '\0' };
302 static const pcre_uchar string_pXsp[] = {
303   CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET,
304   CHAR_X, CHAR_s, CHAR_p, CHAR_RIGHT_CURLY_BRACKET, '\0' };
305 static const pcre_uchar string_PXwd[] = {
306   CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET,
307   CHAR_X, CHAR_w, CHAR_d, CHAR_RIGHT_CURLY_BRACKET, '\0' };
308 static const pcre_uchar string_pXwd[] = {
309   CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET,
310   CHAR_X, CHAR_w, CHAR_d, CHAR_RIGHT_CURLY_BRACKET, '\0' };
311
312 static const pcre_uchar *substitutes[] = {
313   string_PNd,           /* \D */
314   string_pNd,           /* \d */
315   string_PXsp,          /* \S */       /* NOTE: Xsp is Perl space */
316   string_pXsp,          /* \s */
317   string_PXwd,          /* \W */
318   string_pXwd           /* \w */
319 };
320
321 static const pcre_uchar string_pL[] =   {
322   CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET,
323   CHAR_L, CHAR_RIGHT_CURLY_BRACKET, '\0' };
324 static const pcre_uchar string_pLl[] =  {
325   CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET,
326   CHAR_L, CHAR_l, CHAR_RIGHT_CURLY_BRACKET, '\0' };
327 static const pcre_uchar string_pLu[] =  {
328   CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET,
329   CHAR_L, CHAR_u, CHAR_RIGHT_CURLY_BRACKET, '\0' };
330 static const pcre_uchar string_pXan[] = {
331   CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET,
332   CHAR_X, CHAR_a, CHAR_n, CHAR_RIGHT_CURLY_BRACKET, '\0' };
333 static const pcre_uchar string_h[] =    {
334   CHAR_BACKSLASH, CHAR_h, '\0' };
335 static const pcre_uchar string_pXps[] = {
336   CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET,
337   CHAR_X, CHAR_p, CHAR_s, CHAR_RIGHT_CURLY_BRACKET, '\0' };
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
356 static const pcre_uchar *posix_substitutes[] = {
357   string_pL,            /* alpha */
358   string_pLl,           /* lower */
359   string_pLu,           /* upper */
360   string_pXan,          /* alnum */
361   NULL,                 /* ascii */
362   string_h,             /* blank */
363   NULL,                 /* cntrl */
364   string_pNd,           /* digit */
365   NULL,                 /* graph */
366   NULL,                 /* print */
367   NULL,                 /* punct */
368   string_pXps,          /* space */    /* NOTE: Xps is POSIX space */
369   string_pXwd,          /* word */
370   NULL,                 /* xdigit */
371   /* Negated cases */
372   string_PL,            /* ^alpha */
373   string_PLl,           /* ^lower */
374   string_PLu,           /* ^upper */
375   string_PXan,          /* ^alnum */
376   NULL,                 /* ^ascii */
377   string_H,             /* ^blank */
378   NULL,                 /* ^cntrl */
379   string_PNd,           /* ^digit */
380   NULL,                 /* ^graph */
381   NULL,                 /* ^print */
382   NULL,                 /* ^punct */
383   string_PXps,          /* ^space */   /* NOTE: Xps is POSIX space */
384   string_PXwd,          /* ^word */
385   NULL                  /* ^xdigit */
386 };
387 #define POSIX_SUBSIZE (sizeof(posix_substitutes) / sizeof(pcre_uchar *))
388 #endif
389
390 #define STRING(a)  # a
391 #define XSTRING(s) STRING(s)
392
393 /* The texts of compile-time error messages. These are "char *" because they
394 are passed to the outside world. Do not ever re-use any error number, because
395 they are documented. Always add a new error instead. Messages marked DEAD below
396 are no longer used. This used to be a table of strings, but in order to reduce
397 the number of relocations needed when a shared library is loaded dynamically,
398 it is now one long string. We cannot use a table of offsets, because the
399 lengths of inserts such as XSTRING(MAX_NAME_SIZE) are not known. Instead, we
400 simply count through to the one we want - this isn't a performance issue
401 because these strings are used only when there is a compilation error.
402
403 Each substring ends with \0 to insert a null character. This includes the final
404 substring, so that the whole string ends with \0\0, which can be detected when
405 counting through. */
406
407 static const char error_texts[] =
408   "no error\0"
409   "\\ at end of pattern\0"
410   "\\c at end of pattern\0"
411   "unrecognized character follows \\\0"
412   "numbers out of order in {} quantifier\0"
413   /* 5 */
414   "number too big in {} quantifier\0"
415   "missing terminating ] for character class\0"
416   "invalid escape sequence in character class\0"
417   "range out of order in character class\0"
418   "nothing to repeat\0"
419   /* 10 */
420   "operand of unlimited repeat could match the empty string\0"  /** DEAD **/
421   "internal error: unexpected repeat\0"
422   "unrecognized character after (? or (?-\0"
423   "POSIX named classes are supported only within a class\0"
424   "missing )\0"
425   /* 15 */
426   "reference to non-existent subpattern\0"
427   "erroffset passed as NULL\0"
428   "unknown option bit(s) set\0"
429   "missing ) after comment\0"
430   "parentheses nested too deeply\0"  /** DEAD **/
431   /* 20 */
432   "regular expression is too large\0"
433   "failed to get memory\0"
434   "unmatched parentheses\0"
435   "internal error: code overflow\0"
436   "unrecognized character after (?<\0"
437   /* 25 */
438   "lookbehind assertion is not fixed length\0"
439   "malformed number or name after (?(\0"
440   "conditional group contains more than two branches\0"
441   "assertion expected after (?(\0"
442   "(?R or (?[+-]digits must be followed by )\0"
443   /* 30 */
444   "unknown POSIX class name\0"
445   "POSIX collating elements are not supported\0"
446   "this version of PCRE is compiled without UTF support\0"
447   "spare error\0"  /** DEAD **/
448   "character value in \\x{...} sequence is too large\0"
449   /* 35 */
450   "invalid condition (?(0)\0"
451   "\\C not allowed in lookbehind assertion\0"
452   "PCRE does not support \\L, \\l, \\N{name}, \\U, or \\u\0"
453   "number after (?C is > 255\0"
454   "closing ) for (?C expected\0"
455   /* 40 */
456   "recursive call could loop indefinitely\0"
457   "unrecognized character after (?P\0"
458   "syntax error in subpattern name (missing terminator)\0"
459   "two named subpatterns have the same name\0"
460   "invalid UTF-8 string\0"
461   /* 45 */
462   "support for \\P, \\p, and \\X has not been compiled\0"
463   "malformed \\P or \\p sequence\0"
464   "unknown property name after \\P or \\p\0"
465   "subpattern name is too long (maximum " XSTRING(MAX_NAME_SIZE) " characters)\0"
466   "too many named subpatterns (maximum " XSTRING(MAX_NAME_COUNT) ")\0"
467   /* 50 */
468   "repeated subpattern is too long\0"    /** DEAD **/
469   "octal value is greater than \\377 in 8-bit non-UTF-8 mode\0"
470   "internal error: overran compiling workspace\0"
471   "internal error: previously-checked referenced subpattern not found\0"
472   "DEFINE group contains more than one branch\0"
473   /* 55 */
474   "repeating a DEFINE group is not allowed\0"  /** DEAD **/
475   "inconsistent NEWLINE options\0"
476   "\\g is not followed by a braced, angle-bracketed, or quoted name/number or by a plain number\0"
477   "a numbered reference must not be zero\0"
478   "an argument is not allowed for (*ACCEPT), (*FAIL), or (*COMMIT)\0"
479   /* 60 */
480   "(*VERB) not recognized\0"
481   "number is too big\0"
482   "subpattern name expected\0"
483   "digit expected after (?+\0"
484   "] is an invalid data character in JavaScript compatibility mode\0"
485   /* 65 */
486   "different names for subpatterns of the same number are not allowed\0"
487   "(*MARK) must have an argument\0"
488   "this version of PCRE is not compiled with Unicode property support\0"
489   "\\c must be followed by an ASCII character\0"
490   "\\k is not followed by a braced, angle-bracketed, or quoted name\0"
491   /* 70 */
492   "internal error: unknown opcode in find_fixedlength()\0"
493   "\\N is not supported in a class\0"
494   "too many forward references\0"
495   "disallowed Unicode code point (>= 0xd800 && <= 0xdfff)\0"
496   "invalid UTF-16 string\0"
497   /* 75 */
498   "name is too long in (*MARK), (*PRUNE), (*SKIP), or (*THEN)\0"
499   "character value in \\u.... sequence is too large\0"
500   ;
501
502 /* Table to identify digits and hex digits. This is used when compiling
503 patterns. Note that the tables in chartables are dependent on the locale, and
504 may mark arbitrary characters as digits - but the PCRE compiling code expects
505 to handle only 0-9, a-z, and A-Z as digits when compiling. That is why we have
506 a private table here. It costs 256 bytes, but it is a lot faster than doing
507 character value tests (at least in some simple cases I timed), and in some
508 applications one wants PCRE to compile efficiently as well as match
509 efficiently.
510
511 For convenience, we use the same bit definitions as in chartables:
512
513   0x04   decimal digit
514   0x08   hexadecimal digit
515
516 Then we can use ctype_digit and ctype_xdigit in the code. */
517
518 /* Using a simple comparison for decimal numbers rather than a memory read
519 is much faster, and the resulting code is simpler (the compiler turns it
520 into a subtraction and unsigned comparison). */
521
522 #define IS_DIGIT(x) ((x) >= CHAR_0 && (x) <= CHAR_9)
523
524 #if 0
525 #ifndef EBCDIC
526
527 /* This is the "normal" case, for ASCII systems, and EBCDIC systems running in
528 UTF-8 mode. */
529
530 static const pcre_uint8 digitab[] =
531   {
532   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*   0-  7 */
533   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*   8- 15 */
534   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  16- 23 */
535   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  24- 31 */
536   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*    - '  */
537   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  ( - /  */
538   0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c, /*  0 - 7  */
539   0x0c,0x0c,0x00,0x00,0x00,0x00,0x00,0x00, /*  8 - ?  */
540   0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /*  @ - G  */
541   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  H - O  */
542   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  P - W  */
543   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  X - _  */
544   0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /*  ` - g  */
545   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  h - o  */
546   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  p - w  */
547   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  x -127 */
548   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 128-135 */
549   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 136-143 */
550   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 144-151 */
551   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 152-159 */
552   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 160-167 */
553   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 168-175 */
554   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 176-183 */
555   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 184-191 */
556   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 192-199 */
557   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 200-207 */
558   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 208-215 */
559   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 216-223 */
560   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 224-231 */
561   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 232-239 */
562   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 240-247 */
563   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};/* 248-255 */
564
565 #else
566
567 /* This is the "abnormal" case, for EBCDIC systems not running in UTF-8 mode. */
568
569 static const pcre_uint8 digitab[] =
570   {
571   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*   0-  7  0 */
572   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*   8- 15    */
573   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  16- 23 10 */
574   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  24- 31    */
575   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  32- 39 20 */
576   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  40- 47    */
577   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  48- 55 30 */
578   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  56- 63    */
579   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*    - 71 40 */
580   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  72- |     */
581   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  & - 87 50 */
582   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  88- 95    */
583   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  - -103 60 */
584   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 104- ?     */
585   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 112-119 70 */
586   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 120- "     */
587   0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* 128- g  80 */
588   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  h -143    */
589   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 144- p  90 */
590   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  q -159    */
591   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 160- x  A0 */
592   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  y -175    */
593   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  ^ -183 B0 */
594   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 184-191    */
595   0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /*  { - G  C0 */
596   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  H -207    */
597   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  } - P  D0 */
598   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  Q -223    */
599   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  \ - X  E0 */
600   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  Y -239    */
601   0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c, /*  0 - 7  F0 */
602   0x0c,0x0c,0x00,0x00,0x00,0x00,0x00,0x00};/*  8 -255    */
603
604 static const pcre_uint8 ebcdic_chartab[] = { /* chartable partial dup */
605   0x80,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /*   0-  7 */
606   0x00,0x00,0x00,0x00,0x01,0x01,0x00,0x00, /*   8- 15 */
607   0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /*  16- 23 */
608   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  24- 31 */
609   0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /*  32- 39 */
610   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  40- 47 */
611   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  48- 55 */
612   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  56- 63 */
613   0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*    - 71 */
614   0x00,0x00,0x00,0x80,0x00,0x80,0x80,0x80, /*  72- |  */
615   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  & - 87 */
616   0x00,0x00,0x00,0x80,0x80,0x80,0x00,0x00, /*  88- 95 */
617   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  - -103 */
618   0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x80, /* 104- ?  */
619   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 112-119 */
620   0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 120- "  */
621   0x00,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* 128- g  */
622   0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /*  h -143 */
623   0x00,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* 144- p  */
624   0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /*  q -159 */
625   0x00,0x00,0x12,0x12,0x12,0x12,0x12,0x12, /* 160- x  */
626   0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /*  y -175 */
627   0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*  ^ -183 */
628   0x00,0x00,0x80,0x00,0x00,0x00,0x00,0x00, /* 184-191 */
629   0x80,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /*  { - G  */
630   0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /*  H -207 */
631   0x00,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /*  } - P  */
632   0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /*  Q -223 */
633   0x00,0x00,0x12,0x12,0x12,0x12,0x12,0x12, /*  \ - X  */
634   0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /*  Y -239 */
635   0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c, /*  0 - 7  */
636   0x1c,0x1c,0x00,0x00,0x00,0x00,0x00,0x00};/*  8 -255 */
637 #endif
638 #endif /* 0 */
639
640 /* Definition to allow mutual recursion */
641
642 static BOOL
643   compile_regex(int, pcre_uchar **, const pcre_uchar **, int *, BOOL, BOOL, int, int,
644     int *, int *, branch_chain *, compile_data *, int *);
645
646
647
648 /*************************************************
649 *            Find an error text                  *
650 *************************************************/
651
652 /* The error texts are now all in one long string, to save on relocations. As
653 some of the text is of unknown length, we can't use a table of offsets.
654 Instead, just count through the strings. This is not a performance issue
655 because it happens only when there has been a compilation error.
656
657 Argument:   the error number
658 Returns:    pointer to the error string
659 */
660
661 static const char *
662 find_error_text(int n)
663 {
664 const char *s = error_texts;
665 for (; n > 0; n--)
666   {
667   while (*s++ != 0) {};
668   if (*s == 0) return "Error text not found (please report)";
669   }
670 return s;
671 }
672
673
674 /*************************************************
675 *           Expand the workspace                 *
676 *************************************************/
677
678 /* This function is called during the second compiling phase, if the number of
679 forward references fills the existing workspace, which is originally a block on
680 the stack. A larger block is obtained from malloc() unless the ultimate limit
681 has been reached or the increase will be rather small.
682
683 Argument: pointer to the compile data block
684 Returns:  0 if all went well, else an error number
685 */
686
687 static int
688 expand_workspace(compile_data *cd)
689 {
690 pcre_uchar *newspace;
691 int newsize = cd->workspace_size * 2;
692
693 if (newsize > COMPILE_WORK_SIZE_MAX) newsize = COMPILE_WORK_SIZE_MAX;
694 if (cd->workspace_size >= COMPILE_WORK_SIZE_MAX ||
695     newsize - cd->workspace_size < WORK_SIZE_SAFETY_MARGIN)
696  return ERR72;
697
698 newspace = (PUBL(malloc))(IN_UCHARS(newsize));
699 if (newspace == NULL) return ERR21;
700 memcpy(newspace, cd->start_workspace, cd->workspace_size * sizeof(pcre_uchar));
701 cd->hwm = (pcre_uchar *)newspace + (cd->hwm - cd->start_workspace);
702 if (cd->workspace_size > COMPILE_WORK_SIZE)
703   (PUBL(free))((void *)cd->start_workspace);
704 cd->start_workspace = newspace;
705 cd->workspace_size = newsize;
706 return 0;
707 }
708
709
710
711 /*************************************************
712 *            Check for counted repeat            *
713 *************************************************/
714
715 /* This function is called when a '{' is encountered in a place where it might
716 start a quantifier. It looks ahead to see if it really is a quantifier or not.
717 It is only a quantifier if it is one of the forms {ddd} {ddd,} or {ddd,ddd}
718 where the ddds are digits.
719
720 Arguments:
721   p         pointer to the first char after '{'
722
723 Returns:    TRUE or FALSE
724 */
725
726 static BOOL
727 is_counted_repeat(const pcre_uchar *p)
728 {
729 if (!IS_DIGIT(*p)) return FALSE;
730 p++;
731 while (IS_DIGIT(*p)) p++;
732 if (*p == CHAR_RIGHT_CURLY_BRACKET) return TRUE;
733
734 if (*p++ != CHAR_COMMA) return FALSE;
735 if (*p == CHAR_RIGHT_CURLY_BRACKET) return TRUE;
736
737 if (!IS_DIGIT(*p)) return FALSE;
738 p++;
739 while (IS_DIGIT(*p)) p++;
740
741 return (*p == CHAR_RIGHT_CURLY_BRACKET);
742 }
743
744
745
746 /*************************************************
747 *            Handle escapes                      *
748 *************************************************/
749
750 /* This function is called when a \ has been encountered. It either returns a
751 positive value for a simple escape such as \n, or a negative value which
752 encodes one of the more complicated things such as \d. A backreference to group
753 n is returned as -(ESC_REF + n); ESC_REF is the highest ESC_xxx macro. When
754 UTF-8 is enabled, a positive value greater than 255 may be returned. On entry,
755 ptr is pointing at the \. On exit, it is on the final character of the escape
756 sequence.
757
758 Arguments:
759   ptrptr         points to the pattern position pointer
760   errorcodeptr   points to the errorcode variable
761   bracount       number of previous extracting brackets
762   options        the options bits
763   isclass        TRUE if inside a character class
764
765 Returns:         zero or positive => a data character
766                  negative => a special escape sequence
767                  on error, errorcodeptr is set
768 */
769
770 static int
771 check_escape(const pcre_uchar **ptrptr, int *errorcodeptr, int bracount,
772   int options, BOOL isclass)
773 {
774 /* PCRE_UTF16 has the same value as PCRE_UTF8. */
775 BOOL utf = (options & PCRE_UTF8) != 0;
776 const pcre_uchar *ptr = *ptrptr + 1;
777 pcre_int32 c;
778 int i;
779
780 GETCHARINCTEST(c, ptr);           /* Get character value, increment pointer */
781 ptr--;                            /* Set pointer back to the last byte */
782
783 /* If backslash is at the end of the pattern, it's an error. */
784
785 if (c == 0) *errorcodeptr = ERR1;
786
787 /* Non-alphanumerics are literals. For digits or letters, do an initial lookup
788 in a table. A non-zero result is something that can be returned immediately.
789 Otherwise further processing may be required. */
790
791 #ifndef EBCDIC  /* ASCII/UTF-8 coding */
792 /* Not alphanumeric */
793 else if (c < CHAR_0 || c > CHAR_z) {}
794 else if ((i = escapes[c - CHAR_0]) != 0) c = i;
795
796 #else           /* EBCDIC coding */
797 /* Not alphanumeric */
798 else if (c < 'a' || (!MAX_255(c) || (ebcdic_chartab[c] & 0x0E) == 0)) {}
799 else if ((i = escapes[c - 0x48]) != 0)  c = i;
800 #endif
801
802 /* Escapes that need further processing, or are illegal. */
803
804 else
805   {
806   const pcre_uchar *oldptr;
807   BOOL braced, negated;
808
809   switch (c)
810     {
811     /* A number of Perl escapes are not handled by PCRE. We give an explicit
812     error. */
813
814     case CHAR_l:
815     case CHAR_L:
816     *errorcodeptr = ERR37;
817     break;
818
819     case CHAR_u:
820     if ((options & PCRE_JAVASCRIPT_COMPAT) != 0)
821       {
822       /* In JavaScript, \u must be followed by four hexadecimal numbers.
823       Otherwise it is a lowercase u letter. */
824       if (MAX_255(ptr[1]) && g_ascii_isxdigit(ptr[1]) != 0
825         && MAX_255(ptr[2]) && g_ascii_isxdigit(ptr[2]) != 0
826         && MAX_255(ptr[3]) && g_ascii_isxdigit(ptr[3]) != 0
827         && MAX_255(ptr[4]) && g_ascii_isxdigit(ptr[4]) != 0)
828         {
829         c = 0;
830         for (i = 0; i < 4; ++i)
831           {
832           int cc = *(++ptr);
833 #ifndef EBCDIC  /* ASCII/UTF-8 coding */
834           if (cc >= CHAR_a) cc -= 32;               /* Convert to upper case */
835           c = (c << 4) + cc - ((cc < CHAR_A)? CHAR_0 : (CHAR_A - 10));
836 #else           /* EBCDIC coding */
837           if (cc >= CHAR_a && cc <= CHAR_z) cc += 64;  /* Convert to upper case */
838           c = (c << 4) + cc - ((cc >= CHAR_0)? CHAR_0 : (CHAR_A - 10));
839 #endif
840           }
841
842 #ifdef COMPILE_PCRE8
843         if (c > (utf ? 0x10ffff : 0xff))
844 #else
845 #ifdef COMPILE_PCRE16
846         if (c > (utf ? 0x10ffff : 0xffff))
847 #endif
848 #endif
849           {
850           *errorcodeptr = ERR76;
851           }
852         else if (utf && c >= 0xd800 && c <= 0xdfff) *errorcodeptr = ERR73;
853         }
854       }
855     else
856       *errorcodeptr = ERR37;
857     break;
858
859     case CHAR_U:
860     /* In JavaScript, \U is an uppercase U letter. */
861     if ((options & PCRE_JAVASCRIPT_COMPAT) == 0) *errorcodeptr = ERR37;
862     break;
863
864     /* In a character class, \g is just a literal "g". Outside a character
865     class, \g must be followed by one of a number of specific things:
866
867     (1) A number, either plain or braced. If positive, it is an absolute
868     backreference. If negative, it is a relative backreference. This is a Perl
869     5.10 feature.
870
871     (2) Perl 5.10 also supports \g{name} as a reference to a named group. This
872     is part of Perl's movement towards a unified syntax for back references. As
873     this is synonymous with \k{name}, we fudge it up by pretending it really
874     was \k.
875
876     (3) For Oniguruma compatibility we also support \g followed by a name or a
877     number either in angle brackets or in single quotes. However, these are
878     (possibly recursive) subroutine calls, _not_ backreferences. Just return
879     the -ESC_g code (cf \k). */
880
881     case CHAR_g:
882     if (isclass) break;
883     if (ptr[1] == CHAR_LESS_THAN_SIGN || ptr[1] == CHAR_APOSTROPHE)
884       {
885       c = -ESC_g;
886       break;
887       }
888
889     /* Handle the Perl-compatible cases */
890
891     if (ptr[1] == CHAR_LEFT_CURLY_BRACKET)
892       {
893       const pcre_uchar *p;
894       for (p = ptr+2; *p != 0 && *p != CHAR_RIGHT_CURLY_BRACKET; p++)
895         if (*p != CHAR_MINUS && !IS_DIGIT(*p)) break;
896       if (*p != 0 && *p != CHAR_RIGHT_CURLY_BRACKET)
897         {
898         c = -ESC_k;
899         break;
900         }
901       braced = TRUE;
902       ptr++;
903       }
904     else braced = FALSE;
905
906     if (ptr[1] == CHAR_MINUS)
907       {
908       negated = TRUE;
909       ptr++;
910       }
911     else negated = FALSE;
912
913     /* The integer range is limited by the machine's int representation. */
914     c = 0;
915     while (IS_DIGIT(ptr[1]))
916       {
917       if (((unsigned int)c) > INT_MAX / 10) /* Integer overflow */
918         {
919         c = -1;
920         break;
921         }
922       c = c * 10 + *(++ptr) - CHAR_0;
923       }
924     if (((unsigned int)c) > INT_MAX) /* Integer overflow */
925       {
926       while (IS_DIGIT(ptr[1]))
927         ptr++;
928       *errorcodeptr = ERR61;
929       break;
930       }
931
932     if (braced && *(++ptr) != CHAR_RIGHT_CURLY_BRACKET)
933       {
934       *errorcodeptr = ERR57;
935       break;
936       }
937
938     if (c == 0)
939       {
940       *errorcodeptr = ERR58;
941       break;
942       }
943
944     if (negated)
945       {
946       if (c > bracount)
947         {
948         *errorcodeptr = ERR15;
949         break;
950         }
951       c = bracount - (c - 1);
952       }
953
954     c = -(ESC_REF + c);
955     break;
956
957     /* The handling of escape sequences consisting of a string of digits
958     starting with one that is not zero is not straightforward. By experiment,
959     the way Perl works seems to be as follows:
960
961     Outside a character class, the digits are read as a decimal number. If the
962     number is less than 10, or if there are that many previous extracting
963     left brackets, then it is a back reference. Otherwise, up to three octal
964     digits are read to form an escaped byte. Thus \123 is likely to be octal
965     123 (cf \0123, which is octal 012 followed by the literal 3). If the octal
966     value is greater than 377, the least significant 8 bits are taken. Inside a
967     character class, \ followed by a digit is always an octal number. */
968
969     case CHAR_1: case CHAR_2: case CHAR_3: case CHAR_4: case CHAR_5:
970     case CHAR_6: case CHAR_7: case CHAR_8: case CHAR_9:
971
972     if (!isclass)
973       {
974       oldptr = ptr;
975       /* The integer range is limited by the machine's int representation. */
976       c -= CHAR_0;
977       while (IS_DIGIT(ptr[1]))
978         {
979         if (((unsigned int)c) > INT_MAX / 10) /* Integer overflow */
980           {
981           c = -1;
982           break;
983           }
984         c = c * 10 + *(++ptr) - CHAR_0;
985         }
986       if (((unsigned int)c) > INT_MAX) /* Integer overflow */
987         {
988         while (IS_DIGIT(ptr[1]))
989           ptr++;
990         *errorcodeptr = ERR61;
991         break;
992         }
993       if (c < 10 || c <= bracount)
994         {
995         c = -(ESC_REF + c);
996         break;
997         }
998       ptr = oldptr;      /* Put the pointer back and fall through */
999       }
1000
1001     /* Handle an octal number following \. If the first digit is 8 or 9, Perl
1002     generates a binary zero byte and treats the digit as a following literal.
1003     Thus we have to pull back the pointer by one. */
1004
1005     if ((c = *ptr) >= CHAR_8)
1006       {
1007       ptr--;
1008       c = 0;
1009       break;
1010       }
1011
1012     /* \0 always starts an octal number, but we may drop through to here with a
1013     larger first octal digit. The original code used just to take the least
1014     significant 8 bits of octal numbers (I think this is what early Perls used
1015     to do). Nowadays we allow for larger numbers in UTF-8 mode and 16-bit mode,
1016     but no more than 3 octal digits. */
1017
1018     case CHAR_0:
1019     c -= CHAR_0;
1020     while(i++ < 2 && ptr[1] >= CHAR_0 && ptr[1] <= CHAR_7)
1021         c = c * 8 + *(++ptr) - CHAR_0;
1022 #ifdef COMPILE_PCRE8
1023     if (!utf && c > 0xff) *errorcodeptr = ERR51;
1024 #endif
1025     break;
1026
1027     /* \x is complicated. \x{ddd} is a character number which can be greater
1028     than 0xff in utf or non-8bit mode, but only if the ddd are hex digits.
1029     If not, { is treated as a data character. */
1030
1031     case CHAR_x:
1032     if ((options & PCRE_JAVASCRIPT_COMPAT) != 0)
1033       {
1034       /* In JavaScript, \x must be followed by two hexadecimal numbers.
1035       Otherwise it is a lowercase x letter. */
1036       if (MAX_255(ptr[1]) && g_ascii_isxdigit(ptr[1]) != 0
1037         && MAX_255(ptr[2]) && g_ascii_isxdigit(ptr[2]) != 0)
1038         {
1039         c = 0;
1040         for (i = 0; i < 2; ++i)
1041           {
1042           int cc = *(++ptr);
1043 #ifndef EBCDIC  /* ASCII/UTF-8 coding */
1044           if (cc >= CHAR_a) cc -= 32;               /* Convert to upper case */
1045           c = (c << 4) + cc - ((cc < CHAR_A)? CHAR_0 : (CHAR_A - 10));
1046 #else           /* EBCDIC coding */
1047           if (cc >= CHAR_a && cc <= CHAR_z) cc += 64;  /* Convert to upper case */
1048           c = (c << 4) + cc - ((cc >= CHAR_0)? CHAR_0 : (CHAR_A - 10));
1049 #endif
1050           }
1051         }
1052       break;
1053       }
1054
1055     if (ptr[1] == CHAR_LEFT_CURLY_BRACKET)
1056       {
1057       const pcre_uchar *pt = ptr + 2;
1058
1059       c = 0;
1060       while (MAX_255(*pt) && g_ascii_isxdigit(*pt) != 0)
1061         {
1062         int cc = *pt++;
1063         if (c == 0 && cc == CHAR_0) continue;     /* Leading zeroes */
1064
1065 #ifndef EBCDIC  /* ASCII/UTF-8 coding */
1066         if (cc >= CHAR_a) cc -= 32;               /* Convert to upper case */
1067         c = (c << 4) + cc - ((cc < CHAR_A)? CHAR_0 : (CHAR_A - 10));
1068 #else           /* EBCDIC coding */
1069         if (cc >= CHAR_a && cc <= CHAR_z) cc += 64;  /* Convert to upper case */
1070         c = (c << 4) + cc - ((cc >= CHAR_0)? CHAR_0 : (CHAR_A - 10));
1071 #endif
1072
1073 #ifdef COMPILE_PCRE8
1074         if (c > (utf ? 0x10ffff : 0xff)) { c = -1; break; }
1075 #else
1076 #ifdef COMPILE_PCRE16
1077         if (c > (utf ? 0x10ffff : 0xffff)) { c = -1; break; }
1078 #endif
1079 #endif
1080         }
1081
1082       if (c < 0)
1083         {
1084         while (MAX_255(*pt) && g_ascii_isxdigit(*pt) != 0) pt++;
1085         *errorcodeptr = ERR34;
1086         }
1087
1088       if (*pt == CHAR_RIGHT_CURLY_BRACKET)
1089         {
1090         if (utf && c >= 0xd800 && c <= 0xdfff) *errorcodeptr = ERR73;
1091         ptr = pt;
1092         break;
1093         }
1094
1095       /* If the sequence of hex digits does not end with '}', then we don't
1096       recognize this construct; fall through to the normal \x handling. */
1097       }
1098
1099     /* Read just a single-byte hex-defined char */
1100
1101     c = 0;
1102     while (i++ < 2 && MAX_255(ptr[1]) && g_ascii_isxdigit(ptr[1]) != 0)
1103       {
1104       int cc;                                  /* Some compilers don't like */
1105       cc = *(++ptr);                           /* ++ in initializers */
1106 #ifndef EBCDIC  /* ASCII/UTF-8 coding */
1107       if (cc >= CHAR_a) cc -= 32;              /* Convert to upper case */
1108       c = c * 16 + cc - ((cc < CHAR_A)? CHAR_0 : (CHAR_A - 10));
1109 #else           /* EBCDIC coding */
1110       if (cc <= CHAR_z) cc += 64;              /* Convert to upper case */
1111       c = c * 16 + cc - ((cc >= CHAR_0)? CHAR_0 : (CHAR_A - 10));
1112 #endif
1113       }
1114     break;
1115
1116     /* For \c, a following letter is upper-cased; then the 0x40 bit is flipped.
1117     An error is given if the byte following \c is not an ASCII character. This
1118     coding is ASCII-specific, but then the whole concept of \cx is
1119     ASCII-specific. (However, an EBCDIC equivalent has now been added.) */
1120
1121     case CHAR_c:
1122     c = *(++ptr);
1123     if (c == 0)
1124       {
1125       *errorcodeptr = ERR2;
1126       break;
1127       }
1128 #ifndef EBCDIC    /* ASCII/UTF-8 coding */
1129     if (c > 127)  /* Excludes all non-ASCII in either mode */
1130       {
1131       *errorcodeptr = ERR68;
1132       break;
1133       }
1134     if (c >= CHAR_a && c <= CHAR_z) c -= 32;
1135     c ^= 0x40;
1136 #else             /* EBCDIC coding */
1137     if (c >= CHAR_a && c <= CHAR_z) c += 64;
1138     c ^= 0xC0;
1139 #endif
1140     break;
1141
1142     /* PCRE_EXTRA enables extensions to Perl in the matter of escapes. Any
1143     other alphanumeric following \ is an error if PCRE_EXTRA was set;
1144     otherwise, for Perl compatibility, it is a literal. This code looks a bit
1145     odd, but there used to be some cases other than the default, and there may
1146     be again in future, so I haven't "optimized" it. */
1147
1148     default:
1149     if ((options & PCRE_EXTRA) != 0) switch(c)
1150       {
1151       default:
1152       *errorcodeptr = ERR3;
1153       break;
1154       }
1155     break;
1156     }
1157   }
1158
1159 /* Perl supports \N{name} for character names, as well as plain \N for "not
1160 newline". PCRE does not support \N{name}. However, it does support
1161 quantification such as \N{2,3}. */
1162
1163 if (c == -ESC_N && ptr[1] == CHAR_LEFT_CURLY_BRACKET &&
1164      !is_counted_repeat(ptr+2))
1165   *errorcodeptr = ERR37;
1166
1167 /* If PCRE_UCP is set, we change the values for \d etc. */
1168
1169 if ((options & PCRE_UCP) != 0 && c <= -ESC_D && c >= -ESC_w)
1170   c -= (ESC_DU - ESC_D);
1171
1172 /* Set the pointer to the final character before returning. */
1173
1174 *ptrptr = ptr;
1175 return c;
1176 }
1177
1178
1179
1180 #ifdef SUPPORT_UCP
1181 /*************************************************
1182 *               Handle \P and \p                 *
1183 *************************************************/
1184
1185 /* This function is called after \P or \p has been encountered, provided that
1186 PCRE is compiled with support for Unicode properties. On entry, ptrptr is
1187 pointing at the P or p. On exit, it is pointing at the final character of the
1188 escape sequence.
1189
1190 Argument:
1191   ptrptr         points to the pattern position pointer
1192   negptr         points to a boolean that is set TRUE for negation else FALSE
1193   dptr           points to an int that is set to the detailed property value
1194   errorcodeptr   points to the error code variable
1195
1196 Returns:         type value from ucp_type_table, or -1 for an invalid type
1197 */
1198
1199 static int
1200 get_ucp(const pcre_uchar **ptrptr, BOOL *negptr, int *dptr, int *errorcodeptr)
1201 {
1202 int c, i, bot, top;
1203 const pcre_uchar *ptr = *ptrptr;
1204 pcre_uchar name[32];
1205
1206 c = *(++ptr);
1207 if (c == 0) goto ERROR_RETURN;
1208
1209 *negptr = FALSE;
1210
1211 /* \P or \p can be followed by a name in {}, optionally preceded by ^ for
1212 negation. */
1213
1214 if (c == CHAR_LEFT_CURLY_BRACKET)
1215   {
1216   if (ptr[1] == CHAR_CIRCUMFLEX_ACCENT)
1217     {
1218     *negptr = TRUE;
1219     ptr++;
1220     }
1221   for (i = 0; i < (int)(sizeof(name) / sizeof(pcre_uchar)) - 1; i++)
1222     {
1223     c = *(++ptr);
1224     if (c == 0) goto ERROR_RETURN;
1225     if (c == CHAR_RIGHT_CURLY_BRACKET) break;
1226     name[i] = c;
1227     }
1228   if (c != CHAR_RIGHT_CURLY_BRACKET) goto ERROR_RETURN;
1229   name[i] = 0;
1230   }
1231
1232 /* Otherwise there is just one following character */
1233
1234 else
1235   {
1236   name[0] = c;
1237   name[1] = 0;
1238   }
1239
1240 *ptrptr = ptr;
1241
1242 /* Search for a recognized property name using binary chop */
1243
1244 bot = 0;
1245 top = PRIV(utt_size);
1246
1247 while (bot < top)
1248   {
1249   i = (bot + top) >> 1;
1250   c = STRCMP_UC_C8(name, PRIV(utt_names) + PRIV(utt)[i].name_offset);
1251   if (c == 0)
1252     {
1253     *dptr = PRIV(utt)[i].value;
1254     return PRIV(utt)[i].type;
1255     }
1256   if (c > 0) bot = i + 1; else top = i;
1257   }
1258
1259 *errorcodeptr = ERR47;
1260 *ptrptr = ptr;
1261 return -1;
1262
1263 ERROR_RETURN:
1264 *errorcodeptr = ERR46;
1265 *ptrptr = ptr;
1266 return -1;
1267 }
1268 #endif
1269
1270
1271
1272
1273 /*************************************************
1274 *         Read repeat counts                     *
1275 *************************************************/
1276
1277 /* Read an item of the form {n,m} and return the values. This is called only
1278 after is_counted_repeat() has confirmed that a repeat-count quantifier exists,
1279 so the syntax is guaranteed to be correct, but we need to check the values.
1280
1281 Arguments:
1282   p              pointer to first char after '{'
1283   minp           pointer to int for min
1284   maxp           pointer to int for max
1285                  returned as -1 if no max
1286   errorcodeptr   points to error code variable
1287
1288 Returns:         pointer to '}' on success;
1289                  current ptr on error, with errorcodeptr set non-zero
1290 */
1291
1292 static const pcre_uchar *
1293 read_repeat_counts(const pcre_uchar *p, int *minp, int *maxp, int *errorcodeptr)
1294 {
1295 int min = 0;
1296 int max = -1;
1297
1298 /* Read the minimum value and do a paranoid check: a negative value indicates
1299 an integer overflow. */
1300
1301 while (IS_DIGIT(*p)) min = min * 10 + *p++ - CHAR_0;
1302 if (min < 0 || min > 65535)
1303   {
1304   *errorcodeptr = ERR5;
1305   return p;
1306   }
1307
1308 /* Read the maximum value if there is one, and again do a paranoid on its size.
1309 Also, max must not be less than min. */
1310
1311 if (*p == CHAR_RIGHT_CURLY_BRACKET) max = min; else
1312   {
1313   if (*(++p) != CHAR_RIGHT_CURLY_BRACKET)
1314     {
1315     max = 0;
1316     while(IS_DIGIT(*p)) max = max * 10 + *p++ - CHAR_0;
1317     if (max < 0 || max > 65535)
1318       {
1319       *errorcodeptr = ERR5;
1320       return p;
1321       }
1322     if (max < min)
1323       {
1324       *errorcodeptr = ERR4;
1325       return p;
1326       }
1327     }
1328   }
1329
1330 /* Fill in the required variables, and pass back the pointer to the terminating
1331 '}'. */
1332
1333 *minp = min;
1334 *maxp = max;
1335 return p;
1336 }
1337
1338
1339
1340 /*************************************************
1341 *  Subroutine for finding forward reference      *
1342 *************************************************/
1343
1344 /* This recursive function is called only from find_parens() below. The
1345 top-level call starts at the beginning of the pattern. All other calls must
1346 start at a parenthesis. It scans along a pattern's text looking for capturing
1347 subpatterns, and counting them. If it finds a named pattern that matches the
1348 name it is given, it returns its number. Alternatively, if the name is NULL, it
1349 returns when it reaches a given numbered subpattern. Recursion is used to keep
1350 track of subpatterns that reset the capturing group numbers - the (?| feature.
1351
1352 This function was originally called only from the second pass, in which we know
1353 that if (?< or (?' or (?P< is encountered, the name will be correctly
1354 terminated because that is checked in the first pass. There is now one call to
1355 this function in the first pass, to check for a recursive back reference by
1356 name (so that we can make the whole group atomic). In this case, we need check
1357 only up to the current position in the pattern, and that is still OK because
1358 and previous occurrences will have been checked. To make this work, the test
1359 for "end of pattern" is a check against cd->end_pattern in the main loop,
1360 instead of looking for a binary zero. This means that the special first-pass
1361 call can adjust cd->end_pattern temporarily. (Checks for binary zero while
1362 processing items within the loop are OK, because afterwards the main loop will
1363 terminate.)
1364
1365 Arguments:
1366   ptrptr       address of the current character pointer (updated)
1367   cd           compile background data
1368   name         name to seek, or NULL if seeking a numbered subpattern
1369   lorn         name length, or subpattern number if name is NULL
1370   xmode        TRUE if we are in /x mode
1371   utf          TRUE if we are in UTF-8 / UTF-16 mode
1372   count        pointer to the current capturing subpattern number (updated)
1373
1374 Returns:       the number of the named subpattern, or -1 if not found
1375 */
1376
1377 static int
1378 find_parens_sub(pcre_uchar **ptrptr, compile_data *cd, const pcre_uchar *name, int lorn,
1379   BOOL xmode, BOOL utf, int *count)
1380 {
1381 pcre_uchar *ptr = *ptrptr;
1382 int start_count = *count;
1383 int hwm_count = start_count;
1384 BOOL dup_parens = FALSE;
1385
1386 /* If the first character is a parenthesis, check on the type of group we are
1387 dealing with. The very first call may not start with a parenthesis. */
1388
1389 if (ptr[0] == CHAR_LEFT_PARENTHESIS)
1390   {
1391   /* Handle specials such as (*SKIP) or (*UTF8) etc. */
1392
1393   if (ptr[1] == CHAR_ASTERISK) ptr += 2;
1394
1395   /* Handle a normal, unnamed capturing parenthesis. */
1396
1397   else if (ptr[1] != CHAR_QUESTION_MARK)
1398     {
1399     *count += 1;
1400     if (name == NULL && *count == lorn) return *count;
1401     ptr++;
1402     }
1403
1404   /* All cases now have (? at the start. Remember when we are in a group
1405   where the parenthesis numbers are duplicated. */
1406
1407   else if (ptr[2] == CHAR_VERTICAL_LINE)
1408     {
1409     ptr += 3;
1410     dup_parens = TRUE;
1411     }
1412
1413   /* Handle comments; all characters are allowed until a ket is reached. */
1414
1415   else if (ptr[2] == CHAR_NUMBER_SIGN)
1416     {
1417     for (ptr += 3; *ptr != 0; ptr++) if (*ptr == CHAR_RIGHT_PARENTHESIS) break;
1418     goto FAIL_EXIT;
1419     }
1420
1421   /* Handle a condition. If it is an assertion, just carry on so that it
1422   is processed as normal. If not, skip to the closing parenthesis of the
1423   condition (there can't be any nested parens). */
1424
1425   else if (ptr[2] == CHAR_LEFT_PARENTHESIS)
1426     {
1427     ptr += 2;
1428     if (ptr[1] != CHAR_QUESTION_MARK)
1429       {
1430       while (*ptr != 0 && *ptr != CHAR_RIGHT_PARENTHESIS) ptr++;
1431       if (*ptr != 0) ptr++;
1432       }
1433     }
1434
1435   /* Start with (? but not a condition. */
1436
1437   else
1438     {
1439     ptr += 2;
1440     if (*ptr == CHAR_P) ptr++;                      /* Allow optional P */
1441
1442     /* We have to disambiguate (?<! and (?<= from (?<name> for named groups */
1443
1444     if ((*ptr == CHAR_LESS_THAN_SIGN && ptr[1] != CHAR_EXCLAMATION_MARK &&
1445         ptr[1] != CHAR_EQUALS_SIGN) || *ptr == CHAR_APOSTROPHE)
1446       {
1447       int term;
1448       const pcre_uchar *thisname;
1449       *count += 1;
1450       if (name == NULL && *count == lorn) return *count;
1451       term = *ptr++;
1452       if (term == CHAR_LESS_THAN_SIGN) term = CHAR_GREATER_THAN_SIGN;
1453       thisname = ptr;
1454       while (*ptr != term) ptr++;
1455       if (name != NULL && lorn == ptr - thisname &&
1456           STRNCMP_UC_UC(name, thisname, lorn) == 0)
1457         return *count;
1458       term++;
1459       }
1460     }
1461   }
1462
1463 /* Past any initial parenthesis handling, scan for parentheses or vertical
1464 bars. Stop if we get to cd->end_pattern. Note that this is important for the
1465 first-pass call when this value is temporarily adjusted to stop at the current
1466 position. So DO NOT change this to a test for binary zero. */
1467
1468 for (; ptr < cd->end_pattern; ptr++)
1469   {
1470   /* Skip over backslashed characters and also entire \Q...\E */
1471
1472   if (*ptr == CHAR_BACKSLASH)
1473     {
1474     if (*(++ptr) == 0) goto FAIL_EXIT;
1475     if (*ptr == CHAR_Q) for (;;)
1476       {
1477       while (*(++ptr) != 0 && *ptr != CHAR_BACKSLASH) {};
1478       if (*ptr == 0) goto FAIL_EXIT;
1479       if (*(++ptr) == CHAR_E) break;
1480       }
1481     continue;
1482     }
1483
1484   /* Skip over character classes; this logic must be similar to the way they
1485   are handled for real. If the first character is '^', skip it. Also, if the
1486   first few characters (either before or after ^) are \Q\E or \E we skip them
1487   too. This makes for compatibility with Perl. Note the use of STR macros to
1488   encode "Q\\E" so that it works in UTF-8 on EBCDIC platforms. */
1489
1490   if (*ptr == CHAR_LEFT_SQUARE_BRACKET)
1491     {
1492     BOOL negate_class = FALSE;
1493     for (;;)
1494       {
1495       if (ptr[1] == CHAR_BACKSLASH)
1496         {
1497         if (ptr[2] == CHAR_E)
1498           ptr+= 2;
1499         else if (STRNCMP_UC_C8(ptr + 2,
1500                  STR_Q STR_BACKSLASH STR_E, 3) == 0)
1501           ptr += 4;
1502         else
1503           break;
1504         }
1505       else if (!negate_class && ptr[1] == CHAR_CIRCUMFLEX_ACCENT)
1506         {
1507         negate_class = TRUE;
1508         ptr++;
1509         }
1510       else break;
1511       }
1512
1513     /* If the next character is ']', it is a data character that must be
1514     skipped, except in JavaScript compatibility mode. */
1515
1516     if (ptr[1] == CHAR_RIGHT_SQUARE_BRACKET &&
1517         (cd->external_options & PCRE_JAVASCRIPT_COMPAT) == 0)
1518       ptr++;
1519
1520     while (*(++ptr) != CHAR_RIGHT_SQUARE_BRACKET)
1521       {
1522       if (*ptr == 0) return -1;
1523       if (*ptr == CHAR_BACKSLASH)
1524         {
1525         if (*(++ptr) == 0) goto FAIL_EXIT;
1526         if (*ptr == CHAR_Q) for (;;)
1527           {
1528           while (*(++ptr) != 0 && *ptr != CHAR_BACKSLASH) {};
1529           if (*ptr == 0) goto FAIL_EXIT;
1530           if (*(++ptr) == CHAR_E) break;
1531           }
1532         continue;
1533         }
1534       }
1535     continue;
1536     }
1537
1538   /* Skip comments in /x mode */
1539
1540   if (xmode && *ptr == CHAR_NUMBER_SIGN)
1541     {
1542     ptr++;
1543     while (*ptr != 0)
1544       {
1545       if (IS_NEWLINE(ptr)) { ptr += cd->nllen - 1; break; }
1546       ptr++;
1547 #ifdef SUPPORT_UTF
1548       if (utf) FORWARDCHAR(ptr);
1549 #endif
1550       }
1551     if (*ptr == 0) goto FAIL_EXIT;
1552     continue;
1553     }
1554
1555   /* Check for the special metacharacters */
1556
1557   if (*ptr == CHAR_LEFT_PARENTHESIS)
1558     {
1559     int rc = find_parens_sub(&ptr, cd, name, lorn, xmode, utf, count);
1560     if (rc > 0) return rc;
1561     if (*ptr == 0) goto FAIL_EXIT;
1562     }
1563
1564   else if (*ptr == CHAR_RIGHT_PARENTHESIS)
1565     {
1566     if (dup_parens && *count < hwm_count) *count = hwm_count;
1567     goto FAIL_EXIT;
1568     }
1569
1570   else if (*ptr == CHAR_VERTICAL_LINE && dup_parens)
1571     {
1572     if (*count > hwm_count) hwm_count = *count;
1573     *count = start_count;
1574     }
1575   }
1576
1577 FAIL_EXIT:
1578 *ptrptr = ptr;
1579 return -1;
1580 }
1581
1582
1583
1584
1585 /*************************************************
1586 *       Find forward referenced subpattern       *
1587 *************************************************/
1588
1589 /* This function scans along a pattern's text looking for capturing
1590 subpatterns, and counting them. If it finds a named pattern that matches the
1591 name it is given, it returns its number. Alternatively, if the name is NULL, it
1592 returns when it reaches a given numbered subpattern. This is used for forward
1593 references to subpatterns. We used to be able to start this scan from the
1594 current compiling point, using the current count value from cd->bracount, and
1595 do it all in a single loop, but the addition of the possibility of duplicate
1596 subpattern numbers means that we have to scan from the very start, in order to
1597 take account of such duplicates, and to use a recursive function to keep track
1598 of the different types of group.
1599
1600 Arguments:
1601   cd           compile background data
1602   name         name to seek, or NULL if seeking a numbered subpattern
1603   lorn         name length, or subpattern number if name is NULL
1604   xmode        TRUE if we are in /x mode
1605   utf          TRUE if we are in UTF-8 / UTF-16 mode
1606
1607 Returns:       the number of the found subpattern, or -1 if not found
1608 */
1609
1610 static int
1611 find_parens(compile_data *cd, const pcre_uchar *name, int lorn, BOOL xmode,
1612   BOOL utf)
1613 {
1614 pcre_uchar *ptr = (pcre_uchar *)cd->start_pattern;
1615 int count = 0;
1616 int rc;
1617
1618 /* If the pattern does not start with an opening parenthesis, the first call
1619 to find_parens_sub() will scan right to the end (if necessary). However, if it
1620 does start with a parenthesis, find_parens_sub() will return when it hits the
1621 matching closing parens. That is why we have to have a loop. */
1622
1623 for (;;)
1624   {
1625   rc = find_parens_sub(&ptr, cd, name, lorn, xmode, utf, &count);
1626   if (rc > 0 || *ptr++ == 0) break;
1627   }
1628
1629 return rc;
1630 }
1631
1632
1633
1634
1635 /*************************************************
1636 *      Find first significant op code            *
1637 *************************************************/
1638
1639 /* This is called by several functions that scan a compiled expression looking
1640 for a fixed first character, or an anchoring op code etc. It skips over things
1641 that do not influence this. For some calls, it makes sense to skip negative
1642 forward and all backward assertions, and also the \b assertion; for others it
1643 does not.
1644
1645 Arguments:
1646   code         pointer to the start of the group
1647   skipassert   TRUE if certain assertions are to be skipped
1648
1649 Returns:       pointer to the first significant opcode
1650 */
1651
1652 static const pcre_uchar*
1653 first_significant_code(const pcre_uchar *code, BOOL skipassert)
1654 {
1655 for (;;)
1656   {
1657   switch ((int)*code)
1658     {
1659     case OP_ASSERT_NOT:
1660     case OP_ASSERTBACK:
1661     case OP_ASSERTBACK_NOT:
1662     if (!skipassert) return code;
1663     do code += GET(code, 1); while (*code == OP_ALT);
1664     code += PRIV(OP_lengths)[*code];
1665     break;
1666
1667     case OP_WORD_BOUNDARY:
1668     case OP_NOT_WORD_BOUNDARY:
1669     if (!skipassert) return code;
1670     /* Fall through */
1671
1672     case OP_CALLOUT:
1673     case OP_CREF:
1674     case OP_NCREF:
1675     case OP_RREF:
1676     case OP_NRREF:
1677     case OP_DEF:
1678     code += PRIV(OP_lengths)[*code];
1679     break;
1680
1681     default:
1682     return code;
1683     }
1684   }
1685 /* Control never reaches here */
1686 }
1687
1688
1689
1690
1691 /*************************************************
1692 *        Find the fixed length of a branch       *
1693 *************************************************/
1694
1695 /* Scan a branch and compute the fixed length of subject that will match it,
1696 if the length is fixed. This is needed for dealing with backward assertions.
1697 In UTF8 mode, the result is in characters rather than bytes. The branch is
1698 temporarily terminated with OP_END when this function is called.
1699
1700 This function is called when a backward assertion is encountered, so that if it
1701 fails, the error message can point to the correct place in the pattern.
1702 However, we cannot do this when the assertion contains subroutine calls,
1703 because they can be forward references. We solve this by remembering this case
1704 and doing the check at the end; a flag specifies which mode we are running in.
1705
1706 Arguments:
1707   code     points to the start of the pattern (the bracket)
1708   utf      TRUE in UTF-8 / UTF-16 mode
1709   atend    TRUE if called when the pattern is complete
1710   cd       the "compile data" structure
1711
1712 Returns:   the fixed length,
1713              or -1 if there is no fixed length,
1714              or -2 if \C was encountered (in UTF-8 mode only)
1715              or -3 if an OP_RECURSE item was encountered and atend is FALSE
1716              or -4 if an unknown opcode was encountered (internal error)
1717 */
1718
1719 static int
1720 find_fixedlength(pcre_uchar *code, BOOL utf, BOOL atend, compile_data *cd)
1721 {
1722 int length = -1;
1723
1724 int branchlength = 0;
1725 pcre_uchar *cc = code + 1 + LINK_SIZE;
1726
1727 /* Scan along the opcodes for this branch. If we get to the end of the
1728 branch, check the length against that of the other branches. */
1729
1730 for (;;)
1731   {
1732   int d;
1733   pcre_uchar *ce, *cs;
1734   int op = *cc;
1735
1736   switch (op)
1737     {
1738     /* We only need to continue for OP_CBRA (normal capturing bracket) and
1739     OP_BRA (normal non-capturing bracket) because the other variants of these
1740     opcodes are all concerned with unlimited repeated groups, which of course
1741     are not of fixed length. */
1742
1743     case OP_CBRA:
1744     case OP_BRA:
1745     case OP_ONCE:
1746     case OP_ONCE_NC:
1747     case OP_COND:
1748     d = find_fixedlength(cc + ((op == OP_CBRA)? IMM2_SIZE : 0), utf, atend, cd);
1749     if (d < 0) return d;
1750     branchlength += d;
1751     do cc += GET(cc, 1); while (*cc == OP_ALT);
1752     cc += 1 + LINK_SIZE;
1753     break;
1754
1755     /* Reached end of a branch; if it's a ket it is the end of a nested call.
1756     If it's ALT it is an alternation in a nested call. An ACCEPT is effectively
1757     an ALT. If it is END it's the end of the outer call. All can be handled by
1758     the same code. Note that we must not include the OP_KETRxxx opcodes here,
1759     because they all imply an unlimited repeat. */
1760
1761     case OP_ALT:
1762     case OP_KET:
1763     case OP_END:
1764     case OP_ACCEPT:
1765     case OP_ASSERT_ACCEPT:
1766     if (length < 0) length = branchlength;
1767       else if (length != branchlength) return -1;
1768     if (*cc != OP_ALT) return length;
1769     cc += 1 + LINK_SIZE;
1770     branchlength = 0;
1771     break;
1772
1773     /* A true recursion implies not fixed length, but a subroutine call may
1774     be OK. If the subroutine is a forward reference, we can't deal with
1775     it until the end of the pattern, so return -3. */
1776
1777     case OP_RECURSE:
1778     if (!atend) return -3;
1779     cs = ce = (pcre_uchar *)cd->start_code + GET(cc, 1);  /* Start subpattern */
1780     do ce += GET(ce, 1); while (*ce == OP_ALT);           /* End subpattern */
1781     if (cc > cs && cc < ce) return -1;                    /* Recursion */
1782     d = find_fixedlength(cs + IMM2_SIZE, utf, atend, cd);
1783     if (d < 0) return d;
1784     branchlength += d;
1785     cc += 1 + LINK_SIZE;
1786     break;
1787
1788     /* Skip over assertive subpatterns */
1789
1790     case OP_ASSERT:
1791     case OP_ASSERT_NOT:
1792     case OP_ASSERTBACK:
1793     case OP_ASSERTBACK_NOT:
1794     do cc += GET(cc, 1); while (*cc == OP_ALT);
1795     cc += PRIV(OP_lengths)[*cc];
1796     break;
1797
1798     /* Skip over things that don't match chars */
1799
1800     case OP_MARK:
1801     case OP_PRUNE_ARG:
1802     case OP_SKIP_ARG:
1803     case OP_THEN_ARG:
1804     cc += cc[1] + PRIV(OP_lengths)[*cc];
1805     break;
1806
1807     case OP_CALLOUT:
1808     case OP_CIRC:
1809     case OP_CIRCM:
1810     case OP_CLOSE:
1811     case OP_COMMIT:
1812     case OP_CREF:
1813     case OP_DEF:
1814     case OP_DOLL:
1815     case OP_DOLLM:
1816     case OP_EOD:
1817     case OP_EODN:
1818     case OP_FAIL:
1819     case OP_NCREF:
1820     case OP_NRREF:
1821     case OP_NOT_WORD_BOUNDARY:
1822     case OP_PRUNE:
1823     case OP_REVERSE:
1824     case OP_RREF:
1825     case OP_SET_SOM:
1826     case OP_SKIP:
1827     case OP_SOD:
1828     case OP_SOM:
1829     case OP_THEN:
1830     case OP_WORD_BOUNDARY:
1831     cc += PRIV(OP_lengths)[*cc];
1832     break;
1833
1834     /* Handle literal characters */
1835
1836     case OP_CHAR:
1837     case OP_CHARI:
1838     case OP_NOT:
1839     case OP_NOTI:
1840     branchlength++;
1841     cc += 2;
1842 #ifdef SUPPORT_UTF
1843     if (utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);
1844 #endif
1845     break;
1846
1847     /* Handle exact repetitions. The count is already in characters, but we
1848     need to skip over a multibyte character in UTF8 mode.  */
1849
1850     case OP_EXACT:
1851     case OP_EXACTI:
1852     case OP_NOTEXACT:
1853     case OP_NOTEXACTI:
1854     branchlength += GET2(cc,1);
1855     cc += 2 + IMM2_SIZE;
1856 #ifdef SUPPORT_UTF
1857     if (utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);
1858 #endif
1859     break;
1860
1861     case OP_TYPEEXACT:
1862     branchlength += GET2(cc,1);
1863     if (cc[1 + IMM2_SIZE] == OP_PROP || cc[1 + IMM2_SIZE] == OP_NOTPROP) cc += 2;
1864     cc += 1 + IMM2_SIZE + 1;
1865     break;
1866
1867     /* Handle single-char matchers */
1868
1869     case OP_PROP:
1870     case OP_NOTPROP:
1871     cc += 2;
1872     /* Fall through */
1873
1874     case OP_HSPACE:
1875     case OP_VSPACE:
1876     case OP_NOT_HSPACE:
1877     case OP_NOT_VSPACE:
1878     case OP_NOT_DIGIT:
1879     case OP_DIGIT:
1880     case OP_NOT_WHITESPACE:
1881     case OP_WHITESPACE:
1882     case OP_NOT_WORDCHAR:
1883     case OP_WORDCHAR:
1884     case OP_ANY:
1885     case OP_ALLANY:
1886     branchlength++;
1887     cc++;
1888     break;
1889
1890     /* The single-byte matcher isn't allowed. This only happens in UTF-8 mode;
1891     otherwise \C is coded as OP_ALLANY. */
1892
1893     case OP_ANYBYTE:
1894     return -2;
1895
1896     /* Check a class for variable quantification */
1897
1898 #if defined SUPPORT_UTF || defined COMPILE_PCRE16
1899     case OP_XCLASS:
1900     cc += GET(cc, 1) - PRIV(OP_lengths)[OP_CLASS];
1901     /* Fall through */
1902 #endif
1903
1904     case OP_CLASS:
1905     case OP_NCLASS:
1906     cc += PRIV(OP_lengths)[OP_CLASS];
1907
1908     switch (*cc)
1909       {
1910       case OP_CRPLUS:
1911       case OP_CRMINPLUS:
1912       case OP_CRSTAR:
1913       case OP_CRMINSTAR:
1914       case OP_CRQUERY:
1915       case OP_CRMINQUERY:
1916       return -1;
1917
1918       case OP_CRRANGE:
1919       case OP_CRMINRANGE:
1920       if (GET2(cc,1) != GET2(cc,1+IMM2_SIZE)) return -1;
1921       branchlength += GET2(cc,1);
1922       cc += 1 + 2 * IMM2_SIZE;
1923       break;
1924
1925       default:
1926       branchlength++;
1927       }
1928     break;
1929
1930     /* Anything else is variable length */
1931
1932     case OP_ANYNL:
1933     case OP_BRAMINZERO:
1934     case OP_BRAPOS:
1935     case OP_BRAPOSZERO:
1936     case OP_BRAZERO:
1937     case OP_CBRAPOS:
1938     case OP_EXTUNI:
1939     case OP_KETRMAX:
1940     case OP_KETRMIN:
1941     case OP_KETRPOS:
1942     case OP_MINPLUS:
1943     case OP_MINPLUSI:
1944     case OP_MINQUERY:
1945     case OP_MINQUERYI:
1946     case OP_MINSTAR:
1947     case OP_MINSTARI:
1948     case OP_MINUPTO:
1949     case OP_MINUPTOI:
1950     case OP_NOTMINPLUS:
1951     case OP_NOTMINPLUSI:
1952     case OP_NOTMINQUERY:
1953     case OP_NOTMINQUERYI:
1954     case OP_NOTMINSTAR:
1955     case OP_NOTMINSTARI:
1956     case OP_NOTMINUPTO:
1957     case OP_NOTMINUPTOI:
1958     case OP_NOTPLUS:
1959     case OP_NOTPLUSI:
1960     case OP_NOTPOSPLUS:
1961     case OP_NOTPOSPLUSI:
1962     case OP_NOTPOSQUERY:
1963     case OP_NOTPOSQUERYI:
1964     case OP_NOTPOSSTAR:
1965     case OP_NOTPOSSTARI:
1966     case OP_NOTPOSUPTO:
1967     case OP_NOTPOSUPTOI:
1968     case OP_NOTQUERY:
1969     case OP_NOTQUERYI:
1970     case OP_NOTSTAR:
1971     case OP_NOTSTARI:
1972     case OP_NOTUPTO:
1973     case OP_NOTUPTOI:
1974     case OP_PLUS:
1975     case OP_PLUSI:
1976     case OP_POSPLUS:
1977     case OP_POSPLUSI:
1978     case OP_POSQUERY:
1979     case OP_POSQUERYI:
1980     case OP_POSSTAR:
1981     case OP_POSSTARI:
1982     case OP_POSUPTO:
1983     case OP_POSUPTOI:
1984     case OP_QUERY:
1985     case OP_QUERYI:
1986     case OP_REF:
1987     case OP_REFI:
1988     case OP_SBRA:
1989     case OP_SBRAPOS:
1990     case OP_SCBRA:
1991     case OP_SCBRAPOS:
1992     case OP_SCOND:
1993     case OP_SKIPZERO:
1994     case OP_STAR:
1995     case OP_STARI:
1996     case OP_TYPEMINPLUS:
1997     case OP_TYPEMINQUERY:
1998     case OP_TYPEMINSTAR:
1999     case OP_TYPEMINUPTO:
2000     case OP_TYPEPLUS:
2001     case OP_TYPEPOSPLUS:
2002     case OP_TYPEPOSQUERY:
2003     case OP_TYPEPOSSTAR:
2004     case OP_TYPEPOSUPTO:
2005     case OP_TYPEQUERY:
2006     case OP_TYPESTAR:
2007     case OP_TYPEUPTO:
2008     case OP_UPTO:
2009     case OP_UPTOI:
2010     return -1;
2011
2012     /* Catch unrecognized opcodes so that when new ones are added they
2013     are not forgotten, as has happened in the past. */
2014
2015     default:
2016     return -4;
2017     }
2018   }
2019 /* Control never gets here */
2020 }
2021
2022
2023
2024
2025 /*************************************************
2026 *    Scan compiled regex for specific bracket    *
2027 *************************************************/
2028
2029 /* This little function scans through a compiled pattern until it finds a
2030 capturing bracket with the given number, or, if the number is negative, an
2031 instance of OP_REVERSE for a lookbehind. The function is global in the C sense
2032 so that it can be called from pcre_study() when finding the minimum matching
2033 length.
2034
2035 Arguments:
2036   code        points to start of expression
2037   utf         TRUE in UTF-8 / UTF-16 mode
2038   number      the required bracket number or negative to find a lookbehind
2039
2040 Returns:      pointer to the opcode for the bracket, or NULL if not found
2041 */
2042
2043 const pcre_uchar *
2044 PRIV(find_bracket)(const pcre_uchar *code, BOOL utf, int number)
2045 {
2046 for (;;)
2047   {
2048   int c = *code;
2049
2050   if (c == OP_END) return NULL;
2051
2052   /* XCLASS is used for classes that cannot be represented just by a bit
2053   map. This includes negated single high-valued characters. The length in
2054   the table is zero; the actual length is stored in the compiled code. */
2055
2056   if (c == OP_XCLASS) code += GET(code, 1);
2057
2058   /* Handle recursion */
2059
2060   else if (c == OP_REVERSE)
2061     {
2062     if (number < 0) return (pcre_uchar *)code;
2063     code += PRIV(OP_lengths)[c];
2064     }
2065
2066   /* Handle capturing bracket */
2067
2068   else if (c == OP_CBRA || c == OP_SCBRA ||
2069            c == OP_CBRAPOS || c == OP_SCBRAPOS)
2070     {
2071     int n = GET2(code, 1+LINK_SIZE);
2072     if (n == number) return (pcre_uchar *)code;
2073     code += PRIV(OP_lengths)[c];
2074     }
2075
2076   /* Otherwise, we can get the item's length from the table, except that for
2077   repeated character types, we have to test for \p and \P, which have an extra
2078   two bytes of parameters, and for MARK/PRUNE/SKIP/THEN with an argument, we
2079   must add in its length. */
2080
2081   else
2082     {
2083     switch(c)
2084       {
2085       case OP_TYPESTAR:
2086       case OP_TYPEMINSTAR:
2087       case OP_TYPEPLUS:
2088       case OP_TYPEMINPLUS:
2089       case OP_TYPEQUERY:
2090       case OP_TYPEMINQUERY:
2091       case OP_TYPEPOSSTAR:
2092       case OP_TYPEPOSPLUS:
2093       case OP_TYPEPOSQUERY:
2094       if (code[1] == OP_PROP || code[1] == OP_NOTPROP) code += 2;
2095       break;
2096
2097       case OP_TYPEUPTO:
2098       case OP_TYPEMINUPTO:
2099       case OP_TYPEEXACT:
2100       case OP_TYPEPOSUPTO:
2101       if (code[1 + IMM2_SIZE] == OP_PROP
2102         || code[1 + IMM2_SIZE] == OP_NOTPROP) code += 2;
2103       break;
2104
2105       case OP_MARK:
2106       case OP_PRUNE_ARG:
2107       case OP_SKIP_ARG:
2108       code += code[1];
2109       break;
2110
2111       case OP_THEN_ARG:
2112       code += code[1];
2113       break;
2114       }
2115
2116     /* Add in the fixed length from the table */
2117
2118     code += PRIV(OP_lengths)[c];
2119
2120   /* In UTF-8 mode, opcodes that are followed by a character may be followed by
2121   a multi-byte character. The length in the table is a minimum, so we have to
2122   arrange to skip the extra bytes. */
2123
2124 #ifdef SUPPORT_UTF
2125     if (utf) switch(c)
2126       {
2127       case OP_CHAR:
2128       case OP_CHARI:
2129       case OP_EXACT:
2130       case OP_EXACTI:
2131       case OP_UPTO:
2132       case OP_UPTOI:
2133       case OP_MINUPTO:
2134       case OP_MINUPTOI:
2135       case OP_POSUPTO:
2136       case OP_POSUPTOI:
2137       case OP_STAR:
2138       case OP_STARI:
2139       case OP_MINSTAR:
2140       case OP_MINSTARI:
2141       case OP_POSSTAR:
2142       case OP_POSSTARI:
2143       case OP_PLUS:
2144       case OP_PLUSI:
2145       case OP_MINPLUS:
2146       case OP_MINPLUSI:
2147       case OP_POSPLUS:
2148       case OP_POSPLUSI:
2149       case OP_QUERY:
2150       case OP_QUERYI:
2151       case OP_MINQUERY:
2152       case OP_MINQUERYI:
2153       case OP_POSQUERY:
2154       case OP_POSQUERYI:
2155       if (HAS_EXTRALEN(code[-1])) code += GET_EXTRALEN(code[-1]);
2156       break;
2157       }
2158 #else
2159     (void)(utf);  /* Keep compiler happy by referencing function argument */
2160 #endif
2161     }
2162   }
2163 }
2164
2165
2166
2167 /*************************************************
2168 *   Scan compiled regex for recursion reference  *
2169 *************************************************/
2170
2171 /* This little function scans through a compiled pattern until it finds an
2172 instance of OP_RECURSE.
2173
2174 Arguments:
2175   code        points to start of expression
2176   utf         TRUE in UTF-8 / UTF-16 mode
2177
2178 Returns:      pointer to the opcode for OP_RECURSE, or NULL if not found
2179 */
2180
2181 static const pcre_uchar *
2182 find_recurse(const pcre_uchar *code, BOOL utf)
2183 {
2184 for (;;)
2185   {
2186   int c = *code;
2187   if (c == OP_END) return NULL;
2188   if (c == OP_RECURSE) return code;
2189
2190   /* XCLASS is used for classes that cannot be represented just by a bit
2191   map. This includes negated single high-valued characters. The length in
2192   the table is zero; the actual length is stored in the compiled code. */
2193
2194   if (c == OP_XCLASS) code += GET(code, 1);
2195
2196   /* Otherwise, we can get the item's length from the table, except that for
2197   repeated character types, we have to test for \p and \P, which have an extra
2198   two bytes of parameters, and for MARK/PRUNE/SKIP/THEN with an argument, we
2199   must add in its length. */
2200
2201   else
2202     {
2203     switch(c)
2204       {
2205       case OP_TYPESTAR:
2206       case OP_TYPEMINSTAR:
2207       case OP_TYPEPLUS:
2208       case OP_TYPEMINPLUS:
2209       case OP_TYPEQUERY:
2210       case OP_TYPEMINQUERY:
2211       case OP_TYPEPOSSTAR:
2212       case OP_TYPEPOSPLUS:
2213       case OP_TYPEPOSQUERY:
2214       if (code[1] == OP_PROP || code[1] == OP_NOTPROP) code += 2;
2215       break;
2216
2217       case OP_TYPEPOSUPTO:
2218       case OP_TYPEUPTO:
2219       case OP_TYPEMINUPTO:
2220       case OP_TYPEEXACT:
2221       if (code[1 + IMM2_SIZE] == OP_PROP
2222         || code[1 + IMM2_SIZE] == OP_NOTPROP) code += 2;
2223       break;
2224
2225       case OP_MARK:
2226       case OP_PRUNE_ARG:
2227       case OP_SKIP_ARG:
2228       code += code[1];
2229       break;
2230
2231       case OP_THEN_ARG:
2232       code += code[1];
2233       break;
2234       }
2235
2236     /* Add in the fixed length from the table */
2237
2238     code += PRIV(OP_lengths)[c];
2239
2240     /* In UTF-8 mode, opcodes that are followed by a character may be followed
2241     by a multi-byte character. The length in the table is a minimum, so we have
2242     to arrange to skip the extra bytes. */
2243
2244 #ifdef SUPPORT_UTF
2245     if (utf) switch(c)
2246       {
2247       case OP_CHAR:
2248       case OP_CHARI:
2249       case OP_NOT:
2250       case OP_NOTI:
2251       case OP_EXACT:
2252       case OP_EXACTI:
2253       case OP_NOTEXACT:
2254       case OP_NOTEXACTI:
2255       case OP_UPTO:
2256       case OP_UPTOI:
2257       case OP_NOTUPTO:
2258       case OP_NOTUPTOI:
2259       case OP_MINUPTO:
2260       case OP_MINUPTOI:
2261       case OP_NOTMINUPTO:
2262       case OP_NOTMINUPTOI:
2263       case OP_POSUPTO:
2264       case OP_POSUPTOI:
2265       case OP_NOTPOSUPTO:
2266       case OP_NOTPOSUPTOI:
2267       case OP_STAR:
2268       case OP_STARI:
2269       case OP_NOTSTAR:
2270       case OP_NOTSTARI:
2271       case OP_MINSTAR:
2272       case OP_MINSTARI:
2273       case OP_NOTMINSTAR:
2274       case OP_NOTMINSTARI:
2275       case OP_POSSTAR:
2276       case OP_POSSTARI:
2277       case OP_NOTPOSSTAR:
2278       case OP_NOTPOSSTARI:
2279       case OP_PLUS:
2280       case OP_PLUSI:
2281       case OP_NOTPLUS:
2282       case OP_NOTPLUSI:
2283       case OP_MINPLUS:
2284       case OP_MINPLUSI:
2285       case OP_NOTMINPLUS:
2286       case OP_NOTMINPLUSI:
2287       case OP_POSPLUS:
2288       case OP_POSPLUSI:
2289       case OP_NOTPOSPLUS:
2290       case OP_NOTPOSPLUSI:
2291       case OP_QUERY:
2292       case OP_QUERYI:
2293       case OP_NOTQUERY:
2294       case OP_NOTQUERYI:
2295       case OP_MINQUERY:
2296       case OP_MINQUERYI:
2297       case OP_NOTMINQUERY:
2298       case OP_NOTMINQUERYI:
2299       case OP_POSQUERY:
2300       case OP_POSQUERYI:
2301       case OP_NOTPOSQUERY:
2302       case OP_NOTPOSQUERYI:
2303       if (HAS_EXTRALEN(code[-1])) code += GET_EXTRALEN(code[-1]);
2304       break;
2305       }
2306 #else
2307     (void)(utf);  /* Keep compiler happy by referencing function argument */
2308 #endif
2309     }
2310   }
2311 }
2312
2313
2314
2315 /*************************************************
2316 *    Scan compiled branch for non-emptiness      *
2317 *************************************************/
2318
2319 /* This function scans through a branch of a compiled pattern to see whether it
2320 can match the empty string or not. It is called from could_be_empty()
2321 below and from compile_branch() when checking for an unlimited repeat of a
2322 group that can match nothing. Note that first_significant_code() skips over
2323 backward and negative forward assertions when its final argument is TRUE. If we
2324 hit an unclosed bracket, we return "empty" - this means we've struck an inner
2325 bracket whose current branch will already have been scanned.
2326
2327 Arguments:
2328   code        points to start of search
2329   endcode     points to where to stop
2330   utf         TRUE if in UTF-8 / UTF-16 mode
2331   cd          contains pointers to tables etc.
2332
2333 Returns:      TRUE if what is matched could be empty
2334 */
2335
2336 static BOOL
2337 could_be_empty_branch(const pcre_uchar *code, const pcre_uchar *endcode,
2338   BOOL utf, compile_data *cd)
2339 {
2340 int c;
2341 for (code = first_significant_code(code + PRIV(OP_lengths)[*code], TRUE);
2342      code < endcode;
2343      code = first_significant_code(code + PRIV(OP_lengths)[c], TRUE))
2344   {
2345   const pcre_uchar *ccode;
2346
2347   c = *code;
2348
2349   /* Skip over forward assertions; the other assertions are skipped by
2350   first_significant_code() with a TRUE final argument. */
2351
2352   if (c == OP_ASSERT)
2353     {
2354     do code += GET(code, 1); while (*code == OP_ALT);
2355     c = *code;
2356     continue;
2357     }
2358
2359   /* For a recursion/subroutine call, if its end has been reached, which
2360   implies a backward reference subroutine call, we can scan it. If it's a
2361   forward reference subroutine call, we can't. To detect forward reference
2362   we have to scan up the list that is kept in the workspace. This function is
2363   called only when doing the real compile, not during the pre-compile that
2364   measures the size of the compiled pattern. */
2365
2366   if (c == OP_RECURSE)
2367     {
2368     const pcre_uchar *scode;
2369     BOOL empty_branch;
2370
2371     /* Test for forward reference */
2372
2373     for (scode = cd->start_workspace; scode < cd->hwm; scode += LINK_SIZE)
2374       if (GET(scode, 0) == code + 1 - cd->start_code) return TRUE;
2375
2376     /* Not a forward reference, test for completed backward reference */
2377
2378     empty_branch = FALSE;
2379     scode = cd->start_code + GET(code, 1);
2380     if (GET(scode, 1) == 0) return TRUE;    /* Unclosed */
2381
2382     /* Completed backwards reference */
2383
2384     do
2385       {
2386       if (could_be_empty_branch(scode, endcode, utf, cd))
2387         {
2388         empty_branch = TRUE;
2389         break;
2390         }
2391       scode += GET(scode, 1);
2392       }
2393     while (*scode == OP_ALT);
2394
2395     if (!empty_branch) return FALSE;  /* All branches are non-empty */
2396     continue;
2397     }
2398
2399   /* Groups with zero repeats can of course be empty; skip them. */
2400
2401   if (c == OP_BRAZERO || c == OP_BRAMINZERO || c == OP_SKIPZERO ||
2402       c == OP_BRAPOSZERO)
2403     {
2404     code += PRIV(OP_lengths)[c];
2405     do code += GET(code, 1); while (*code == OP_ALT);
2406     c = *code;
2407     continue;
2408     }
2409
2410   /* A nested group that is already marked as "could be empty" can just be
2411   skipped. */
2412
2413   if (c == OP_SBRA  || c == OP_SBRAPOS ||
2414       c == OP_SCBRA || c == OP_SCBRAPOS)
2415     {
2416     do code += GET(code, 1); while (*code == OP_ALT);
2417     c = *code;
2418     continue;
2419     }
2420
2421   /* For other groups, scan the branches. */
2422
2423   if (c == OP_BRA  || c == OP_BRAPOS ||
2424       c == OP_CBRA || c == OP_CBRAPOS ||
2425       c == OP_ONCE || c == OP_ONCE_NC ||
2426       c == OP_COND)
2427     {
2428     BOOL empty_branch;
2429     if (GET(code, 1) == 0) return TRUE;    /* Hit unclosed bracket */
2430
2431     /* If a conditional group has only one branch, there is a second, implied,
2432     empty branch, so just skip over the conditional, because it could be empty.
2433     Otherwise, scan the individual branches of the group. */
2434
2435     if (c == OP_COND && code[GET(code, 1)] != OP_ALT)
2436       code += GET(code, 1);
2437     else
2438       {
2439       empty_branch = FALSE;
2440       do
2441         {
2442         if (!empty_branch && could_be_empty_branch(code, endcode, utf, cd))
2443           empty_branch = TRUE;
2444         code += GET(code, 1);
2445         }
2446       while (*code == OP_ALT);
2447       if (!empty_branch) return FALSE;   /* All branches are non-empty */
2448       }
2449
2450     c = *code;
2451     continue;
2452     }
2453
2454   /* Handle the other opcodes */
2455
2456   switch (c)
2457     {
2458     /* Check for quantifiers after a class. XCLASS is used for classes that
2459     cannot be represented just by a bit map. This includes negated single
2460     high-valued characters. The length in PRIV(OP_lengths)[] is zero; the
2461     actual length is stored in the compiled code, so we must update "code"
2462     here. */
2463
2464 #if defined SUPPORT_UTF || !defined COMPILE_PCRE8
2465     case OP_XCLASS:
2466     ccode = code += GET(code, 1);
2467     goto CHECK_CLASS_REPEAT;
2468 #endif
2469
2470     case OP_CLASS:
2471     case OP_NCLASS:
2472     ccode = code + PRIV(OP_lengths)[OP_CLASS];
2473
2474 #if defined SUPPORT_UTF || !defined COMPILE_PCRE8
2475     CHECK_CLASS_REPEAT:
2476 #endif
2477
2478     switch (*ccode)
2479       {
2480       case OP_CRSTAR:            /* These could be empty; continue */
2481       case OP_CRMINSTAR:
2482       case OP_CRQUERY:
2483       case OP_CRMINQUERY:
2484       break;
2485
2486       default:                   /* Non-repeat => class must match */
2487       case OP_CRPLUS:            /* These repeats aren't empty */
2488       case OP_CRMINPLUS:
2489       return FALSE;
2490
2491       case OP_CRRANGE:
2492       case OP_CRMINRANGE:
2493       if (GET2(ccode, 1) > 0) return FALSE;  /* Minimum > 0 */
2494       break;
2495       }
2496     break;
2497
2498     /* Opcodes that must match a character */
2499
2500     case OP_PROP:
2501     case OP_NOTPROP:
2502     case OP_EXTUNI:
2503     case OP_NOT_DIGIT:
2504     case OP_DIGIT:
2505     case OP_NOT_WHITESPACE:
2506     case OP_WHITESPACE:
2507     case OP_NOT_WORDCHAR:
2508     case OP_WORDCHAR:
2509     case OP_ANY:
2510     case OP_ALLANY:
2511     case OP_ANYBYTE:
2512     case OP_CHAR:
2513     case OP_CHARI:
2514     case OP_NOT:
2515     case OP_NOTI:
2516     case OP_PLUS:
2517     case OP_MINPLUS:
2518     case OP_POSPLUS:
2519     case OP_EXACT:
2520     case OP_NOTPLUS:
2521     case OP_NOTMINPLUS:
2522     case OP_NOTPOSPLUS:
2523     case OP_NOTEXACT:
2524     case OP_TYPEPLUS:
2525     case OP_TYPEMINPLUS:
2526     case OP_TYPEPOSPLUS:
2527     case OP_TYPEEXACT:
2528     return FALSE;
2529
2530     /* These are going to continue, as they may be empty, but we have to
2531     fudge the length for the \p and \P cases. */
2532
2533     case OP_TYPESTAR:
2534     case OP_TYPEMINSTAR:
2535     case OP_TYPEPOSSTAR:
2536     case OP_TYPEQUERY:
2537     case OP_TYPEMINQUERY:
2538     case OP_TYPEPOSQUERY:
2539     if (code[1] == OP_PROP || code[1] == OP_NOTPROP) code += 2;
2540     break;
2541
2542     /* Same for these */
2543
2544     case OP_TYPEUPTO:
2545     case OP_TYPEMINUPTO:
2546     case OP_TYPEPOSUPTO:
2547     if (code[1 + IMM2_SIZE] == OP_PROP
2548       || code[1 + IMM2_SIZE] == OP_NOTPROP) code += 2;
2549     break;
2550
2551     /* End of branch */
2552
2553     case OP_KET:
2554     case OP_KETRMAX:
2555     case OP_KETRMIN:
2556     case OP_KETRPOS:
2557     case OP_ALT:
2558     return TRUE;
2559
2560     /* In UTF-8 mode, STAR, MINSTAR, POSSTAR, QUERY, MINQUERY, POSQUERY, UPTO,
2561     MINUPTO, and POSUPTO may be followed by a multibyte character */
2562
2563 #ifdef SUPPORT_UTF
2564     case OP_STAR:
2565     case OP_STARI:
2566     case OP_MINSTAR:
2567     case OP_MINSTARI:
2568     case OP_POSSTAR:
2569     case OP_POSSTARI:
2570     case OP_QUERY:
2571     case OP_QUERYI:
2572     case OP_MINQUERY:
2573     case OP_MINQUERYI:
2574     case OP_POSQUERY:
2575     case OP_POSQUERYI:
2576     if (utf && HAS_EXTRALEN(code[1])) code += GET_EXTRALEN(code[1]);
2577     break;
2578
2579     case OP_UPTO:
2580     case OP_UPTOI:
2581     case OP_MINUPTO:
2582     case OP_MINUPTOI:
2583     case OP_POSUPTO:
2584     case OP_POSUPTOI:
2585     if (utf && HAS_EXTRALEN(code[1 + IMM2_SIZE])) code += GET_EXTRALEN(code[1 + IMM2_SIZE]);
2586     break;
2587 #endif
2588
2589     /* MARK, and PRUNE/SKIP/THEN with an argument must skip over the argument
2590     string. */
2591
2592     case OP_MARK:
2593     case OP_PRUNE_ARG:
2594     case OP_SKIP_ARG:
2595     code += code[1];
2596     break;
2597
2598     case OP_THEN_ARG:
2599     code += code[1];
2600     break;
2601
2602     /* None of the remaining opcodes are required to match a character. */
2603
2604     default:
2605     break;
2606     }
2607   }
2608
2609 return TRUE;
2610 }
2611
2612
2613
2614 /*************************************************
2615 *    Scan compiled regex for non-emptiness       *
2616 *************************************************/
2617
2618 /* This function is called to check for left recursive calls. We want to check
2619 the current branch of the current pattern to see if it could match the empty
2620 string. If it could, we must look outwards for branches at other levels,
2621 stopping when we pass beyond the bracket which is the subject of the recursion.
2622 This function is called only during the real compile, not during the
2623 pre-compile.
2624
2625 Arguments:
2626   code        points to start of the recursion
2627   endcode     points to where to stop (current RECURSE item)
2628   bcptr       points to the chain of current (unclosed) branch starts
2629   utf         TRUE if in UTF-8 / UTF-16 mode
2630   cd          pointers to tables etc
2631
2632 Returns:      TRUE if what is matched could be empty
2633 */
2634
2635 static BOOL
2636 could_be_empty(const pcre_uchar *code, const pcre_uchar *endcode,
2637   branch_chain *bcptr, BOOL utf, compile_data *cd)
2638 {
2639 while (bcptr != NULL && bcptr->current_branch >= code)
2640   {
2641   if (!could_be_empty_branch(bcptr->current_branch, endcode, utf, cd))
2642     return FALSE;
2643   bcptr = bcptr->outer;
2644   }
2645 return TRUE;
2646 }
2647
2648
2649
2650 /*************************************************
2651 *           Check for POSIX class syntax         *
2652 *************************************************/
2653
2654 /* This function is called when the sequence "[:" or "[." or "[=" is
2655 encountered in a character class. It checks whether this is followed by a
2656 sequence of characters terminated by a matching ":]" or ".]" or "=]". If we
2657 reach an unescaped ']' without the special preceding character, return FALSE.
2658
2659 Originally, this function only recognized a sequence of letters between the
2660 terminators, but it seems that Perl recognizes any sequence of characters,
2661 though of course unknown POSIX names are subsequently rejected. Perl gives an
2662 "Unknown POSIX class" error for [:f\oo:] for example, where previously PCRE
2663 didn't consider this to be a POSIX class. Likewise for [:1234:].
2664
2665 The problem in trying to be exactly like Perl is in the handling of escapes. We
2666 have to be sure that [abc[:x\]pqr] is *not* treated as containing a POSIX
2667 class, but [abc[:x\]pqr:]] is (so that an error can be generated). The code
2668 below handles the special case of \], but does not try to do any other escape
2669 processing. This makes it different from Perl for cases such as [:l\ower:]
2670 where Perl recognizes it as the POSIX class "lower" but PCRE does not recognize
2671 "l\ower". This is a lesser evil that not diagnosing bad classes when Perl does,
2672 I think.
2673
2674 A user pointed out that PCRE was rejecting [:a[:digit:]] whereas Perl was not.
2675 It seems that the appearance of a nested POSIX class supersedes an apparent
2676 external class. For example, [:a[:digit:]b:] matches "a", "b", ":", or
2677 a digit.
2678
2679 In Perl, unescaped square brackets may also appear as part of class names. For
2680 example, [:a[:abc]b:] gives unknown POSIX class "[:abc]b:]". However, for
2681 [:a[:abc]b][b:] it gives unknown POSIX class "[:abc]b][b:]", which does not
2682 seem right at all. PCRE does not allow closing square brackets in POSIX class
2683 names.
2684
2685 Arguments:
2686   ptr      pointer to the initial [
2687   endptr   where to return the end pointer
2688
2689 Returns:   TRUE or FALSE
2690 */
2691
2692 static BOOL
2693 check_posix_syntax(const pcre_uchar *ptr, const pcre_uchar **endptr)
2694 {
2695 int terminator;          /* Don't combine these lines; the Solaris cc */
2696 terminator = *(++ptr);   /* compiler warns about "non-constant" initializer. */
2697 for (++ptr; *ptr != 0; ptr++)
2698   {
2699   if (*ptr == CHAR_BACKSLASH && ptr[1] == CHAR_RIGHT_SQUARE_BRACKET)
2700     ptr++;
2701   else if (*ptr == CHAR_RIGHT_SQUARE_BRACKET) return FALSE;
2702   else
2703     {
2704     if (*ptr == terminator && ptr[1] == CHAR_RIGHT_SQUARE_BRACKET)
2705       {
2706       *endptr = ptr;
2707       return TRUE;
2708       }
2709     if (*ptr == CHAR_LEFT_SQUARE_BRACKET &&
2710          (ptr[1] == CHAR_COLON || ptr[1] == CHAR_DOT ||
2711           ptr[1] == CHAR_EQUALS_SIGN) &&
2712         check_posix_syntax(ptr, endptr))
2713       return FALSE;
2714     }
2715   }
2716 return FALSE;
2717 }
2718
2719
2720
2721
2722 /*************************************************
2723 *          Check POSIX class name                *
2724 *************************************************/
2725
2726 /* This function is called to check the name given in a POSIX-style class entry
2727 such as [:alnum:].
2728
2729 Arguments:
2730   ptr        points to the first letter
2731   len        the length of the name
2732
2733 Returns:     a value representing the name, or -1 if unknown
2734 */
2735
2736 static int
2737 check_posix_name(const pcre_uchar *ptr, int len)
2738 {
2739 const char *pn = posix_names;
2740 int yield = 0;
2741 while (posix_name_lengths[yield] != 0)
2742   {
2743   if (len == posix_name_lengths[yield] &&
2744     STRNCMP_UC_C8(ptr, pn, len) == 0) return yield;
2745   pn += posix_name_lengths[yield] + 1;
2746   yield++;
2747   }
2748 return -1;
2749 }
2750
2751
2752 /*************************************************
2753 *    Adjust OP_RECURSE items in repeated group   *
2754 *************************************************/
2755
2756 /* OP_RECURSE items contain an offset from the start of the regex to the group
2757 that is referenced. This means that groups can be replicated for fixed
2758 repetition simply by copying (because the recursion is allowed to refer to
2759 earlier groups that are outside the current group). However, when a group is
2760 optional (i.e. the minimum quantifier is zero), OP_BRAZERO or OP_SKIPZERO is
2761 inserted before it, after it has been compiled. This means that any OP_RECURSE
2762 items within it that refer to the group itself or any contained groups have to
2763 have their offsets adjusted. That one of the jobs of this function. Before it
2764 is called, the partially compiled regex must be temporarily terminated with
2765 OP_END.
2766
2767 This function has been extended with the possibility of forward references for
2768 recursions and subroutine calls. It must also check the list of such references
2769 for the group we are dealing with. If it finds that one of the recursions in
2770 the current group is on this list, it adjusts the offset in the list, not the
2771 value in the reference (which is a group number).
2772
2773 Arguments:
2774   group      points to the start of the group
2775   adjust     the amount by which the group is to be moved
2776   utf        TRUE in UTF-8 / UTF-16 mode
2777   cd         contains pointers to tables etc.
2778   save_hwm   the hwm forward reference pointer at the start of the group
2779
2780 Returns:     nothing
2781 */
2782
2783 static void
2784 adjust_recurse(pcre_uchar *group, int adjust, BOOL utf, compile_data *cd,
2785   pcre_uchar *save_hwm)
2786 {
2787 pcre_uchar *ptr = group;
2788
2789 while ((ptr = (pcre_uchar *)find_recurse(ptr, utf)) != NULL)
2790   {
2791   int offset;
2792   pcre_uchar *hc;
2793
2794   /* See if this recursion is on the forward reference list. If so, adjust the
2795   reference. */
2796
2797   for (hc = save_hwm; hc < cd->hwm; hc += LINK_SIZE)
2798     {
2799     offset = GET(hc, 0);
2800     if (cd->start_code + offset == ptr + 1)
2801       {
2802       PUT(hc, 0, offset + adjust);
2803       break;
2804       }
2805     }
2806
2807   /* Otherwise, adjust the recursion offset if it's after the start of this
2808   group. */
2809
2810   if (hc >= cd->hwm)
2811     {
2812     offset = GET(ptr, 1);
2813     if (cd->start_code + offset >= group) PUT(ptr, 1, offset + adjust);
2814     }
2815
2816   ptr += 1 + LINK_SIZE;
2817   }
2818 }
2819
2820
2821
2822 /*************************************************
2823 *        Insert an automatic callout point       *
2824 *************************************************/
2825
2826 /* This function is called when the PCRE_AUTO_CALLOUT option is set, to insert
2827 callout points before each pattern item.
2828
2829 Arguments:
2830   code           current code pointer
2831   ptr            current pattern pointer
2832   cd             pointers to tables etc
2833
2834 Returns:         new code pointer
2835 */
2836
2837 static pcre_uchar *
2838 auto_callout(pcre_uchar *code, const pcre_uchar *ptr, compile_data *cd)
2839 {
2840 *code++ = OP_CALLOUT;
2841 *code++ = 255;
2842 PUT(code, 0, (int)(ptr - cd->start_pattern));  /* Pattern offset */
2843 PUT(code, LINK_SIZE, 0);                       /* Default length */
2844 return code + 2 * LINK_SIZE;
2845 }
2846
2847
2848
2849 /*************************************************
2850 *         Complete a callout item                *
2851 *************************************************/
2852
2853 /* A callout item contains the length of the next item in the pattern, which
2854 we can't fill in till after we have reached the relevant point. This is used
2855 for both automatic and manual callouts.
2856
2857 Arguments:
2858   previous_callout   points to previous callout item
2859   ptr                current pattern pointer
2860   cd                 pointers to tables etc
2861
2862 Returns:             nothing
2863 */
2864
2865 static void
2866 complete_callout(pcre_uchar *previous_callout, const pcre_uchar *ptr, compile_data *cd)
2867 {
2868 int length = (int)(ptr - cd->start_pattern - GET(previous_callout, 2));
2869 PUT(previous_callout, 2 + LINK_SIZE, length);
2870 }
2871
2872
2873
2874 #ifdef SUPPORT_UCP
2875 /*************************************************
2876 *           Get othercase range                  *
2877 *************************************************/
2878
2879 /* This function is passed the start and end of a class range, in UTF-8 mode
2880 with UCP support. It searches up the characters, looking for internal ranges of
2881 characters in the "other" case. Each call returns the next one, updating the
2882 start address.
2883
2884 Arguments:
2885   cptr        points to starting character value; updated
2886   d           end value
2887   ocptr       where to put start of othercase range
2888   odptr       where to put end of othercase range
2889
2890 Yield:        TRUE when range returned; FALSE when no more
2891 */
2892
2893 static BOOL
2894 get_othercase_range(unsigned int *cptr, unsigned int d, unsigned int *ocptr,
2895   unsigned int *odptr)
2896 {
2897 unsigned int c, othercase, next;
2898
2899 for (c = *cptr; c <= d; c++)
2900   { if ((othercase = UCD_OTHERCASE(c)) != c) break; }
2901
2902 if (c > d) return FALSE;
2903
2904 *ocptr = othercase;
2905 next = othercase + 1;
2906
2907 for (++c; c <= d; c++)
2908   {
2909   if (UCD_OTHERCASE(c) != next) break;
2910   next++;
2911   }
2912
2913 *odptr = next - 1;
2914 *cptr = c;
2915
2916 return TRUE;
2917 }
2918
2919
2920
2921 /*************************************************
2922 *        Check a character and a property        *
2923 *************************************************/
2924
2925 /* This function is called by check_auto_possessive() when a property item
2926 is adjacent to a fixed character.
2927
2928 Arguments:
2929   c            the character
2930   ptype        the property type
2931   pdata        the data for the type
2932   negated      TRUE if it's a negated property (\P or \p{^)
2933
2934 Returns:       TRUE if auto-possessifying is OK
2935 */
2936
2937 static BOOL
2938 check_char_prop(int c, int ptype, int pdata, BOOL negated)
2939 {
2940 const pcre_uint8 chartype = UCD_CHARTYPE(c);
2941 switch(ptype)
2942   {
2943   case PT_LAMP:
2944   return (chartype == ucp_Lu ||
2945           chartype == ucp_Ll ||
2946           chartype == ucp_Lt) == negated;
2947
2948   case PT_GC:
2949   return (pdata == PRIV(ucp_gentype)[chartype]) == negated;
2950
2951   case PT_PC:
2952   return (pdata == chartype) == negated;
2953
2954   case PT_SC:
2955   return (pdata == UCD_SCRIPT(c)) == negated;
2956
2957   /* These are specials */
2958
2959   case PT_ALNUM:
2960   return (PRIV(ucp_gentype)[chartype] == ucp_L ||
2961           PRIV(ucp_gentype)[chartype] == ucp_N) == negated;
2962
2963   case PT_SPACE:    /* Perl space */
2964   return (PRIV(ucp_gentype)[chartype] == ucp_Z ||
2965           c == CHAR_HT || c == CHAR_NL || c == CHAR_FF || c == CHAR_CR)
2966           == negated;
2967
2968   case PT_PXSPACE:  /* POSIX space */
2969   return (PRIV(ucp_gentype)[chartype] == ucp_Z ||
2970           c == CHAR_HT || c == CHAR_NL || c == CHAR_VT ||
2971           c == CHAR_FF || c == CHAR_CR)
2972           == negated;
2973
2974   case PT_WORD:
2975   return (PRIV(ucp_gentype)[chartype] == ucp_L ||
2976           PRIV(ucp_gentype)[chartype] == ucp_N ||
2977           c == CHAR_UNDERSCORE) == negated;
2978   }
2979 return FALSE;
2980 }
2981 #endif  /* SUPPORT_UCP */
2982
2983
2984
2985 /*************************************************
2986 *     Check if auto-possessifying is possible    *
2987 *************************************************/
2988
2989 /* This function is called for unlimited repeats of certain items, to see
2990 whether the next thing could possibly match the repeated item. If not, it makes
2991 sense to automatically possessify the repeated item.
2992
2993 Arguments:
2994   previous      pointer to the repeated opcode
2995   utf           TRUE in UTF-8 / UTF-16 mode
2996   ptr           next character in pattern
2997   options       options bits
2998   cd            contains pointers to tables etc.
2999
3000 Returns:        TRUE if possessifying is wanted
3001 */
3002
3003 static BOOL
3004 check_auto_possessive(const pcre_uchar *previous, BOOL utf,
3005   const pcre_uchar *ptr, int options, compile_data *cd)
3006 {
3007 pcre_int32 c, next;
3008 int op_code = *previous++;
3009
3010 /* Skip whitespace and comments in extended mode */
3011
3012 if ((options & PCRE_EXTENDED) != 0)
3013   {
3014   for (;;)
3015     {
3016     while (MAX_255(*ptr) && (cd->ctypes[*ptr] & ctype_space) != 0) ptr++;
3017     if (*ptr == CHAR_NUMBER_SIGN)
3018       {
3019       ptr++;
3020       while (*ptr != 0)
3021         {
3022         if (IS_NEWLINE(ptr)) { ptr += cd->nllen; break; }
3023         ptr++;
3024 #ifdef SUPPORT_UTF
3025         if (utf) FORWARDCHAR(ptr);
3026 #endif
3027         }
3028       }
3029     else break;
3030     }
3031   }
3032
3033 /* If the next item is one that we can handle, get its value. A non-negative
3034 value is a character, a negative value is an escape value. */
3035
3036 if (*ptr == CHAR_BACKSLASH)
3037   {
3038   int temperrorcode = 0;
3039   next = check_escape(&ptr, &temperrorcode, cd->bracount, options, FALSE);
3040   if (temperrorcode != 0) return FALSE;
3041   ptr++;    /* Point after the escape sequence */
3042   }
3043 else if (!MAX_255(*ptr) || (cd->ctypes[*ptr] & ctype_meta) == 0)
3044   {
3045 #ifdef SUPPORT_UTF
3046   if (utf) { GETCHARINC(next, ptr); } else
3047 #endif
3048   next = *ptr++;
3049   }
3050 else return FALSE;
3051
3052 /* Skip whitespace and comments in extended mode */
3053
3054 if ((options & PCRE_EXTENDED) != 0)
3055   {
3056   for (;;)
3057     {
3058     while (MAX_255(*ptr) && (cd->ctypes[*ptr] & ctype_space) != 0) ptr++;
3059     if (*ptr == CHAR_NUMBER_SIGN)
3060       {
3061       ptr++;
3062       while (*ptr != 0)
3063         {
3064         if (IS_NEWLINE(ptr)) { ptr += cd->nllen; break; }
3065         ptr++;
3066 #ifdef SUPPORT_UTF
3067         if (utf) FORWARDCHAR(ptr);
3068 #endif
3069         }
3070       }
3071     else break;
3072     }
3073   }
3074
3075 /* If the next thing is itself optional, we have to give up. */
3076
3077 if (*ptr == CHAR_ASTERISK || *ptr == CHAR_QUESTION_MARK ||
3078   STRNCMP_UC_C8(ptr, STR_LEFT_CURLY_BRACKET STR_0 STR_COMMA, 3) == 0)
3079     return FALSE;
3080
3081 /* Now compare the next item with the previous opcode. First, handle cases when
3082 the next item is a character. */
3083
3084 if (next >= 0) switch(op_code)
3085   {
3086   case OP_CHAR:
3087 #ifdef SUPPORT_UTF
3088   GETCHARTEST(c, previous);
3089 #else
3090   c = *previous;
3091 #endif
3092   return c != next;
3093
3094   /* For CHARI (caseless character) we must check the other case. If we have
3095   Unicode property support, we can use it to test the other case of
3096   high-valued characters. */
3097
3098   case OP_CHARI:
3099 #ifdef SUPPORT_UTF
3100   GETCHARTEST(c, previous);
3101 #else
3102   c = *previous;
3103 #endif
3104   if (c == next) return FALSE;
3105 #ifdef SUPPORT_UTF
3106   if (utf)
3107     {
3108     unsigned int othercase;
3109     if (next < 128) othercase = cd->fcc[next]; else
3110 #ifdef SUPPORT_UCP
3111     othercase = UCD_OTHERCASE((unsigned int)next);
3112 #else
3113     othercase = NOTACHAR;
3114 #endif
3115     return (unsigned int)c != othercase;
3116     }
3117   else
3118 #endif  /* SUPPORT_UTF */
3119   return (c != TABLE_GET((unsigned int)next, cd->fcc, next));  /* Non-UTF-8 mode */
3120
3121   case OP_NOT:
3122 #ifdef SUPPORT_UTF
3123   GETCHARTEST(c, previous);
3124 #else
3125   c = *previous;
3126 #endif
3127   return c == next;
3128
3129   case OP_NOTI:
3130 #ifdef SUPPORT_UTF
3131   GETCHARTEST(c, previous);
3132 #else
3133   c = *previous;
3134 #endif
3135   if (c == next) return TRUE;
3136 #ifdef SUPPORT_UTF
3137   if (utf)
3138     {
3139     unsigned int othercase;
3140     if (next < 128) othercase = cd->fcc[next]; else
3141 #ifdef SUPPORT_UCP
3142     othercase = UCD_OTHERCASE((unsigned int)next);
3143 #else
3144     othercase = NOTACHAR;
3145 #endif
3146     return (unsigned int)c == othercase;
3147     }
3148   else
3149 #endif  /* SUPPORT_UTF */
3150   return (c == TABLE_GET((unsigned int)next, cd->fcc, next));  /* Non-UTF-8 mode */
3151
3152   /* Note that OP_DIGIT etc. are generated only when PCRE_UCP is *not* set.
3153   When it is set, \d etc. are converted into OP_(NOT_)PROP codes. */
3154
3155   case OP_DIGIT:
3156   return next > 255 || (cd->ctypes[next] & ctype_digit) == 0;
3157
3158   case OP_NOT_DIGIT:
3159   return next <= 255 && (cd->ctypes[next] & ctype_digit) != 0;
3160
3161   case OP_WHITESPACE:
3162   return next > 255 || (cd->ctypes[next] & ctype_space) == 0;
3163
3164   case OP_NOT_WHITESPACE:
3165   return next <= 255 && (cd->ctypes[next] & ctype_space) != 0;
3166
3167   case OP_WORDCHAR:
3168   return next > 255 || (cd->ctypes[next] & ctype_word) == 0;
3169
3170   case OP_NOT_WORDCHAR:
3171   return next <= 255 && (cd->ctypes[next] & ctype_word) != 0;
3172
3173   case OP_HSPACE:
3174   case OP_NOT_HSPACE:
3175   switch(next)
3176     {
3177     case 0x09:
3178     case 0x20:
3179     case 0xa0:
3180     case 0x1680:
3181     case 0x180e:
3182     case 0x2000:
3183     case 0x2001:
3184     case 0x2002:
3185     case 0x2003:
3186     case 0x2004:
3187     case 0x2005:
3188     case 0x2006:
3189     case 0x2007:
3190     case 0x2008:
3191     case 0x2009:
3192     case 0x200A:
3193     case 0x202f:
3194     case 0x205f:
3195     case 0x3000:
3196     return op_code == OP_NOT_HSPACE;
3197     default:
3198     return op_code != OP_NOT_HSPACE;
3199     }
3200
3201   case OP_ANYNL:
3202   case OP_VSPACE:
3203   case OP_NOT_VSPACE:
3204   switch(next)
3205     {
3206     case 0x0a:
3207     case 0x0b:
3208     case 0x0c:
3209     case 0x0d:
3210     case 0x85:
3211     case 0x2028:
3212     case 0x2029:
3213     return op_code == OP_NOT_VSPACE;
3214     default:
3215     return op_code != OP_NOT_VSPACE;
3216     }
3217
3218 #ifdef SUPPORT_UCP
3219   case OP_PROP:
3220   return check_char_prop(next, previous[0], previous[1], FALSE);
3221
3222   case OP_NOTPROP:
3223   return check_char_prop(next, previous[0], previous[1], TRUE);
3224 #endif
3225
3226   default:
3227   return FALSE;
3228   }
3229
3230
3231 /* Handle the case when the next item is \d, \s, etc. Note that when PCRE_UCP
3232 is set, \d turns into ESC_du rather than ESC_d, etc., so ESC_d etc. are
3233 generated only when PCRE_UCP is *not* set, that is, when only ASCII
3234 characteristics are recognized. Similarly, the opcodes OP_DIGIT etc. are
3235 replaced by OP_PROP codes when PCRE_UCP is set. */
3236
3237 switch(op_code)
3238   {
3239   case OP_CHAR:
3240   case OP_CHARI:
3241 #ifdef SUPPORT_UTF
3242   GETCHARTEST(c, previous);
3243 #else
3244   c = *previous;
3245 #endif
3246   switch(-next)
3247     {
3248     case ESC_d:
3249     return c > 255 || (cd->ctypes[c] & ctype_digit) == 0;
3250
3251     case ESC_D:
3252     return c <= 255 && (cd->ctypes[c] & ctype_digit) != 0;
3253
3254     case ESC_s:
3255     return c > 255 || (cd->ctypes[c] & ctype_space) == 0;
3256
3257     case ESC_S:
3258     return c <= 255 && (cd->ctypes[c] & ctype_space) != 0;
3259
3260     case ESC_w:
3261     return c > 255 || (cd->ctypes[c] & ctype_word) == 0;
3262
3263     case ESC_W:
3264     return c <= 255 && (cd->ctypes[c] & ctype_word) != 0;
3265
3266     case ESC_h:
3267     case ESC_H:
3268     switch(c)
3269       {
3270       case 0x09:
3271       case 0x20:
3272       case 0xa0:
3273       case 0x1680:
3274       case 0x180e:
3275       case 0x2000:
3276       case 0x2001:
3277       case 0x2002:
3278       case 0x2003:
3279       case 0x2004:
3280       case 0x2005:
3281       case 0x2006:
3282       case 0x2007:
3283       case 0x2008:
3284       case 0x2009:
3285       case 0x200A:
3286       case 0x202f:
3287       case 0x205f:
3288       case 0x3000:
3289       return -next != ESC_h;
3290       default:
3291       return -next == ESC_h;
3292       }
3293
3294     case ESC_v:
3295     case ESC_V:
3296     switch(c)
3297       {
3298       case 0x0a:
3299       case 0x0b:
3300       case 0x0c:
3301       case 0x0d:
3302       case 0x85:
3303       case 0x2028:
3304       case 0x2029:
3305       return -next != ESC_v;
3306       default:
3307       return -next == ESC_v;
3308       }
3309
3310     /* When PCRE_UCP is set, these values get generated for \d etc. Find
3311     their substitutions and process them. The result will always be either
3312     -ESC_p or -ESC_P. Then fall through to process those values. */
3313
3314 #ifdef SUPPORT_UCP
3315     case ESC_du:
3316     case ESC_DU:
3317     case ESC_wu:
3318     case ESC_WU:
3319     case ESC_su:
3320     case ESC_SU:
3321       {
3322       int temperrorcode = 0;
3323       ptr = substitutes[-next - ESC_DU];
3324       next = check_escape(&ptr, &temperrorcode, 0, options, FALSE);
3325       if (temperrorcode != 0) return FALSE;
3326       ptr++;    /* For compatibility */
3327       }
3328     /* Fall through */
3329
3330     case ESC_p:
3331     case ESC_P:
3332       {
3333       int ptype, pdata, errorcodeptr;
3334       BOOL negated;
3335
3336       ptr--;      /* Make ptr point at the p or P */
3337       ptype = get_ucp(&ptr, &negated, &pdata, &errorcodeptr);
3338       if (ptype < 0) return FALSE;
3339       ptr++;      /* Point past the final curly ket */
3340
3341       /* If the property item is optional, we have to give up. (When generated
3342       from \d etc by PCRE_UCP, this test will have been applied much earlier,
3343       to the original \d etc. At this point, ptr will point to a zero byte. */
3344
3345       if (*ptr == CHAR_ASTERISK || *ptr == CHAR_QUESTION_MARK ||
3346         STRNCMP_UC_C8(ptr, STR_LEFT_CURLY_BRACKET STR_0 STR_COMMA, 3) == 0)
3347           return FALSE;
3348
3349       /* Do the property check. */
3350
3351       return check_char_prop(c, ptype, pdata, (next == -ESC_P) != negated);
3352       }
3353 #endif
3354
3355     default:
3356     return FALSE;
3357     }
3358
3359   /* In principle, support for Unicode properties should be integrated here as
3360   well. It means re-organizing the above code so as to get hold of the property
3361   values before switching on the op-code. However, I wonder how many patterns
3362   combine ASCII \d etc with Unicode properties? (Note that if PCRE_UCP is set,
3363   these op-codes are never generated.) */
3364
3365   case OP_DIGIT:
3366   return next == -ESC_D || next == -ESC_s || next == -ESC_W ||
3367          next == -ESC_h || next == -ESC_v || next == -ESC_R;
3368
3369   case OP_NOT_DIGIT:
3370   return next == -ESC_d;
3371
3372   case OP_WHITESPACE:
3373   return next == -ESC_S || next == -ESC_d || next == -ESC_w;
3374
3375   case OP_NOT_WHITESPACE:
3376   return next == -ESC_s || next == -ESC_h || next == -ESC_v || next == -ESC_R;
3377
3378   case OP_HSPACE:
3379   return next == -ESC_S || next == -ESC_H || next == -ESC_d ||
3380          next == -ESC_w || next == -ESC_v || next == -ESC_R;
3381
3382   case OP_NOT_HSPACE:
3383   return next == -ESC_h;
3384
3385   /* Can't have \S in here because VT matches \S (Perl anomaly) */
3386   case OP_ANYNL:
3387   case OP_VSPACE:
3388   return next == -ESC_V || next == -ESC_d || next == -ESC_w;
3389
3390   case OP_NOT_VSPACE:
3391   return next == -ESC_v || next == -ESC_R;
3392
3393   case OP_WORDCHAR:
3394   return next == -ESC_W || next == -ESC_s || next == -ESC_h ||
3395          next == -ESC_v || next == -ESC_R;
3396
3397   case OP_NOT_WORDCHAR:
3398   return next == -ESC_w || next == -ESC_d;
3399
3400   default:
3401   return FALSE;
3402   }
3403
3404 /* Control does not reach here */
3405 }
3406
3407
3408
3409 /*************************************************
3410 *           Compile one branch                   *
3411 *************************************************/
3412
3413 /* Scan the pattern, compiling it into the a vector. If the options are
3414 changed during the branch, the pointer is used to change the external options
3415 bits. This function is used during the pre-compile phase when we are trying
3416 to find out the amount of memory needed, as well as during the real compile
3417 phase. The value of lengthptr distinguishes the two phases.
3418
3419 Arguments:
3420   optionsptr     pointer to the option bits
3421   codeptr        points to the pointer to the current code point
3422   ptrptr         points to the current pattern pointer
3423   errorcodeptr   points to error code variable
3424   firstcharptr   set to initial literal character, or < 0 (REQ_UNSET, REQ_NONE)
3425   reqcharptr     set to the last literal character required, else < 0
3426   bcptr          points to current branch chain
3427   cond_depth     conditional nesting depth
3428   cd             contains pointers to tables etc.
3429   lengthptr      NULL during the real compile phase
3430                  points to length accumulator during pre-compile phase
3431
3432 Returns:         TRUE on success
3433                  FALSE, with *errorcodeptr set non-zero on error
3434 */
3435
3436 static BOOL
3437 compile_branch(int *optionsptr, pcre_uchar **codeptr,
3438   const pcre_uchar **ptrptr, int *errorcodeptr, pcre_int32 *firstcharptr,
3439   pcre_int32 *reqcharptr, branch_chain *bcptr, int cond_depth,
3440   compile_data *cd, int *lengthptr)
3441 {
3442 int repeat_type, op_type;
3443 int repeat_min = 0, repeat_max = 0;      /* To please picky compilers */
3444 int bravalue = 0;
3445 int greedy_default, greedy_non_default;
3446 pcre_int32 firstchar, reqchar;
3447 pcre_int32 zeroreqchar, zerofirstchar;
3448 pcre_int32 req_caseopt, reqvary, tempreqvary;
3449 int options = *optionsptr;               /* May change dynamically */
3450 int after_manual_callout = 0;
3451 int length_prevgroup = 0;
3452 int c;
3453 pcre_uchar *code = *codeptr;
3454 pcre_uchar *last_code = code;
3455 pcre_uchar *orig_code = code;
3456 pcre_uchar *tempcode;
3457 BOOL inescq = FALSE;
3458 BOOL groupsetfirstchar = FALSE;
3459 const pcre_uchar *ptr = *ptrptr;
3460 const pcre_uchar *tempptr;
3461 const pcre_uchar *nestptr = NULL;
3462 pcre_uchar *previous = NULL;
3463 pcre_uchar *previous_callout = NULL;
3464 pcre_uchar *save_hwm = NULL;
3465 pcre_uint8 classbits[32];
3466
3467 /* We can fish out the UTF-8 setting once and for all into a BOOL, but we
3468 must not do this for other options (e.g. PCRE_EXTENDED) because they may change
3469 dynamically as we process the pattern. */
3470
3471 #ifdef SUPPORT_UTF
3472 /* PCRE_UTF16 has the same value as PCRE_UTF8. */
3473 BOOL utf = (options & PCRE_UTF8) != 0;
3474 pcre_uchar utf_chars[6];
3475 #else
3476 BOOL utf = FALSE;
3477 #endif
3478
3479 /* Helper variables for OP_XCLASS opcode (for characters > 255). */
3480
3481 #if defined SUPPORT_UTF || !defined COMPILE_PCRE8
3482 BOOL xclass;
3483 pcre_uchar *class_uchardata;
3484 pcre_uchar *class_uchardata_base;
3485 #endif
3486
3487 #ifdef PCRE_DEBUG
3488 if (lengthptr != NULL) DPRINTF((">> start branch\n"));
3489 #endif
3490
3491 /* Set up the default and non-default settings for greediness */
3492
3493 greedy_default = ((options & PCRE_UNGREEDY) != 0);
3494 greedy_non_default = greedy_default ^ 1;
3495
3496 /* Initialize no first byte, no required byte. REQ_UNSET means "no char
3497 matching encountered yet". It gets changed to REQ_NONE if we hit something that
3498 matches a non-fixed char first char; reqchar just remains unset if we never
3499 find one.
3500
3501 When we hit a repeat whose minimum is zero, we may have to adjust these values
3502 to take the zero repeat into account. This is implemented by setting them to
3503 zerofirstbyte and zeroreqchar when such a repeat is encountered. The individual
3504 item types that can be repeated set these backoff variables appropriately. */
3505
3506 firstchar = reqchar = zerofirstchar = zeroreqchar = REQ_UNSET;
3507
3508 /* The variable req_caseopt contains either the REQ_CASELESS value
3509 or zero, according to the current setting of the caseless flag. The
3510 REQ_CASELESS leaves the lower 28 bit empty. It is added into the
3511 firstchar or reqchar variables to record the case status of the
3512 value. This is used only for ASCII characters. */
3513
3514 req_caseopt = ((options & PCRE_CASELESS) != 0)? REQ_CASELESS:0;
3515
3516 /* Switch on next character until the end of the branch */
3517
3518 for (;; ptr++)
3519   {
3520   BOOL negate_class;
3521   BOOL should_flip_negation;
3522   BOOL possessive_quantifier;
3523   BOOL is_quantifier;
3524   BOOL is_recurse;
3525   BOOL reset_bracount;
3526   int class_has_8bitchar;
3527   int class_single_char;
3528   int newoptions;
3529   int recno;
3530   int refsign;
3531   int skipbytes;
3532   int subreqchar;
3533   int subfirstchar;
3534   int terminator;
3535   int mclength;
3536   int tempbracount;
3537   pcre_uchar mcbuffer[8];
3538
3539   /* Get next character in the pattern */
3540
3541   c = *ptr;
3542
3543   /* If we are at the end of a nested substitution, revert to the outer level
3544   string. Nesting only happens one level deep. */
3545
3546   if (c == 0 && nestptr != NULL)
3547     {
3548     ptr = nestptr;
3549     nestptr = NULL;
3550     c = *ptr;
3551     }
3552
3553   /* If we are in the pre-compile phase, accumulate the length used for the
3554   previous cycle of this loop. */
3555
3556   if (lengthptr != NULL)
3557     {
3558 #ifdef PCRE_DEBUG
3559     if (code > cd->hwm) cd->hwm = code;                 /* High water info */
3560 #endif
3561     if (code > cd->start_workspace + cd->workspace_size -
3562         WORK_SIZE_SAFETY_MARGIN)                       /* Check for overrun */
3563       {
3564       *errorcodeptr = ERR52;
3565       goto FAILED;
3566       }
3567
3568     /* There is at least one situation where code goes backwards: this is the
3569     case of a zero quantifier after a class (e.g. [ab]{0}). At compile time,
3570     the class is simply eliminated. However, it is created first, so we have to
3571     allow memory for it. Therefore, don't ever reduce the length at this point.
3572     */
3573
3574     if (code < last_code) code = last_code;
3575
3576     /* Paranoid check for integer overflow */
3577
3578     if (OFLOW_MAX - *lengthptr < code - last_code)
3579       {
3580       *errorcodeptr = ERR20;
3581       goto FAILED;
3582       }
3583
3584     *lengthptr += (int)(code - last_code);
3585     DPRINTF(("length=%d added %d c=%c (0x%x)\n", *lengthptr,
3586       (int)(code - last_code), c, c));
3587
3588     /* If "previous" is set and it is not at the start of the work space, move
3589     it back to there, in order to avoid filling up the work space. Otherwise,
3590     if "previous" is NULL, reset the current code pointer to the start. */
3591
3592     if (previous != NULL)
3593       {
3594       if (previous > orig_code)
3595         {
3596         memmove(orig_code, previous, IN_UCHARS(code - previous));
3597         code -= previous - orig_code;
3598         previous = orig_code;
3599         }
3600       }
3601     else code = orig_code;
3602
3603     /* Remember where this code item starts so we can pick up the length
3604     next time round. */
3605
3606     last_code = code;
3607     }
3608
3609   /* In the real compile phase, just check the workspace used by the forward
3610   reference list. */
3611
3612   else if (cd->hwm > cd->start_workspace + cd->workspace_size -
3613            WORK_SIZE_SAFETY_MARGIN)
3614     {
3615     *errorcodeptr = ERR52;
3616     goto FAILED;
3617     }
3618
3619   /* If in \Q...\E, check for the end; if not, we have a literal */
3620
3621   if (inescq && c != 0)
3622     {
3623     if (c == CHAR_BACKSLASH && ptr[1] == CHAR_E)
3624       {
3625       inescq = FALSE;
3626       ptr++;
3627       continue;
3628       }
3629     else
3630       {
3631       if (previous_callout != NULL)
3632         {
3633         if (lengthptr == NULL)  /* Don't attempt in pre-compile phase */
3634           complete_callout(previous_callout, ptr, cd);
3635         previous_callout = NULL;
3636         }
3637       if ((options & PCRE_AUTO_CALLOUT) != 0)
3638         {
3639         previous_callout = code;
3640         code = auto_callout(code, ptr, cd);
3641         }
3642       goto NORMAL_CHAR;
3643       }
3644     }
3645
3646   /* Fill in length of a previous callout, except when the next thing is
3647   a quantifier. */
3648
3649   is_quantifier =
3650     c == CHAR_ASTERISK || c == CHAR_PLUS || c == CHAR_QUESTION_MARK ||
3651     (c == CHAR_LEFT_CURLY_BRACKET && is_counted_repeat(ptr+1));
3652
3653   if (!is_quantifier && previous_callout != NULL &&
3654        after_manual_callout-- <= 0)
3655     {
3656     if (lengthptr == NULL)      /* Don't attempt in pre-compile phase */
3657       complete_callout(previous_callout, ptr, cd);
3658     previous_callout = NULL;
3659     }
3660
3661   /* In extended mode, skip white space and comments. */
3662
3663   if ((options & PCRE_EXTENDED) != 0)
3664     {
3665     if (MAX_255(*ptr) && (cd->ctypes[c] & ctype_space) != 0) continue;
3666     if (c == CHAR_NUMBER_SIGN)
3667       {
3668       ptr++;
3669       while (*ptr != 0)
3670         {
3671         if (IS_NEWLINE(ptr)) { ptr += cd->nllen - 1; break; }
3672         ptr++;
3673 #ifdef SUPPORT_UTF
3674         if (utf) FORWARDCHAR(ptr);
3675 #endif
3676         }
3677       if (*ptr != 0) continue;
3678
3679       /* Else fall through to handle end of string */
3680       c = 0;
3681       }
3682     }
3683
3684   /* No auto callout for quantifiers. */
3685
3686   if ((options & PCRE_AUTO_CALLOUT) != 0 && !is_quantifier)
3687     {
3688     previous_callout = code;
3689     code = auto_callout(code, ptr, cd);
3690     }
3691
3692   switch(c)
3693     {
3694     /* ===================================================================*/
3695     case 0:                        /* The branch terminates at string end */
3696     case CHAR_VERTICAL_LINE:       /* or | or ) */
3697     case CHAR_RIGHT_PARENTHESIS:
3698     *firstcharptr = firstchar;
3699     *reqcharptr = reqchar;
3700     *codeptr = code;
3701     *ptrptr = ptr;
3702     if (lengthptr != NULL)
3703       {
3704       if (OFLOW_MAX - *lengthptr < code - last_code)
3705         {
3706         *errorcodeptr = ERR20;
3707         goto FAILED;
3708         }
3709       *lengthptr += (int)(code - last_code);   /* To include callout length */
3710       DPRINTF((">> end branch\n"));
3711       }
3712     return TRUE;
3713
3714
3715     /* ===================================================================*/
3716     /* Handle single-character metacharacters. In multiline mode, ^ disables
3717     the setting of any following char as a first character. */
3718
3719     case CHAR_CIRCUMFLEX_ACCENT:
3720     previous = NULL;
3721     if ((options & PCRE_MULTILINE) != 0)
3722       {
3723       if (firstchar == REQ_UNSET) firstchar = REQ_NONE;
3724       *code++ = OP_CIRCM;
3725       }
3726     else *code++ = OP_CIRC;
3727     break;
3728
3729     case CHAR_DOLLAR_SIGN:
3730     previous = NULL;
3731     *code++ = ((options & PCRE_MULTILINE) != 0)? OP_DOLLM : OP_DOLL;
3732     break;
3733
3734     /* There can never be a first char if '.' is first, whatever happens about
3735     repeats. The value of reqchar doesn't change either. */
3736
3737     case CHAR_DOT:
3738     if (firstchar == REQ_UNSET) firstchar = REQ_NONE;
3739     zerofirstchar = firstchar;
3740     zeroreqchar = reqchar;
3741     previous = code;
3742     *code++ = ((options & PCRE_DOTALL) != 0)? OP_ALLANY: OP_ANY;
3743     break;
3744
3745
3746     /* ===================================================================*/
3747     /* Character classes. If the included characters are all < 256, we build a
3748     32-byte bitmap of the permitted characters, except in the special case
3749     where there is only one such character. For negated classes, we build the
3750     map as usual, then invert it at the end. However, we use a different opcode
3751     so that data characters > 255 can be handled correctly.
3752
3753     If the class contains characters outside the 0-255 range, a different
3754     opcode is compiled. It may optionally have a bit map for characters < 256,
3755     but those above are are explicitly listed afterwards. A flag byte tells
3756     whether the bitmap is present, and whether this is a negated class or not.
3757
3758     In JavaScript compatibility mode, an isolated ']' causes an error. In
3759     default (Perl) mode, it is treated as a data character. */
3760
3761     case CHAR_RIGHT_SQUARE_BRACKET:
3762     if ((cd->external_options & PCRE_JAVASCRIPT_COMPAT) != 0)
3763       {
3764       *errorcodeptr = ERR64;
3765       goto FAILED;
3766       }
3767     goto NORMAL_CHAR;
3768
3769     case CHAR_LEFT_SQUARE_BRACKET:
3770     previous = code;
3771
3772     /* PCRE supports POSIX class stuff inside a class. Perl gives an error if
3773     they are encountered at the top level, so we'll do that too. */
3774
3775     if ((ptr[1] == CHAR_COLON || ptr[1] == CHAR_DOT ||
3776          ptr[1] == CHAR_EQUALS_SIGN) &&
3777         check_posix_syntax(ptr, &tempptr))
3778       {
3779       *errorcodeptr = (ptr[1] == CHAR_COLON)? ERR13 : ERR31;
3780       goto FAILED;
3781       }
3782
3783     /* If the first character is '^', set the negation flag and skip it. Also,
3784     if the first few characters (either before or after ^) are \Q\E or \E we
3785     skip them too. This makes for compatibility with Perl. */
3786
3787     negate_class = FALSE;
3788     for (;;)
3789       {
3790       c = *(++ptr);
3791       if (c == CHAR_BACKSLASH)
3792         {
3793         if (ptr[1] == CHAR_E)
3794           ptr++;
3795         else if (STRNCMP_UC_C8(ptr + 1, STR_Q STR_BACKSLASH STR_E, 3) == 0)
3796           ptr += 3;
3797         else
3798           break;
3799         }
3800       else if (!negate_class && c == CHAR_CIRCUMFLEX_ACCENT)
3801         negate_class = TRUE;
3802       else break;
3803       }
3804
3805     /* Empty classes are allowed in JavaScript compatibility mode. Otherwise,
3806     an initial ']' is taken as a data character -- the code below handles
3807     that. In JS mode, [] must always fail, so generate OP_FAIL, whereas
3808     [^] must match any character, so generate OP_ALLANY. */
3809
3810     if (c == CHAR_RIGHT_SQUARE_BRACKET &&
3811         (cd->external_options & PCRE_JAVASCRIPT_COMPAT) != 0)
3812       {
3813       *code++ = negate_class? OP_ALLANY : OP_FAIL;
3814       if (firstchar == REQ_UNSET) firstchar = REQ_NONE;
3815       zerofirstchar = firstchar;
3816       break;
3817       }
3818
3819     /* If a class contains a negative special such as \S, we need to flip the
3820     negation flag at the end, so that support for characters > 255 works
3821     correctly (they are all included in the class). */
3822
3823     should_flip_negation = FALSE;
3824
3825     /* For optimization purposes, we track some properties of the class.
3826     class_has_8bitchar will be non-zero, if the class contains at least one
3827     < 256 character. class_single_char will be 1 if the class contains only
3828     a single character. */
3829
3830     class_has_8bitchar = 0;
3831     class_single_char = 0;
3832
3833     /* Initialize the 32-char bit map to all zeros. We build the map in a
3834     temporary bit of memory, in case the class contains only 1 character (less
3835     than 256), because in that case the compiled code doesn't use the bit map.
3836     */
3837
3838     memset(classbits, 0, 32 * sizeof(pcre_uint8));
3839
3840 #if defined SUPPORT_UTF || !defined COMPILE_PCRE8
3841     xclass = FALSE;                           /* No chars >= 256 */
3842     class_uchardata = code + LINK_SIZE + 2;   /* For UTF-8 items */
3843     class_uchardata_base = class_uchardata;   /* For resetting in pass 1 */
3844 #endif
3845
3846     /* Process characters until ] is reached. By writing this as a "do" it
3847     means that an initial ] is taken as a data character. At the start of the
3848     loop, c contains the first byte of the character. */
3849
3850     if (c != 0) do
3851       {
3852       const pcre_uchar *oldptr;
3853
3854 #ifdef SUPPORT_UTF
3855       if (utf && HAS_EXTRALEN(c))
3856         {                           /* Braces are required because the */
3857         GETCHARLEN(c, ptr, ptr);    /* macro generates multiple statements */
3858         }
3859 #endif
3860
3861 #if defined SUPPORT_UTF || !defined COMPILE_PCRE8
3862       /* In the pre-compile phase, accumulate the length of any extra
3863       data and reset the pointer. This is so that very large classes that
3864       contain a zillion > 255 characters no longer overwrite the work space
3865       (which is on the stack). */
3866
3867       if (lengthptr != NULL)
3868         {
3869         *lengthptr += class_uchardata - class_uchardata_base;
3870         class_uchardata = class_uchardata_base;
3871         }
3872 #endif
3873
3874       /* Inside \Q...\E everything is literal except \E */
3875
3876       if (inescq)
3877         {
3878         if (c == CHAR_BACKSLASH && ptr[1] == CHAR_E)  /* If we are at \E */
3879           {
3880           inescq = FALSE;                   /* Reset literal state */
3881           ptr++;                            /* Skip the 'E' */
3882           continue;                         /* Carry on with next */
3883           }
3884         goto CHECK_RANGE;                   /* Could be range if \E follows */
3885         }
3886
3887       /* Handle POSIX class names. Perl allows a negation extension of the
3888       form [:^name:]. A square bracket that doesn't match the syntax is
3889       treated as a literal. We also recognize the POSIX constructions
3890       [.ch.] and [=ch=] ("collating elements") and fault them, as Perl
3891       5.6 and 5.8 do. */
3892
3893       if (c == CHAR_LEFT_SQUARE_BRACKET &&
3894           (ptr[1] == CHAR_COLON || ptr[1] == CHAR_DOT ||
3895            ptr[1] == CHAR_EQUALS_SIGN) && check_posix_syntax(ptr, &tempptr))
3896         {
3897         BOOL local_negate = FALSE;
3898         int posix_class, taboffset, tabopt;
3899         const pcre_uint8 *cbits = cd->cbits;
3900         pcre_uint8 pbits[32];
3901
3902         if (ptr[1] != CHAR_COLON)
3903           {
3904           *errorcodeptr = ERR31;
3905           goto FAILED;
3906           }
3907
3908         ptr += 2;
3909         if (*ptr == CHAR_CIRCUMFLEX_ACCENT)
3910           {
3911           local_negate = TRUE;
3912           should_flip_negation = TRUE;  /* Note negative special */
3913           ptr++;
3914           }
3915
3916         posix_class = check_posix_name(ptr, (int)(tempptr - ptr));
3917         if (posix_class < 0)
3918           {
3919           *errorcodeptr = ERR30;
3920           goto FAILED;
3921           }
3922
3923         /* If matching is caseless, upper and lower are converted to
3924         alpha. This relies on the fact that the class table starts with
3925         alpha, lower, upper as the first 3 entries. */
3926
3927         if ((options & PCRE_CASELESS) != 0 && posix_class <= 2)
3928           posix_class = 0;
3929
3930         /* When PCRE_UCP is set, some of the POSIX classes are converted to
3931         different escape sequences that use Unicode properties. */
3932
3933 #ifdef SUPPORT_UCP
3934         if ((options & PCRE_UCP) != 0)
3935           {
3936           int pc = posix_class + ((local_negate)? POSIX_SUBSIZE/2 : 0);
3937           if (posix_substitutes[pc] != NULL)
3938             {
3939             nestptr = tempptr + 1;
3940             ptr = posix_substitutes[pc] - 1;
3941             continue;
3942             }
3943           }
3944 #endif
3945         /* In the non-UCP case, we build the bit map for the POSIX class in a
3946         chunk of local store because we may be adding and subtracting from it,
3947         and we don't want to subtract bits that may be in the main map already.
3948         At the end we or the result into the bit map that is being built. */
3949
3950         posix_class *= 3;
3951
3952         /* Copy in the first table (always present) */
3953
3954         memcpy(pbits, cbits + posix_class_maps[posix_class],
3955           32 * sizeof(pcre_uint8));
3956
3957         /* If there is a second table, add or remove it as required. */
3958
3959         taboffset = posix_class_maps[posix_class + 1];
3960         tabopt = posix_class_maps[posix_class + 2];
3961
3962         if (taboffset >= 0)
3963           {
3964           if (tabopt >= 0)
3965             for (c = 0; c < 32; c++) pbits[c] |= cbits[c + taboffset];
3966           else
3967             for (c = 0; c < 32; c++) pbits[c] &= ~cbits[c + taboffset];
3968           }
3969
3970         /* Not see if we need to remove any special characters. An option
3971         value of 1 removes vertical space and 2 removes underscore. */
3972
3973         if (tabopt < 0) tabopt = -tabopt;
3974         if (tabopt == 1) pbits[1] &= ~0x3c;
3975           else if (tabopt == 2) pbits[11] &= 0x7f;
3976
3977         /* Add the POSIX table or its complement into the main table that is
3978         being built and we are done. */
3979
3980         if (local_negate)
3981           for (c = 0; c < 32; c++) classbits[c] |= ~pbits[c];
3982         else
3983           for (c = 0; c < 32; c++) classbits[c] |= pbits[c];
3984
3985         ptr = tempptr + 1;
3986         /* Every class contains at least one < 256 characters. */
3987         class_has_8bitchar = 1;
3988         /* Every class contains at least two characters. */
3989         class_single_char = 2;
3990         continue;    /* End of POSIX syntax handling */
3991         }
3992
3993       /* Backslash may introduce a single character, or it may introduce one
3994       of the specials, which just set a flag. The sequence \b is a special
3995       case. Inside a class (and only there) it is treated as backspace. We
3996       assume that other escapes have more than one character in them, so
3997       speculatively set both class_has_8bitchar and class_single_char bigger
3998       than one. Unrecognized escapes fall through and are either treated
3999       as literal characters (by default), or are faulted if
4000       PCRE_EXTRA is set. */
4001
4002       if (c == CHAR_BACKSLASH)
4003         {
4004         c = check_escape(&ptr, errorcodeptr, cd->bracount, options, TRUE);
4005         if (*errorcodeptr != 0) goto FAILED;
4006
4007         if (-c == ESC_b) c = CHAR_BS;    /* \b is backspace in a class */
4008         else if (-c == ESC_N)            /* \N is not supported in a class */
4009           {
4010           *errorcodeptr = ERR71;
4011           goto FAILED;
4012           }
4013         else if (-c == ESC_Q)            /* Handle start of quoted string */
4014           {
4015           if (ptr[1] == CHAR_BACKSLASH && ptr[2] == CHAR_E)
4016             {
4017             ptr += 2; /* avoid empty string */
4018             }
4019           else inescq = TRUE;
4020           continue;
4021           }
4022         else if (-c == ESC_E) continue;  /* Ignore orphan \E */
4023
4024         if (c < 0)
4025           {
4026           const pcre_uint8 *cbits = cd->cbits;
4027           /* Every class contains at least two < 256 characters. */
4028           class_has_8bitchar++;
4029           /* Every class contains at least two characters. */
4030           class_single_char += 2;
4031
4032           switch (-c)
4033             {
4034 #ifdef SUPPORT_UCP
4035             case ESC_du:     /* These are the values given for \d etc */
4036             case ESC_DU:     /* when PCRE_UCP is set. We replace the */
4037             case ESC_wu:     /* escape sequence with an appropriate \p */
4038             case ESC_WU:     /* or \P to test Unicode properties instead */
4039             case ESC_su:     /* of the default ASCII testing. */
4040             case ESC_SU:
4041             nestptr = ptr;
4042             ptr = substitutes[-c - ESC_DU] - 1;  /* Just before substitute */
4043             class_has_8bitchar--;                /* Undo! */
4044             continue;
4045 #endif
4046             case ESC_d:
4047             for (c = 0; c < 32; c++) classbits[c] |= cbits[c+cbit_digit];
4048             continue;
4049
4050             case ESC_D:
4051             should_flip_negation = TRUE;
4052             for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_digit];
4053             continue;
4054
4055             case ESC_w:
4056             for (c = 0; c < 32; c++) classbits[c] |= cbits[c+cbit_word];
4057             continue;
4058
4059             case ESC_W:
4060             should_flip_negation = TRUE;
4061             for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_word];
4062             continue;
4063
4064             /* Perl 5.004 onwards omits VT from \s, but we must preserve it
4065             if it was previously set by something earlier in the character
4066             class. */
4067
4068             case ESC_s:
4069             classbits[0] |= cbits[cbit_space];
4070             classbits[1] |= cbits[cbit_space+1] & ~0x08;
4071             for (c = 2; c < 32; c++) classbits[c] |= cbits[c+cbit_space];
4072             continue;
4073
4074             case ESC_S:
4075             should_flip_negation = TRUE;
4076             for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_space];
4077             classbits[1] |= 0x08;    /* Perl 5.004 onwards omits VT from \s */
4078             continue;
4079
4080             case ESC_h:
4081             SETBIT(classbits, 0x09); /* VT */
4082             SETBIT(classbits, 0x20); /* SPACE */
4083             SETBIT(classbits, 0xa0); /* NSBP */
4084 #ifndef COMPILE_PCRE8
4085             xclass = TRUE;
4086             *class_uchardata++ = XCL_SINGLE;
4087             *class_uchardata++ = 0x1680;
4088             *class_uchardata++ = XCL_SINGLE;
4089             *class_uchardata++ = 0x180e;
4090             *class_uchardata++ = XCL_RANGE;
4091             *class_uchardata++ = 0x2000;
4092             *class_uchardata++ = 0x200a;
4093             *class_uchardata++ = XCL_SINGLE;
4094             *class_uchardata++ = 0x202f;
4095             *class_uchardata++ = XCL_SINGLE;
4096             *class_uchardata++ = 0x205f;
4097             *class_uchardata++ = XCL_SINGLE;
4098             *class_uchardata++ = 0x3000;
4099 #elif defined SUPPORT_UTF
4100             if (utf)
4101               {
4102               xclass = TRUE;
4103               *class_uchardata++ = XCL_SINGLE;
4104               class_uchardata += PRIV(ord2utf)(0x1680, class_uchardata);
4105               *class_uchardata++ = XCL_SINGLE;
4106               class_uchardata += PRIV(ord2utf)(0x180e, class_uchardata);
4107               *class_uchardata++ = XCL_RANGE;
4108               class_uchardata += PRIV(ord2utf)(0x2000, class_uchardata);
4109               class_uchardata += PRIV(ord2utf)(0x200a, class_uchardata);
4110               *class_uchardata++ = XCL_SINGLE;
4111               class_uchardata += PRIV(ord2utf)(0x202f, class_uchardata);
4112               *class_uchardata++ = XCL_SINGLE;
4113               class_uchardata += PRIV(ord2utf)(0x205f, class_uchardata);
4114               *class_uchardata++ = XCL_SINGLE;
4115               class_uchardata += PRIV(ord2utf)(0x3000, class_uchardata);
4116               }
4117 #endif
4118             continue;
4119
4120             case ESC_H:
4121             for (c = 0; c < 32; c++)
4122               {
4123               int x = 0xff;
4124               switch (c)
4125                 {
4126                 case 0x09/8: x ^= 1 << (0x09%8); break;
4127                 case 0x20/8: x ^= 1 << (0x20%8); break;
4128                 case 0xa0/8: x ^= 1 << (0xa0%8); break;
4129                 default: break;
4130                 }
4131               classbits[c] |= x;
4132               }
4133 #ifndef COMPILE_PCRE8
4134             xclass = TRUE;
4135             *class_uchardata++ = XCL_RANGE;
4136             *class_uchardata++ = 0x0100;
4137             *class_uchardata++ = 0x167f;
4138             *class_uchardata++ = XCL_RANGE;
4139             *class_uchardata++ = 0x1681;
4140             *class_uchardata++ = 0x180d;
4141             *class_uchardata++ = XCL_RANGE;
4142             *class_uchardata++ = 0x180f;
4143             *class_uchardata++ = 0x1fff;
4144             *class_uchardata++ = XCL_RANGE;
4145             *class_uchardata++ = 0x200b;
4146             *class_uchardata++ = 0x202e;
4147             *class_uchardata++ = XCL_RANGE;
4148             *class_uchardata++ = 0x2030;
4149             *class_uchardata++ = 0x205e;
4150             *class_uchardata++ = XCL_RANGE;
4151             *class_uchardata++ = 0x2060;
4152             *class_uchardata++ = 0x2fff;
4153             *class_uchardata++ = XCL_RANGE;
4154             *class_uchardata++ = 0x3001;
4155 #ifdef SUPPORT_UTF
4156             if (utf)
4157               class_uchardata += PRIV(ord2utf)(0x10ffff, class_uchardata);
4158             else
4159 #endif
4160               *class_uchardata++ = 0xffff;
4161 #elif defined SUPPORT_UTF
4162             if (utf)
4163               {
4164               xclass = TRUE;
4165               *class_uchardata++ = XCL_RANGE;
4166               class_uchardata += PRIV(ord2utf)(0x0100, class_uchardata);
4167               class_uchardata += PRIV(ord2utf)(0x167f, class_uchardata);
4168               *class_uchardata++ = XCL_RANGE;
4169               class_uchardata += PRIV(ord2utf)(0x1681, class_uchardata);
4170               class_uchardata += PRIV(ord2utf)(0x180d, class_uchardata);
4171               *class_uchardata++ = XCL_RANGE;
4172               class_uchardata += PRIV(ord2utf)(0x180f, class_uchardata);
4173               class_uchardata += PRIV(ord2utf)(0x1fff, class_uchardata);
4174               *class_uchardata++ = XCL_RANGE;
4175               class_uchardata += PRIV(ord2utf)(0x200b, class_uchardata);
4176               class_uchardata += PRIV(ord2utf)(0x202e, class_uchardata);
4177               *class_uchardata++ = XCL_RANGE;
4178               class_uchardata += PRIV(ord2utf)(0x2030, class_uchardata);
4179               class_uchardata += PRIV(ord2utf)(0x205e, class_uchardata);
4180               *class_uchardata++ = XCL_RANGE;
4181               class_uchardata += PRIV(ord2utf)(0x2060, class_uchardata);
4182               class_uchardata += PRIV(ord2utf)(0x2fff, class_uchardata);
4183               *class_uchardata++ = XCL_RANGE;
4184               class_uchardata += PRIV(ord2utf)(0x3001, class_uchardata);
4185               class_uchardata += PRIV(ord2utf)(0x10ffff, class_uchardata);
4186               }
4187 #endif
4188             continue;
4189
4190             case ESC_v:
4191             SETBIT(classbits, 0x0a); /* LF */
4192             SETBIT(classbits, 0x0b); /* VT */
4193             SETBIT(classbits, 0x0c); /* FF */
4194             SETBIT(classbits, 0x0d); /* CR */
4195             SETBIT(classbits, 0x85); /* NEL */
4196 #ifndef COMPILE_PCRE8
4197             xclass = TRUE;
4198             *class_uchardata++ = XCL_RANGE;
4199             *class_uchardata++ = 0x2028;
4200             *class_uchardata++ = 0x2029;
4201 #elif defined SUPPORT_UTF
4202             if (utf)
4203               {
4204               xclass = TRUE;
4205               *class_uchardata++ = XCL_RANGE;
4206               class_uchardata += PRIV(ord2utf)(0x2028, class_uchardata);
4207               class_uchardata += PRIV(ord2utf)(0x2029, class_uchardata);
4208               }
4209 #endif
4210             continue;
4211
4212             case ESC_V:
4213             for (c = 0; c < 32; c++)
4214               {
4215               int x = 0xff;
4216               switch (c)
4217                 {
4218                 case 0x0a/8: x ^= 1 << (0x0a%8);
4219                              x ^= 1 << (0x0b%8);
4220                              x ^= 1 << (0x0c%8);
4221                              x ^= 1 << (0x0d%8);
4222                              break;
4223                 case 0x85/8: x ^= 1 << (0x85%8); break;
4224                 default: break;
4225                 }
4226               classbits[c] |= x;
4227               }
4228
4229 #ifndef COMPILE_PCRE8
4230             xclass = TRUE;
4231             *class_uchardata++ = XCL_RANGE;
4232             *class_uchardata++ = 0x0100;
4233             *class_uchardata++ = 0x2027;
4234             *class_uchardata++ = XCL_RANGE;
4235             *class_uchardata++ = 0x202a;
4236 #ifdef SUPPORT_UTF
4237             if (utf)
4238               class_uchardata += PRIV(ord2utf)(0x10ffff, class_uchardata);
4239             else
4240 #endif
4241               *class_uchardata++ = 0xffff;
4242 #elif defined SUPPORT_UTF
4243             if (utf)
4244               {
4245               xclass = TRUE;
4246               *class_uchardata++ = XCL_RANGE;
4247               class_uchardata += PRIV(ord2utf)(0x0100, class_uchardata);
4248               class_uchardata += PRIV(ord2utf)(0x2027, class_uchardata);
4249               *class_uchardata++ = XCL_RANGE;
4250               class_uchardata += PRIV(ord2utf)(0x202a, class_uchardata);
4251               class_uchardata += PRIV(ord2utf)(0x10ffff, class_uchardata);
4252               }
4253 #endif
4254             continue;
4255
4256 #ifdef SUPPORT_UCP
4257             case ESC_p:
4258             case ESC_P:
4259               {
4260               BOOL negated;
4261               int pdata;
4262               int ptype = get_ucp(&ptr, &negated, &pdata, errorcodeptr);
4263               if (ptype < 0) goto FAILED;
4264               xclass = TRUE;
4265               *class_uchardata++ = ((-c == ESC_p) != negated)?
4266                 XCL_PROP : XCL_NOTPROP;
4267               *class_uchardata++ = ptype;
4268               *class_uchardata++ = pdata;
4269               class_has_8bitchar--;                /* Undo! */
4270               continue;
4271               }
4272 #endif
4273             /* Unrecognized escapes are faulted if PCRE is running in its
4274             strict mode. By default, for compatibility with Perl, they are
4275             treated as literals. */
4276
4277             default:
4278             if ((options & PCRE_EXTRA) != 0)
4279               {
4280               *errorcodeptr = ERR7;
4281               goto FAILED;
4282               }
4283             class_has_8bitchar--;    /* Undo the speculative increase. */
4284             class_single_char -= 2;  /* Undo the speculative increase. */
4285             c = *ptr;                /* Get the final character and fall through */
4286             break;
4287             }
4288           }
4289
4290         /* Fall through if we have a single character (c >= 0). This may be
4291         greater than 256. */
4292
4293         }   /* End of backslash handling */
4294
4295       /* A single character may be followed by '-' to form a range. However,
4296       Perl does not permit ']' to be the end of the range. A '-' character
4297       at the end is treated as a literal. Perl ignores orphaned \E sequences
4298       entirely. The code for handling \Q and \E is messy. */
4299
4300       CHECK_RANGE:
4301       while (ptr[1] == CHAR_BACKSLASH && ptr[2] == CHAR_E)
4302         {
4303         inescq = FALSE;
4304         ptr += 2;
4305         }
4306
4307       oldptr = ptr;
4308
4309       /* Remember \r or \n */
4310
4311       if (c == CHAR_CR || c == CHAR_NL) cd->external_flags |= PCRE_HASCRORLF;
4312
4313       /* Check for range */
4314
4315       if (!inescq && ptr[1] == CHAR_MINUS)
4316         {
4317         int d;
4318         ptr += 2;
4319         while (*ptr == CHAR_BACKSLASH && ptr[1] == CHAR_E) ptr += 2;
4320
4321         /* If we hit \Q (not followed by \E) at this point, go into escaped
4322         mode. */
4323
4324         while (*ptr == CHAR_BACKSLASH && ptr[1] == CHAR_Q)
4325           {
4326           ptr += 2;
4327           if (*ptr == CHAR_BACKSLASH && ptr[1] == CHAR_E)
4328             { ptr += 2; continue; }
4329           inescq = TRUE;
4330           break;
4331           }
4332
4333         if (*ptr == 0 || (!inescq && *ptr == CHAR_RIGHT_SQUARE_BRACKET))
4334           {
4335           ptr = oldptr;
4336           goto LONE_SINGLE_CHARACTER;
4337           }
4338
4339 #ifdef SUPPORT_UTF
4340         if (utf)
4341           {                           /* Braces are required because the */
4342           GETCHARLEN(d, ptr, ptr);    /* macro generates multiple statements */
4343           }
4344         else
4345 #endif
4346         d = *ptr;  /* Not UTF-8 mode */
4347
4348         /* The second part of a range can be a single-character escape, but
4349         not any of the other escapes. Perl 5.6 treats a hyphen as a literal
4350         in such circumstances. */
4351
4352         if (!inescq && d == CHAR_BACKSLASH)
4353           {
4354           d = check_escape(&ptr, errorcodeptr, cd->bracount, options, TRUE);
4355           if (*errorcodeptr != 0) goto FAILED;
4356
4357           /* \b is backspace; any other special means the '-' was literal */
4358
4359           if (d < 0)
4360             {
4361             if (d == -ESC_b) d = CHAR_BS; else
4362               {
4363               ptr = oldptr;
4364               goto LONE_SINGLE_CHARACTER;  /* A few lines below */
4365               }
4366             }
4367           }
4368
4369         /* Check that the two values are in the correct order. Optimize
4370         one-character ranges */
4371
4372         if (d < c)
4373           {
4374           *errorcodeptr = ERR8;
4375           goto FAILED;
4376           }
4377
4378         if (d == c) goto LONE_SINGLE_CHARACTER;  /* A few lines below */
4379
4380         /* Remember \r or \n */
4381
4382         if (d == CHAR_CR || d == CHAR_NL) cd->external_flags |= PCRE_HASCRORLF;
4383
4384         /* Since we found a character range, single character optimizations
4385         cannot be done anymore. */
4386         class_single_char = 2;
4387
4388         /* In UTF-8 mode, if the upper limit is > 255, or > 127 for caseless
4389         matching, we have to use an XCLASS with extra data items. Caseless
4390         matching for characters > 127 is available only if UCP support is
4391         available. */
4392
4393 #if defined SUPPORT_UTF && !(defined COMPILE_PCRE8)
4394         if ((d > 255) || (utf && ((options & PCRE_CASELESS) != 0 && d > 127)))
4395 #elif defined  SUPPORT_UTF
4396         if (utf && (d > 255 || ((options & PCRE_CASELESS) != 0 && d > 127)))
4397 #elif !(defined COMPILE_PCRE8)
4398         if (d > 255)
4399 #endif
4400 #if defined SUPPORT_UTF || !(defined COMPILE_PCRE8)
4401           {
4402           xclass = TRUE;
4403
4404           /* With UCP support, we can find the other case equivalents of
4405           the relevant characters. There may be several ranges. Optimize how
4406           they fit with the basic range. */
4407
4408 #ifdef SUPPORT_UCP
4409 #ifndef COMPILE_PCRE8
4410           if (utf && (options & PCRE_CASELESS) != 0)
4411 #else
4412           if ((options & PCRE_CASELESS) != 0)
4413 #endif
4414             {
4415             unsigned int occ, ocd;
4416             unsigned int cc = c;
4417             unsigned int origd = d;
4418             while (get_othercase_range(&cc, origd, &occ, &ocd))
4419               {
4420               if (occ >= (unsigned int)c &&
4421                   ocd <= (unsigned int)d)
4422                 continue;                          /* Skip embedded ranges */
4423
4424               if (occ < (unsigned int)c  &&
4425                   ocd >= (unsigned int)c - 1)      /* Extend the basic range */
4426                 {                                  /* if there is overlap,   */
4427                 c = occ;                           /* noting that if occ < c */
4428                 continue;                          /* we can't have ocd > d  */
4429                 }                                  /* because a subrange is  */
4430               if (ocd > (unsigned int)d &&
4431                   occ <= (unsigned int)d + 1)      /* always shorter than    */
4432                 {                                  /* the basic range.       */
4433                 d = ocd;
4434                 continue;
4435                 }
4436
4437               if (occ == ocd)
4438                 {
4439                 *class_uchardata++ = XCL_SINGLE;
4440                 }
4441               else
4442                 {
4443                 *class_uchardata++ = XCL_RANGE;
4444                 class_uchardata += PRIV(ord2utf)(occ, class_uchardata);
4445                 }
4446               class_uchardata += PRIV(ord2utf)(ocd, class_uchardata);
4447               }
4448             }
4449 #endif  /* SUPPORT_UCP */
4450
4451           /* Now record the original range, possibly modified for UCP caseless
4452           overlapping ranges. */
4453
4454           *class_uchardata++ = XCL_RANGE;
4455 #ifdef SUPPORT_UTF
4456 #ifndef COMPILE_PCRE8
4457           if (utf)
4458             {
4459             class_uchardata += PRIV(ord2utf)(c, class_uchardata);
4460             class_uchardata += PRIV(ord2utf)(d, class_uchardata);
4461             }
4462           else
4463             {
4464             *class_uchardata++ = c;
4465             *class_uchardata++ = d;
4466             }
4467 #else
4468           class_uchardata += PRIV(ord2utf)(c, class_uchardata);
4469           class_uchardata += PRIV(ord2utf)(d, class_uchardata);
4470 #endif
4471 #else /* SUPPORT_UTF */
4472           *class_uchardata++ = c;
4473           *class_uchardata++ = d;
4474 #endif /* SUPPORT_UTF */
4475
4476           /* With UCP support, we are done. Without UCP support, there is no
4477           caseless matching for UTF characters > 127; we can use the bit map
4478           for the smaller ones. As for 16 bit characters without UTF, we
4479           can still use  */
4480
4481 #ifdef SUPPORT_UCP
4482 #ifndef COMPILE_PCRE8
4483           if (utf)
4484 #endif
4485             continue;    /* With next character in the class */
4486 #endif  /* SUPPORT_UCP */
4487
4488 #if defined SUPPORT_UTF && !defined(SUPPORT_UCP) && !(defined COMPILE_PCRE8)
4489           if (utf)
4490             {
4491             if ((options & PCRE_CASELESS) == 0 || c > 127) continue;
4492             /* Adjust upper limit and fall through to set up the map */
4493             d = 127;
4494             }
4495           else
4496             {
4497             if (c > 255) continue;
4498             /* Adjust upper limit and fall through to set up the map */
4499             d = 255;
4500             }
4501 #elif defined SUPPORT_UTF && !defined(SUPPORT_UCP)
4502           if ((options & PCRE_CASELESS) == 0 || c > 127) continue;
4503           /* Adjust upper limit and fall through to set up the map */
4504           d = 127;
4505 #else
4506           if (c > 255) continue;
4507           /* Adjust upper limit and fall through to set up the map */
4508           d = 255;
4509 #endif  /* SUPPORT_UTF && !SUPPORT_UCP && !COMPILE_PCRE8 */
4510           }
4511 #endif  /* SUPPORT_UTF || !COMPILE_PCRE8 */
4512
4513         /* We use the bit map for 8 bit mode, or when the characters fall
4514         partially or entirely to [0-255] ([0-127] for UCP) ranges. */
4515
4516         class_has_8bitchar = 1;
4517
4518         /* We can save a bit of time by skipping this in the pre-compile. */
4519
4520         if (lengthptr == NULL) for (; c <= d; c++)
4521           {
4522           classbits[c/8] |= (1 << (c&7));
4523           if ((options & PCRE_CASELESS) != 0)
4524             {
4525             int uc = cd->fcc[c]; /* flip case */
4526             classbits[uc/8] |= (1 << (uc&7));
4527             }
4528           }
4529
4530         continue;   /* Go get the next char in the class */
4531         }
4532
4533       /* Handle a lone single character - we can get here for a normal
4534       non-escape char, or after \ that introduces a single character or for an
4535       apparent range that isn't. */
4536
4537       LONE_SINGLE_CHARACTER:
4538
4539       /* Only the value of 1 matters for class_single_char. */
4540
4541       if (class_single_char < 2) class_single_char++;
4542
4543       /* If class_charcount is 1, we saw precisely one character. As long as
4544       there was no use of \p or \P, in other words, no use of any XCLASS
4545       features, we can optimize.
4546
4547       The optimization throws away the bit map. We turn the item into a
4548       1-character OP_CHAR[I] if it's positive, or OP_NOT[I] if it's negative.
4549       In the positive case, it can cause firstchar to be set. Otherwise, there
4550       can be no first char if this item is first, whatever repeat count may
4551       follow. In the case of reqchar, save the previous value for reinstating. */
4552
4553       if (class_single_char == 1 && ptr[1] == CHAR_RIGHT_SQUARE_BRACKET)
4554         {
4555         ptr++;
4556         zeroreqchar = reqchar;
4557
4558         if (negate_class)
4559           {
4560           if (firstchar == REQ_UNSET) firstchar = REQ_NONE;
4561           zerofirstchar = firstchar;
4562           *code++ = ((options & PCRE_CASELESS) != 0)? OP_NOTI: OP_NOT;
4563 #ifdef SUPPORT_UTF
4564           if (utf && c > MAX_VALUE_FOR_SINGLE_CHAR)
4565             code += PRIV(ord2utf)(c, code);
4566           else
4567 #endif
4568             *code++ = c;
4569           goto NOT_CHAR;
4570           }
4571
4572         /* For a single, positive character, get the value into mcbuffer, and
4573         then we can handle this with the normal one-character code. */
4574
4575 #ifdef SUPPORT_UTF
4576         if (utf && c > MAX_VALUE_FOR_SINGLE_CHAR)
4577           mclength = PRIV(ord2utf)(c, mcbuffer);
4578         else
4579 #endif
4580           {
4581           mcbuffer[0] = c;
4582           mclength = 1;
4583           }
4584         goto ONE_CHAR;
4585         }       /* End of 1-char optimization */
4586
4587       /* Handle a character that cannot go in the bit map. */
4588
4589 #if defined SUPPORT_UTF && !(defined COMPILE_PCRE8)
4590       if ((c > 255) || (utf && ((options & PCRE_CASELESS) != 0 && c > 127)))
4591 #elif defined SUPPORT_UTF
4592       if (utf && (c > 255 || ((options & PCRE_CASELESS) != 0 && c > 127)))
4593 #elif !(defined COMPILE_PCRE8)
4594       if (c > 255)
4595 #endif
4596
4597 #if defined SUPPORT_UTF || !(defined COMPILE_PCRE8)
4598         {
4599         xclass = TRUE;
4600         *class_uchardata++ = XCL_SINGLE;
4601 #ifdef SUPPORT_UTF
4602 #ifndef COMPILE_PCRE8
4603         /* In non 8 bit mode, we can get here even if we are not in UTF mode. */
4604         if (!utf)
4605           *class_uchardata++ = c;
4606         else
4607 #endif
4608           class_uchardata += PRIV(ord2utf)(c, class_uchardata);
4609 #else /* SUPPORT_UTF */
4610         *class_uchardata++ = c;
4611 #endif /* SUPPORT_UTF */
4612
4613 #ifdef SUPPORT_UCP
4614 #ifdef COMPILE_PCRE8
4615         if ((options & PCRE_CASELESS) != 0)
4616 #else
4617         /* In non 8 bit mode, we can get here even if we are not in UTF mode. */
4618         if (utf && (options & PCRE_CASELESS) != 0)
4619 #endif
4620           {
4621           unsigned int othercase;
4622           if ((int)(othercase = UCD_OTHERCASE(c)) != c)
4623             {
4624             *class_uchardata++ = XCL_SINGLE;
4625             class_uchardata += PRIV(ord2utf)(othercase, class_uchardata);
4626             }
4627           }
4628 #endif  /* SUPPORT_UCP */
4629
4630         }
4631       else
4632 #endif  /* SUPPORT_UTF || COMPILE_PCRE16 */
4633
4634       /* Handle a single-byte character */
4635         {
4636         class_has_8bitchar = 1;
4637         classbits[c/8] |= (1 << (c&7));
4638         if ((options & PCRE_CASELESS) != 0)
4639           {
4640           c = cd->fcc[c]; /* flip case */
4641           classbits[c/8] |= (1 << (c&7));
4642           }
4643         }
4644       }
4645
4646     /* Loop until ']' reached. This "while" is the end of the "do" far above.
4647     If we are at the end of an internal nested string, revert to the outer
4648     string. */
4649
4650     while (((c = *(++ptr)) != 0 ||
4651            (nestptr != NULL &&
4652              (ptr = nestptr, nestptr = NULL, c = *(++ptr)) != 0)) &&
4653            (c != CHAR_RIGHT_SQUARE_BRACKET || inescq));
4654
4655     /* Check for missing terminating ']' */
4656
4657     if (c == 0)
4658       {
4659       *errorcodeptr = ERR6;
4660       goto FAILED;
4661       }
4662
4663     /* If this is the first thing in the branch, there can be no first char
4664     setting, whatever the repeat count. Any reqchar setting must remain
4665     unchanged after any kind of repeat. */
4666
4667     if (firstchar == REQ_UNSET) firstchar = REQ_NONE;
4668     zerofirstchar = firstchar;
4669     zeroreqchar = reqchar;
4670
4671     /* If there are characters with values > 255, we have to compile an
4672     extended class, with its own opcode, unless there was a negated special
4673     such as \S in the class, and PCRE_UCP is not set, because in that case all
4674     characters > 255 are in the class, so any that were explicitly given as
4675     well can be ignored. If (when there are explicit characters > 255 that must
4676     be listed) there are no characters < 256, we can omit the bitmap in the
4677     actual compiled code. */
4678
4679 #ifdef SUPPORT_UTF
4680     if (xclass && (!should_flip_negation || (options & PCRE_UCP) != 0))
4681 #elif !defined COMPILE_PCRE8
4682     if (xclass && !should_flip_negation)
4683 #endif
4684 #if defined SUPPORT_UTF || !defined COMPILE_PCRE8
4685       {
4686       *class_uchardata++ = XCL_END;    /* Marks the end of extra data */
4687       *code++ = OP_XCLASS;
4688       code += LINK_SIZE;
4689       *code = negate_class? XCL_NOT:0;
4690
4691       /* If the map is required, move up the extra data to make room for it;
4692       otherwise just move the code pointer to the end of the extra data. */
4693
4694       if (class_has_8bitchar > 0)
4695         {
4696         *code++ |= XCL_MAP;
4697         memmove(code + (32 / sizeof(pcre_uchar)), code,
4698           IN_UCHARS(class_uchardata - code));
4699         memcpy(code, classbits, 32);
4700         code = class_uchardata + (32 / sizeof(pcre_uchar));
4701         }
4702       else code = class_uchardata;
4703
4704       /* Now fill in the complete length of the item */
4705
4706       PUT(previous, 1, (int)(code - previous));
4707       break;   /* End of class handling */
4708       }
4709 #endif
4710
4711     /* If there are no characters > 255, or they are all to be included or
4712     excluded, set the opcode to OP_CLASS or OP_NCLASS, depending on whether the
4713     whole class was negated and whether there were negative specials such as \S
4714     (non-UCP) in the class. Then copy the 32-byte map into the code vector,
4715     negating it if necessary. */
4716
4717     *code++ = (negate_class == should_flip_negation) ? OP_CLASS : OP_NCLASS;
4718     if (lengthptr == NULL)    /* Save time in the pre-compile phase */
4719       {
4720       if (negate_class)
4721         for (c = 0; c < 32; c++) classbits[c] = ~classbits[c];
4722       memcpy(code, classbits, 32);
4723       }
4724     code += 32 / sizeof(pcre_uchar);
4725     NOT_CHAR:
4726     break;
4727
4728
4729     /* ===================================================================*/
4730     /* Various kinds of repeat; '{' is not necessarily a quantifier, but this
4731     has been tested above. */
4732
4733     case CHAR_LEFT_CURLY_BRACKET:
4734     if (!is_quantifier) goto NORMAL_CHAR;
4735     ptr = read_repeat_counts(ptr+1, &repeat_min, &repeat_max, errorcodeptr);
4736     if (*errorcodeptr != 0) goto FAILED;
4737     goto REPEAT;
4738
4739     case CHAR_ASTERISK:
4740     repeat_min = 0;
4741     repeat_max = -1;
4742     goto REPEAT;
4743
4744     case CHAR_PLUS:
4745     repeat_min = 1;
4746     repeat_max = -1;
4747     goto REPEAT;
4748
4749     case CHAR_QUESTION_MARK:
4750     repeat_min = 0;
4751     repeat_max = 1;
4752
4753     REPEAT:
4754     if (previous == NULL)
4755       {
4756       *errorcodeptr = ERR9;
4757       goto FAILED;
4758       }
4759
4760     if (repeat_min == 0)
4761       {
4762       firstchar = zerofirstchar;    /* Adjust for zero repeat */
4763       reqchar = zeroreqchar;        /* Ditto */
4764       }
4765
4766     /* Remember whether this is a variable length repeat */
4767
4768     reqvary = (repeat_min == repeat_max)? 0 : REQ_VARY;
4769
4770     op_type = 0;                    /* Default single-char op codes */
4771     possessive_quantifier = FALSE;  /* Default not possessive quantifier */
4772
4773     /* Save start of previous item, in case we have to move it up in order to
4774     insert something before it. */
4775
4776     tempcode = previous;
4777
4778     /* If the next character is '+', we have a possessive quantifier. This
4779     implies greediness, whatever the setting of the PCRE_UNGREEDY option.
4780     If the next character is '?' this is a minimizing repeat, by default,
4781     but if PCRE_UNGREEDY is set, it works the other way round. We change the
4782     repeat type to the non-default. */
4783
4784     if (ptr[1] == CHAR_PLUS)
4785       {
4786       repeat_type = 0;                  /* Force greedy */
4787       possessive_quantifier = TRUE;
4788       ptr++;
4789       }
4790     else if (ptr[1] == CHAR_QUESTION_MARK)
4791       {
4792       repeat_type = greedy_non_default;
4793       ptr++;
4794       }
4795     else repeat_type = greedy_default;
4796
4797     /* If previous was a recursion call, wrap it in atomic brackets so that
4798     previous becomes the atomic group. All recursions were so wrapped in the
4799     past, but it no longer happens for non-repeated recursions. In fact, the
4800     repeated ones could be re-implemented independently so as not to need this,
4801     but for the moment we rely on the code for repeating groups. */
4802
4803     if (*previous == OP_RECURSE)
4804       {
4805       memmove(previous + 1 + LINK_SIZE, previous, IN_UCHARS(1 + LINK_SIZE));
4806       *previous = OP_ONCE;
4807       PUT(previous, 1, 2 + 2*LINK_SIZE);
4808       previous[2 + 2*LINK_SIZE] = OP_KET;
4809       PUT(previous, 3 + 2*LINK_SIZE, 2 + 2*LINK_SIZE);
4810       code += 2 + 2 * LINK_SIZE;
4811       length_prevgroup = 3 + 3*LINK_SIZE;
4812
4813       /* When actually compiling, we need to check whether this was a forward
4814       reference, and if so, adjust the offset. */
4815
4816       if (lengthptr == NULL && cd->hwm >= cd->start_workspace + LINK_SIZE)
4817         {
4818         int offset = GET(cd->hwm, -LINK_SIZE);
4819         if (offset == previous + 1 - cd->start_code)
4820           PUT(cd->hwm, -LINK_SIZE, offset + 1 + LINK_SIZE);
4821         }
4822       }
4823
4824     /* Now handle repetition for the different types of item. */
4825
4826     /* If previous was a character or negated character match, abolish the item
4827     and generate a repeat item instead. If a char item has a minimum of more
4828     than one, ensure that it is set in reqchar - it might not be if a sequence
4829     such as x{3} is the first thing in a branch because the x will have gone
4830     into firstchar instead.  */
4831
4832     if (*previous == OP_CHAR || *previous == OP_CHARI
4833         || *previous == OP_NOT || *previous == OP_NOTI)
4834       {
4835       switch (*previous)
4836         {
4837         default: /* Make compiler happy. */
4838         case OP_CHAR:  op_type = OP_STAR - OP_STAR; break;
4839         case OP_CHARI: op_type = OP_STARI - OP_STAR; break;
4840         case OP_NOT:   op_type = OP_NOTSTAR - OP_STAR; break;
4841         case OP_NOTI:  op_type = OP_NOTSTARI - OP_STAR; break;
4842         }
4843
4844       /* Deal with UTF characters that take up more than one character. It's
4845       easier to write this out separately than try to macrify it. Use c to
4846       hold the length of the character in bytes, plus UTF_LENGTH to flag that
4847       it's a length rather than a small character. */
4848
4849 #ifdef SUPPORT_UTF
4850       if (utf && NOT_FIRSTCHAR(code[-1]))
4851         {
4852         pcre_uchar *lastchar = code - 1;
4853         BACKCHAR(lastchar);
4854         c = (int)(code - lastchar);     /* Length of UTF-8 character */
4855         memcpy(utf_chars, lastchar, IN_UCHARS(c)); /* Save the char */
4856         c |= UTF_LENGTH;                /* Flag c as a length */
4857         }
4858       else
4859 #endif /* SUPPORT_UTF */
4860
4861       /* Handle the case of a single charater - either with no UTF support, or
4862       with UTF disabled, or for a single character UTF character. */
4863         {
4864         c = code[-1];
4865         if (*previous <= OP_CHARI && repeat_min > 1)
4866           reqchar = c | req_caseopt | cd->req_varyopt;
4867         }
4868
4869       /* If the repetition is unlimited, it pays to see if the next thing on
4870       the line is something that cannot possibly match this character. If so,
4871       automatically possessifying this item gains some performance in the case
4872       where the match fails. */
4873
4874       if (!possessive_quantifier &&
4875           repeat_max < 0 &&
4876           check_auto_possessive(previous, utf, ptr + 1, options, cd))
4877         {
4878         repeat_type = 0;    /* Force greedy */
4879         possessive_quantifier = TRUE;
4880         }
4881
4882       goto OUTPUT_SINGLE_REPEAT;   /* Code shared with single character types */
4883       }
4884
4885     /* If previous was a character type match (\d or similar), abolish it and
4886     create a suitable repeat item. The code is shared with single-character
4887     repeats by setting op_type to add a suitable offset into repeat_type. Note
4888     the the Unicode property types will be present only when SUPPORT_UCP is
4889     defined, but we don't wrap the little bits of code here because it just
4890     makes it horribly messy. */
4891
4892     else if (*previous < OP_EODN)
4893       {
4894       pcre_uchar *oldcode;
4895       int prop_type, prop_value;
4896       op_type = OP_TYPESTAR - OP_STAR;  /* Use type opcodes */
4897       c = *previous;
4898
4899       if (!possessive_quantifier &&
4900           repeat_max < 0 &&
4901           check_auto_possessive(previous, utf, ptr + 1, options, cd))
4902         {
4903         repeat_type = 0;    /* Force greedy */
4904         possessive_quantifier = TRUE;
4905         }
4906
4907       OUTPUT_SINGLE_REPEAT:
4908       if (*previous == OP_PROP || *previous == OP_NOTPROP)
4909         {
4910         prop_type = previous[1];
4911         prop_value = previous[2];
4912         }
4913       else prop_type = prop_value = -1;
4914
4915       oldcode = code;
4916       code = previous;                  /* Usually overwrite previous item */
4917
4918       /* If the maximum is zero then the minimum must also be zero; Perl allows
4919       this case, so we do too - by simply omitting the item altogether. */
4920
4921       if (repeat_max == 0) goto END_REPEAT;
4922
4923       /*--------------------------------------------------------------------*/
4924       /* This code is obsolete from release 8.00; the restriction was finally
4925       removed: */
4926
4927       /* All real repeats make it impossible to handle partial matching (maybe
4928       one day we will be able to remove this restriction). */
4929
4930       /* if (repeat_max != 1) cd->external_flags |= PCRE_NOPARTIAL; */
4931       /*--------------------------------------------------------------------*/
4932
4933       /* Combine the op_type with the repeat_type */
4934
4935       repeat_type += op_type;
4936
4937       /* A minimum of zero is handled either as the special case * or ?, or as
4938       an UPTO, with the maximum given. */
4939
4940       if (repeat_min == 0)
4941         {
4942         if (repeat_max == -1) *code++ = OP_STAR + repeat_type;
4943           else if (repeat_max == 1) *code++ = OP_QUERY + repeat_type;
4944         else
4945           {
4946           *code++ = OP_UPTO + repeat_type;
4947           PUT2INC(code, 0, repeat_max);
4948           }
4949         }
4950
4951       /* A repeat minimum of 1 is optimized into some special cases. If the
4952       maximum is unlimited, we use OP_PLUS. Otherwise, the original item is
4953       left in place and, if the maximum is greater than 1, we use OP_UPTO with
4954       one less than the maximum. */
4955
4956       else if (repeat_min == 1)
4957         {
4958         if (repeat_max == -1)
4959           *code++ = OP_PLUS + repeat_type;
4960         else
4961           {
4962           code = oldcode;                 /* leave previous item in place */
4963           if (repeat_max == 1) goto END_REPEAT;
4964           *code++ = OP_UPTO + repeat_type;
4965           PUT2INC(code, 0, repeat_max - 1);
4966           }
4967         }
4968
4969       /* The case {n,n} is just an EXACT, while the general case {n,m} is
4970       handled as an EXACT followed by an UPTO. */
4971
4972       else
4973         {
4974         *code++ = OP_EXACT + op_type;  /* NB EXACT doesn't have repeat_type */
4975         PUT2INC(code, 0, repeat_min);
4976
4977         /* If the maximum is unlimited, insert an OP_STAR. Before doing so,
4978         we have to insert the character for the previous code. For a repeated
4979         Unicode property match, there are two extra bytes that define the
4980         required property. In UTF-8 mode, long characters have their length in
4981         c, with the UTF_LENGTH bit as a flag. */
4982
4983         if (repeat_max < 0)
4984           {
4985 #ifdef SUPPORT_UTF
4986           if (utf && (c & UTF_LENGTH) != 0)
4987             {
4988             memcpy(code, utf_chars, IN_UCHARS(c & 7));
4989             code += c & 7;
4990             }
4991           else
4992 #endif
4993             {
4994             *code++ = c;
4995             if (prop_type >= 0)
4996               {
4997               *code++ = prop_type;
4998               *code++ = prop_value;
4999               }
5000             }
5001           *code++ = OP_STAR + repeat_type;
5002           }
5003
5004         /* Else insert an UPTO if the max is greater than the min, again
5005         preceded by the character, for the previously inserted code. If the
5006         UPTO is just for 1 instance, we can use QUERY instead. */
5007
5008         else if (repeat_max != repeat_min)
5009           {
5010 #ifdef SUPPORT_UTF
5011           if (utf && (c & UTF_LENGTH) != 0)
5012             {
5013             memcpy(code, utf_chars, IN_UCHARS(c & 7));
5014             code += c & 7;
5015             }
5016           else
5017 #endif
5018           *code++ = c;
5019           if (prop_type >= 0)
5020             {
5021             *code++ = prop_type;
5022             *code++ = prop_value;
5023             }
5024           repeat_max -= repeat_min;
5025
5026           if (repeat_max == 1)
5027             {
5028             *code++ = OP_QUERY + repeat_type;
5029             }
5030           else
5031             {
5032             *code++ = OP_UPTO + repeat_type;
5033             PUT2INC(code, 0, repeat_max);
5034             }
5035           }
5036         }
5037
5038       /* The character or character type itself comes last in all cases. */
5039
5040 #ifdef SUPPORT_UTF
5041       if (utf && (c & UTF_LENGTH) != 0)
5042         {
5043         memcpy(code, utf_chars, IN_UCHARS(c & 7));
5044         code += c & 7;
5045         }
5046       else
5047 #endif
5048       *code++ = c;
5049
5050       /* For a repeated Unicode property match, there are two extra bytes that
5051       define the required property. */
5052
5053 #ifdef SUPPORT_UCP
5054       if (prop_type >= 0)
5055         {
5056         *code++ = prop_type;
5057         *code++ = prop_value;
5058         }
5059 #endif
5060       }
5061
5062     /* If previous was a character class or a back reference, we put the repeat
5063     stuff after it, but just skip the item if the repeat was {0,0}. */
5064
5065     else if (*previous == OP_CLASS ||
5066              *previous == OP_NCLASS ||
5067 #if defined SUPPORT_UTF || !defined COMPILE_PCRE8
5068              *previous == OP_XCLASS ||
5069 #endif
5070              *previous == OP_REF ||
5071              *previous == OP_REFI)
5072       {
5073       if (repeat_max == 0)
5074         {
5075         code = previous;
5076         goto END_REPEAT;
5077         }
5078
5079       /*--------------------------------------------------------------------*/
5080       /* This code is obsolete from release 8.00; the restriction was finally
5081       removed: */
5082
5083       /* All real repeats make it impossible to handle partial matching (maybe
5084       one day we will be able to remove this restriction). */
5085
5086       /* if (repeat_max != 1) cd->external_flags |= PCRE_NOPARTIAL; */
5087       /*--------------------------------------------------------------------*/
5088
5089       if (repeat_min == 0 && repeat_max == -1)
5090         *code++ = OP_CRSTAR + repeat_type;
5091       else if (repeat_min == 1 && repeat_max == -1)
5092         *code++ = OP_CRPLUS + repeat_type;
5093       else if (repeat_min == 0 && repeat_max == 1)
5094         *code++ = OP_CRQUERY + repeat_type;
5095       else
5096         {
5097         *code++ = OP_CRRANGE + repeat_type;
5098         PUT2INC(code, 0, repeat_min);
5099         if (repeat_max == -1) repeat_max = 0;  /* 2-byte encoding for max */
5100         PUT2INC(code, 0, repeat_max);
5101         }
5102       }
5103
5104     /* If previous was a bracket group, we may have to replicate it in certain
5105     cases. Note that at this point we can encounter only the "basic" bracket
5106     opcodes such as BRA and CBRA, as this is the place where they get converted
5107     into the more special varieties such as BRAPOS and SBRA. A test for >=
5108     OP_ASSERT and <= OP_COND includes ASSERT, ASSERT_NOT, ASSERTBACK,
5109     ASSERTBACK_NOT, ONCE, BRA, CBRA, and COND. Originally, PCRE did not allow
5110     repetition of assertions, but now it does, for Perl compatibility. */
5111
5112     else if (*previous >= OP_ASSERT && *previous <= OP_COND)
5113       {
5114       int i;
5115       int len = (int)(code - previous);
5116       pcre_uchar *bralink = NULL;
5117       pcre_uchar *brazeroptr = NULL;
5118
5119       /* Repeating a DEFINE group is pointless, but Perl allows the syntax, so
5120       we just ignore the repeat. */
5121
5122       if (*previous == OP_COND && previous[LINK_SIZE+1] == OP_DEF)
5123         goto END_REPEAT;
5124
5125       /* There is no sense in actually repeating assertions. The only potential
5126       use of repetition is in cases when the assertion is optional. Therefore,
5127       if the minimum is greater than zero, just ignore the repeat. If the
5128       maximum is not not zero or one, set it to 1. */
5129
5130       if (*previous < OP_ONCE)    /* Assertion */
5131         {
5132         if (repeat_min > 0) goto END_REPEAT;
5133         if (repeat_max < 0 || repeat_max > 1) repeat_max = 1;
5134         }
5135
5136       /* The case of a zero minimum is special because of the need to stick
5137       OP_BRAZERO in front of it, and because the group appears once in the
5138       data, whereas in other cases it appears the minimum number of times. For
5139       this reason, it is simplest to treat this case separately, as otherwise
5140       the code gets far too messy. There are several special subcases when the
5141       minimum is zero. */
5142
5143       if (repeat_min == 0)
5144         {
5145         /* If the maximum is also zero, we used to just omit the group from the
5146         output altogether, like this:
5147
5148         ** if (repeat_max == 0)
5149         **   {
5150         **   code = previous;
5151         **   goto END_REPEAT;
5152         **   }
5153
5154         However, that fails when a group or a subgroup within it is referenced
5155         as a subroutine from elsewhere in the pattern, so now we stick in
5156         OP_SKIPZERO in front of it so that it is skipped on execution. As we
5157         don't have a list of which groups are referenced, we cannot do this
5158         selectively.
5159
5160         If the maximum is 1 or unlimited, we just have to stick in the BRAZERO
5161         and do no more at this point. However, we do need to adjust any
5162         OP_RECURSE calls inside the group that refer to the group itself or any
5163         internal or forward referenced group, because the offset is from the
5164         start of the whole regex. Temporarily terminate the pattern while doing
5165         this. */
5166
5167         if (repeat_max <= 1)    /* Covers 0, 1, and unlimited */
5168           {
5169           *code = OP_END;
5170           adjust_recurse(previous, 1, utf, cd, save_hwm);
5171           memmove(previous + 1, previous, IN_UCHARS(len));
5172           code++;
5173           if (repeat_max == 0)
5174             {
5175             *previous++ = OP_SKIPZERO;
5176             goto END_REPEAT;
5177             }
5178           brazeroptr = previous;    /* Save for possessive optimizing */
5179           *previous++ = OP_BRAZERO + repeat_type;
5180           }
5181
5182         /* If the maximum is greater than 1 and limited, we have to replicate
5183         in a nested fashion, sticking OP_BRAZERO before each set of brackets.
5184         The first one has to be handled carefully because it's the original
5185         copy, which has to be moved up. The remainder can be handled by code
5186         that is common with the non-zero minimum case below. We have to
5187         adjust the value or repeat_max, since one less copy is required. Once
5188         again, we may have to adjust any OP_RECURSE calls inside the group. */
5189
5190         else
5191           {
5192           int offset;
5193           *code = OP_END;
5194           adjust_recurse(previous, 2 + LINK_SIZE, utf, cd, save_hwm);
5195           memmove(previous + 2 + LINK_SIZE, previous, IN_UCHARS(len));
5196           code += 2 + LINK_SIZE;
5197           *previous++ = OP_BRAZERO + repeat_type;
5198           *previous++ = OP_BRA;
5199
5200           /* We chain together the bracket offset fields that have to be
5201           filled in later when the ends of the brackets are reached. */
5202
5203           offset = (bralink == NULL)? 0 : (int)(previous - bralink);
5204           bralink = previous;
5205           PUTINC(previous, 0, offset);
5206           }
5207
5208         repeat_max--;
5209         }
5210
5211       /* If the minimum is greater than zero, replicate the group as many
5212       times as necessary, and adjust the maximum to the number of subsequent
5213       copies that we need. If we set a first char from the group, and didn't
5214       set a required char, copy the latter from the former. If there are any
5215       forward reference subroutine calls in the group, there will be entries on
5216       the workspace list; replicate these with an appropriate increment. */
5217
5218       else
5219         {
5220         if (repeat_min > 1)
5221           {
5222           /* In the pre-compile phase, we don't actually do the replication. We
5223           just adjust the length as if we had. Do some paranoid checks for
5224           potential integer overflow. The INT64_OR_DOUBLE type is a 64-bit
5225           integer type when available, otherwise double. */
5226
5227           if (lengthptr != NULL)
5228             {
5229             int delta = (repeat_min - 1)*length_prevgroup;
5230             if ((INT64_OR_DOUBLE)(repeat_min - 1)*
5231                   (INT64_OR_DOUBLE)length_prevgroup >
5232                     (INT64_OR_DOUBLE)INT_MAX ||
5233                 OFLOW_MAX - *lengthptr < delta)
5234               {
5235               *errorcodeptr = ERR20;
5236               goto FAILED;
5237               }
5238             *lengthptr += delta;
5239             }
5240
5241           /* This is compiling for real. If there is a set first byte for
5242           the group, and we have not yet set a "required byte", set it. Make
5243           sure there is enough workspace for copying forward references before
5244           doing the copy. */
5245
5246           else
5247             {
5248             if (groupsetfirstchar && reqchar < 0) reqchar = firstchar;
5249
5250             for (i = 1; i < repeat_min; i++)
5251               {
5252               pcre_uchar *hc;
5253               pcre_uchar *this_hwm = cd->hwm;
5254               memcpy(code, previous, IN_UCHARS(len));
5255
5256               while (cd->hwm > cd->start_workspace + cd->workspace_size -
5257                      WORK_SIZE_SAFETY_MARGIN - (this_hwm - save_hwm))
5258                 {
5259                 int save_offset = save_hwm - cd->start_workspace;
5260                 int this_offset = this_hwm - cd->start_workspace;
5261                 *errorcodeptr = expand_workspace(cd);
5262                 if (*errorcodeptr != 0) goto FAILED;
5263                 save_hwm = (pcre_uchar *)cd->start_workspace + save_offset;
5264                 this_hwm = (pcre_uchar *)cd->start_workspace + this_offset;
5265                 }
5266
5267               for (hc = save_hwm; hc < this_hwm; hc += LINK_SIZE)
5268                 {
5269                 PUT(cd->hwm, 0, GET(hc, 0) + len);
5270                 cd->hwm += LINK_SIZE;
5271                 }
5272               save_hwm = this_hwm;
5273               code += len;
5274               }
5275             }
5276           }
5277
5278         if (repeat_max > 0) repeat_max -= repeat_min;
5279         }
5280
5281       /* This code is common to both the zero and non-zero minimum cases. If
5282       the maximum is limited, it replicates the group in a nested fashion,
5283       remembering the bracket starts on a stack. In the case of a zero minimum,
5284       the first one was set up above. In all cases the repeat_max now specifies
5285       the number of additional copies needed. Again, we must remember to
5286       replicate entries on the forward reference list. */
5287
5288       if (repeat_max >= 0)
5289         {
5290         /* In the pre-compile phase, we don't actually do the replication. We
5291         just adjust the length as if we had. For each repetition we must add 1
5292         to the length for BRAZERO and for all but the last repetition we must
5293         add 2 + 2*LINKSIZE to allow for the nesting that occurs. Do some
5294         paranoid checks to avoid integer overflow. The INT64_OR_DOUBLE type is
5295         a 64-bit integer type when available, otherwise double. */
5296
5297         if (lengthptr != NULL && repeat_max > 0)
5298           {
5299           int delta = repeat_max * (length_prevgroup + 1 + 2 + 2*LINK_SIZE) -
5300                       2 - 2*LINK_SIZE;   /* Last one doesn't nest */
5301           if ((INT64_OR_DOUBLE)repeat_max *
5302                 (INT64_OR_DOUBLE)(length_prevgroup + 1 + 2 + 2*LINK_SIZE)
5303                   > (INT64_OR_DOUBLE)INT_MAX ||
5304               OFLOW_MAX - *lengthptr < delta)
5305             {
5306             *errorcodeptr = ERR20;
5307             goto FAILED;
5308             }
5309           *lengthptr += delta;
5310           }
5311
5312         /* This is compiling for real */
5313
5314         else for (i = repeat_max - 1; i >= 0; i--)
5315           {
5316           pcre_uchar *hc;
5317           pcre_uchar *this_hwm = cd->hwm;
5318
5319           *code++ = OP_BRAZERO + repeat_type;
5320
5321           /* All but the final copy start a new nesting, maintaining the
5322           chain of brackets outstanding. */
5323
5324           if (i != 0)
5325             {
5326             int offset;
5327             *code++ = OP_BRA;
5328             offset = (bralink == NULL)? 0 : (int)(code - bralink);
5329             bralink = code;
5330             PUTINC(code, 0, offset);
5331             }
5332
5333           memcpy(code, previous, IN_UCHARS(len));
5334
5335           /* Ensure there is enough workspace for forward references before
5336           copying them. */
5337
5338           while (cd->hwm > cd->start_workspace + cd->workspace_size -
5339                  WORK_SIZE_SAFETY_MARGIN - (this_hwm - save_hwm))
5340             {
5341             int save_offset = save_hwm - cd->start_workspace;
5342             int this_offset = this_hwm - cd->start_workspace;
5343             *errorcodeptr = expand_workspace(cd);
5344             if (*errorcodeptr != 0) goto FAILED;
5345             save_hwm = (pcre_uchar *)cd->start_workspace + save_offset;
5346             this_hwm = (pcre_uchar *)cd->start_workspace + this_offset;
5347             }
5348
5349           for (hc = save_hwm; hc < this_hwm; hc += LINK_SIZE)
5350             {
5351             PUT(cd->hwm, 0, GET(hc, 0) + len + ((i != 0)? 2+LINK_SIZE : 1));
5352             cd->hwm += LINK_SIZE;
5353             }
5354           save_hwm = this_hwm;
5355           code += len;
5356           }
5357
5358         /* Now chain through the pending brackets, and fill in their length
5359         fields (which are holding the chain links pro tem). */
5360
5361         while (bralink != NULL)
5362           {
5363           int oldlinkoffset;
5364           int offset = (int)(code - bralink + 1);
5365           pcre_uchar *bra = code - offset;
5366           oldlinkoffset = GET(bra, 1);
5367           bralink = (oldlinkoffset == 0)? NULL : bralink - oldlinkoffset;
5368           *code++ = OP_KET;
5369           PUTINC(code, 0, offset);
5370           PUT(bra, 1, offset);
5371           }
5372         }
5373
5374       /* If the maximum is unlimited, set a repeater in the final copy. For
5375       ONCE brackets, that's all we need to do. However, possessively repeated
5376       ONCE brackets can be converted into non-capturing brackets, as the
5377       behaviour of (?:xx)++ is the same as (?>xx)++ and this saves having to
5378       deal with possessive ONCEs specially.
5379
5380       Otherwise, when we are doing the actual compile phase, check to see
5381       whether this group is one that could match an empty string. If so,
5382       convert the initial operator to the S form (e.g. OP_BRA -> OP_SBRA) so
5383       that runtime checking can be done. [This check is also applied to ONCE
5384       groups at runtime, but in a different way.]
5385
5386       Then, if the quantifier was possessive and the bracket is not a
5387       conditional, we convert the BRA code to the POS form, and the KET code to
5388       KETRPOS. (It turns out to be convenient at runtime to detect this kind of
5389       subpattern at both the start and at the end.) The use of special opcodes
5390       makes it possible to reduce greatly the stack usage in pcre_exec(). If
5391       the group is preceded by OP_BRAZERO, convert this to OP_BRAPOSZERO.
5392
5393       Then, if the minimum number of matches is 1 or 0, cancel the possessive
5394       flag so that the default action below, of wrapping everything inside
5395       atomic brackets, does not happen. When the minimum is greater than 1,
5396       there will be earlier copies of the group, and so we still have to wrap
5397       the whole thing. */
5398
5399       else
5400         {
5401         pcre_uchar *ketcode = code - 1 - LINK_SIZE;
5402         pcre_uchar *bracode = ketcode - GET(ketcode, 1);
5403
5404         /* Convert possessive ONCE brackets to non-capturing */
5405
5406         if ((*bracode == OP_ONCE || *bracode == OP_ONCE_NC) &&
5407             possessive_quantifier) *bracode = OP_BRA;
5408
5409         /* For non-possessive ONCE brackets, all we need to do is to
5410         set the KET. */
5411
5412         if (*bracode == OP_ONCE || *bracode == OP_ONCE_NC)
5413           *ketcode = OP_KETRMAX + repeat_type;
5414
5415         /* Handle non-ONCE brackets and possessive ONCEs (which have been
5416         converted to non-capturing above). */
5417
5418         else
5419           {
5420           /* In the compile phase, check for empty string matching. */
5421
5422           if (lengthptr == NULL)
5423             {
5424             pcre_uchar *scode = bracode;
5425             do
5426               {
5427               if (could_be_empty_branch(scode, ketcode, utf, cd))
5428                 {
5429                 *bracode += OP_SBRA - OP_BRA;
5430                 break;
5431                 }
5432               scode += GET(scode, 1);
5433               }
5434             while (*scode == OP_ALT);
5435             }
5436
5437           /* Handle possessive quantifiers. */
5438
5439           if (possessive_quantifier)
5440             {
5441             /* For COND brackets, we wrap the whole thing in a possessively
5442             repeated non-capturing bracket, because we have not invented POS
5443             versions of the COND opcodes. Because we are moving code along, we
5444             must ensure that any pending recursive references are updated. */
5445
5446             if (*bracode == OP_COND || *bracode == OP_SCOND)
5447               {
5448               int nlen = (int)(code - bracode);
5449               *code = OP_END;
5450               adjust_recurse(bracode, 1 + LINK_SIZE, utf, cd, save_hwm);
5451               memmove(bracode + 1 + LINK_SIZE, bracode, IN_UCHARS(nlen));
5452               code += 1 + LINK_SIZE;
5453               nlen += 1 + LINK_SIZE;
5454               *bracode = OP_BRAPOS;
5455               *code++ = OP_KETRPOS;
5456               PUTINC(code, 0, nlen);
5457               PUT(bracode, 1, nlen);
5458               }
5459
5460             /* For non-COND brackets, we modify the BRA code and use KETRPOS. */
5461
5462             else
5463               {
5464               *bracode += 1;              /* Switch to xxxPOS opcodes */
5465               *ketcode = OP_KETRPOS;
5466               }
5467
5468             /* If the minimum is zero, mark it as possessive, then unset the
5469             possessive flag when the minimum is 0 or 1. */
5470
5471             if (brazeroptr != NULL) *brazeroptr = OP_BRAPOSZERO;
5472             if (repeat_min < 2) possessive_quantifier = FALSE;
5473             }
5474
5475           /* Non-possessive quantifier */
5476
5477           else *ketcode = OP_KETRMAX + repeat_type;
5478           }
5479         }
5480       }
5481
5482     /* If previous is OP_FAIL, it was generated by an empty class [] in
5483     JavaScript mode. The other ways in which OP_FAIL can be generated, that is
5484     by (*FAIL) or (?!) set previous to NULL, which gives a "nothing to repeat"
5485     error above. We can just ignore the repeat in JS case. */
5486
5487     else if (*previous == OP_FAIL) goto END_REPEAT;
5488
5489     /* Else there's some kind of shambles */
5490
5491     else
5492       {
5493       *errorcodeptr = ERR11;
5494       goto FAILED;
5495       }
5496
5497     /* If the character following a repeat is '+', or if certain optimization
5498     tests above succeeded, possessive_quantifier is TRUE. For some opcodes,
5499     there are special alternative opcodes for this case. For anything else, we
5500     wrap the entire repeated item inside OP_ONCE brackets. Logically, the '+'
5501     notation is just syntactic sugar, taken from Sun's Java package, but the
5502     special opcodes can optimize it.
5503
5504     Some (but not all) possessively repeated subpatterns have already been
5505     completely handled in the code just above. For them, possessive_quantifier
5506     is always FALSE at this stage.
5507
5508     Note that the repeated item starts at tempcode, not at previous, which
5509     might be the first part of a string whose (former) last char we repeated.
5510
5511     Possessifying an 'exact' quantifier has no effect, so we can ignore it. But
5512     an 'upto' may follow. We skip over an 'exact' item, and then test the
5513     length of what remains before proceeding. */
5514
5515     if (possessive_quantifier)
5516       {
5517       int len;
5518
5519       if (*tempcode == OP_TYPEEXACT)
5520         tempcode += PRIV(OP_lengths)[*tempcode] +
5521           ((tempcode[1 + IMM2_SIZE] == OP_PROP
5522           || tempcode[1 + IMM2_SIZE] == OP_NOTPROP)? 2 : 0);
5523
5524       else if (*tempcode == OP_EXACT || *tempcode == OP_NOTEXACT)
5525         {
5526         tempcode += PRIV(OP_lengths)[*tempcode];
5527 #ifdef SUPPORT_UTF
5528         if (utf && HAS_EXTRALEN(tempcode[-1]))
5529           tempcode += GET_EXTRALEN(tempcode[-1]);
5530 #endif
5531         }
5532
5533       len = (int)(code - tempcode);
5534       if (len > 0) switch (*tempcode)
5535         {
5536         case OP_STAR:  *tempcode = OP_POSSTAR; break;
5537         case OP_PLUS:  *tempcode = OP_POSPLUS; break;
5538         case OP_QUERY: *tempcode = OP_POSQUERY; break;
5539         case OP_UPTO:  *tempcode = OP_POSUPTO; break;
5540
5541         case OP_STARI:  *tempcode = OP_POSSTARI; break;
5542         case OP_PLUSI:  *tempcode = OP_POSPLUSI; break;
5543         case OP_QUERYI: *tempcode = OP_POSQUERYI; break;
5544         case OP_UPTOI:  *tempcode = OP_POSUPTOI; break;
5545
5546         case OP_NOTSTAR:  *tempcode = OP_NOTPOSSTAR; break;
5547         case OP_NOTPLUS:  *tempcode = OP_NOTPOSPLUS; break;
5548         case OP_NOTQUERY: *tempcode = OP_NOTPOSQUERY; break;
5549         case OP_NOTUPTO:  *tempcode = OP_NOTPOSUPTO; break;
5550
5551         case OP_NOTSTARI:  *tempcode = OP_NOTPOSSTARI; break;
5552         case OP_NOTPLUSI:  *tempcode = OP_NOTPOSPLUSI; break;
5553         case OP_NOTQUERYI: *tempcode = OP_NOTPOSQUERYI; break;
5554         case OP_NOTUPTOI:  *tempcode = OP_NOTPOSUPTOI; break;
5555
5556         case OP_TYPESTAR:  *tempcode = OP_TYPEPOSSTAR; break;
5557         case OP_TYPEPLUS:  *tempcode = OP_TYPEPOSPLUS; break;
5558         case OP_TYPEQUERY: *tempcode = OP_TYPEPOSQUERY; break;
5559         case OP_TYPEUPTO:  *tempcode = OP_TYPEPOSUPTO; break;
5560
5561         /* Because we are moving code along, we must ensure that any
5562         pending recursive references are updated. */
5563
5564         default:
5565         *code = OP_END;
5566         adjust_recurse(tempcode, 1 + LINK_SIZE, utf, cd, save_hwm);
5567         memmove(tempcode + 1 + LINK_SIZE, tempcode, IN_UCHARS(len));
5568         code += 1 + LINK_SIZE;
5569         len += 1 + LINK_SIZE;
5570         tempcode[0] = OP_ONCE;
5571         *code++ = OP_KET;
5572         PUTINC(code, 0, len);
5573         PUT(tempcode, 1, len);
5574         break;
5575         }
5576       }
5577
5578     /* In all case we no longer have a previous item. We also set the
5579     "follows varying string" flag for subsequently encountered reqchars if
5580     it isn't already set and we have just passed a varying length item. */
5581
5582     END_REPEAT:
5583     previous = NULL;
5584     cd->req_varyopt |= reqvary;
5585     break;
5586
5587
5588     /* ===================================================================*/
5589     /* Start of nested parenthesized sub-expression, or comment or lookahead or
5590     lookbehind or option setting or condition or all the other extended
5591     parenthesis forms.  */
5592
5593     case CHAR_LEFT_PARENTHESIS:
5594     newoptions = options;
5595     skipbytes = 0;
5596     bravalue = OP_CBRA;
5597     save_hwm = cd->hwm;
5598     reset_bracount = FALSE;
5599
5600     /* First deal with various "verbs" that can be introduced by '*'. */
5601
5602     ptr++;
5603     if (ptr[0] == CHAR_ASTERISK && (ptr[1] == ':'
5604          || (MAX_255(ptr[1]) && ((cd->ctypes[ptr[1]] & ctype_letter) != 0))))
5605       {
5606       int i, namelen;
5607       int arglen = 0;
5608       const char *vn = verbnames;
5609       const pcre_uchar *name = ptr + 1;
5610       const pcre_uchar *arg = NULL;
5611       previous = NULL;
5612       ptr++;
5613       while (MAX_255(*ptr) && (cd->ctypes[*ptr] & ctype_letter) != 0) ptr++;
5614       namelen = (int)(ptr - name);
5615
5616       /* It appears that Perl allows any characters whatsoever, other than
5617       a closing parenthesis, to appear in arguments, so we no longer insist on
5618       letters, digits, and underscores. */
5619
5620       if (*ptr == CHAR_COLON)
5621         {
5622         arg = ++ptr;
5623         while (*ptr != 0 && *ptr != CHAR_RIGHT_PARENTHESIS) ptr++;
5624         arglen = (int)(ptr - arg);
5625         if (arglen > (int)MAX_MARK)
5626           {
5627           *errorcodeptr = ERR75;
5628           goto FAILED;
5629           }
5630         }
5631
5632       if (*ptr != CHAR_RIGHT_PARENTHESIS)
5633         {
5634         *errorcodeptr = ERR60;
5635         goto FAILED;
5636         }
5637
5638       /* Scan the table of verb names */
5639
5640       for (i = 0; i < verbcount; i++)
5641         {
5642         if (namelen == verbs[i].len &&
5643             STRNCMP_UC_C8(name, vn, namelen) == 0)
5644           {
5645           /* Check for open captures before ACCEPT and convert it to
5646           ASSERT_ACCEPT if in an assertion. */
5647
5648           if (verbs[i].op == OP_ACCEPT)
5649             {
5650             open_capitem *oc;
5651             if (arglen != 0)
5652               {
5653               *errorcodeptr = ERR59;
5654               goto FAILED;
5655               }
5656             cd->had_accept = TRUE;
5657             for (oc = cd->open_caps; oc != NULL; oc = oc->next)
5658               {
5659               *code++ = OP_CLOSE;
5660               PUT2INC(code, 0, oc->number);
5661               }
5662             *code++ = (cd->assert_depth > 0)? OP_ASSERT_ACCEPT : OP_ACCEPT;
5663
5664             /* Do not set firstchar after *ACCEPT */
5665             if (firstchar == REQ_UNSET) firstchar = REQ_NONE;
5666             }
5667
5668           /* Handle other cases with/without an argument */
5669
5670           else if (arglen == 0)
5671             {
5672             if (verbs[i].op < 0)   /* Argument is mandatory */
5673               {
5674               *errorcodeptr = ERR66;
5675               goto FAILED;
5676               }
5677             *code = verbs[i].op;
5678             if (*code++ == OP_THEN) cd->external_flags |= PCRE_HASTHEN;
5679             }
5680
5681           else
5682             {
5683             if (verbs[i].op_arg < 0)   /* Argument is forbidden */
5684               {
5685               *errorcodeptr = ERR59;
5686               goto FAILED;
5687               }
5688             *code = verbs[i].op_arg;
5689             if (*code++ == OP_THEN_ARG) cd->external_flags |= PCRE_HASTHEN;
5690             *code++ = arglen;
5691             memcpy(code, arg, IN_UCHARS(arglen));
5692             code += arglen;
5693             *code++ = 0;
5694             }
5695
5696           break;  /* Found verb, exit loop */
5697           }
5698
5699         vn += verbs[i].len + 1;
5700         }
5701
5702       if (i < verbcount) continue;    /* Successfully handled a verb */
5703       *errorcodeptr = ERR60;          /* Verb not recognized */
5704       goto FAILED;
5705       }
5706
5707     /* Deal with the extended parentheses; all are introduced by '?', and the
5708     appearance of any of them means that this is not a capturing group. */
5709
5710     else if (*ptr == CHAR_QUESTION_MARK)
5711       {
5712       int i, set, unset, namelen;
5713       int *optset;
5714       const pcre_uchar *name;
5715       pcre_uchar *slot;
5716
5717       switch (*(++ptr))
5718         {
5719         case CHAR_NUMBER_SIGN:                 /* Comment; skip to ket */
5720         ptr++;
5721         while (*ptr != 0 && *ptr != CHAR_RIGHT_PARENTHESIS) ptr++;
5722         if (*ptr == 0)
5723           {
5724           *errorcodeptr = ERR18;
5725           goto FAILED;
5726           }
5727         continue;
5728
5729
5730         /* ------------------------------------------------------------ */
5731         case CHAR_VERTICAL_LINE:  /* Reset capture count for each branch */
5732         reset_bracount = TRUE;
5733         /* Fall through */
5734
5735         /* ------------------------------------------------------------ */
5736         case CHAR_COLON:          /* Non-capturing bracket */
5737         bravalue = OP_BRA;
5738         ptr++;
5739         break;
5740
5741
5742         /* ------------------------------------------------------------ */
5743         case CHAR_LEFT_PARENTHESIS:
5744         bravalue = OP_COND;       /* Conditional group */
5745
5746         /* A condition can be an assertion, a number (referring to a numbered
5747         group), a name (referring to a named group), or 'R', referring to
5748         recursion. R<digits> and R&name are also permitted for recursion tests.
5749
5750         There are several syntaxes for testing a named group: (?(name)) is used
5751         by Python; Perl 5.10 onwards uses (?(<name>) or (?('name')).
5752
5753         There are two unfortunate ambiguities, caused by history. (a) 'R' can
5754         be the recursive thing or the name 'R' (and similarly for 'R' followed
5755         by digits), and (b) a number could be a name that consists of digits.
5756         In both cases, we look for a name first; if not found, we try the other
5757         cases. */
5758
5759         /* For conditions that are assertions, check the syntax, and then exit
5760         the switch. This will take control down to where bracketed groups,
5761         including assertions, are processed. */
5762
5763         if (ptr[1] == CHAR_QUESTION_MARK && (ptr[2] == CHAR_EQUALS_SIGN ||
5764             ptr[2] == CHAR_EXCLAMATION_MARK || ptr[2] == CHAR_LESS_THAN_SIGN))
5765           break;
5766
5767         /* Most other conditions use OP_CREF (a couple change to OP_RREF
5768         below), and all need to skip 1+IMM2_SIZE bytes at the start of the group. */
5769
5770         code[1+LINK_SIZE] = OP_CREF;
5771         skipbytes = 1+IMM2_SIZE;
5772         refsign = -1;
5773
5774         /* Check for a test for recursion in a named group. */
5775
5776         if (ptr[1] == CHAR_R && ptr[2] == CHAR_AMPERSAND)
5777           {
5778           terminator = -1;
5779           ptr += 2;
5780           code[1+LINK_SIZE] = OP_RREF;    /* Change the type of test */
5781           }
5782
5783         /* Check for a test for a named group's having been set, using the Perl
5784         syntax (?(<name>) or (?('name') */
5785
5786         else if (ptr[1] == CHAR_LESS_THAN_SIGN)
5787           {
5788           terminator = CHAR_GREATER_THAN_SIGN;
5789           ptr++;
5790           }
5791         else if (ptr[1] == CHAR_APOSTROPHE)
5792           {
5793           terminator = CHAR_APOSTROPHE;
5794           ptr++;
5795           }
5796         else
5797           {
5798           terminator = 0;
5799           if (ptr[1] == CHAR_MINUS || ptr[1] == CHAR_PLUS) refsign = *(++ptr);
5800           }
5801
5802         /* We now expect to read a name; any thing else is an error */
5803
5804         if (!MAX_255(ptr[1]) || (cd->ctypes[ptr[1]] & ctype_word) == 0)
5805           {
5806           ptr += 1;  /* To get the right offset */
5807           *errorcodeptr = ERR28;
5808           goto FAILED;
5809           }
5810
5811         /* Read the name, but also get it as a number if it's all digits */
5812
5813         recno = 0;
5814         name = ++ptr;
5815         while (MAX_255(*ptr) && (cd->ctypes[*ptr] & ctype_word) != 0)
5816           {
5817           if (recno >= 0)
5818             recno = (IS_DIGIT(*ptr))? recno * 10 + *ptr - CHAR_0 : -1;
5819           ptr++;
5820           }
5821         namelen = (int)(ptr - name);
5822
5823         if ((terminator > 0 && *ptr++ != terminator) ||
5824             *ptr++ != CHAR_RIGHT_PARENTHESIS)
5825           {
5826           ptr--;      /* Error offset */
5827           *errorcodeptr = ERR26;
5828           goto FAILED;
5829           }
5830
5831         /* Do no further checking in the pre-compile phase. */
5832
5833         if (lengthptr != NULL) break;
5834
5835         /* In the real compile we do the work of looking for the actual
5836         reference. If the string started with "+" or "-" we require the rest to
5837         be digits, in which case recno will be set. */
5838
5839         if (refsign > 0)
5840           {
5841           if (recno <= 0)
5842             {
5843             *errorcodeptr = ERR58;
5844             goto FAILED;
5845             }
5846           recno = (refsign == CHAR_MINUS)?
5847             cd->bracount - recno + 1 : recno +cd->bracount;
5848           if (recno <= 0 || recno > cd->final_bracount)
5849             {
5850             *errorcodeptr = ERR15;
5851             goto FAILED;
5852             }
5853           PUT2(code, 2+LINK_SIZE, recno);
5854           break;
5855           }
5856
5857         /* Otherwise (did not start with "+" or "-"), start by looking for the
5858         name. If we find a name, add one to the opcode to change OP_CREF or
5859         OP_RREF into OP_NCREF or OP_NRREF. These behave exactly the same,
5860         except they record that the reference was originally to a name. The
5861         information is used to check duplicate names. */
5862
5863         slot = cd->name_table;
5864         for (i = 0; i < cd->names_found; i++)
5865           {
5866           if (STRNCMP_UC_UC(name, slot+IMM2_SIZE, namelen) == 0) break;
5867           slot += cd->name_entry_size;
5868           }
5869
5870         /* Found a previous named subpattern */
5871
5872         if (i < cd->names_found)
5873           {
5874           recno = GET2(slot, 0);
5875           PUT2(code, 2+LINK_SIZE, recno);
5876           code[1+LINK_SIZE]++;
5877           }
5878
5879         /* Search the pattern for a forward reference */
5880
5881         else if ((i = find_parens(cd, name, namelen,
5882                         (options & PCRE_EXTENDED) != 0, utf)) > 0)
5883           {
5884           PUT2(code, 2+LINK_SIZE, i);
5885           code[1+LINK_SIZE]++;
5886           }
5887
5888         /* If terminator == 0 it means that the name followed directly after
5889         the opening parenthesis [e.g. (?(abc)...] and in this case there are
5890         some further alternatives to try. For the cases where terminator != 0
5891         [things like (?(<name>... or (?('name')... or (?(R&name)... ] we have
5892         now checked all the possibilities, so give an error. */
5893
5894         else if (terminator != 0)
5895           {
5896           *errorcodeptr = ERR15;
5897           goto FAILED;
5898           }
5899
5900         /* Check for (?(R) for recursion. Allow digits after R to specify a
5901         specific group number. */
5902
5903         else if (*name == CHAR_R)
5904           {
5905           recno = 0;
5906           for (i = 1; i < namelen; i++)
5907             {
5908             if (!IS_DIGIT(name[i]))
5909               {
5910               *errorcodeptr = ERR15;
5911               goto FAILED;
5912               }
5913             recno = recno * 10 + name[i] - CHAR_0;
5914             }
5915           if (recno == 0) recno = RREF_ANY;
5916           code[1+LINK_SIZE] = OP_RREF;      /* Change test type */
5917           PUT2(code, 2+LINK_SIZE, recno);
5918           }
5919
5920         /* Similarly, check for the (?(DEFINE) "condition", which is always
5921         false. */
5922
5923         else if (namelen == 6 && STRNCMP_UC_C8(name, STRING_DEFINE, 6) == 0)
5924           {
5925           code[1+LINK_SIZE] = OP_DEF;
5926           skipbytes = 1;
5927           }
5928
5929         /* Check for the "name" actually being a subpattern number. We are
5930         in the second pass here, so final_bracount is set. */
5931
5932         else if (recno > 0 && recno <= cd->final_bracount)
5933           {
5934           PUT2(code, 2+LINK_SIZE, recno);
5935           }
5936
5937         /* Either an unidentified subpattern, or a reference to (?(0) */
5938
5939         else
5940           {
5941           *errorcodeptr = (recno == 0)? ERR35: ERR15;
5942           goto FAILED;
5943           }
5944         break;
5945
5946
5947         /* ------------------------------------------------------------ */
5948         case CHAR_EQUALS_SIGN:                 /* Positive lookahead */
5949         bravalue = OP_ASSERT;
5950         cd->assert_depth += 1;
5951         ptr++;
5952         break;
5953
5954
5955         /* ------------------------------------------------------------ */
5956         case CHAR_EXCLAMATION_MARK:            /* Negative lookahead */
5957         ptr++;
5958         if (*ptr == CHAR_RIGHT_PARENTHESIS)    /* Optimize (?!) */
5959           {
5960           *code++ = OP_FAIL;
5961           previous = NULL;
5962           continue;
5963           }
5964         bravalue = OP_ASSERT_NOT;
5965         cd->assert_depth += 1;
5966         break;
5967
5968
5969         /* ------------------------------------------------------------ */
5970         case CHAR_LESS_THAN_SIGN:              /* Lookbehind or named define */
5971         switch (ptr[1])
5972           {
5973           case CHAR_EQUALS_SIGN:               /* Positive lookbehind */
5974           bravalue = OP_ASSERTBACK;
5975           cd->assert_depth += 1;
5976           ptr += 2;
5977           break;
5978
5979           case CHAR_EXCLAMATION_MARK:          /* Negative lookbehind */
5980           bravalue = OP_ASSERTBACK_NOT;
5981           cd->assert_depth += 1;
5982           ptr += 2;
5983           break;
5984
5985           default:                /* Could be name define, else bad */
5986           if (MAX_255(ptr[1]) && (cd->ctypes[ptr[1]] & ctype_word) != 0)
5987             goto DEFINE_NAME;
5988           ptr++;                  /* Correct offset for error */
5989           *errorcodeptr = ERR24;
5990           goto FAILED;
5991           }
5992         break;
5993
5994
5995         /* ------------------------------------------------------------ */
5996         case CHAR_GREATER_THAN_SIGN:           /* One-time brackets */
5997         bravalue = OP_ONCE;
5998         ptr++;
5999         break;
6000
6001
6002         /* ------------------------------------------------------------ */
6003         case CHAR_C:                 /* Callout - may be followed by digits; */
6004         previous_callout = code;     /* Save for later completion */
6005         after_manual_callout = 1;    /* Skip one item before completing */
6006         *code++ = OP_CALLOUT;
6007           {
6008           int n = 0;
6009           ptr++;
6010           while(IS_DIGIT(*ptr))
6011             n = n * 10 + *ptr++ - CHAR_0;
6012           if (*ptr != CHAR_RIGHT_PARENTHESIS)
6013             {
6014             *errorcodeptr = ERR39;
6015             goto FAILED;
6016             }
6017           if (n > 255)
6018             {
6019             *errorcodeptr = ERR38;
6020             goto FAILED;
6021             }
6022           *code++ = n;
6023           PUT(code, 0, (int)(ptr - cd->start_pattern + 1)); /* Pattern offset */
6024           PUT(code, LINK_SIZE, 0);                          /* Default length */
6025           code += 2 * LINK_SIZE;
6026           }
6027         previous = NULL;
6028         continue;
6029
6030
6031         /* ------------------------------------------------------------ */
6032         case CHAR_P:              /* Python-style named subpattern handling */
6033         if (*(++ptr) == CHAR_EQUALS_SIGN ||
6034             *ptr == CHAR_GREATER_THAN_SIGN)  /* Reference or recursion */
6035           {
6036           is_recurse = *ptr == CHAR_GREATER_THAN_SIGN;
6037           terminator = CHAR_RIGHT_PARENTHESIS;
6038           goto NAMED_REF_OR_RECURSE;
6039           }
6040         else if (*ptr != CHAR_LESS_THAN_SIGN)  /* Test for Python-style defn */
6041           {
6042           *errorcodeptr = ERR41;
6043           goto FAILED;
6044           }
6045         /* Fall through to handle (?P< as (?< is handled */
6046
6047
6048         /* ------------------------------------------------------------ */
6049         DEFINE_NAME:    /* Come here from (?< handling */
6050         case CHAR_APOSTROPHE:
6051           {
6052           terminator = (*ptr == CHAR_LESS_THAN_SIGN)?
6053             CHAR_GREATER_THAN_SIGN : CHAR_APOSTROPHE;
6054           name = ++ptr;
6055
6056           while (MAX_255(*ptr) && (cd->ctypes[*ptr] & ctype_word) != 0) ptr++;
6057           namelen = (int)(ptr - name);
6058
6059           /* In the pre-compile phase, just do a syntax check. */
6060
6061           if (lengthptr != NULL)
6062             {
6063             if (*ptr != terminator)
6064               {
6065               *errorcodeptr = ERR42;
6066               goto FAILED;
6067               }
6068             if (cd->names_found >= MAX_NAME_COUNT)
6069               {
6070               *errorcodeptr = ERR49;
6071               goto FAILED;
6072               }
6073             if (namelen + IMM2_SIZE + 1 > cd->name_entry_size)
6074               {
6075               cd->name_entry_size = namelen + IMM2_SIZE + 1;
6076               if (namelen > MAX_NAME_SIZE)
6077                 {
6078                 *errorcodeptr = ERR48;
6079                 goto FAILED;
6080                 }
6081               }
6082             }
6083
6084           /* In the real compile, create the entry in the table, maintaining
6085           alphabetical order. Duplicate names for different numbers are
6086           permitted only if PCRE_DUPNAMES is set. Duplicate names for the same
6087           number are always OK. (An existing number can be re-used if (?|
6088           appears in the pattern.) In either event, a duplicate name results in
6089           a duplicate entry in the table, even if the number is the same. This
6090           is because the number of names, and hence the table size, is computed
6091           in the pre-compile, and it affects various numbers and pointers which
6092           would all have to be modified, and the compiled code moved down, if
6093           duplicates with the same number were omitted from the table. This
6094           doesn't seem worth the hassle. However, *different* names for the
6095           same number are not permitted. */
6096
6097           else
6098             {
6099             BOOL dupname = FALSE;
6100             slot = cd->name_table;
6101
6102             for (i = 0; i < cd->names_found; i++)
6103               {
6104               int crc = memcmp(name, slot+IMM2_SIZE, IN_UCHARS(namelen));
6105               if (crc == 0)
6106                 {
6107                 if (slot[IMM2_SIZE+namelen] == 0)
6108                   {
6109                   if (GET2(slot, 0) != cd->bracount + 1 &&
6110                       (options & PCRE_DUPNAMES) == 0)
6111                     {
6112                     *errorcodeptr = ERR43;
6113                     goto FAILED;
6114                     }
6115                   else dupname = TRUE;
6116                   }
6117                 else crc = -1;      /* Current name is a substring */
6118                 }
6119
6120               /* Make space in the table and break the loop for an earlier
6121               name. For a duplicate or later name, carry on. We do this for
6122               duplicates so that in the simple case (when ?(| is not used) they
6123               are in order of their numbers. */
6124
6125               if (crc < 0)
6126                 {
6127                 memmove(slot + cd->name_entry_size, slot,
6128                   IN_UCHARS((cd->names_found - i) * cd->name_entry_size));
6129                 break;
6130                 }
6131
6132               /* Continue the loop for a later or duplicate name */
6133
6134               slot += cd->name_entry_size;
6135               }
6136
6137             /* For non-duplicate names, check for a duplicate number before
6138             adding the new name. */
6139
6140             if (!dupname)
6141               {
6142               pcre_uchar *cslot = cd->name_table;
6143               for (i = 0; i < cd->names_found; i++)
6144                 {
6145                 if (cslot != slot)
6146                   {
6147                   if (GET2(cslot, 0) == cd->bracount + 1)
6148                     {
6149                     *errorcodeptr = ERR65;
6150                     goto FAILED;
6151                     }
6152                   }
6153                 else i--;
6154                 cslot += cd->name_entry_size;
6155                 }
6156               }
6157
6158             PUT2(slot, 0, cd->bracount + 1);
6159             memcpy(slot + IMM2_SIZE, name, IN_UCHARS(namelen));
6160             slot[IMM2_SIZE + namelen] = 0;
6161             }
6162           }
6163
6164         /* In both pre-compile and compile, count the number of names we've
6165         encountered. */
6166
6167         cd->names_found++;
6168         ptr++;                    /* Move past > or ' */
6169         goto NUMBERED_GROUP;
6170
6171
6172         /* ------------------------------------------------------------ */
6173         case CHAR_AMPERSAND:            /* Perl recursion/subroutine syntax */
6174         terminator = CHAR_RIGHT_PARENTHESIS;
6175         is_recurse = TRUE;
6176         /* Fall through */
6177
6178         /* We come here from the Python syntax above that handles both
6179         references (?P=name) and recursion (?P>name), as well as falling
6180         through from the Perl recursion syntax (?&name). We also come here from
6181         the Perl \k<name> or \k'name' back reference syntax and the \k{name}
6182         .NET syntax, and the Oniguruma \g<...> and \g'...' subroutine syntax. */
6183
6184         NAMED_REF_OR_RECURSE:
6185         name = ++ptr;
6186         while (MAX_255(*ptr) && (cd->ctypes[*ptr] & ctype_word) != 0) ptr++;
6187         namelen = (int)(ptr - name);
6188
6189         /* In the pre-compile phase, do a syntax check. We used to just set
6190         a dummy reference number, because it was not used in the first pass.
6191         However, with the change of recursive back references to be atomic,
6192         we have to look for the number so that this state can be identified, as
6193         otherwise the incorrect length is computed. If it's not a backwards
6194         reference, the dummy number will do. */
6195
6196         if (lengthptr != NULL)
6197           {
6198           const pcre_uchar *temp;
6199
6200           if (namelen == 0)
6201             {
6202             *errorcodeptr = ERR62;
6203             goto FAILED;
6204             }
6205           if (*ptr != terminator)
6206             {
6207             *errorcodeptr = ERR42;
6208             goto FAILED;
6209             }
6210           if (namelen > MAX_NAME_SIZE)
6211             {
6212             *errorcodeptr = ERR48;
6213             goto FAILED;
6214             }
6215
6216           /* The name table does not exist in the first pass, so we cannot
6217           do a simple search as in the code below. Instead, we have to scan the
6218           pattern to find the number. It is important that we scan it only as
6219           far as we have got because the syntax of named subpatterns has not
6220           been checked for the rest of the pattern, and find_parens() assumes
6221           correct syntax. In any case, it's a waste of resources to scan
6222           further. We stop the scan at the current point by temporarily
6223           adjusting the value of cd->endpattern. */
6224
6225           temp = cd->end_pattern;
6226           cd->end_pattern = ptr;
6227           recno = find_parens(cd, name, namelen,
6228             (options & PCRE_EXTENDED) != 0, utf);
6229           cd->end_pattern = temp;
6230           if (recno < 0) recno = 0;    /* Forward ref; set dummy number */
6231           }
6232
6233         /* In the real compile, seek the name in the table. We check the name
6234         first, and then check that we have reached the end of the name in the
6235         table. That way, if the name that is longer than any in the table,
6236         the comparison will fail without reading beyond the table entry. */
6237
6238         else
6239           {
6240           slot = cd->name_table;
6241           for (i = 0; i < cd->names_found; i++)
6242             {
6243             if (STRNCMP_UC_UC(name, slot+IMM2_SIZE, namelen) == 0 &&
6244                 slot[IMM2_SIZE+namelen] == 0)
6245               break;
6246             slot += cd->name_entry_size;
6247             }
6248
6249           if (i < cd->names_found)         /* Back reference */
6250             {
6251             recno = GET2(slot, 0);
6252             }
6253           else if ((recno =                /* Forward back reference */
6254                     find_parens(cd, name, namelen,
6255                       (options & PCRE_EXTENDED) != 0, utf)) <= 0)
6256             {
6257             *errorcodeptr = ERR15;
6258             goto FAILED;
6259             }
6260           }
6261
6262         /* In both phases, we can now go to the code than handles numerical
6263         recursion or backreferences. */
6264
6265         if (is_recurse) goto HANDLE_RECURSION;
6266           else goto HANDLE_REFERENCE;
6267
6268
6269         /* ------------------------------------------------------------ */
6270         case CHAR_R:              /* Recursion */
6271         ptr++;                    /* Same as (?0)      */
6272         /* Fall through */
6273
6274
6275         /* ------------------------------------------------------------ */
6276         case CHAR_MINUS: case CHAR_PLUS:  /* Recursion or subroutine */
6277         case CHAR_0: case CHAR_1: case CHAR_2: case CHAR_3: case CHAR_4:
6278         case CHAR_5: case CHAR_6: case CHAR_7: case CHAR_8: case CHAR_9:
6279           {
6280           const pcre_uchar *called;
6281           terminator = CHAR_RIGHT_PARENTHESIS;
6282
6283           /* Come here from the \g<...> and \g'...' code (Oniguruma
6284           compatibility). However, the syntax has been checked to ensure that
6285           the ... are a (signed) number, so that neither ERR63 nor ERR29 will
6286           be called on this path, nor with the jump to OTHER_CHAR_AFTER_QUERY
6287           ever be taken. */
6288
6289           HANDLE_NUMERICAL_RECURSION:
6290
6291           if ((refsign = *ptr) == CHAR_PLUS)
6292             {
6293             ptr++;
6294             if (!IS_DIGIT(*ptr))
6295               {
6296               *errorcodeptr = ERR63;
6297               goto FAILED;
6298               }
6299             }
6300           else if (refsign == CHAR_MINUS)
6301             {
6302             if (!IS_DIGIT(ptr[1]))
6303               goto OTHER_CHAR_AFTER_QUERY;
6304             ptr++;
6305             }
6306
6307           recno = 0;
6308           while(IS_DIGIT(*ptr))
6309             recno = recno * 10 + *ptr++ - CHAR_0;
6310
6311           if (*ptr != terminator)
6312             {
6313             *errorcodeptr = ERR29;
6314             goto FAILED;
6315             }
6316
6317           if (refsign == CHAR_MINUS)
6318             {
6319             if (recno == 0)
6320               {
6321               *errorcodeptr = ERR58;
6322               goto FAILED;
6323               }
6324             recno = cd->bracount - recno + 1;
6325             if (recno <= 0)
6326               {
6327               *errorcodeptr = ERR15;
6328               goto FAILED;
6329               }
6330             }
6331           else if (refsign == CHAR_PLUS)
6332             {
6333             if (recno == 0)
6334               {
6335               *errorcodeptr = ERR58;
6336               goto FAILED;
6337               }
6338             recno += cd->bracount;
6339             }
6340
6341           /* Come here from code above that handles a named recursion */
6342
6343           HANDLE_RECURSION:
6344
6345           previous = code;
6346           called = cd->start_code;
6347
6348           /* When we are actually compiling, find the bracket that is being
6349           referenced. Temporarily end the regex in case it doesn't exist before
6350           this point. If we end up with a forward reference, first check that
6351           the bracket does occur later so we can give the error (and position)
6352           now. Then remember this forward reference in the workspace so it can
6353           be filled in at the end. */
6354
6355           if (lengthptr == NULL)
6356             {
6357             *code = OP_END;
6358             if (recno != 0)
6359               called = PRIV(find_bracket)(cd->start_code, utf, recno);
6360
6361             /* Forward reference */
6362
6363             if (called == NULL)
6364               {
6365               if (find_parens(cd, NULL, recno,
6366                     (options & PCRE_EXTENDED) != 0, utf) < 0)
6367                 {
6368                 *errorcodeptr = ERR15;
6369                 goto FAILED;
6370                 }
6371
6372               /* Fudge the value of "called" so that when it is inserted as an
6373               offset below, what it actually inserted is the reference number
6374               of the group. Then remember the forward reference. */
6375
6376               called = cd->start_code + recno;
6377               if (cd->hwm >= cd->start_workspace + cd->workspace_size -
6378                   WORK_SIZE_SAFETY_MARGIN)
6379                 {
6380                 *errorcodeptr = expand_workspace(cd);
6381                 if (*errorcodeptr != 0) goto FAILED;
6382                 }
6383               PUTINC(cd->hwm, 0, (int)(code + 1 - cd->start_code));
6384               }
6385
6386             /* If not a forward reference, and the subpattern is still open,
6387             this is a recursive call. We check to see if this is a left
6388             recursion that could loop for ever, and diagnose that case. We
6389             must not, however, do this check if we are in a conditional
6390             subpattern because the condition might be testing for recursion in
6391             a pattern such as /(?(R)a+|(?R)b)/, which is perfectly valid.
6392             Forever loops are also detected at runtime, so those that occur in
6393             conditional subpatterns will be picked up then. */
6394
6395             else if (GET(called, 1) == 0 && cond_depth <= 0 &&
6396                      could_be_empty(called, code, bcptr, utf, cd))
6397               {
6398               *errorcodeptr = ERR40;
6399               goto FAILED;
6400               }
6401             }
6402
6403           /* Insert the recursion/subroutine item. It does not have a set first
6404           character (relevant if it is repeated, because it will then be
6405           wrapped with ONCE brackets). */
6406
6407           *code = OP_RECURSE;
6408           PUT(code, 1, (int)(called - cd->start_code));
6409           code += 1 + LINK_SIZE;
6410           groupsetfirstchar = FALSE;
6411           }
6412
6413         /* Can't determine a first byte now */
6414
6415         if (firstchar == REQ_UNSET) firstchar = REQ_NONE;
6416         continue;
6417
6418
6419         /* ------------------------------------------------------------ */
6420         default:              /* Other characters: check option setting */
6421         OTHER_CHAR_AFTER_QUERY:
6422         set = unset = 0;
6423         optset = &set;
6424
6425         while (*ptr != CHAR_RIGHT_PARENTHESIS && *ptr != CHAR_COLON)
6426           {
6427           switch (*ptr++)
6428             {
6429             case CHAR_MINUS: optset = &unset; break;
6430
6431             case CHAR_J:    /* Record that it changed in the external options */
6432             *optset |= PCRE_DUPNAMES;
6433             cd->external_flags |= PCRE_JCHANGED;
6434             break;
6435
6436             case CHAR_i: *optset |= PCRE_CASELESS; break;
6437             case CHAR_m: *optset |= PCRE_MULTILINE; break;
6438             case CHAR_s: *optset |= PCRE_DOTALL; break;
6439             case CHAR_x: *optset |= PCRE_EXTENDED; break;
6440             case CHAR_U: *optset |= PCRE_UNGREEDY; break;
6441             case CHAR_X: *optset |= PCRE_EXTRA; break;
6442
6443             default:  *errorcodeptr = ERR12;
6444                       ptr--;    /* Correct the offset */
6445                       goto FAILED;
6446             }
6447           }
6448
6449         /* Set up the changed option bits, but don't change anything yet. */
6450
6451         newoptions = (options | set) & (~unset);
6452
6453         /* If the options ended with ')' this is not the start of a nested
6454         group with option changes, so the options change at this level. If this
6455         item is right at the start of the pattern, the options can be
6456         abstracted and made external in the pre-compile phase, and ignored in
6457         the compile phase. This can be helpful when matching -- for instance in
6458         caseless checking of required bytes.
6459
6460         If the code pointer is not (cd->start_code + 1 + LINK_SIZE), we are
6461         definitely *not* at the start of the pattern because something has been
6462         compiled. In the pre-compile phase, however, the code pointer can have
6463         that value after the start, because it gets reset as code is discarded
6464         during the pre-compile. However, this can happen only at top level - if
6465         we are within parentheses, the starting BRA will still be present. At
6466         any parenthesis level, the length value can be used to test if anything
6467         has been compiled at that level. Thus, a test for both these conditions
6468         is necessary to ensure we correctly detect the start of the pattern in
6469         both phases.
6470
6471         If we are not at the pattern start, reset the greedy defaults and the
6472         case value for firstchar and reqchar. */
6473
6474         if (*ptr == CHAR_RIGHT_PARENTHESIS)
6475           {
6476           if (code == cd->start_code + 1 + LINK_SIZE &&
6477                (lengthptr == NULL || *lengthptr == 2 + 2*LINK_SIZE))
6478             {
6479             cd->external_options = newoptions;
6480             }
6481           else
6482             {
6483             greedy_default = ((newoptions & PCRE_UNGREEDY) != 0);
6484             greedy_non_default = greedy_default ^ 1;
6485             req_caseopt = ((newoptions & PCRE_CASELESS) != 0)? REQ_CASELESS:0;
6486             }
6487
6488           /* Change options at this level, and pass them back for use
6489           in subsequent branches. */
6490
6491           *optionsptr = options = newoptions;
6492           previous = NULL;       /* This item can't be repeated */
6493           continue;              /* It is complete */
6494           }
6495
6496         /* If the options ended with ':' we are heading into a nested group
6497         with possible change of options. Such groups are non-capturing and are
6498         not assertions of any kind. All we need to do is skip over the ':';
6499         the newoptions value is handled below. */
6500
6501         bravalue = OP_BRA;
6502         ptr++;
6503         }     /* End of switch for character following (? */
6504       }       /* End of (? handling */
6505
6506     /* Opening parenthesis not followed by '*' or '?'. If PCRE_NO_AUTO_CAPTURE
6507     is set, all unadorned brackets become non-capturing and behave like (?:...)
6508     brackets. */
6509
6510     else if ((options & PCRE_NO_AUTO_CAPTURE) != 0)
6511       {
6512       bravalue = OP_BRA;
6513       }
6514
6515     /* Else we have a capturing group. */
6516
6517     else
6518       {
6519       NUMBERED_GROUP:
6520       cd->bracount += 1;
6521       PUT2(code, 1+LINK_SIZE, cd->bracount);
6522       skipbytes = IMM2_SIZE;
6523       }
6524
6525     /* Process nested bracketed regex. Assertions used not to be repeatable,
6526     but this was changed for Perl compatibility, so all kinds can now be
6527     repeated. We copy code into a non-register variable (tempcode) in order to
6528     be able to pass its address because some compilers complain otherwise. */
6529
6530     previous = code;                      /* For handling repetition */
6531     *code = bravalue;
6532     tempcode = code;
6533     tempreqvary = cd->req_varyopt;        /* Save value before bracket */
6534     tempbracount = cd->bracount;          /* Save value before bracket */
6535     length_prevgroup = 0;                 /* Initialize for pre-compile phase */
6536
6537     if (!compile_regex(
6538          newoptions,                      /* The complete new option state */
6539          &tempcode,                       /* Where to put code (updated) */
6540          &ptr,                            /* Input pointer (updated) */
6541          errorcodeptr,                    /* Where to put an error message */
6542          (bravalue == OP_ASSERTBACK ||
6543           bravalue == OP_ASSERTBACK_NOT), /* TRUE if back assert */
6544          reset_bracount,                  /* True if (?| group */
6545          skipbytes,                       /* Skip over bracket number */
6546          cond_depth +
6547            ((bravalue == OP_COND)?1:0),   /* Depth of condition subpatterns */
6548          &subfirstchar,                   /* For possible first char */
6549          &subreqchar,                     /* For possible last char */
6550          bcptr,                           /* Current branch chain */
6551          cd,                              /* Tables block */
6552          (lengthptr == NULL)? NULL :      /* Actual compile phase */
6553            &length_prevgroup              /* Pre-compile phase */
6554          ))
6555       goto FAILED;
6556
6557     /* If this was an atomic group and there are no capturing groups within it,
6558     generate OP_ONCE_NC instead of OP_ONCE. */
6559
6560     if (bravalue == OP_ONCE && cd->bracount <= tempbracount)
6561       *code = OP_ONCE_NC;
6562
6563     if (bravalue >= OP_ASSERT && bravalue <= OP_ASSERTBACK_NOT)
6564       cd->assert_depth -= 1;
6565
6566     /* At the end of compiling, code is still pointing to the start of the
6567     group, while tempcode has been updated to point past the end of the group.
6568     The pattern pointer (ptr) is on the bracket.
6569
6570     If this is a conditional bracket, check that there are no more than
6571     two branches in the group, or just one if it's a DEFINE group. We do this
6572     in the real compile phase, not in the pre-pass, where the whole group may
6573     not be available. */
6574
6575     if (bravalue == OP_COND && lengthptr == NULL)
6576       {
6577       pcre_uchar *tc = code;
6578       int condcount = 0;
6579
6580       do {
6581          condcount++;
6582          tc += GET(tc,1);
6583          }
6584       while (*tc != OP_KET);
6585
6586       /* A DEFINE group is never obeyed inline (the "condition" is always
6587       false). It must have only one branch. */
6588
6589       if (code[LINK_SIZE+1] == OP_DEF)
6590         {
6591         if (condcount > 1)
6592           {
6593           *errorcodeptr = ERR54;
6594           goto FAILED;
6595           }
6596         bravalue = OP_DEF;   /* Just a flag to suppress char handling below */
6597         }
6598
6599       /* A "normal" conditional group. If there is just one branch, we must not
6600       make use of its firstchar or reqchar, because this is equivalent to an
6601       empty second branch. */
6602
6603       else
6604         {
6605         if (condcount > 2)
6606           {
6607           *errorcodeptr = ERR27;
6608           goto FAILED;
6609           }
6610         if (condcount == 1) subfirstchar = subreqchar = REQ_NONE;
6611         }
6612       }
6613
6614     /* Error if hit end of pattern */
6615
6616     if (*ptr != CHAR_RIGHT_PARENTHESIS)
6617       {
6618       *errorcodeptr = ERR14;
6619       goto FAILED;
6620       }
6621
6622     /* In the pre-compile phase, update the length by the length of the group,
6623     less the brackets at either end. Then reduce the compiled code to just a
6624     set of non-capturing brackets so that it doesn't use much memory if it is
6625     duplicated by a quantifier.*/
6626
6627     if (lengthptr != NULL)
6628       {
6629       if (OFLOW_MAX - *lengthptr < length_prevgroup - 2 - 2*LINK_SIZE)
6630         {
6631         *errorcodeptr = ERR20;
6632         goto FAILED;
6633         }
6634       *lengthptr += length_prevgroup - 2 - 2*LINK_SIZE;
6635       code++;   /* This already contains bravalue */
6636       PUTINC(code, 0, 1 + LINK_SIZE);
6637       *code++ = OP_KET;
6638       PUTINC(code, 0, 1 + LINK_SIZE);
6639       break;    /* No need to waste time with special character handling */
6640       }
6641
6642     /* Otherwise update the main code pointer to the end of the group. */
6643
6644     code = tempcode;
6645
6646     /* For a DEFINE group, required and first character settings are not
6647     relevant. */
6648
6649     if (bravalue == OP_DEF) break;
6650
6651     /* Handle updating of the required and first characters for other types of
6652     group. Update for normal brackets of all kinds, and conditions with two
6653     branches (see code above). If the bracket is followed by a quantifier with
6654     zero repeat, we have to back off. Hence the definition of zeroreqchar and
6655     zerofirstchar outside the main loop so that they can be accessed for the
6656     back off. */
6657
6658     zeroreqchar = reqchar;
6659     zerofirstchar = firstchar;
6660     groupsetfirstchar = FALSE;
6661
6662     if (bravalue >= OP_ONCE)
6663       {
6664       /* If we have not yet set a firstchar in this branch, take it from the
6665       subpattern, remembering that it was set here so that a repeat of more
6666       than one can replicate it as reqchar if necessary. If the subpattern has
6667       no firstchar, set "none" for the whole branch. In both cases, a zero
6668       repeat forces firstchar to "none". */
6669
6670       if (firstchar == REQ_UNSET)
6671         {
6672         if (subfirstchar >= 0)
6673           {
6674           firstchar = subfirstchar;
6675           groupsetfirstchar = TRUE;
6676           }
6677         else firstchar = REQ_NONE;
6678         zerofirstchar = REQ_NONE;
6679         }
6680
6681       /* If firstchar was previously set, convert the subpattern's firstchar
6682       into reqchar if there wasn't one, using the vary flag that was in
6683       existence beforehand. */
6684
6685       else if (subfirstchar >= 0 && subreqchar < 0)
6686         subreqchar = subfirstchar | tempreqvary;
6687
6688       /* If the subpattern set a required byte (or set a first byte that isn't
6689       really the first byte - see above), set it. */
6690
6691       if (subreqchar >= 0) reqchar = subreqchar;
6692       }
6693
6694     /* For a forward assertion, we take the reqchar, if set. This can be
6695     helpful if the pattern that follows the assertion doesn't set a different
6696     char. For example, it's useful for /(?=abcde).+/. We can't set firstchar
6697     for an assertion, however because it leads to incorrect effect for patterns
6698     such as /(?=a)a.+/ when the "real" "a" would then become a reqchar instead
6699     of a firstchar. This is overcome by a scan at the end if there's no
6700     firstchar, looking for an asserted first char. */
6701
6702     else if (bravalue == OP_ASSERT && subreqchar >= 0) reqchar = subreqchar;
6703     break;     /* End of processing '(' */
6704
6705
6706     /* ===================================================================*/
6707     /* Handle metasequences introduced by \. For ones like \d, the ESC_ values
6708     are arranged to be the negation of the corresponding OP_values in the
6709     default case when PCRE_UCP is not set. For the back references, the values
6710     are ESC_REF plus the reference number. Only back references and those types
6711     that consume a character may be repeated. We can test for values between
6712     ESC_b and ESC_Z for the latter; this may have to change if any new ones are
6713     ever created. */
6714
6715     case CHAR_BACKSLASH:
6716     tempptr = ptr;
6717     c = check_escape(&ptr, errorcodeptr, cd->bracount, options, FALSE);
6718     if (*errorcodeptr != 0) goto FAILED;
6719
6720     if (c < 0)
6721       {
6722       if (-c == ESC_Q)            /* Handle start of quoted string */
6723         {
6724         if (ptr[1] == CHAR_BACKSLASH && ptr[2] == CHAR_E)
6725           ptr += 2;               /* avoid empty string */
6726             else inescq = TRUE;
6727         continue;
6728         }
6729
6730       if (-c == ESC_E) continue;  /* Perl ignores an orphan \E */
6731
6732       /* For metasequences that actually match a character, we disable the
6733       setting of a first character if it hasn't already been set. */
6734
6735       if (firstchar == REQ_UNSET && -c > ESC_b && -c < ESC_Z)
6736         firstchar = REQ_NONE;
6737
6738       /* Set values to reset to if this is followed by a zero repeat. */
6739
6740       zerofirstchar = firstchar;
6741       zeroreqchar = reqchar;
6742
6743       /* \g<name> or \g'name' is a subroutine call by name and \g<n> or \g'n'
6744       is a subroutine call by number (Oniguruma syntax). In fact, the value
6745       -ESC_g is returned only for these cases. So we don't need to check for <
6746       or ' if the value is -ESC_g. For the Perl syntax \g{n} the value is
6747       -ESC_REF+n, and for the Perl syntax \g{name} the result is -ESC_k (as
6748       that is a synonym for a named back reference). */
6749
6750       if (-c == ESC_g)
6751         {
6752         const pcre_uchar *p;
6753         save_hwm = cd->hwm;   /* Normally this is set when '(' is read */
6754         terminator = (*(++ptr) == CHAR_LESS_THAN_SIGN)?
6755           CHAR_GREATER_THAN_SIGN : CHAR_APOSTROPHE;
6756
6757         /* These two statements stop the compiler for warning about possibly
6758         unset variables caused by the jump to HANDLE_NUMERICAL_RECURSION. In
6759         fact, because we actually check for a number below, the paths that
6760         would actually be in error are never taken. */
6761
6762         skipbytes = 0;
6763         reset_bracount = FALSE;
6764
6765         /* Test for a name */
6766
6767         if (ptr[1] != CHAR_PLUS && ptr[1] != CHAR_MINUS)
6768           {
6769           BOOL is_a_number = TRUE;
6770           for (p = ptr + 1; *p != 0 && *p != terminator; p++)
6771             {
6772             if (!MAX_255(*p)) { is_a_number = FALSE; break; }
6773             if ((cd->ctypes[*p] & ctype_digit) == 0) is_a_number = FALSE;
6774             if ((cd->ctypes[*p] & ctype_word) == 0) break;
6775             }
6776           if (*p != terminator)
6777             {
6778             *errorcodeptr = ERR57;
6779             break;
6780             }
6781           if (is_a_number)
6782             {
6783             ptr++;
6784             goto HANDLE_NUMERICAL_RECURSION;
6785             }
6786           is_recurse = TRUE;
6787           goto NAMED_REF_OR_RECURSE;
6788           }
6789
6790         /* Test a signed number in angle brackets or quotes. */
6791
6792         p = ptr + 2;
6793         while (IS_DIGIT(*p)) p++;
6794         if (*p != terminator)
6795           {
6796           *errorcodeptr = ERR57;
6797           break;
6798           }
6799         ptr++;
6800         goto HANDLE_NUMERICAL_RECURSION;
6801         }
6802
6803       /* \k<name> or \k'name' is a back reference by name (Perl syntax).
6804       We also support \k{name} (.NET syntax).  */
6805
6806       if (-c == ESC_k)
6807         {
6808         if ((ptr[1] != CHAR_LESS_THAN_SIGN &&
6809           ptr[1] != CHAR_APOSTROPHE && ptr[1] != CHAR_LEFT_CURLY_BRACKET))
6810           {
6811           *errorcodeptr = ERR69;
6812           break;
6813           }
6814         is_recurse = FALSE;
6815         terminator = (*(++ptr) == CHAR_LESS_THAN_SIGN)?
6816           CHAR_GREATER_THAN_SIGN : (*ptr == CHAR_APOSTROPHE)?
6817           CHAR_APOSTROPHE : CHAR_RIGHT_CURLY_BRACKET;
6818         goto NAMED_REF_OR_RECURSE;
6819         }
6820
6821       /* Back references are handled specially; must disable firstchar if
6822       not set to cope with cases like (?=(\w+))\1: which would otherwise set
6823       ':' later. */
6824
6825       if (-c >= ESC_REF)
6826         {
6827         open_capitem *oc;
6828         recno = -c - ESC_REF;
6829
6830         HANDLE_REFERENCE:    /* Come here from named backref handling */
6831         if (firstchar == REQ_UNSET) firstchar = REQ_NONE;
6832         previous = code;
6833         *code++ = ((options & PCRE_CASELESS) != 0)? OP_REFI : OP_REF;
6834         PUT2INC(code, 0, recno);
6835         cd->backref_map |= (recno < 32)? (1 << recno) : 1;
6836         if (recno > cd->top_backref) cd->top_backref = recno;
6837
6838         /* Check to see if this back reference is recursive, that it, it
6839         is inside the group that it references. A flag is set so that the
6840         group can be made atomic. */
6841
6842         for (oc = cd->open_caps; oc != NULL; oc = oc->next)
6843           {
6844           if (oc->number == recno)
6845             {
6846             oc->flag = TRUE;
6847             break;
6848             }
6849           }
6850         }
6851
6852       /* So are Unicode property matches, if supported. */
6853
6854 #ifdef SUPPORT_UCP
6855       else if (-c == ESC_P || -c == ESC_p)
6856         {
6857         BOOL negated;
6858         int pdata;
6859         int ptype = get_ucp(&ptr, &negated, &pdata, errorcodeptr);
6860         if (ptype < 0) goto FAILED;
6861         previous = code;
6862         *code++ = ((-c == ESC_p) != negated)? OP_PROP : OP_NOTPROP;
6863         *code++ = ptype;
6864         *code++ = pdata;
6865         }
6866 #else
6867
6868       /* If Unicode properties are not supported, \X, \P, and \p are not
6869       allowed. */
6870
6871       else if (-c == ESC_X || -c == ESC_P || -c == ESC_p)
6872         {
6873         *errorcodeptr = ERR45;
6874         goto FAILED;
6875         }
6876 #endif
6877
6878       /* For the rest (including \X when Unicode properties are supported), we
6879       can obtain the OP value by negating the escape value in the default
6880       situation when PCRE_UCP is not set. When it *is* set, we substitute
6881       Unicode property tests. Note that \b and \B do a one-character
6882       lookbehind. */
6883
6884       else
6885         {
6886         if ((-c == ESC_b || -c == ESC_B) && cd->max_lookbehind == 0)
6887           cd->max_lookbehind = 1;
6888 #ifdef SUPPORT_UCP
6889         if (-c >= ESC_DU && -c <= ESC_wu)
6890           {
6891           nestptr = ptr + 1;                   /* Where to resume */
6892           ptr = substitutes[-c - ESC_DU] - 1;  /* Just before substitute */
6893           }
6894         else
6895 #endif
6896         /* In non-UTF-8 mode, we turn \C into OP_ALLANY instead of OP_ANYBYTE
6897         so that it works in DFA mode and in lookbehinds. */
6898
6899           {
6900           previous = (-c > ESC_b && -c < ESC_Z)? code : NULL;
6901           *code++ = (!utf && c == -ESC_C)? OP_ALLANY : -c;
6902           }
6903         }
6904       continue;
6905       }
6906
6907     /* We have a data character whose value is in c. In UTF-8 mode it may have
6908     a value > 127. We set its representation in the length/buffer, and then
6909     handle it as a data character. */
6910
6911 #ifdef SUPPORT_UTF
6912     if (utf && c > MAX_VALUE_FOR_SINGLE_CHAR)
6913       mclength = PRIV(ord2utf)(c, mcbuffer);
6914     else
6915 #endif
6916
6917      {
6918      mcbuffer[0] = c;
6919      mclength = 1;
6920      }
6921     goto ONE_CHAR;
6922
6923
6924     /* ===================================================================*/
6925     /* Handle a literal character. It is guaranteed not to be whitespace or #
6926     when the extended flag is set. If we are in UTF-8 mode, it may be a
6927     multi-byte literal character. */
6928
6929     default:
6930     NORMAL_CHAR:
6931     mclength = 1;
6932     mcbuffer[0] = c;
6933
6934 #ifdef SUPPORT_UTF
6935     if (utf && HAS_EXTRALEN(c))
6936       ACROSSCHAR(TRUE, ptr[1], mcbuffer[mclength++] = *(++ptr));
6937 #endif
6938
6939     /* At this point we have the character's bytes in mcbuffer, and the length
6940     in mclength. When not in UTF-8 mode, the length is always 1. */
6941
6942     ONE_CHAR:
6943     previous = code;
6944     *code++ = ((options & PCRE_CASELESS) != 0)? OP_CHARI : OP_CHAR;
6945     for (c = 0; c < mclength; c++) *code++ = mcbuffer[c];
6946
6947     /* Remember if \r or \n were seen */
6948
6949     if (mcbuffer[0] == CHAR_CR || mcbuffer[0] == CHAR_NL)
6950       cd->external_flags |= PCRE_HASCRORLF;
6951
6952     /* Set the first and required bytes appropriately. If no previous first
6953     byte, set it from this character, but revert to none on a zero repeat.
6954     Otherwise, leave the firstchar value alone, and don't change it on a zero
6955     repeat. */
6956
6957     if (firstchar == REQ_UNSET)
6958       {
6959       zerofirstchar = REQ_NONE;
6960       zeroreqchar = reqchar;
6961
6962       /* If the character is more than one byte long, we can set firstchar
6963       only if it is not to be matched caselessly. */
6964
6965       if (mclength == 1 || req_caseopt == 0)
6966         {
6967         firstchar = mcbuffer[0] | req_caseopt;
6968         if (mclength != 1) reqchar = code[-1] | cd->req_varyopt;
6969         }
6970       else firstchar = reqchar = REQ_NONE;
6971       }
6972
6973     /* firstchar was previously set; we can set reqchar only if the length is
6974     1 or the matching is caseful. */
6975
6976     else
6977       {
6978       zerofirstchar = firstchar;
6979       zeroreqchar = reqchar;
6980       if (mclength == 1 || req_caseopt == 0)
6981         reqchar = code[-1] | req_caseopt | cd->req_varyopt;
6982       }
6983
6984     break;            /* End of literal character handling */
6985     }
6986   }                   /* end of big loop */
6987
6988
6989 /* Control never reaches here by falling through, only by a goto for all the
6990 error states. Pass back the position in the pattern so that it can be displayed
6991 to the user for diagnosing the error. */
6992
6993 FAILED:
6994 *ptrptr = ptr;
6995 return FALSE;
6996 }
6997
6998
6999
7000
7001 /*************************************************
7002 *     Compile sequence of alternatives           *
7003 *************************************************/
7004
7005 /* On entry, ptr is pointing past the bracket character, but on return it
7006 points to the closing bracket, or vertical bar, or end of string. The code
7007 variable is pointing at the byte into which the BRA operator has been stored.
7008 This function is used during the pre-compile phase when we are trying to find
7009 out the amount of memory needed, as well as during the real compile phase. The
7010 value of lengthptr distinguishes the two phases.
7011
7012 Arguments:
7013   options        option bits, including any changes for this subpattern
7014   codeptr        -> the address of the current code pointer
7015   ptrptr         -> the address of the current pattern pointer
7016   errorcodeptr   -> pointer to error code variable
7017   lookbehind     TRUE if this is a lookbehind assertion
7018   reset_bracount TRUE to reset the count for each branch
7019   skipbytes      skip this many bytes at start (for brackets and OP_COND)
7020   cond_depth     depth of nesting for conditional subpatterns
7021   firstcharptr   place to put the first required character, or a negative number
7022   reqcharptr     place to put the last required character, or a negative number
7023   bcptr          pointer to the chain of currently open branches
7024   cd             points to the data block with tables pointers etc.
7025   lengthptr      NULL during the real compile phase
7026                  points to length accumulator during pre-compile phase
7027
7028 Returns:         TRUE on success
7029 */
7030
7031 static BOOL
7032 compile_regex(int options, pcre_uchar **codeptr, const pcre_uchar **ptrptr,
7033   int *errorcodeptr, BOOL lookbehind, BOOL reset_bracount, int skipbytes,
7034   int cond_depth, pcre_int32 *firstcharptr, pcre_int32 *reqcharptr,
7035   branch_chain *bcptr, compile_data *cd, int *lengthptr)
7036 {
7037 const pcre_uchar *ptr = *ptrptr;
7038 pcre_uchar *code = *codeptr;
7039 pcre_uchar *last_branch = code;
7040 pcre_uchar *start_bracket = code;
7041 pcre_uchar *reverse_count = NULL;
7042 open_capitem capitem;
7043 int capnumber = 0;
7044 pcre_int32 firstchar, reqchar;
7045 pcre_int32 branchfirstchar, branchreqchar;
7046 int length;
7047 int orig_bracount;
7048 int max_bracount;
7049 branch_chain bc;
7050
7051 bc.outer = bcptr;
7052 bc.current_branch = code;
7053
7054 firstchar = reqchar = REQ_UNSET;
7055
7056 /* Accumulate the length for use in the pre-compile phase. Start with the
7057 length of the BRA and KET and any extra bytes that are required at the
7058 beginning. We accumulate in a local variable to save frequent testing of
7059 lenthptr for NULL. We cannot do this by looking at the value of code at the
7060 start and end of each alternative, because compiled items are discarded during
7061 the pre-compile phase so that the work space is not exceeded. */
7062
7063 length = 2 + 2*LINK_SIZE + skipbytes;
7064
7065 /* WARNING: If the above line is changed for any reason, you must also change
7066 the code that abstracts option settings at the start of the pattern and makes
7067 them global. It tests the value of length for (2 + 2*LINK_SIZE) in the
7068 pre-compile phase to find out whether anything has yet been compiled or not. */
7069
7070 /* If this is a capturing subpattern, add to the chain of open capturing items
7071 so that we can detect them if (*ACCEPT) is encountered. This is also used to
7072 detect groups that contain recursive back references to themselves. Note that
7073 only OP_CBRA need be tested here; changing this opcode to one of its variants,
7074 e.g. OP_SCBRAPOS, happens later, after the group has been compiled. */
7075
7076 if (*code == OP_CBRA)
7077   {
7078   capnumber = GET2(code, 1 + LINK_SIZE);
7079   capitem.number = capnumber;
7080   capitem.next = cd->open_caps;
7081   capitem.flag = FALSE;
7082   cd->open_caps = &capitem;
7083   }
7084
7085 /* Offset is set zero to mark that this bracket is still open */
7086
7087 PUT(code, 1, 0);
7088 code += 1 + LINK_SIZE + skipbytes;
7089
7090 /* Loop for each alternative branch */
7091
7092 orig_bracount = max_bracount = cd->bracount;
7093 for (;;)
7094   {
7095   /* For a (?| group, reset the capturing bracket count so that each branch
7096   uses the same numbers. */
7097
7098   if (reset_bracount) cd->bracount = orig_bracount;
7099
7100   /* Set up dummy OP_REVERSE if lookbehind assertion */
7101
7102   if (lookbehind)
7103     {
7104     *code++ = OP_REVERSE;
7105     reverse_count = code;
7106     PUTINC(code, 0, 0);
7107     length += 1 + LINK_SIZE;
7108     }
7109
7110   /* Now compile the branch; in the pre-compile phase its length gets added
7111   into the length. */
7112
7113   if (!compile_branch(&options, &code, &ptr, errorcodeptr, &branchfirstchar,
7114         &branchreqchar, &bc, cond_depth, cd,
7115         (lengthptr == NULL)? NULL : &length))
7116     {
7117     *ptrptr = ptr;
7118     return FALSE;
7119     }
7120
7121   /* Keep the highest bracket count in case (?| was used and some branch
7122   has fewer than the rest. */
7123
7124   if (cd->bracount > max_bracount) max_bracount = cd->bracount;
7125
7126   /* In the real compile phase, there is some post-processing to be done. */
7127
7128   if (lengthptr == NULL)
7129     {
7130     /* If this is the first branch, the firstchar and reqchar values for the
7131     branch become the values for the regex. */
7132
7133     if (*last_branch != OP_ALT)
7134       {
7135       firstchar = branchfirstchar;
7136       reqchar = branchreqchar;
7137       }
7138
7139     /* If this is not the first branch, the first char and reqchar have to
7140     match the values from all the previous branches, except that if the
7141     previous value for reqchar didn't have REQ_VARY set, it can still match,
7142     and we set REQ_VARY for the regex. */
7143
7144     else
7145       {
7146       /* If we previously had a firstchar, but it doesn't match the new branch,
7147       we have to abandon the firstchar for the regex, but if there was
7148       previously no reqchar, it takes on the value of the old firstchar. */
7149
7150       if (firstchar >= 0 && firstchar != branchfirstchar)
7151         {
7152         if (reqchar < 0) reqchar = firstchar;
7153         firstchar = REQ_NONE;
7154         }
7155
7156       /* If we (now or from before) have no firstchar, a firstchar from the
7157       branch becomes a reqchar if there isn't a branch reqchar. */
7158
7159       if (firstchar < 0 && branchfirstchar >= 0 && branchreqchar < 0)
7160           branchreqchar = branchfirstchar;
7161
7162       /* Now ensure that the reqchars match */
7163
7164       if ((reqchar & ~REQ_VARY) != (branchreqchar & ~REQ_VARY))
7165         reqchar = REQ_NONE;
7166       else reqchar |= branchreqchar;   /* To "or" REQ_VARY */
7167       }
7168
7169     /* If lookbehind, check that this branch matches a fixed-length string, and
7170     put the length into the OP_REVERSE item. Temporarily mark the end of the
7171     branch with OP_END. If the branch contains OP_RECURSE, the result is -3
7172     because there may be forward references that we can't check here. Set a
7173     flag to cause another lookbehind check at the end. Why not do it all at the
7174     end? Because common, erroneous checks are picked up here and the offset of
7175     the problem can be shown. */
7176
7177     if (lookbehind)
7178       {
7179       int fixed_length;
7180       *code = OP_END;
7181       fixed_length = find_fixedlength(last_branch,  (options & PCRE_UTF8) != 0,
7182         FALSE, cd);
7183       DPRINTF(("fixed length = %d\n", fixed_length));
7184       if (fixed_length == -3)
7185         {
7186         cd->check_lookbehind = TRUE;
7187         }
7188       else if (fixed_length < 0)
7189         {
7190         *errorcodeptr = (fixed_length == -2)? ERR36 :
7191                         (fixed_length == -4)? ERR70: ERR25;
7192         *ptrptr = ptr;
7193         return FALSE;
7194         }
7195       else
7196         {
7197         if (fixed_length > cd->max_lookbehind)
7198           cd->max_lookbehind = fixed_length;
7199         PUT(reverse_count, 0, fixed_length);
7200         }
7201       }
7202     }
7203
7204   /* Reached end of expression, either ')' or end of pattern. In the real
7205   compile phase, go back through the alternative branches and reverse the chain
7206   of offsets, with the field in the BRA item now becoming an offset to the
7207   first alternative. If there are no alternatives, it points to the end of the
7208   group. The length in the terminating ket is always the length of the whole
7209   bracketed item. Return leaving the pointer at the terminating char. */
7210
7211   if (*ptr != CHAR_VERTICAL_LINE)
7212     {
7213     if (lengthptr == NULL)
7214       {
7215       int branch_length = (int)(code - last_branch);
7216       do
7217         {
7218         int prev_length = GET(last_branch, 1);
7219         PUT(last_branch, 1, branch_length);
7220         branch_length = prev_length;
7221         last_branch -= branch_length;
7222         }
7223       while (branch_length > 0);
7224       }
7225
7226     /* Fill in the ket */
7227
7228     *code = OP_KET;
7229     PUT(code, 1, (int)(code - start_bracket));
7230     code += 1 + LINK_SIZE;
7231
7232     /* If it was a capturing subpattern, check to see if it contained any
7233     recursive back references. If so, we must wrap it in atomic brackets.
7234     In any event, remove the block from the chain. */
7235
7236     if (capnumber > 0)
7237       {
7238       if (cd->open_caps->flag)
7239         {
7240         memmove(start_bracket + 1 + LINK_SIZE, start_bracket,
7241           IN_UCHARS(code - start_bracket));
7242         *start_bracket = OP_ONCE;
7243         code += 1 + LINK_SIZE;
7244         PUT(start_bracket, 1, (int)(code - start_bracket));
7245         *code = OP_KET;
7246         PUT(code, 1, (int)(code - start_bracket));
7247         code += 1 + LINK_SIZE;
7248         length += 2 + 2*LINK_SIZE;
7249         }
7250       cd->open_caps = cd->open_caps->next;
7251       }
7252
7253     /* Retain the highest bracket number, in case resetting was used. */
7254
7255     cd->bracount = max_bracount;
7256
7257     /* Set values to pass back */
7258
7259     *codeptr = code;
7260     *ptrptr = ptr;
7261     *firstcharptr = firstchar;
7262     *reqcharptr = reqchar;
7263     if (lengthptr != NULL)
7264       {
7265       if (OFLOW_MAX - *lengthptr < length)
7266         {
7267         *errorcodeptr = ERR20;
7268         return FALSE;
7269         }
7270       *lengthptr += length;
7271       }
7272     return TRUE;
7273     }
7274
7275   /* Another branch follows. In the pre-compile phase, we can move the code
7276   pointer back to where it was for the start of the first branch. (That is,
7277   pretend that each branch is the only one.)
7278
7279   In the real compile phase, insert an ALT node. Its length field points back
7280   to the previous branch while the bracket remains open. At the end the chain
7281   is reversed. It's done like this so that the start of the bracket has a
7282   zero offset until it is closed, making it possible to detect recursion. */
7283
7284   if (lengthptr != NULL)
7285     {
7286     code = *codeptr + 1 + LINK_SIZE + skipbytes;
7287     length += 1 + LINK_SIZE;
7288     }
7289   else
7290     {
7291     *code = OP_ALT;
7292     PUT(code, 1, (int)(code - last_branch));
7293     bc.current_branch = last_branch = code;
7294     code += 1 + LINK_SIZE;
7295     }
7296
7297   ptr++;
7298   }
7299 /* Control never reaches here */
7300 }
7301
7302
7303
7304
7305 /*************************************************
7306 *          Check for anchored expression         *
7307 *************************************************/
7308
7309 /* Try to find out if this is an anchored regular expression. Consider each
7310 alternative branch. If they all start with OP_SOD or OP_CIRC, or with a bracket
7311 all of whose alternatives start with OP_SOD or OP_CIRC (recurse ad lib), then
7312 it's anchored. However, if this is a multiline pattern, then only OP_SOD will
7313 be found, because ^ generates OP_CIRCM in that mode.
7314
7315 We can also consider a regex to be anchored if OP_SOM starts all its branches.
7316 This is the code for \G, which means "match at start of match position, taking
7317 into account the match offset".
7318
7319 A branch is also implicitly anchored if it starts with .* and DOTALL is set,
7320 because that will try the rest of the pattern at all possible matching points,
7321 so there is no point trying again.... er ....
7322
7323 .... except when the .* appears inside capturing parentheses, and there is a
7324 subsequent back reference to those parentheses. We haven't enough information
7325 to catch that case precisely.
7326
7327 At first, the best we could do was to detect when .* was in capturing brackets
7328 and the highest back reference was greater than or equal to that level.
7329 However, by keeping a bitmap of the first 31 back references, we can catch some
7330 of the more common cases more precisely.
7331
7332 Arguments:
7333   code           points to start of expression (the bracket)
7334   bracket_map    a bitmap of which brackets we are inside while testing; this
7335                   handles up to substring 31; after that we just have to take
7336                   the less precise approach
7337   backref_map    the back reference bitmap
7338
7339 Returns:     TRUE or FALSE
7340 */
7341
7342 static BOOL
7343 is_anchored(const pcre_uchar *code, unsigned int bracket_map,
7344   unsigned int backref_map)
7345 {
7346 do {
7347    const pcre_uchar *scode = first_significant_code(
7348      code + PRIV(OP_lengths)[*code], FALSE);
7349    int op = *scode;
7350
7351    /* Non-capturing brackets */
7352
7353    if (op == OP_BRA  || op == OP_BRAPOS ||
7354        op == OP_SBRA || op == OP_SBRAPOS)
7355      {
7356      if (!is_anchored(scode, bracket_map, backref_map)) return FALSE;
7357      }
7358
7359    /* Capturing brackets */
7360
7361    else if (op == OP_CBRA  || op == OP_CBRAPOS ||
7362             op == OP_SCBRA || op == OP_SCBRAPOS)
7363      {
7364      int n = GET2(scode, 1+LINK_SIZE);
7365      int new_map = bracket_map | ((n < 32)? (1 << n) : 1);
7366      if (!is_anchored(scode, new_map, backref_map)) return FALSE;
7367      }
7368
7369    /* Other brackets */
7370
7371    else if (op == OP_ASSERT || op == OP_ONCE || op == OP_ONCE_NC ||
7372             op == OP_COND)
7373      {
7374      if (!is_anchored(scode, bracket_map, backref_map)) return FALSE;
7375      }
7376
7377    /* .* is not anchored unless DOTALL is set (which generates OP_ALLANY) and
7378    it isn't in brackets that are or may be referenced. */
7379
7380    else if ((op == OP_TYPESTAR || op == OP_TYPEMINSTAR ||
7381              op == OP_TYPEPOSSTAR))
7382      {
7383      if (scode[1] != OP_ALLANY || (bracket_map & backref_map) != 0)
7384        return FALSE;
7385      }
7386
7387    /* Check for explicit anchoring */
7388
7389    else if (op != OP_SOD && op != OP_SOM && op != OP_CIRC) return FALSE;
7390    code += GET(code, 1);
7391    }
7392 while (*code == OP_ALT);   /* Loop for each alternative */
7393 return TRUE;
7394 }
7395
7396
7397
7398 /*************************************************
7399 *         Check for starting with ^ or .*        *
7400 *************************************************/
7401
7402 /* This is called to find out if every branch starts with ^ or .* so that
7403 "first char" processing can be done to speed things up in multiline
7404 matching and for non-DOTALL patterns that start with .* (which must start at
7405 the beginning or after \n). As in the case of is_anchored() (see above), we
7406 have to take account of back references to capturing brackets that contain .*
7407 because in that case we can't make the assumption.
7408
7409 Arguments:
7410   code           points to start of expression (the bracket)
7411   bracket_map    a bitmap of which brackets we are inside while testing; this
7412                   handles up to substring 31; after that we just have to take
7413                   the less precise approach
7414   backref_map    the back reference bitmap
7415
7416 Returns:         TRUE or FALSE
7417 */
7418
7419 static BOOL
7420 is_startline(const pcre_uchar *code, unsigned int bracket_map,
7421   unsigned int backref_map)
7422 {
7423 do {
7424    const pcre_uchar *scode = first_significant_code(
7425      code + PRIV(OP_lengths)[*code], FALSE);
7426    int op = *scode;
7427
7428    /* If we are at the start of a conditional assertion group, *both* the
7429    conditional assertion *and* what follows the condition must satisfy the test
7430    for start of line. Other kinds of condition fail. Note that there may be an
7431    auto-callout at the start of a condition. */
7432
7433    if (op == OP_COND)
7434      {
7435      scode += 1 + LINK_SIZE;
7436      if (*scode == OP_CALLOUT) scode += PRIV(OP_lengths)[OP_CALLOUT];
7437      switch (*scode)
7438        {
7439        case OP_CREF:
7440        case OP_NCREF:
7441        case OP_RREF:
7442        case OP_NRREF:
7443        case OP_DEF:
7444        return FALSE;
7445
7446        default:     /* Assertion */
7447        if (!is_startline(scode, bracket_map, backref_map)) return FALSE;
7448        do scode += GET(scode, 1); while (*scode == OP_ALT);
7449        scode += 1 + LINK_SIZE;
7450        break;
7451        }
7452      scode = first_significant_code(scode, FALSE);
7453      op = *scode;
7454      }
7455
7456    /* Non-capturing brackets */
7457
7458    if (op == OP_BRA  || op == OP_BRAPOS ||
7459        op == OP_SBRA || op == OP_SBRAPOS)
7460      {
7461      if (!is_startline(scode, bracket_map, backref_map)) return FALSE;
7462      }
7463
7464    /* Capturing brackets */
7465
7466    else if (op == OP_CBRA  || op == OP_CBRAPOS ||
7467             op == OP_SCBRA || op == OP_SCBRAPOS)
7468      {
7469      int n = GET2(scode, 1+LINK_SIZE);
7470      int new_map = bracket_map | ((n < 32)? (1 << n) : 1);
7471      if (!is_startline(scode, new_map, backref_map)) return FALSE;
7472      }
7473
7474    /* Other brackets */
7475
7476    else if (op == OP_ASSERT || op == OP_ONCE || op == OP_ONCE_NC)
7477      {
7478      if (!is_startline(scode, bracket_map, backref_map)) return FALSE;
7479      }
7480
7481    /* .* means "start at start or after \n" if it isn't in brackets that
7482    may be referenced. */
7483
7484    else if (op == OP_TYPESTAR || op == OP_TYPEMINSTAR || op == OP_TYPEPOSSTAR)
7485      {
7486      if (scode[1] != OP_ANY || (bracket_map & backref_map) != 0) return FALSE;
7487      }
7488
7489    /* Check for explicit circumflex */
7490
7491    else if (op != OP_CIRC && op != OP_CIRCM) return FALSE;
7492
7493    /* Move on to the next alternative */
7494
7495    code += GET(code, 1);
7496    }
7497 while (*code == OP_ALT);  /* Loop for each alternative */
7498 return TRUE;
7499 }
7500
7501
7502
7503 /*************************************************
7504 *       Check for asserted fixed first char      *
7505 *************************************************/
7506
7507 /* During compilation, the "first char" settings from forward assertions are
7508 discarded, because they can cause conflicts with actual literals that follow.
7509 However, if we end up without a first char setting for an unanchored pattern,
7510 it is worth scanning the regex to see if there is an initial asserted first
7511 char. If all branches start with the same asserted char, or with a bracket all
7512 of whose alternatives start with the same asserted char (recurse ad lib), then
7513 we return that char, otherwise -1.
7514
7515 Arguments:
7516   code       points to start of expression (the bracket)
7517   inassert   TRUE if in an assertion
7518
7519 Returns:     -1 or the fixed first char
7520 */
7521
7522 static int
7523 find_firstassertedchar(const pcre_uchar *code, BOOL inassert)
7524 {
7525 int c = -1;
7526 do {
7527    int d;
7528    int xl = (*code == OP_CBRA || *code == OP_SCBRA ||
7529              *code == OP_CBRAPOS || *code == OP_SCBRAPOS)? IMM2_SIZE:0;
7530    const pcre_uchar *scode = first_significant_code(code + 1+LINK_SIZE + xl,
7531      TRUE);
7532    int op = *scode;
7533
7534    switch(op)
7535      {
7536      default:
7537      return -1;
7538
7539      case OP_BRA:
7540      case OP_BRAPOS:
7541      case OP_CBRA:
7542      case OP_SCBRA:
7543      case OP_CBRAPOS:
7544      case OP_SCBRAPOS:
7545      case OP_ASSERT:
7546      case OP_ONCE:
7547      case OP_ONCE_NC:
7548      case OP_COND:
7549      if ((d = find_firstassertedchar(scode, op == OP_ASSERT)) < 0)
7550        return -1;
7551      if (c < 0) c = d; else if (c != d) return -1;
7552      break;
7553
7554      case OP_EXACT:
7555      scode += IMM2_SIZE;
7556      /* Fall through */
7557
7558      case OP_CHAR:
7559      case OP_PLUS:
7560      case OP_MINPLUS:
7561      case OP_POSPLUS:
7562      if (!inassert) return -1;
7563      if (c < 0) c = scode[1];
7564        else if (c != scode[1]) return -1;
7565      break;
7566
7567      case OP_EXACTI:
7568      scode += IMM2_SIZE;
7569      /* Fall through */
7570
7571      case OP_CHARI:
7572      case OP_PLUSI:
7573      case OP_MINPLUSI:
7574      case OP_POSPLUSI:
7575      if (!inassert) return -1;
7576      if (c < 0) c = scode[1] | REQ_CASELESS;
7577        else if (c != scode[1]) return -1;
7578      break;
7579      }
7580
7581    code += GET(code, 1);
7582    }
7583 while (*code == OP_ALT);
7584 return c;
7585 }
7586
7587
7588
7589 /*************************************************
7590 *        Compile a Regular Expression            *
7591 *************************************************/
7592
7593 /* This function takes a string and returns a pointer to a block of store
7594 holding a compiled version of the expression. The original API for this
7595 function had no error code return variable; it is retained for backwards
7596 compatibility. The new function is given a new name.
7597
7598 Arguments:
7599   pattern       the regular expression
7600   options       various option bits
7601   errorcodeptr  pointer to error code variable (pcre_compile2() only)
7602                   can be NULL if you don't want a code value
7603   errorptr      pointer to pointer to error text
7604   erroroffset   ptr offset in pattern where error was detected
7605   tables        pointer to character tables or NULL
7606
7607 Returns:        pointer to compiled data block, or NULL on error,
7608                 with errorptr and erroroffset set
7609 */
7610
7611 #ifdef COMPILE_PCRE8
7612 PCRE_EXP_DEFN pcre * PCRE_CALL_CONVENTION
7613 pcre_compile(const char *pattern, int options, const char **errorptr,
7614   int *erroroffset, const unsigned char *tables)
7615 #else
7616 PCRE_EXP_DEFN pcre16 * PCRE_CALL_CONVENTION
7617 pcre16_compile(PCRE_SPTR16 pattern, int options, const char **errorptr,
7618   int *erroroffset, const unsigned char *tables)
7619 #endif
7620 {
7621 #ifdef COMPILE_PCRE8
7622 return pcre_compile2(pattern, options, NULL, errorptr, erroroffset, tables);
7623 #else
7624 return pcre16_compile2(pattern, options, NULL, errorptr, erroroffset, tables);
7625 #endif
7626 }
7627
7628
7629 #ifdef COMPILE_PCRE8
7630 PCRE_EXP_DEFN pcre * PCRE_CALL_CONVENTION
7631 pcre_compile2(const char *pattern, int options, int *errorcodeptr,
7632   const char **errorptr, int *erroroffset, const unsigned char *tables)
7633 #else
7634 PCRE_EXP_DEFN pcre16 * PCRE_CALL_CONVENTION
7635 pcre16_compile2(PCRE_SPTR16 pattern, int options, int *errorcodeptr,
7636   const char **errorptr, int *erroroffset, const unsigned char *tables)
7637 #endif
7638 {
7639 REAL_PCRE *re;
7640 int length = 1;  /* For final END opcode */
7641 pcre_int32 firstchar, reqchar;
7642 int newline;
7643 int errorcode = 0;
7644 int skipatstart = 0;
7645 BOOL utf;
7646 size_t size;
7647 pcre_uchar *code;
7648 const pcre_uchar *codestart;
7649 const pcre_uchar *ptr;
7650 compile_data compile_block;
7651 compile_data *cd = &compile_block;
7652
7653 /* This space is used for "compiling" into during the first phase, when we are
7654 computing the amount of memory that is needed. Compiled items are thrown away
7655 as soon as possible, so that a fairly large buffer should be sufficient for
7656 this purpose. The same space is used in the second phase for remembering where
7657 to fill in forward references to subpatterns. That may overflow, in which case
7658 new memory is obtained from malloc(). */
7659
7660 pcre_uchar cworkspace[COMPILE_WORK_SIZE];
7661
7662 /* Set this early so that early errors get offset 0. */
7663
7664 ptr = (const pcre_uchar *)pattern;
7665
7666 /* We can't pass back an error message if errorptr is NULL; I guess the best we
7667 can do is just return NULL, but we can set a code value if there is a code
7668 pointer. */
7669
7670 if (errorptr == NULL)
7671   {
7672   if (errorcodeptr != NULL) *errorcodeptr = 99;
7673   return NULL;
7674   }
7675
7676 *errorptr = NULL;
7677 if (errorcodeptr != NULL) *errorcodeptr = ERR0;
7678
7679 /* However, we can give a message for this error */
7680
7681 if (erroroffset == NULL)
7682   {
7683   errorcode = ERR16;
7684   goto PCRE_EARLY_ERROR_RETURN2;
7685   }
7686
7687 *erroroffset = 0;
7688
7689 /* Set up pointers to the individual character tables */
7690
7691 if (tables == NULL) tables = PRIV(default_tables);
7692 cd->lcc = tables + lcc_offset;
7693 cd->fcc = tables + fcc_offset;
7694 cd->cbits = tables + cbits_offset;
7695 cd->ctypes = tables + ctypes_offset;
7696
7697 /* Check that all undefined public option bits are zero */
7698
7699 if ((options & ~PUBLIC_COMPILE_OPTIONS) != 0)
7700   {
7701   errorcode = ERR17;
7702   goto PCRE_EARLY_ERROR_RETURN;
7703   }
7704
7705 /* Check for global one-time settings at the start of the pattern, and remember
7706 the offset for later. */
7707
7708 while (ptr[skipatstart] == CHAR_LEFT_PARENTHESIS &&
7709        ptr[skipatstart+1] == CHAR_ASTERISK)
7710   {
7711   int newnl = 0;
7712   int newbsr = 0;
7713
7714 #ifdef COMPILE_PCRE8
7715   if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_UTF_RIGHTPAR, 5) == 0)
7716     { skipatstart += 7; options |= PCRE_UTF8; continue; }
7717 #endif
7718 #ifdef COMPILE_PCRE16
7719   if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_UTF_RIGHTPAR, 6) == 0)
7720     { skipatstart += 8; options |= PCRE_UTF16; continue; }
7721 #endif
7722   else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_UCP_RIGHTPAR, 4) == 0)
7723     { skipatstart += 6; options |= PCRE_UCP; continue; }
7724   else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_NO_START_OPT_RIGHTPAR, 13) == 0)
7725     { skipatstart += 15; options |= PCRE_NO_START_OPTIMIZE; continue; }
7726
7727   if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_CR_RIGHTPAR, 3) == 0)
7728     { skipatstart += 5; newnl = PCRE_NEWLINE_CR; }
7729   else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_LF_RIGHTPAR, 3)  == 0)
7730     { skipatstart += 5; newnl = PCRE_NEWLINE_LF; }
7731   else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_CRLF_RIGHTPAR, 5)  == 0)
7732     { skipatstart += 7; newnl = PCRE_NEWLINE_CR + PCRE_NEWLINE_LF; }
7733   else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_ANY_RIGHTPAR, 4) == 0)
7734     { skipatstart += 6; newnl = PCRE_NEWLINE_ANY; }
7735   else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_ANYCRLF_RIGHTPAR, 8) == 0)
7736     { skipatstart += 10; newnl = PCRE_NEWLINE_ANYCRLF; }
7737
7738   else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_BSR_ANYCRLF_RIGHTPAR, 12) == 0)
7739     { skipatstart += 14; newbsr = PCRE_BSR_ANYCRLF; }
7740   else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_BSR_UNICODE_RIGHTPAR, 12) == 0)
7741     { skipatstart += 14; newbsr = PCRE_BSR_UNICODE; }
7742
7743   if (newnl != 0)
7744     options = (options & ~PCRE_NEWLINE_BITS) | newnl;
7745   else if (newbsr != 0)
7746     options = (options & ~(PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE)) | newbsr;
7747   else break;
7748   }
7749
7750 /* PCRE_UTF16 has the same value as PCRE_UTF8. */
7751 utf = (options & PCRE_UTF8) != 0;
7752
7753 /* Can't support UTF unless PCRE has been compiled to include the code. The
7754 return of an error code from PRIV(valid_utf)() is a new feature, introduced in
7755 release 8.13. It is passed back from pcre_[dfa_]exec(), but at the moment is
7756 not used here. */
7757
7758 #ifdef SUPPORT_UTF
7759 if (utf && (options & PCRE_NO_UTF8_CHECK) == 0 &&
7760      (errorcode = PRIV(valid_utf)((PCRE_PUCHAR)pattern, -1, erroroffset)) != 0)
7761   {
7762 #ifdef COMPILE_PCRE8
7763   errorcode = ERR44;
7764 #else
7765   errorcode = ERR74;
7766 #endif
7767   goto PCRE_EARLY_ERROR_RETURN2;
7768   }
7769 #else
7770 if (utf)
7771   {
7772   errorcode = ERR32;
7773   goto PCRE_EARLY_ERROR_RETURN;
7774   }
7775 #endif
7776
7777 /* Can't support UCP unless PCRE has been compiled to include the code. */
7778
7779 #ifndef SUPPORT_UCP
7780 if ((options & PCRE_UCP) != 0)
7781   {
7782   errorcode = ERR67;
7783   goto PCRE_EARLY_ERROR_RETURN;
7784   }
7785 #endif
7786
7787 /* Check validity of \R options. */
7788
7789 if ((options & (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE)) ==
7790      (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE))
7791   {
7792   errorcode = ERR56;
7793   goto PCRE_EARLY_ERROR_RETURN;
7794   }
7795
7796 /* Handle different types of newline. The three bits give seven cases. The
7797 current code allows for fixed one- or two-byte sequences, plus "any" and
7798 "anycrlf". */
7799
7800 switch (options & PCRE_NEWLINE_BITS)
7801   {
7802   case 0: newline = NEWLINE; break;   /* Build-time default */
7803   case PCRE_NEWLINE_CR: newline = CHAR_CR; break;
7804   case PCRE_NEWLINE_LF: newline = CHAR_NL; break;
7805   case PCRE_NEWLINE_CR+
7806        PCRE_NEWLINE_LF: newline = (CHAR_CR << 8) | CHAR_NL; break;
7807   case PCRE_NEWLINE_ANY: newline = -1; break;
7808   case PCRE_NEWLINE_ANYCRLF: newline = -2; break;
7809   default: errorcode = ERR56; goto PCRE_EARLY_ERROR_RETURN;
7810   }
7811
7812 if (newline == -2)
7813   {
7814   cd->nltype = NLTYPE_ANYCRLF;
7815   }
7816 else if (newline < 0)
7817   {
7818   cd->nltype = NLTYPE_ANY;
7819   }
7820 else
7821   {
7822   cd->nltype = NLTYPE_FIXED;
7823   if (newline > 255)
7824     {
7825     cd->nllen = 2;
7826     cd->nl[0] = (newline >> 8) & 255;
7827     cd->nl[1] = newline & 255;
7828     }
7829   else
7830     {
7831     cd->nllen = 1;
7832     cd->nl[0] = newline;
7833     }
7834   }
7835
7836 /* Maximum back reference and backref bitmap. The bitmap records up to 31 back
7837 references to help in deciding whether (.*) can be treated as anchored or not.
7838 */
7839
7840 cd->top_backref = 0;
7841 cd->backref_map = 0;
7842
7843 /* Reflect pattern for debugging output */
7844
7845 DPRINTF(("------------------------------------------------------------------\n"));
7846 #ifdef PCRE_DEBUG
7847 print_puchar(stdout, (PCRE_PUCHAR)pattern);
7848 #endif
7849 DPRINTF(("\n"));
7850
7851 /* Pretend to compile the pattern while actually just accumulating the length
7852 of memory required. This behaviour is triggered by passing a non-NULL final
7853 argument to compile_regex(). We pass a block of workspace (cworkspace) for it
7854 to compile parts of the pattern into; the compiled code is discarded when it is
7855 no longer needed, so hopefully this workspace will never overflow, though there
7856 is a test for its doing so. */
7857
7858 cd->bracount = cd->final_bracount = 0;
7859 cd->names_found = 0;
7860 cd->name_entry_size = 0;
7861 cd->name_table = NULL;
7862 cd->start_code = cworkspace;
7863 cd->hwm = cworkspace;
7864 cd->start_workspace = cworkspace;
7865 cd->workspace_size = COMPILE_WORK_SIZE;
7866 cd->start_pattern = (const pcre_uchar *)pattern;
7867 cd->end_pattern = (const pcre_uchar *)(pattern + STRLEN_UC((const pcre_uchar *)pattern));
7868 cd->req_varyopt = 0;
7869 cd->assert_depth = 0;
7870 cd->max_lookbehind = 0;
7871 cd->external_options = options;
7872 cd->external_flags = 0;
7873 cd->open_caps = NULL;
7874
7875 /* Now do the pre-compile. On error, errorcode will be set non-zero, so we
7876 don't need to look at the result of the function here. The initial options have
7877 been put into the cd block so that they can be changed if an option setting is
7878 found within the regex right at the beginning. Bringing initial option settings
7879 outside can help speed up starting point checks. */
7880
7881 ptr += skipatstart;
7882 code = cworkspace;
7883 *code = OP_BRA;
7884 (void)compile_regex(cd->external_options, &code, &ptr, &errorcode, FALSE,
7885   FALSE, 0, 0, &firstchar, &reqchar, NULL, cd, &length);
7886 if (errorcode != 0) goto PCRE_EARLY_ERROR_RETURN;
7887
7888 DPRINTF(("end pre-compile: length=%d workspace=%d\n", length,
7889   (int)(cd->hwm - cworkspace)));
7890
7891 if (length > MAX_PATTERN_SIZE)
7892   {
7893   errorcode = ERR20;
7894   goto PCRE_EARLY_ERROR_RETURN;
7895   }
7896
7897 /* Compute the size of data block needed and get it, either from malloc or
7898 externally provided function. Integer overflow should no longer be possible
7899 because nowadays we limit the maximum value of cd->names_found and
7900 cd->name_entry_size. */
7901
7902 size = sizeof(REAL_PCRE) + (length + cd->names_found * cd->name_entry_size) * sizeof(pcre_uchar);
7903 re = (REAL_PCRE *)(PUBL(malloc))(size);
7904
7905 if (re == NULL)
7906   {
7907   errorcode = ERR21;
7908   goto PCRE_EARLY_ERROR_RETURN;
7909   }
7910
7911 /* Put in the magic number, and save the sizes, initial options, internal
7912 flags, and character table pointer. NULL is used for the default character
7913 tables. The nullpad field is at the end; it's there to help in the case when a
7914 regex compiled on a system with 4-byte pointers is run on another with 8-byte
7915 pointers. */
7916
7917 re->magic_number = MAGIC_NUMBER;
7918 re->size = (int)size;
7919 re->options = cd->external_options;
7920 re->flags = cd->external_flags;
7921 re->first_char = 0;
7922 re->req_char = 0;
7923 re->name_table_offset = sizeof(REAL_PCRE) / sizeof(pcre_uchar);
7924 re->name_entry_size = cd->name_entry_size;
7925 re->name_count = cd->names_found;
7926 re->ref_count = 0;
7927 re->tables = (tables == PRIV(default_tables))? NULL : tables;
7928 re->nullpad = NULL;
7929
7930 /* The starting points of the name/number translation table and of the code are
7931 passed around in the compile data block. The start/end pattern and initial
7932 options are already set from the pre-compile phase, as is the name_entry_size
7933 field. Reset the bracket count and the names_found field. Also reset the hwm
7934 field; this time it's used for remembering forward references to subpatterns.
7935 */
7936
7937 cd->final_bracount = cd->bracount;  /* Save for checking forward references */
7938 cd->assert_depth = 0;
7939 cd->bracount = 0;
7940 cd->max_lookbehind = 0;
7941 cd->names_found = 0;
7942 cd->name_table = (pcre_uchar *)re + re->name_table_offset;
7943 codestart = cd->name_table + re->name_entry_size * re->name_count;
7944 cd->start_code = codestart;
7945 cd->hwm = (pcre_uchar *)(cd->start_workspace);
7946 cd->req_varyopt = 0;
7947 cd->had_accept = FALSE;
7948 cd->check_lookbehind = FALSE;
7949 cd->open_caps = NULL;
7950
7951 /* Set up a starting, non-extracting bracket, then compile the expression. On
7952 error, errorcode will be set non-zero, so we don't need to look at the result
7953 of the function here. */
7954
7955 ptr = (const pcre_uchar *)pattern + skipatstart;
7956 code = (pcre_uchar *)codestart;
7957 *code = OP_BRA;
7958 (void)compile_regex(re->options, &code, &ptr, &errorcode, FALSE, FALSE, 0, 0,
7959   &firstchar, &reqchar, NULL, cd, NULL);
7960 re->top_bracket = cd->bracount;
7961 re->top_backref = cd->top_backref;
7962 re->max_lookbehind = cd->max_lookbehind;
7963 re->flags = cd->external_flags | PCRE_MODE;
7964
7965 if (cd->had_accept) reqchar = REQ_NONE;   /* Must disable after (*ACCEPT) */
7966
7967 /* If not reached end of pattern on success, there's an excess bracket. */
7968
7969 if (errorcode == 0 && *ptr != 0) errorcode = ERR22;
7970
7971 /* Fill in the terminating state and check for disastrous overflow, but
7972 if debugging, leave the test till after things are printed out. */
7973
7974 *code++ = OP_END;
7975
7976 #ifndef PCRE_DEBUG
7977 if (code - codestart > length) errorcode = ERR23;
7978 #endif
7979
7980 /* Fill in any forward references that are required. There may be repeated
7981 references; optimize for them, as searching a large regex takes time. */
7982
7983 if (cd->hwm > cd->start_workspace)
7984   {
7985   int prev_recno = -1;
7986   const pcre_uchar *groupptr = NULL;
7987   while (errorcode == 0 && cd->hwm > cd->start_workspace)
7988     {
7989     int offset, recno;
7990     cd->hwm -= LINK_SIZE;
7991     offset = GET(cd->hwm, 0);
7992     recno = GET(codestart, offset);
7993     if (recno != prev_recno)
7994       {
7995       groupptr = PRIV(find_bracket)(codestart, utf, recno);
7996       prev_recno = recno;
7997       }
7998     if (groupptr == NULL) errorcode = ERR53;
7999       else PUT(((pcre_uchar *)codestart), offset, (int)(groupptr - codestart));
8000     }
8001   }
8002
8003 /* If the workspace had to be expanded, free the new memory. */
8004
8005 if (cd->workspace_size > COMPILE_WORK_SIZE)
8006   (PUBL(free))((void *)cd->start_workspace);
8007
8008 /* Give an error if there's back reference to a non-existent capturing
8009 subpattern. */
8010
8011 if (errorcode == 0 && re->top_backref > re->top_bracket) errorcode = ERR15;
8012
8013 /* If there were any lookbehind assertions that contained OP_RECURSE
8014 (recursions or subroutine calls), a flag is set for them to be checked here,
8015 because they may contain forward references. Actual recursions can't be fixed
8016 length, but subroutine calls can. It is done like this so that those without
8017 OP_RECURSE that are not fixed length get a diagnosic with a useful offset. The
8018 exceptional ones forgo this. We scan the pattern to check that they are fixed
8019 length, and set their lengths. */
8020
8021 if (cd->check_lookbehind)
8022   {
8023   pcre_uchar *cc = (pcre_uchar *)codestart;
8024
8025   /* Loop, searching for OP_REVERSE items, and process those that do not have
8026   their length set. (Actually, it will also re-process any that have a length
8027   of zero, but that is a pathological case, and it does no harm.) When we find
8028   one, we temporarily terminate the branch it is in while we scan it. */
8029
8030   for (cc = (pcre_uchar *)PRIV(find_bracket)(codestart, utf, -1);
8031        cc != NULL;
8032        cc = (pcre_uchar *)PRIV(find_bracket)(cc, utf, -1))
8033     {
8034     if (GET(cc, 1) == 0)
8035       {
8036       int fixed_length;
8037       pcre_uchar *be = cc - 1 - LINK_SIZE + GET(cc, -LINK_SIZE);
8038       int end_op = *be;
8039       *be = OP_END;
8040       fixed_length = find_fixedlength(cc, (re->options & PCRE_UTF8) != 0, TRUE,
8041         cd);
8042       *be = end_op;
8043       DPRINTF(("fixed length = %d\n", fixed_length));
8044       if (fixed_length < 0)
8045         {
8046         errorcode = (fixed_length == -2)? ERR36 :
8047                     (fixed_length == -4)? ERR70 : ERR25;
8048         break;
8049         }
8050       if (fixed_length > cd->max_lookbehind) cd->max_lookbehind = fixed_length;
8051       PUT(cc, 1, fixed_length);
8052       }
8053     cc += 1 + LINK_SIZE;
8054     }
8055   }
8056
8057 /* Failed to compile, or error while post-processing */
8058
8059 if (errorcode != 0)
8060   {
8061   (PUBL(free))(re);
8062   PCRE_EARLY_ERROR_RETURN:
8063   *erroroffset = (int)(ptr - (const pcre_uchar *)pattern);
8064   PCRE_EARLY_ERROR_RETURN2:
8065   *errorptr = find_error_text(errorcode);
8066   if (errorcodeptr != NULL) *errorcodeptr = errorcode;
8067   return NULL;
8068   }
8069
8070 /* If the anchored option was not passed, set the flag if we can determine that
8071 the pattern is anchored by virtue of ^ characters or \A or anything else (such
8072 as starting with .* when DOTALL is set).
8073
8074 Otherwise, if we know what the first byte has to be, save it, because that
8075 speeds up unanchored matches no end. If not, see if we can set the
8076 PCRE_STARTLINE flag. This is helpful for multiline matches when all branches
8077 start with ^. and also when all branches start with .* for non-DOTALL matches.
8078 */
8079
8080 if ((re->options & PCRE_ANCHORED) == 0)
8081   {
8082   if (is_anchored(codestart, 0, cd->backref_map))
8083     re->options |= PCRE_ANCHORED;
8084   else
8085     {
8086     if (firstchar < 0)
8087       firstchar = find_firstassertedchar(codestart, FALSE);
8088     if (firstchar >= 0)   /* Remove caseless flag for non-caseable chars */
8089       {
8090 #ifdef COMPILE_PCRE8
8091       re->first_char = firstchar & 0xff;
8092 #else
8093 #ifdef COMPILE_PCRE16
8094       re->first_char = firstchar & 0xffff;
8095 #endif
8096 #endif
8097       if ((firstchar & REQ_CASELESS) != 0)
8098         {
8099 #if defined SUPPORT_UCP && !(defined COMPILE_PCRE8)
8100         /* We ignore non-ASCII first chars in 8 bit mode. */
8101         if (utf)
8102           {
8103           if (re->first_char < 128)
8104             {
8105             if (cd->fcc[re->first_char] != re->first_char)
8106               re->flags |= PCRE_FCH_CASELESS;
8107             }
8108           else if (UCD_OTHERCASE(re->first_char) != re->first_char)
8109             re->flags |= PCRE_FCH_CASELESS;
8110           }
8111         else
8112 #endif
8113         if (MAX_255(re->first_char)
8114             && cd->fcc[re->first_char] != re->first_char)
8115           re->flags |= PCRE_FCH_CASELESS;
8116         }
8117
8118       re->flags |= PCRE_FIRSTSET;
8119       }
8120     else if (is_startline(codestart, 0, cd->backref_map))
8121       re->flags |= PCRE_STARTLINE;
8122     }
8123   }
8124
8125 /* For an anchored pattern, we use the "required byte" only if it follows a
8126 variable length item in the regex. Remove the caseless flag for non-caseable
8127 bytes. */
8128
8129 if (reqchar >= 0 &&
8130      ((re->options & PCRE_ANCHORED) == 0 || (reqchar & REQ_VARY) != 0))
8131   {
8132 #ifdef COMPILE_PCRE8
8133   re->req_char = reqchar & 0xff;
8134 #else
8135 #ifdef COMPILE_PCRE16
8136   re->req_char = reqchar & 0xffff;
8137 #endif
8138 #endif
8139   if ((reqchar & REQ_CASELESS) != 0)
8140     {
8141 #if defined SUPPORT_UCP && !(defined COMPILE_PCRE8)
8142     /* We ignore non-ASCII first chars in 8 bit mode. */
8143     if (utf)
8144       {
8145       if (re->req_char < 128)
8146         {
8147         if (cd->fcc[re->req_char] != re->req_char)
8148           re->flags |= PCRE_RCH_CASELESS;
8149         }
8150       else if (UCD_OTHERCASE(re->req_char) != re->req_char)
8151         re->flags |= PCRE_RCH_CASELESS;
8152       }
8153     else
8154 #endif
8155     if (MAX_255(re->req_char) && cd->fcc[re->req_char] != re->req_char)
8156       re->flags |= PCRE_RCH_CASELESS;
8157     }
8158
8159   re->flags |= PCRE_REQCHSET;
8160   }
8161
8162 /* Print out the compiled data if debugging is enabled. This is never the
8163 case when building a production library. */
8164
8165 #ifdef PCRE_DEBUG
8166 printf("Length = %d top_bracket = %d top_backref = %d\n",
8167   length, re->top_bracket, re->top_backref);
8168
8169 printf("Options=%08x\n", re->options);
8170
8171 if ((re->flags & PCRE_FIRSTSET) != 0)
8172   {
8173   pcre_uchar ch = re->first_char;
8174   const char *caseless =
8175     ((re->flags & PCRE_FCH_CASELESS) == 0)? "" : " (caseless)";
8176   if (PRINTABLE(ch)) printf("First char = %c%s\n", ch, caseless);
8177     else printf("First char = \\x%02x%s\n", ch, caseless);
8178   }
8179
8180 if ((re->flags & PCRE_REQCHSET) != 0)
8181   {
8182   pcre_uchar ch = re->req_char;
8183   const char *caseless =
8184     ((re->flags & PCRE_RCH_CASELESS) == 0)? "" : " (caseless)";
8185   if (PRINTABLE(ch)) printf("Req char = %c%s\n", ch, caseless);
8186     else printf("Req char = \\x%02x%s\n", ch, caseless);
8187   }
8188
8189 #ifdef COMPILE_PCRE8
8190 pcre_printint((pcre *)re, stdout, TRUE);
8191 #else
8192 pcre16_printint((pcre *)re, stdout, TRUE);
8193 #endif
8194
8195 /* This check is done here in the debugging case so that the code that
8196 was compiled can be seen. */
8197
8198 if (code - codestart > length)
8199   {
8200   (PUBL(free))(re);
8201   *errorptr = find_error_text(ERR23);
8202   *erroroffset = ptr - (pcre_uchar *)pattern;
8203   if (errorcodeptr != NULL) *errorcodeptr = ERR23;
8204   return NULL;
8205   }
8206 #endif   /* PCRE_DEBUG */
8207
8208 #ifdef COMPILE_PCRE8
8209 return (pcre *)re;
8210 #else
8211 return (pcre16 *)re;
8212 #endif
8213 }
8214
8215 /* End of pcre_compile.c */