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

Contents of /code/trunk/pcre_compile.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 487 - (show annotations) (download)
Wed Jan 6 10:26:55 2010 UTC (4 years, 9 months ago) by ph10
File MIME type: text/plain
File size: 220451 byte(s)
Tidying updates for 8.01-RC1 release.

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