Debian Codegraph @

quickjs/libregexp.c

raw symbols SCIP
1 /*
2 * Regular Expression Engine
3 *
4 * Copyright (c) 2017-2018 Fabrice Bellard
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <stdarg.h>
27 #include <inttypes.h>
28 #include <string.h>
29 #include <assert.h>
30
31 #include "cutils.h"
32 #include "libregexp.h"
33
34 /*
35 TODO:
36
37 - Add a lock step execution mode (=linear time execution guaranteed)
38 when the regular expression is "simple" i.e. no backreference nor
39 complicated lookahead. The opcodes are designed for this execution
40 model.
41 */
42
43 #if defined(TEST)
44 #define DUMP_REOP
45 #endif
46
47 typedef enum {
48 #define DEF(id, size) REOP_ ## id,
49 #include "libregexp-opcode.h"
50 #undef DEF
51 REOP_COUNT,
52 } REOPCodeEnum;
53
54 #define CAPTURE_COUNT_MAX 255
55 #define STACK_SIZE_MAX 255
56
57 /* unicode code points */
58 #define CP_LS 0x2028
59 #define CP_PS 0x2029
60
61 #define TMP_BUF_SIZE 128
62
63 typedef struct {
64 DynBuf byte_code;
65 const uint8_t *buf_ptr;
66 const uint8_t *buf_end;
67 const uint8_t *buf_start;
68 int re_flags;
69 BOOL is_utf16;
70 BOOL ignore_case;
71 BOOL dotall;
72 int capture_count;
73 int total_capture_count; /* -1 = not computed yet */
74 int has_named_captures; /* -1 = don't know, 0 = no, 1 = yes */
75 void *opaque;
76 DynBuf group_names;
77 union {
78 char error_msg[TMP_BUF_SIZE];
79 char tmp_buf[TMP_BUF_SIZE];
80 } u;
81 } REParseState;
82
83 typedef struct {
84 #ifdef DUMP_REOP
85 const char *name;
86 #endif
87 uint8_t size;
88 } REOpCode;
89
90 static const REOpCode reopcode_info[REOP_COUNT] = {
91 #ifdef DUMP_REOP
92 #define DEF(id, size) { #id, size },
93 #else
94 #define DEF(id, size) { size },
95 #endif
96 #include "libregexp-opcode.h"
97 #undef DEF
98 };
99
100 #define RE_HEADER_FLAGS 0
101 #define RE_HEADER_CAPTURE_COUNT 1
102 #define RE_HEADER_STACK_SIZE 2
103
104 #define RE_HEADER_LEN 7
105
106 static inline int is_digit(int c) {
107 return c >= '0' && c <= '9';
108 }
109
110 /* insert 'len' bytes at position 'pos'. Return < 0 if error. */
111 static int dbuf_insert(DynBuf *s, int pos, int len)
112 {
113 if (dbuf_realloc(s, s->size + len))
114 return -1;
115 memmove(s->buf + pos + len, s->buf + pos, s->size - pos);
116 s->size += len;
117 return 0;
118 }
119
120 static const uint16_t char_range_d[] = {
121 1,
122 0x0030, 0x0039 + 1,
123 };
124
125 /* code point ranges for Zs,Zl or Zp property */
126 static const uint16_t char_range_s[] = {
127 10,
128 0x0009, 0x000D + 1,
129 0x0020, 0x0020 + 1,
130 0x00A0, 0x00A0 + 1,
131 0x1680, 0x1680 + 1,
132 0x2000, 0x200A + 1,
133 /* 2028;LINE SEPARATOR;Zl;0;WS;;;;;N;;;;; */
134 /* 2029;PARAGRAPH SEPARATOR;Zp;0;B;;;;;N;;;;; */
135 0x2028, 0x2029 + 1,
136 0x202F, 0x202F + 1,
137 0x205F, 0x205F + 1,
138 0x3000, 0x3000 + 1,
139 /* FEFF;ZERO WIDTH NO-BREAK SPACE;Cf;0;BN;;;;;N;BYTE ORDER MARK;;;; */
140 0xFEFF, 0xFEFF + 1,
141 };
142
143 BOOL lre_is_space(int c)
144 {
145 int i, n, low, high;
146 n = (countof(char_range_s) - 1) / 2;
147 for(i = 0; i < n; i++) {
148 low = char_range_s[2 * i + 1];
149 if (c < low)
150 return FALSE;
151 high = char_range_s[2 * i + 2];
152 if (c < high)
153 return TRUE;
154 }
155 return FALSE;
156 }
157
158 uint32_t const lre_id_start_table_ascii[4] = {
159 /* $ A-Z _ a-z */
160 0x00000000, 0x00000010, 0x87FFFFFE, 0x07FFFFFE
161 };
162
163 uint32_t const lre_id_continue_table_ascii[4] = {
164 /* $ 0-9 A-Z _ a-z */
165 0x00000000, 0x03FF0010, 0x87FFFFFE, 0x07FFFFFE
166 };
167
168
169 static const uint16_t char_range_w[] = {
170 4,
171 0x0030, 0x0039 + 1,
172 0x0041, 0x005A + 1,
173 0x005F, 0x005F + 1,
174 0x0061, 0x007A + 1,
175 };
176
177 #define CLASS_RANGE_BASE 0x40000000
178
179 typedef enum {
180 CHAR_RANGE_d,
181 CHAR_RANGE_D,
182 CHAR_RANGE_s,
183 CHAR_RANGE_S,
184 CHAR_RANGE_w,
185 CHAR_RANGE_W,
186 } CharRangeEnum;
187
188 static const uint16_t *char_range_table[] = {
189 char_range_d,
190 char_range_s,
191 char_range_w,
192 };
193
194 static int cr_init_char_range(REParseState *s, CharRange *cr, uint32_t c)
195 {
196 BOOL invert;
197 const uint16_t *c_pt;
198 int len, i;
199
200 invert = c & 1;
201 c_pt = char_range_table[c >> 1];
202 len = *c_pt++;
203 cr_init(cr, s->opaque, lre_realloc);
204 for(i = 0; i < len * 2; i++) {
205 if (cr_add_point(cr, c_pt[i]))
206 goto fail;
207 }
208 if (invert) {
209 if (cr_invert(cr))
210 goto fail;
211 }
212 return 0;
213 fail:
214 cr_free(cr);
215 return -1;
216 }
217
218 #ifdef DUMP_REOP
219 static __maybe_unused void lre_dump_bytecode(const uint8_t *buf,
220 int buf_len)
221 {
222 int pos, len, opcode, bc_len, re_flags, i;
223 uint32_t val;
224
225 assert(buf_len >= RE_HEADER_LEN);
226
227 re_flags= buf[0];
228 bc_len = get_u32(buf + 3);
229 assert(bc_len + RE_HEADER_LEN <= buf_len);
230 printf("flags: 0x%x capture_count=%d stack_size=%d\n",
231 re_flags, buf[1], buf[2]);
232 if (re_flags & LRE_FLAG_NAMED_GROUPS) {
233 const char *p;
234 p = (char *)buf + RE_HEADER_LEN + bc_len;
235 printf("named groups: ");
236 for(i = 1; i < buf[1]; i++) {
237 if (i != 1)
238 printf(",");
239 printf("<%s>", p);
240 p += strlen(p) + 1;
241 }
242 printf("\n");
243 assert(p == (char *)(buf + buf_len));
244 }
245 printf("bytecode_len=%d\n", bc_len);
246
247 buf += RE_HEADER_LEN;
248 pos = 0;
249 while (pos < bc_len) {
250 printf("%5u: ", pos);
251 opcode = buf[pos];
252 len = reopcode_info[opcode].size;
253 if (opcode >= REOP_COUNT) {
254 printf(" invalid opcode=0x%02x\n", opcode);
255 break;
256 }
257 if ((pos + len) > bc_len) {
258 printf(" buffer overflow (opcode=0x%02x)\n", opcode);
259 break;
260 }
261 printf("%s", reopcode_info[opcode].name);
262 switch(opcode) {
263 case REOP_char:
264 val = get_u16(buf + pos + 1);
265 if (val >= ' ' && val <= 126)
266 printf(" '%c'", val);
267 else
268 printf(" 0x%04x", val);
269 break;
270 case REOP_char32:
271 val = get_u32(buf + pos + 1);
272 if (val >= ' ' && val <= 126)
273 printf(" '%c'", val);
274 else
275 printf(" 0x%08x", val);
276 break;
277 case REOP_goto:
278 case REOP_split_goto_first:
279 case REOP_split_next_first:
280 case REOP_loop:
281 case REOP_lookahead:
282 case REOP_negative_lookahead:
283 val = get_u32(buf + pos + 1);
284 val += (pos + 5);
285 printf(" %u", val);
286 break;
287 case REOP_simple_greedy_quant:
288 printf(" %u %u %u %u",
289 get_u32(buf + pos + 1) + (pos + 17),
290 get_u32(buf + pos + 1 + 4),
291 get_u32(buf + pos + 1 + 8),
292 get_u32(buf + pos + 1 + 12));
293 break;
294 case REOP_save_start:
295 case REOP_save_end:
296 case REOP_back_reference:
297 case REOP_backward_back_reference:
298 printf(" %u", buf[pos + 1]);
299 break;
300 case REOP_save_reset:
301 printf(" %u %u", buf[pos + 1], buf[pos + 2]);
302 break;
303 case REOP_push_i32:
304 val = get_u32(buf + pos + 1);
305 printf(" %d", val);
306 break;
307 case REOP_range:
308 {
309 int n, i;
310 n = get_u16(buf + pos + 1);
311 len += n * 4;
312 for(i = 0; i < n * 2; i++) {
313 val = get_u16(buf + pos + 3 + i * 2);
314 printf(" 0x%04x", val);
315 }
316 }
317 break;
318 case REOP_range32:
319 {
320 int n, i;
321 n = get_u16(buf + pos + 1);
322 len += n * 8;
323 for(i = 0; i < n * 2; i++) {
324 val = get_u32(buf + pos + 3 + i * 4);
325 printf(" 0x%08x", val);
326 }
327 }
328 break;
329 default:
330 break;
331 }
332 printf("\n");
333 pos += len;
334 }
335 }
336 #endif
337
338 static void re_emit_op(REParseState *s, int op)
339 {
340 dbuf_putc(&s->byte_code, op);
341 }
342
343 /* return the offset of the u32 value */
344 static int re_emit_op_u32(REParseState *s, int op, uint32_t val)
345 {
346 int pos;
347 dbuf_putc(&s->byte_code, op);
348 pos = s->byte_code.size;
349 dbuf_put_u32(&s->byte_code, val);
350 return pos;
351 }
352
353 static int re_emit_goto(REParseState *s, int op, uint32_t val)
354 {
355 int pos;
356 dbuf_putc(&s->byte_code, op);
357 pos = s->byte_code.size;
358 dbuf_put_u32(&s->byte_code, val - (pos + 4));
359 return pos;
360 }
361
362 static void re_emit_op_u8(REParseState *s, int op, uint32_t val)
363 {
364 dbuf_putc(&s->byte_code, op);
365 dbuf_putc(&s->byte_code, val);
366 }
367
368 static void re_emit_op_u16(REParseState *s, int op, uint32_t val)
369 {
370 dbuf_putc(&s->byte_code, op);
371 dbuf_put_u16(&s->byte_code, val);
372 }
373
374 static int __attribute__((format(printf, 2, 3))) re_parse_error(REParseState *s, const char *fmt, ...)
375 {
376 va_list ap;
377 va_start(ap, fmt);
378 vsnprintf(s->u.error_msg, sizeof(s->u.error_msg), fmt, ap);
379 va_end(ap);
380 return -1;
381 }
382
383 static int re_parse_out_of_memory(REParseState *s)
384 {
385 return re_parse_error(s, "out of memory");
386 }
387
388 /* If allow_overflow is false, return -1 in case of
389 overflow. Otherwise return INT32_MAX. */
390 static int parse_digits(const uint8_t **pp, BOOL allow_overflow)
391 {
392 const uint8_t *p;
393 uint64_t v;
394 int c;
395
396 p = *pp;
397 v = 0;
398 for(;;) {
399 c = *p;
400 if (c < '0' || c > '9')
401 break;
402 v = v * 10 + c - '0';
403 if (v >= INT32_MAX) {
404 if (allow_overflow)
405 v = INT32_MAX;
406 else
407 return -1;
408 }
409 p++;
410 }
411 *pp = p;
412 return v;
413 }
414
415 static int re_parse_expect(REParseState *s, const uint8_t **pp, int c)
416 {
417 const uint8_t *p;
418 p = *pp;
419 if (*p != c)
420 return re_parse_error(s, "expecting '%c'", c);
421 p++;
422 *pp = p;
423 return 0;
424 }
425
426 /* Parse an escape sequence, *pp points after the '\':
427 allow_utf16 value:
428 0 : no UTF-16 escapes allowed
429 1 : UTF-16 escapes allowed
430 2 : UTF-16 escapes allowed and escapes of surrogate pairs are
431 converted to a unicode character (unicode regexp case).
432
433 Return the unicode char and update *pp if recognized,
434 return -1 if malformed escape,
435 return -2 otherwise. */
436 int lre_parse_escape(const uint8_t **pp, int allow_utf16)
437 {
438 const uint8_t *p;
439 uint32_t c;
440
441 p = *pp;
442 c = *p++;
443 switch(c) {
444 case 'b':
445 c = '\b';
446 break;
447 case 'f':
448 c = '\f';
449 break;
450 case 'n':
451 c = '\n';
452 break;
453 case 'r':
454 c = '\r';
455 break;
456 case 't':
457 c = '\t';
458 break;
459 case 'v':
460 c = '\v';
461 break;
462 case 'x':
463 case 'u':
464 {
465 int h, n, i;
466 uint32_t c1;
467
468 if (*p == '{' && allow_utf16) {
469 p++;
470 c = 0;
471 for(;;) {
472 h = from_hex(*p++);
473 if (h < 0)
474 return -1;
475 c = (c << 4) | h;
476 if (c > 0x10FFFF)
477 return -1;
478 if (*p == '}')
479 break;
480 }
481 p++;
482 } else {
483 if (c == 'x') {
484 n = 2;
485 } else {
486 n = 4;
487 }
488
489 c = 0;
490 for(i = 0; i < n; i++) {
491 h = from_hex(*p++);
492 if (h < 0) {
493 return -1;
494 }
495 c = (c << 4) | h;
496 }
497 if (c >= 0xd800 && c < 0xdc00 &&
498 allow_utf16 == 2 && p[0] == '\\' && p[1] == 'u') {
499 /* convert an escaped surrogate pair into a
500 unicode char */
501 c1 = 0;
502 for(i = 0; i < 4; i++) {
503 h = from_hex(p[2 + i]);
504 if (h < 0)
505 break;
506 c1 = (c1 << 4) | h;
507 }
508 if (i == 4 && c1 >= 0xdc00 && c1 < 0xe000) {
509 p += 6;
510 c = (((c & 0x3ff) << 10) | (c1 & 0x3ff)) + 0x10000;
511 }
512 }
513 }
514 }
515 break;
516 case '0': case '1': case '2': case '3':
517 case '4': case '5': case '6': case '7':
518 c -= '0';
519 if (allow_utf16 == 2) {
520 /* only accept \0 not followed by digit */
521 if (c != 0 || is_digit(*p))
522 return -1;
523 } else {
524 /* parse a legacy octal sequence */
525 uint32_t v;
526 v = *p - '0';
527 if (v > 7)
528 break;
529 c = (c << 3) | v;
530 p++;
531 if (c >= 32)
532 break;
533 v = *p - '0';
534 if (v > 7)
535 break;
536 c = (c << 3) | v;
537 p++;
538 }
539 break;
540 default:
541 return -2;
542 }
543 *pp = p;
544 return c;
545 }
546
547 #ifdef CONFIG_ALL_UNICODE
548 /* XXX: we use the same chars for name and value */
549 static BOOL is_unicode_char(int c)
550 {
551 return ((c >= '0' && c <= '9') ||
552 (c >= 'A' && c <= 'Z') ||
553 (c >= 'a' && c <= 'z') ||
554 (c == '_'));
555 }
556
557 static int parse_unicode_property(REParseState *s, CharRange *cr,
558 const uint8_t **pp, BOOL is_inv)
559 {
560 const uint8_t *p;
561 char name[64], value[64];
562 char *q;
563 BOOL script_ext;
564 int ret;
565
566 p = *pp;
567 if (*p != '{')
568 return re_parse_error(s, "expecting '{' after \\p");
569 p++;
570 q = name;
571 while (is_unicode_char(*p)) {
572 if ((q - name) >= sizeof(name) - 1)
573 goto unknown_property_name;
574 *q++ = *p++;
575 }
576 *q = '\0';
577 q = value;
578 if (*p == '=') {
579 p++;
580 while (is_unicode_char(*p)) {
581 if ((q - value) >= sizeof(value) - 1)
582 return re_parse_error(s, "unknown unicode property value");
583 *q++ = *p++;
584 }
585 }
586 *q = '\0';
587 if (*p != '}')
588 return re_parse_error(s, "expecting '}'");
589 p++;
590 // printf("name=%s value=%s\n", name, value);
591
592 if (!strcmp(name, "Script") || !strcmp(name, "sc")) {
593 script_ext = FALSE;
594 goto do_script;
595 } else if (!strcmp(name, "Script_Extensions") || !strcmp(name, "scx")) {
596 script_ext = TRUE;
597 do_script:
598 cr_init(cr, s->opaque, lre_realloc);
599 ret = unicode_script(cr, value, script_ext);
600 if (ret) {
601 cr_free(cr);
602 if (ret == -2)
603 return re_parse_error(s, "unknown unicode script");
604 else
605 goto out_of_memory;
606 }
607 } else if (!strcmp(name, "General_Category") || !strcmp(name, "gc")) {
608 cr_init(cr, s->opaque, lre_realloc);
609 ret = unicode_general_category(cr, value);
610 if (ret) {
611 cr_free(cr);
612 if (ret == -2)
613 return re_parse_error(s, "unknown unicode general category");
614 else
615 goto out_of_memory;
616 }
617 } else if (value[0] == '\0') {
618 cr_init(cr, s->opaque, lre_realloc);
619 ret = unicode_general_category(cr, name);
620 if (ret == -1) {
621 cr_free(cr);
622 goto out_of_memory;
623 }
624 if (ret < 0) {
625 ret = unicode_prop(cr, name);
626 if (ret) {
627 cr_free(cr);
628 if (ret == -2)
629 goto unknown_property_name;
630 else
631 goto out_of_memory;
632 }
633 }
634 } else {
635 unknown_property_name:
636 return re_parse_error(s, "unknown unicode property name");
637 }
638
639 if (is_inv) {
640 if (cr_invert(cr)) {
641 cr_free(cr);
642 return -1;
643 }
644 }
645 *pp = p;
646 return 0;
647 out_of_memory:
648 return re_parse_out_of_memory(s);
649 }
650 #endif /* CONFIG_ALL_UNICODE */
651
652 /* return -1 if error otherwise the character or a class range
653 (CLASS_RANGE_BASE). In case of class range, 'cr' is
654 initialized. Otherwise, it is ignored. */
655 static int get_class_atom(REParseState *s, CharRange *cr,
656 const uint8_t **pp, BOOL inclass)
657 {
658 const uint8_t *p;
659 uint32_t c;
660 int ret;
661
662 p = *pp;
663
664 c = *p;
665 switch(c) {
666 case '\\':
667 p++;
668 if (p >= s->buf_end)
669 goto unexpected_end;
670 c = *p++;
671 switch(c) {
672 case 'd':
673 c = CHAR_RANGE_d;
674 goto class_range;
675 case 'D':
676 c = CHAR_RANGE_D;
677 goto class_range;
678 case 's':
679 c = CHAR_RANGE_s;
680 goto class_range;
681 case 'S':
682 c = CHAR_RANGE_S;
683 goto class_range;
684 case 'w':
685 c = CHAR_RANGE_w;
686 goto class_range;
687 case 'W':
688 c = CHAR_RANGE_W;
689 class_range:
690 if (cr_init_char_range(s, cr, c))
691 return -1;
692 c = CLASS_RANGE_BASE;
693 break;
694 case 'c':
695 c = *p;
696 if ((c >= 'a' && c <= 'z') ||
697 (c >= 'A' && c <= 'Z') ||
698 (((c >= '0' && c <= '9') || c == '_') &&
699 inclass && !s->is_utf16)) { /* Annex B.1.4 */
700 c &= 0x1f;
701 p++;
702 } else if (s->is_utf16) {
703 goto invalid_escape;
704 } else {
705 /* otherwise return '\' and 'c' */
706 p--;
707 c = '\\';
708 }
709 break;
710 #ifdef CONFIG_ALL_UNICODE
711 case 'p':
712 case 'P':
713 if (s->is_utf16) {
714 if (parse_unicode_property(s, cr, &p, (c == 'P')))
715 return -1;
716 c = CLASS_RANGE_BASE;
717 break;
718 }
719 /* fall thru */
720 #endif
721 default:
722 p--;
723 ret = lre_parse_escape(&p, s->is_utf16 * 2);
724 if (ret >= 0) {
725 c = ret;
726 } else {
727 if (ret == -2 && *p != '\0' && strchr("^$\\.*+?()[]{}|/", *p)) {
728 /* always valid to escape these characters */
729 goto normal_char;
730 } else if (s->is_utf16) {
731 invalid_escape:
732 return re_parse_error(s, "invalid escape sequence in regular expression");
733 } else {
734 /* just ignore the '\' */
735 goto normal_char;
736 }
737 }
738 break;
739 }
740 break;
741 case '\0':
742 if (p >= s->buf_end) {
743 unexpected_end:
744 return re_parse_error(s, "unexpected end");
745 }
746 /* fall thru */
747 default:
748 normal_char:
749 /* normal char */
750 if (c >= 128) {
751 c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p);
752 if ((unsigned)c > 0xffff && !s->is_utf16) {
753 /* XXX: should handle non BMP-1 code points */
754 return re_parse_error(s, "malformed unicode char");
755 }
756 } else {
757 p++;
758 }
759 break;
760 }
761 *pp = p;
762 return c;
763 }
764
765 static int re_emit_range(REParseState *s, const CharRange *cr)
766 {
767 int len, i;
768 uint32_t high;
769
770 len = (unsigned)cr->len / 2;
771 if (len >= 65535)
772 return re_parse_error(s, "too many ranges");
773 if (len == 0) {
774 /* not sure it can really happen. Emit a match that is always
775 false */
776 re_emit_op_u32(s, REOP_char32, -1);
777 } else {
778 high = cr->points[cr->len - 1];
779 if (high == UINT32_MAX)
780 high = cr->points[cr->len - 2];
781 if (high <= 0xffff) {
782 /* can use 16 bit ranges with the conversion that 0xffff =
783 infinity */
784 re_emit_op_u16(s, REOP_range, len);
785 for(i = 0; i < cr->len; i += 2) {
786 dbuf_put_u16(&s->byte_code, cr->points[i]);
787 high = cr->points[i + 1] - 1;
788 if (high == UINT32_MAX - 1)
789 high = 0xffff;
790 dbuf_put_u16(&s->byte_code, high);
791 }
792 } else {
793 re_emit_op_u16(s, REOP_range32, len);
794 for(i = 0; i < cr->len; i += 2) {
795 dbuf_put_u32(&s->byte_code, cr->points[i]);
796 dbuf_put_u32(&s->byte_code, cr->points[i + 1] - 1);
797 }
798 }
799 }
800 return 0;
801 }
802
803 static int re_parse_char_class(REParseState *s, const uint8_t **pp)
804 {
805 const uint8_t *p;
806 uint32_t c1, c2;
807 CharRange cr_s, *cr = &cr_s;
808 CharRange cr1_s, *cr1 = &cr1_s;
809 BOOL invert;
810
811 cr_init(cr, s->opaque, lre_realloc);
812 p = *pp;
813 p++; /* skip '[' */
814 invert = FALSE;
815 if (*p == '^') {
816 p++;
817 invert = TRUE;
818 }
819 for(;;) {
820 if (*p == ']')
821 break;
822 c1 = get_class_atom(s, cr1, &p, TRUE);
823 if ((int)c1 < 0)
824 goto fail;
825 if (*p == '-' && p[1] != ']') {
826 const uint8_t *p0 = p + 1;
827 if (c1 >= CLASS_RANGE_BASE) {
828 if (s->is_utf16) {
829 cr_free(cr1);
830 goto invalid_class_range;
831 }
832 /* Annex B: match '-' character */
833 goto class_atom;
834 }
835 c2 = get_class_atom(s, cr1, &p0, TRUE);
836 if ((int)c2 < 0)
837 goto fail;
838 if (c2 >= CLASS_RANGE_BASE) {
839 cr_free(cr1);
840 if (s->is_utf16) {
841 goto invalid_class_range;
842 }
843 /* Annex B: match '-' character */
844 goto class_atom;
845 }
846 p = p0;
847 if (c2 < c1) {
848 invalid_class_range:
849 re_parse_error(s, "invalid class range");
850 goto fail;
851 }
852 if (cr_union_interval(cr, c1, c2))
853 goto memory_error;
854 } else {
855 class_atom:
856 if (c1 >= CLASS_RANGE_BASE) {
857 int ret;
858 ret = cr_union1(cr, cr1->points, cr1->len);
859 cr_free(cr1);
860 if (ret)
861 goto memory_error;
862 } else {
863 if (cr_union_interval(cr, c1, c1))
864 goto memory_error;
865 }
866 }
867 }
868 if (s->ignore_case) {
869 if (cr_regexp_canonicalize(cr, s->is_utf16))
870 goto memory_error;
871 }
872 if (invert) {
873 if (cr_invert(cr))
874 goto memory_error;
875 }
876 if (re_emit_range(s, cr))
877 goto fail;
878 cr_free(cr);
879 p++; /* skip ']' */
880 *pp = p;
881 return 0;
882 memory_error:
883 re_parse_out_of_memory(s);
884 fail:
885 cr_free(cr);
886 return -1;
887 }
888
889 /* Return:
890 - true if the opcodes may not advance the char pointer
891 - false if the opcodes always advance the char pointer
892 */
893 static BOOL re_need_check_advance(const uint8_t *bc_buf, int bc_buf_len)
894 {
895 int pos, opcode, len;
896 uint32_t val;
897 BOOL ret;
898
899 ret = TRUE;
900 pos = 0;
901 while (pos < bc_buf_len) {
902 opcode = bc_buf[pos];
903 len = reopcode_info[opcode].size;
904 switch(opcode) {
905 case REOP_range:
906 val = get_u16(bc_buf + pos + 1);
907 len += val * 4;
908 goto simple_char;
909 case REOP_range32:
910 val = get_u16(bc_buf + pos + 1);
911 len += val * 8;
912 goto simple_char;
913 case REOP_char:
914 case REOP_char32:
915 case REOP_dot:
916 case REOP_any:
917 simple_char:
918 ret = FALSE;
919 break;
920 case REOP_line_start:
921 case REOP_line_end:
922 case REOP_push_i32:
923 case REOP_push_char_pos:
924 case REOP_drop:
925 case REOP_word_boundary:
926 case REOP_not_word_boundary:
927 case REOP_prev:
928 /* no effect */
929 break;
930 case REOP_save_start:
931 case REOP_save_end:
932 case REOP_save_reset:
933 case REOP_back_reference:
934 case REOP_backward_back_reference:
935 break;
936 default:
937 /* safe behvior: we cannot predict the outcome */
938 return TRUE;
939 }
940 pos += len;
941 }
942 return ret;
943 }
944
945 /* return -1 if a simple quantifier cannot be used. Otherwise return
946 the number of characters in the atom. */
947 static int re_is_simple_quantifier(const uint8_t *bc_buf, int bc_buf_len)
948 {
949 int pos, opcode, len, count;
950 uint32_t val;
951
952 count = 0;
953 pos = 0;
954 while (pos < bc_buf_len) {
955 opcode = bc_buf[pos];
956 len = reopcode_info[opcode].size;
957 switch(opcode) {
958 case REOP_range:
959 val = get_u16(bc_buf + pos + 1);
960 len += val * 4;
961 goto simple_char;
962 case REOP_range32:
963 val = get_u16(bc_buf + pos + 1);
964 len += val * 8;
965 goto simple_char;
966 case REOP_char:
967 case REOP_char32:
968 case REOP_dot:
969 case REOP_any:
970 simple_char:
971 count++;
972 break;
973 case REOP_line_start:
974 case REOP_line_end:
975 case REOP_word_boundary:
976 case REOP_not_word_boundary:
977 break;
978 default:
979 return -1;
980 }
981 pos += len;
982 }
983 return count;
984 }
985
986 /* '*pp' is the first char after '<' */
987 static int re_parse_group_name(char *buf, int buf_size, const uint8_t **pp)
988 {
989 const uint8_t *p, *p1;
990 uint32_t c, d;
991 char *q;
992
993 p = *pp;
994 q = buf;
995 for(;;) {
996 c = *p;
997 if (c == '\\') {
998 p++;
999 if (*p != 'u')
1000 return -1;
1001 c = lre_parse_escape(&p, 2); // accept surrogate pairs
1002 } else if (c == '>') {
1003 break;
1004 } else if (c >= 128) {
1005 c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p);
1006 if (c >= 0xD800 && c <= 0xDBFF) {
1007 d = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p1);
1008 if (d >= 0xDC00 && d <= 0xDFFF) {
1009 c = 0x10000 + 0x400 * (c - 0xD800) + (d - 0xDC00);
1010 p = p1;
1011 }
1012 }
1013 } else {
1014 p++;
1015 }
1016 if (c > 0x10FFFF)
1017 return -1;
1018 if (q == buf) {
1019 if (!lre_js_is_ident_first(c))
1020 return -1;
1021 } else {
1022 if (!lre_js_is_ident_next(c))
1023 return -1;
1024 }
1025 if ((q - buf + UTF8_CHAR_LEN_MAX + 1) > buf_size)
1026 return -1;
1027 if (c < 128) {
1028 *q++ = c;
1029 } else {
1030 q += unicode_to_utf8((uint8_t*)q, c);
1031 }
1032 }
1033 if (q == buf)
1034 return -1;
1035 *q = '\0';
1036 p++;
1037 *pp = p;
1038 return 0;
1039 }
1040
1041 /* if capture_name = NULL: return the number of captures + 1.
1042 Otherwise, return the capture index corresponding to capture_name
1043 or -1 if none */
1044 static int re_parse_captures(REParseState *s, int *phas_named_captures,
1045 const char *capture_name)
1046 {
1047 const uint8_t *p;
1048 int capture_index;
1049 char name[TMP_BUF_SIZE];
1050
1051 capture_index = 1;
1052 *phas_named_captures = 0;
1053 for (p = s->buf_start; p < s->buf_end; p++) {
1054 switch (*p) {
1055 case '(':
1056 if (p[1] == '?') {
1057 if (p[2] == '<' && p[3] != '=' && p[3] != '!') {
1058 *phas_named_captures = 1;
1059 /* potential named capture */
1060 if (capture_name) {
1061 p += 3;
1062 if (re_parse_group_name(name, sizeof(name), &p) == 0) {
1063 if (!strcmp(name, capture_name))
1064 return capture_index;
1065 }
1066 }
1067 capture_index++;
1068 if (capture_index >= CAPTURE_COUNT_MAX)
1069 goto done;
1070 }
1071 } else {
1072 capture_index++;
1073 if (capture_index >= CAPTURE_COUNT_MAX)
1074 goto done;
1075 }
1076 break;
1077 case '\\':
1078 p++;
1079 break;
1080 case '[':
1081 for (p += 1 + (*p == ']'); p < s->buf_end && *p != ']'; p++) {
1082 if (*p == '\\')
1083 p++;
1084 }
1085 break;
1086 }
1087 }
1088 done:
1089 if (capture_name)
1090 return -1;
1091 else
1092 return capture_index;
1093 }
1094
1095 static int re_count_captures(REParseState *s)
1096 {
1097 if (s->total_capture_count < 0) {
1098 s->total_capture_count = re_parse_captures(s, &s->has_named_captures,
1099 NULL);
1100 }
1101 return s->total_capture_count;
1102 }
1103
1104 static BOOL re_has_named_captures(REParseState *s)
1105 {
1106 if (s->has_named_captures < 0)
1107 re_count_captures(s);
1108 return s->has_named_captures;
1109 }
1110
1111 static int find_group_name(REParseState *s, const char *name)
1112 {
1113 const char *p, *buf_end;
1114 size_t len, name_len;
1115 int capture_index;
1116
1117 name_len = strlen(name);
1118 p = (char *)s->group_names.buf;
1119 buf_end = (char *)s->group_names.buf + s->group_names.size;
1120 capture_index = 1;
1121 while (p < buf_end) {
1122 len = strlen(p);
1123 if (len == name_len && memcmp(name, p, name_len) == 0)
1124 return capture_index;
1125 p += len + 1;
1126 capture_index++;
1127 }
1128 return -1;
1129 }
1130
1131 static int re_parse_disjunction(REParseState *s, BOOL is_backward_dir);
1132
1133 static int re_parse_term(REParseState *s, BOOL is_backward_dir)
1134 {
1135 const uint8_t *p;
1136 int c, last_atom_start, quant_min, quant_max, last_capture_count;
1137 BOOL greedy, add_zero_advance_check, is_neg, is_backward_lookahead;
1138 CharRange cr_s, *cr = &cr_s;
1139
1140 last_atom_start = -1;
1141 last_capture_count = 0;
1142 p = s->buf_ptr;
1143 c = *p;
1144 switch(c) {
1145 case '^':
1146 p++;
1147 re_emit_op(s, REOP_line_start);
1148 break;
1149 case '$':
1150 p++;
1151 re_emit_op(s, REOP_line_end);
1152 break;
1153 case '.':
1154 p++;
1155 last_atom_start = s->byte_code.size;
1156 last_capture_count = s->capture_count;
1157 if (is_backward_dir)
1158 re_emit_op(s, REOP_prev);
1159 re_emit_op(s, s->dotall ? REOP_any : REOP_dot);
1160 if (is_backward_dir)
1161 re_emit_op(s, REOP_prev);
1162 break;
1163 case '{':
1164 if (s->is_utf16) {
1165 return re_parse_error(s, "syntax error");
1166 } else if (!is_digit(p[1])) {
1167 /* Annex B: we accept '{' not followed by digits as a
1168 normal atom */
1169 goto parse_class_atom;
1170 } else {
1171 const uint8_t *p1 = p + 1;
1172 /* Annex B: error if it is like a repetition count */
1173 parse_digits(&p1, TRUE);
1174 if (*p1 == ',') {
1175 p1++;
1176 if (is_digit(*p1)) {
1177 parse_digits(&p1, TRUE);
1178 }
1179 }
1180 if (*p1 != '}') {
1181 goto parse_class_atom;
1182 }
1183 }
1184 /* fall thru */
1185 case '*':
1186 case '+':
1187 case '?':
1188 return re_parse_error(s, "nothing to repeat");
1189 case '(':
1190 if (p[1] == '?') {
1191 if (p[2] == ':') {
1192 p += 3;
1193 last_atom_start = s->byte_code.size;
1194 last_capture_count = s->capture_count;
1195 s->buf_ptr = p;
1196 if (re_parse_disjunction(s, is_backward_dir))
1197 return -1;
1198 p = s->buf_ptr;
1199 if (re_parse_expect(s, &p, ')'))
1200 return -1;
1201 } else if ((p[2] == '=' || p[2] == '!')) {
1202 is_neg = (p[2] == '!');
1203 is_backward_lookahead = FALSE;
1204 p += 3;
1205 goto lookahead;
1206 } else if (p[2] == '<' &&
1207 (p[3] == '=' || p[3] == '!')) {
1208 int pos;
1209 is_neg = (p[3] == '!');
1210 is_backward_lookahead = TRUE;
1211 p += 4;
1212 /* lookahead */
1213 lookahead:
1214 /* Annex B allows lookahead to be used as an atom for
1215 the quantifiers */
1216 if (!s->is_utf16 && !is_backward_lookahead) {
1217 last_atom_start = s->byte_code.size;
1218 last_capture_count = s->capture_count;
1219 }
1220 pos = re_emit_op_u32(s, REOP_lookahead + is_neg, 0);
1221 s->buf_ptr = p;
1222 if (re_parse_disjunction(s, is_backward_lookahead))
1223 return -1;
1224 p = s->buf_ptr;
1225 if (re_parse_expect(s, &p, ')'))
1226 return -1;
1227 re_emit_op(s, REOP_match);
1228 /* jump after the 'match' after the lookahead is successful */
1229 if (dbuf_error(&s->byte_code))
1230 return -1;
1231 put_u32(s->byte_code.buf + pos, s->byte_code.size - (pos + 4));
1232 } else if (p[2] == '<') {
1233 p += 3;
1234 if (re_parse_group_name(s->u.tmp_buf, sizeof(s->u.tmp_buf),
1235 &p)) {
1236 return re_parse_error(s, "invalid group name");
1237 }
1238 if (find_group_name(s, s->u.tmp_buf) > 0) {
1239 return re_parse_error(s, "duplicate group name");
1240 }
1241 /* group name with a trailing zero */
1242 dbuf_put(&s->group_names, (uint8_t *)s->u.tmp_buf,
1243 strlen(s->u.tmp_buf) + 1);
1244 s->has_named_captures = 1;
1245 goto parse_capture;
1246 } else {
1247 return re_parse_error(s, "invalid group");
1248 }
1249 } else {
1250 int capture_index;
1251 p++;
1252 /* capture without group name */
1253 dbuf_putc(&s->group_names, 0);
1254 parse_capture:
1255 if (s->capture_count >= CAPTURE_COUNT_MAX)
1256 return re_parse_error(s, "too many captures");
1257 last_atom_start = s->byte_code.size;
1258 last_capture_count = s->capture_count;
1259 capture_index = s->capture_count++;
1260 re_emit_op_u8(s, REOP_save_start + is_backward_dir,
1261 capture_index);
1262
1263 s->buf_ptr = p;
1264 if (re_parse_disjunction(s, is_backward_dir))
1265 return -1;
1266 p = s->buf_ptr;
1267
1268 re_emit_op_u8(s, REOP_save_start + 1 - is_backward_dir,
1269 capture_index);
1270
1271 if (re_parse_expect(s, &p, ')'))
1272 return -1;
1273 }
1274 break;
1275 case '\\':
1276 switch(p[1]) {
1277 case 'b':
1278 case 'B':
1279 re_emit_op(s, REOP_word_boundary + (p[1] != 'b'));
1280 p += 2;
1281 break;
1282 case 'k':
1283 {
1284 const uint8_t *p1;
1285 int dummy_res;
1286
1287 p1 = p;
1288 if (p1[2] != '<') {
1289 /* annex B: we tolerate invalid group names in non
1290 unicode mode if there is no named capture
1291 definition */
1292 if (s->is_utf16 || re_has_named_captures(s))
1293 return re_parse_error(s, "expecting group name");
1294 else
1295 goto parse_class_atom;
1296 }
1297 p1 += 3;
1298 if (re_parse_group_name(s->u.tmp_buf, sizeof(s->u.tmp_buf),
1299 &p1)) {
1300 if (s->is_utf16 || re_has_named_captures(s))
1301 return re_parse_error(s, "invalid group name");
1302 else
1303 goto parse_class_atom;
1304 }
1305 c = find_group_name(s, s->u.tmp_buf);
1306 if (c < 0) {
1307 /* no capture name parsed before, try to look
1308 after (inefficient, but hopefully not common */
1309 c = re_parse_captures(s, &dummy_res, s->u.tmp_buf);
1310 if (c < 0) {
1311 if (s->is_utf16 || re_has_named_captures(s))
1312 return re_parse_error(s, "group name not defined");
1313 else
1314 goto parse_class_atom;
1315 }
1316 }
1317 p = p1;
1318 }
1319 goto emit_back_reference;
1320 case '0':
1321 p += 2;
1322 c = 0;
1323 if (s->is_utf16) {
1324 if (is_digit(*p)) {
1325 return re_parse_error(s, "invalid decimal escape in regular expression");
1326 }
1327 } else {
1328 /* Annex B.1.4: accept legacy octal */
1329 if (*p >= '0' && *p <= '7') {
1330 c = *p++ - '0';
1331 if (*p >= '0' && *p <= '7') {
1332 c = (c << 3) + *p++ - '0';
1333 }
1334 }
1335 }
1336 goto normal_char;
1337 case '1': case '2': case '3': case '4':
1338 case '5': case '6': case '7': case '8':
1339 case '9':
1340 {
1341 const uint8_t *q = ++p;
1342
1343 c = parse_digits(&p, FALSE);
1344 if (c < 0 || (c >= s->capture_count && c >= re_count_captures(s))) {
1345 if (!s->is_utf16) {
1346 /* Annex B.1.4: accept legacy octal */
1347 p = q;
1348 if (*p <= '7') {
1349 c = 0;
1350 if (*p <= '3')
1351 c = *p++ - '0';
1352 if (*p >= '0' && *p <= '7') {
1353 c = (c << 3) + *p++ - '0';
1354 if (*p >= '0' && *p <= '7') {
1355 c = (c << 3) + *p++ - '0';
1356 }
1357 }
1358 } else {
1359 c = *p++;
1360 }
1361 goto normal_char;
1362 }
1363 return re_parse_error(s, "back reference out of range in regular expression");
1364 }
1365 emit_back_reference:
1366 last_atom_start = s->byte_code.size;
1367 last_capture_count = s->capture_count;
1368 re_emit_op_u8(s, REOP_back_reference + is_backward_dir, c);
1369 }
1370 break;
1371 default:
1372 goto parse_class_atom;
1373 }
1374 break;
1375 case '[':
1376 last_atom_start = s->byte_code.size;
1377 last_capture_count = s->capture_count;
1378 if (is_backward_dir)
1379 re_emit_op(s, REOP_prev);
1380 if (re_parse_char_class(s, &p))
1381 return -1;
1382 if (is_backward_dir)
1383 re_emit_op(s, REOP_prev);
1384 break;
1385 case ']':
1386 case '}':
1387 if (s->is_utf16)
1388 return re_parse_error(s, "syntax error");
1389 goto parse_class_atom;
1390 default:
1391 parse_class_atom:
1392 c = get_class_atom(s, cr, &p, FALSE);
1393 if ((int)c < 0)
1394 return -1;
1395 normal_char:
1396 last_atom_start = s->byte_code.size;
1397 last_capture_count = s->capture_count;
1398 if (is_backward_dir)
1399 re_emit_op(s, REOP_prev);
1400 if (c >= CLASS_RANGE_BASE) {
1401 int ret;
1402 /* Note: canonicalization is not needed */
1403 ret = re_emit_range(s, cr);
1404 cr_free(cr);
1405 if (ret)
1406 return -1;
1407 } else {
1408 if (s->ignore_case)
1409 c = lre_canonicalize(c, s->is_utf16);
1410 if (c <= 0xffff)
1411 re_emit_op_u16(s, REOP_char, c);
1412 else
1413 re_emit_op_u32(s, REOP_char32, c);
1414 }
1415 if (is_backward_dir)
1416 re_emit_op(s, REOP_prev);
1417 break;
1418 }
1419
1420 /* quantifier */
1421 if (last_atom_start >= 0) {
1422 c = *p;
1423 switch(c) {
1424 case '*':
1425 p++;
1426 quant_min = 0;
1427 quant_max = INT32_MAX;
1428 goto quantifier;
1429 case '+':
1430 p++;
1431 quant_min = 1;
1432 quant_max = INT32_MAX;
1433 goto quantifier;
1434 case '?':
1435 p++;
1436 quant_min = 0;
1437 quant_max = 1;
1438 goto quantifier;
1439 case '{':
1440 {
1441 const uint8_t *p1 = p;
1442 /* As an extension (see ES6 annex B), we accept '{' not
1443 followed by digits as a normal atom */
1444 if (!is_digit(p[1])) {
1445 if (s->is_utf16)
1446 goto invalid_quant_count;
1447 break;
1448 }
1449 p++;
1450 quant_min = parse_digits(&p, TRUE);
1451 quant_max = quant_min;
1452 if (*p == ',') {
1453 p++;
1454 if (is_digit(*p)) {
1455 quant_max = parse_digits(&p, TRUE);
1456 if (quant_max < quant_min) {
1457 invalid_quant_count:
1458 return re_parse_error(s, "invalid repetition count");
1459 }
1460 } else {
1461 quant_max = INT32_MAX; /* infinity */
1462 }
1463 }
1464 if (*p != '}' && !s->is_utf16) {
1465 /* Annex B: normal atom if invalid '{' syntax */
1466 p = p1;
1467 break;
1468 }
1469 if (re_parse_expect(s, &p, '}'))
1470 return -1;
1471 }
1472 quantifier:
1473 greedy = TRUE;
1474 if (*p == '?') {
1475 p++;
1476 greedy = FALSE;
1477 }
1478 if (last_atom_start < 0) {
1479 return re_parse_error(s, "nothing to repeat");
1480 }
1481 if (greedy) {
1482 int len, pos;
1483
1484 if (quant_max > 0) {
1485 /* specific optimization for simple quantifiers */
1486 if (dbuf_error(&s->byte_code))
1487 goto out_of_memory;
1488 len = re_is_simple_quantifier(s->byte_code.buf + last_atom_start,
1489 s->byte_code.size - last_atom_start);
1490 if (len > 0) {
1491 re_emit_op(s, REOP_match);
1492
1493 if (dbuf_insert(&s->byte_code, last_atom_start, 17))
1494 goto out_of_memory;
1495 pos = last_atom_start;
1496 s->byte_code.buf[pos++] = REOP_simple_greedy_quant;
1497 put_u32(&s->byte_code.buf[pos],
1498 s->byte_code.size - last_atom_start - 17);
1499 pos += 4;
1500 put_u32(&s->byte_code.buf[pos], quant_min);
1501 pos += 4;
1502 put_u32(&s->byte_code.buf[pos], quant_max);
1503 pos += 4;
1504 put_u32(&s->byte_code.buf[pos], len);
1505 pos += 4;
1506 goto done;
1507 }
1508 }
1509
1510 if (dbuf_error(&s->byte_code))
1511 goto out_of_memory;
1512 /* the spec tells that if there is no advance when
1513 running the atom after the first quant_min times,
1514 then there is no match. We remove this test when we
1515 are sure the atom always advances the position. */
1516 add_zero_advance_check = re_need_check_advance(s->byte_code.buf + last_atom_start,
1517 s->byte_code.size - last_atom_start);
1518 } else {
1519 add_zero_advance_check = FALSE;
1520 }
1521
1522 {
1523 int len, pos;
1524 len = s->byte_code.size - last_atom_start;
1525 if (quant_min == 0) {
1526 /* need to reset the capture in case the atom is
1527 not executed */
1528 if (last_capture_count != s->capture_count) {
1529 if (dbuf_insert(&s->byte_code, last_atom_start, 3))
1530 goto out_of_memory;
1531 s->byte_code.buf[last_atom_start++] = REOP_save_reset;
1532 s->byte_code.buf[last_atom_start++] = last_capture_count;
1533 s->byte_code.buf[last_atom_start++] = s->capture_count - 1;
1534 }
1535 if (quant_max == 0) {
1536 s->byte_code.size = last_atom_start;
1537 } else if (quant_max == 1 || quant_max == INT32_MAX) {
1538 BOOL has_goto = (quant_max == INT32_MAX);
1539 if (dbuf_insert(&s->byte_code, last_atom_start, 5 + add_zero_advance_check))
1540 goto out_of_memory;
1541 s->byte_code.buf[last_atom_start] = REOP_split_goto_first +
1542 greedy;
1543 put_u32(s->byte_code.buf + last_atom_start + 1,
1544 len + 5 * has_goto + add_zero_advance_check * 2);
1545 if (add_zero_advance_check) {
1546 s->byte_code.buf[last_atom_start + 1 + 4] = REOP_push_char_pos;
1547 re_emit_op(s, REOP_check_advance);
1548 }
1549 if (has_goto)
1550 re_emit_goto(s, REOP_goto, last_atom_start);
1551 } else {
1552 if (dbuf_insert(&s->byte_code, last_atom_start, 10 + add_zero_advance_check))
1553 goto out_of_memory;
1554 pos = last_atom_start;
1555 s->byte_code.buf[pos++] = REOP_push_i32;
1556 put_u32(s->byte_code.buf + pos, quant_max);
1557 pos += 4;
1558 s->byte_code.buf[pos++] = REOP_split_goto_first + greedy;
1559 put_u32(s->byte_code.buf + pos, len + 5 + add_zero_advance_check * 2);
1560 pos += 4;
1561 if (add_zero_advance_check) {
1562 s->byte_code.buf[pos++] = REOP_push_char_pos;
1563 re_emit_op(s, REOP_check_advance);
1564 }
1565 re_emit_goto(s, REOP_loop, last_atom_start + 5);
1566 re_emit_op(s, REOP_drop);
1567 }
1568 } else if (quant_min == 1 && quant_max == INT32_MAX &&
1569 !add_zero_advance_check) {
1570 re_emit_goto(s, REOP_split_next_first - greedy,
1571 last_atom_start);
1572 } else {
1573 if (quant_min == 1) {
1574 /* nothing to add */
1575 } else {
1576 if (dbuf_insert(&s->byte_code, last_atom_start, 5))
1577 goto out_of_memory;
1578 s->byte_code.buf[last_atom_start] = REOP_push_i32;
1579 put_u32(s->byte_code.buf + last_atom_start + 1,
1580 quant_min);
1581 last_atom_start += 5;
1582 re_emit_goto(s, REOP_loop, last_atom_start);
1583 re_emit_op(s, REOP_drop);
1584 }
1585 if (quant_max == INT32_MAX) {
1586 pos = s->byte_code.size;
1587 re_emit_op_u32(s, REOP_split_goto_first + greedy,
1588 len + 5 + add_zero_advance_check * 2);
1589 if (add_zero_advance_check)
1590 re_emit_op(s, REOP_push_char_pos);
1591 /* copy the atom */
1592 dbuf_put_self(&s->byte_code, last_atom_start, len);
1593 if (add_zero_advance_check)
1594 re_emit_op(s, REOP_check_advance);
1595 re_emit_goto(s, REOP_goto, pos);
1596 } else if (quant_max > quant_min) {
1597 re_emit_op_u32(s, REOP_push_i32, quant_max - quant_min);
1598 pos = s->byte_code.size;
1599 re_emit_op_u32(s, REOP_split_goto_first + greedy,
1600 len + 5 + add_zero_advance_check * 2);
1601 if (add_zero_advance_check)
1602 re_emit_op(s, REOP_push_char_pos);
1603 /* copy the atom */
1604 dbuf_put_self(&s->byte_code, last_atom_start, len);
1605 if (add_zero_advance_check)
1606 re_emit_op(s, REOP_check_advance);
1607 re_emit_goto(s, REOP_loop, pos);
1608 re_emit_op(s, REOP_drop);
1609 }
1610 }
1611 last_atom_start = -1;
1612 }
1613 break;
1614 default:
1615 break;
1616 }
1617 }
1618 done:
1619 s->buf_ptr = p;
1620 return 0;
1621 out_of_memory:
1622 return re_parse_out_of_memory(s);
1623 }
1624
1625 static int re_parse_alternative(REParseState *s, BOOL is_backward_dir)
1626 {
1627 const uint8_t *p;
1628 int ret;
1629 size_t start, term_start, end, term_size;
1630
1631 start = s->byte_code.size;
1632 for(;;) {
1633 p = s->buf_ptr;
1634 if (p >= s->buf_end)
1635 break;
1636 if (*p == '|' || *p == ')')
1637 break;
1638 term_start = s->byte_code.size;
1639 ret = re_parse_term(s, is_backward_dir);
1640 if (ret)
1641 return ret;
1642 if (is_backward_dir) {
1643 /* reverse the order of the terms (XXX: inefficient, but
1644 speed is not really critical here) */
1645 end = s->byte_code.size;
1646 term_size = end - term_start;
1647 if (dbuf_realloc(&s->byte_code, end + term_size))
1648 return -1;
1649 memmove(s->byte_code.buf + start + term_size,
1650 s->byte_code.buf + start,
1651 end - start);
1652 memcpy(s->byte_code.buf + start, s->byte_code.buf + end,
1653 term_size);
1654 }
1655 }
1656 return 0;
1657 }
1658
1659 static int re_parse_disjunction(REParseState *s, BOOL is_backward_dir)
1660 {
1661 int start, len, pos;
1662
1663 if (lre_check_stack_overflow(s->opaque, 0))
1664 return re_parse_error(s, "stack overflow");
1665
1666 start = s->byte_code.size;
1667 if (re_parse_alternative(s, is_backward_dir))
1668 return -1;
1669 while (*s->buf_ptr == '|') {
1670 s->buf_ptr++;
1671
1672 len = s->byte_code.size - start;
1673
1674 /* insert a split before the first alternative */
1675 if (dbuf_insert(&s->byte_code, start, 5)) {
1676 return re_parse_out_of_memory(s);
1677 }
1678 s->byte_code.buf[start] = REOP_split_next_first;
1679 put_u32(s->byte_code.buf + start + 1, len + 5);
1680
1681 pos = re_emit_op_u32(s, REOP_goto, 0);
1682
1683 if (re_parse_alternative(s, is_backward_dir))
1684 return -1;
1685
1686 /* patch the goto */
1687 len = s->byte_code.size - (pos + 4);
1688 put_u32(s->byte_code.buf + pos, len);
1689 }
1690 return 0;
1691 }
1692
1693 /* the control flow is recursive so the analysis can be linear */
1694 static int compute_stack_size(const uint8_t *bc_buf, int bc_buf_len)
1695 {
1696 int stack_size, stack_size_max, pos, opcode, len;
1697 uint32_t val;
1698
1699 stack_size = 0;
1700 stack_size_max = 0;
1701 bc_buf += RE_HEADER_LEN;
1702 bc_buf_len -= RE_HEADER_LEN;
1703 pos = 0;
1704 while (pos < bc_buf_len) {
1705 opcode = bc_buf[pos];
1706 len = reopcode_info[opcode].size;
1707 assert(opcode < REOP_COUNT);
1708 assert((pos + len) <= bc_buf_len);
1709 switch(opcode) {
1710 case REOP_push_i32:
1711 case REOP_push_char_pos:
1712 stack_size++;
1713 if (stack_size > stack_size_max) {
1714 if (stack_size > STACK_SIZE_MAX)
1715 return -1;
1716 stack_size_max = stack_size;
1717 }
1718 break;
1719 case REOP_drop:
1720 case REOP_check_advance:
1721 assert(stack_size > 0);
1722 stack_size--;
1723 break;
1724 case REOP_range:
1725 val = get_u16(bc_buf + pos + 1);
1726 len += val * 4;
1727 break;
1728 case REOP_range32:
1729 val = get_u16(bc_buf + pos + 1);
1730 len += val * 8;
1731 break;
1732 }
1733 pos += len;
1734 }
1735 return stack_size_max;
1736 }
1737
1738 /* 'buf' must be a zero terminated UTF-8 string of length buf_len.
1739 Return NULL if error and allocate an error message in *perror_msg,
1740 otherwise the compiled bytecode and its length in plen.
1741 */
1742 uint8_t *lre_compile(int *plen, char *error_msg, int error_msg_size,
1743 const char *buf, size_t buf_len, int re_flags,
1744 void *opaque)
1745 {
1746 REParseState s_s, *s = &s_s;
1747 int stack_size;
1748 BOOL is_sticky;
1749
1750 memset(s, 0, sizeof(*s));
1751 s->opaque = opaque;
1752 s->buf_ptr = (const uint8_t *)buf;
1753 s->buf_end = s->buf_ptr + buf_len;
1754 s->buf_start = s->buf_ptr;
1755 s->re_flags = re_flags;
1756 s->is_utf16 = ((re_flags & LRE_FLAG_UTF16) != 0);
1757 is_sticky = ((re_flags & LRE_FLAG_STICKY) != 0);
1758 s->ignore_case = ((re_flags & LRE_FLAG_IGNORECASE) != 0);
1759 s->dotall = ((re_flags & LRE_FLAG_DOTALL) != 0);
1760 s->capture_count = 1;
1761 s->total_capture_count = -1;
1762 s->has_named_captures = -1;
1763
1764 dbuf_init2(&s->byte_code, opaque, lre_realloc);
1765 dbuf_init2(&s->group_names, opaque, lre_realloc);
1766
1767 dbuf_putc(&s->byte_code, re_flags); /* first element is the flags */
1768 dbuf_putc(&s->byte_code, 0); /* second element is the number of captures */
1769 dbuf_putc(&s->byte_code, 0); /* stack size */
1770 dbuf_put_u32(&s->byte_code, 0); /* bytecode length */
1771
1772 if (!is_sticky) {
1773 /* iterate thru all positions (about the same as .*?( ... ) )
1774 . We do it without an explicit loop so that lock step
1775 thread execution will be possible in an optimized
1776 implementation */
1777 re_emit_op_u32(s, REOP_split_goto_first, 1 + 5);
1778 re_emit_op(s, REOP_any);
1779 re_emit_op_u32(s, REOP_goto, -(5 + 1 + 5));
1780 }
1781 re_emit_op_u8(s, REOP_save_start, 0);
1782
1783 if (re_parse_disjunction(s, FALSE)) {
1784 error:
1785 dbuf_free(&s->byte_code);
1786 dbuf_free(&s->group_names);
1787 pstrcpy(error_msg, error_msg_size, s->u.error_msg);
1788 *plen = 0;
1789 return NULL;
1790 }
1791
1792 re_emit_op_u8(s, REOP_save_end, 0);
1793
1794 re_emit_op(s, REOP_match);
1795
1796 if (*s->buf_ptr != '\0') {
1797 re_parse_error(s, "extraneous characters at the end");
1798 goto error;
1799 }
1800
1801 if (dbuf_error(&s->byte_code)) {
1802 re_parse_out_of_memory(s);
1803 goto error;
1804 }
1805
1806 stack_size = compute_stack_size(s->byte_code.buf, s->byte_code.size);
1807 if (stack_size < 0) {
1808 re_parse_error(s, "too many imbricated quantifiers");
1809 goto error;
1810 }
1811
1812 s->byte_code.buf[RE_HEADER_CAPTURE_COUNT] = s->capture_count;
1813 s->byte_code.buf[RE_HEADER_STACK_SIZE] = stack_size;
1814 put_u32(s->byte_code.buf + 3, s->byte_code.size - RE_HEADER_LEN);
1815
1816 /* add the named groups if needed */
1817 if (s->group_names.size > (s->capture_count - 1)) {
1818 dbuf_put(&s->byte_code, s->group_names.buf, s->group_names.size);
1819 s->byte_code.buf[RE_HEADER_FLAGS] |= LRE_FLAG_NAMED_GROUPS;
1820 }
1821 dbuf_free(&s->group_names);
1822
1823 #ifdef DUMP_REOP
1824 lre_dump_bytecode(s->byte_code.buf, s->byte_code.size);
1825 #endif
1826
1827 error_msg[0] = '\0';
1828 *plen = s->byte_code.size;
1829 return s->byte_code.buf;
1830 }
1831
1832 static BOOL is_line_terminator(uint32_t c)
1833 {
1834 return (c == '\n' || c == '\r' || c == CP_LS || c == CP_PS);
1835 }
1836
1837 static BOOL is_word_char(uint32_t c)
1838 {
1839 return ((c >= '0' && c <= '9') ||
1840 (c >= 'a' && c <= 'z') ||
1841 (c >= 'A' && c <= 'Z') ||
1842 (c == '_'));
1843 }
1844
1845 #define GET_CHAR(c, cptr, cbuf_end) \
1846 do { \
1847 if (cbuf_type == 0) { \
1848 c = *cptr++; \
1849 } else { \
1850 uint32_t __c1; \
1851 c = *(uint16_t *)cptr; \
1852 cptr += 2; \
1853 if (c >= 0xd800 && c < 0xdc00 && \
1854 cbuf_type == 2 && cptr < cbuf_end) { \
1855 __c1 = *(uint16_t *)cptr; \
1856 if (__c1 >= 0xdc00 && __c1 < 0xe000) { \
1857 c = (((c & 0x3ff) << 10) | (__c1 & 0x3ff)) + 0x10000; \
1858 cptr += 2; \
1859 } \
1860 } \
1861 } \
1862 } while (0)
1863
1864 #define PEEK_CHAR(c, cptr, cbuf_end) \
1865 do { \
1866 if (cbuf_type == 0) { \
1867 c = cptr[0]; \
1868 } else { \
1869 uint32_t __c1; \
1870 c = ((uint16_t *)cptr)[0]; \
1871 if (c >= 0xd800 && c < 0xdc00 && \
1872 cbuf_type == 2 && (cptr + 2) < cbuf_end) { \
1873 __c1 = ((uint16_t *)cptr)[1]; \
1874 if (__c1 >= 0xdc00 && __c1 < 0xe000) { \
1875 c = (((c & 0x3ff) << 10) | (__c1 & 0x3ff)) + 0x10000; \
1876 } \
1877 } \
1878 } \
1879 } while (0)
1880
1881 #define PEEK_PREV_CHAR(c, cptr, cbuf_start) \
1882 do { \
1883 if (cbuf_type == 0) { \
1884 c = cptr[-1]; \
1885 } else { \
1886 uint32_t __c1; \
1887 c = ((uint16_t *)cptr)[-1]; \
1888 if (c >= 0xdc00 && c < 0xe000 && \
1889 cbuf_type == 2 && (cptr - 4) >= cbuf_start) { \
1890 __c1 = ((uint16_t *)cptr)[-2]; \
1891 if (__c1 >= 0xd800 && __c1 < 0xdc00 ) { \
1892 c = (((__c1 & 0x3ff) << 10) | (c & 0x3ff)) + 0x10000; \
1893 } \
1894 } \
1895 } \
1896 } while (0)
1897
1898 #define GET_PREV_CHAR(c, cptr, cbuf_start) \
1899 do { \
1900 if (cbuf_type == 0) { \
1901 cptr--; \
1902 c = cptr[0]; \
1903 } else { \
1904 uint32_t __c1; \
1905 cptr -= 2; \
1906 c = ((uint16_t *)cptr)[0]; \
1907 if (c >= 0xdc00 && c < 0xe000 && \
1908 cbuf_type == 2 && cptr > cbuf_start) { \
1909 __c1 = ((uint16_t *)cptr)[-1]; \
1910 if (__c1 >= 0xd800 && __c1 < 0xdc00 ) { \
1911 cptr -= 2; \
1912 c = (((__c1 & 0x3ff) << 10) | (c & 0x3ff)) + 0x10000; \
1913 } \
1914 } \
1915 } \
1916 } while (0)
1917
1918 #define PREV_CHAR(cptr, cbuf_start) \
1919 do { \
1920 if (cbuf_type == 0) { \
1921 cptr--; \
1922 } else { \
1923 cptr -= 2; \
1924 if (cbuf_type == 2) { \
1925 c = ((uint16_t *)cptr)[0]; \
1926 if (c >= 0xdc00 && c < 0xe000 && cptr > cbuf_start) { \
1927 c = ((uint16_t *)cptr)[-1]; \
1928 if (c >= 0xd800 && c < 0xdc00) \
1929 cptr -= 2; \
1930 } \
1931 } \
1932 } \
1933 } while (0)
1934
1935 typedef uintptr_t StackInt;
1936
1937 typedef enum {
1938 RE_EXEC_STATE_SPLIT,
1939 RE_EXEC_STATE_LOOKAHEAD,
1940 RE_EXEC_STATE_NEGATIVE_LOOKAHEAD,
1941 RE_EXEC_STATE_GREEDY_QUANT,
1942 } REExecStateEnum;
1943
1944 typedef struct REExecState {
1945 REExecStateEnum type : 8;
1946 uint8_t stack_len;
1947 size_t count; /* only used for RE_EXEC_STATE_GREEDY_QUANT */
1948 const uint8_t *cptr;
1949 const uint8_t *pc;
1950 void *buf[0];
1951 } REExecState;
1952
1953 typedef struct {
1954 const uint8_t *cbuf;
1955 const uint8_t *cbuf_end;
1956 /* 0 = 8 bit chars, 1 = 16 bit chars, 2 = 16 bit chars, UTF-16 */
1957 int cbuf_type;
1958 int capture_count;
1959 int stack_size_max;
1960 BOOL multi_line;
1961 BOOL ignore_case;
1962 BOOL is_utf16;
1963 void *opaque; /* used for stack overflow check */
1964
1965 size_t state_size;
1966 uint8_t *state_stack;
1967 size_t state_stack_size;
1968 size_t state_stack_len;
1969 } REExecContext;
1970
1971 static int push_state(REExecContext *s,
1972 uint8_t **capture,
1973 StackInt *stack, size_t stack_len,
1974 const uint8_t *pc, const uint8_t *cptr,
1975 REExecStateEnum type, size_t count)
1976 {
1977 REExecState *rs;
1978 uint8_t *new_stack;
1979 size_t new_size, i, n;
1980 StackInt *stack_buf;
1981
1982 if (unlikely((s->state_stack_len + 1) > s->state_stack_size)) {
1983 /* reallocate the stack */
1984 new_size = s->state_stack_size * 3 / 2;
1985 if (new_size < 8)
1986 new_size = 8;
1987 new_stack = lre_realloc(s->opaque, s->state_stack, new_size * s->state_size);
1988 if (!new_stack)
1989 return -1;
1990 s->state_stack_size = new_size;
1991 s->state_stack = new_stack;
1992 }
1993 rs = (REExecState *)(s->state_stack + s->state_stack_len * s->state_size);
1994 s->state_stack_len++;
1995 rs->type = type;
1996 rs->count = count;
1997 rs->stack_len = stack_len;
1998 rs->cptr = cptr;
1999 rs->pc = pc;
2000 n = 2 * s->capture_count;
2001 for(i = 0; i < n; i++)
2002 rs->buf[i] = capture[i];
2003 stack_buf = (StackInt *)(rs->buf + n);
2004 for(i = 0; i < stack_len; i++)
2005 stack_buf[i] = stack[i];
2006 return 0;
2007 }
2008
2009 /* return 1 if match, 0 if not match or -1 if error. */
2010 static intptr_t lre_exec_backtrack(REExecContext *s, uint8_t **capture,
2011 StackInt *stack, int stack_len,
2012 const uint8_t *pc, const uint8_t *cptr,
2013 BOOL no_recurse)
2014 {
2015 int opcode, ret;
2016 int cbuf_type;
2017 uint32_t val, c;
2018 const uint8_t *cbuf_end;
2019
2020 cbuf_type = s->cbuf_type;
2021 cbuf_end = s->cbuf_end;
2022
2023 for(;;) {
2024 // printf("top=%p: pc=%d\n", th_list.top, (int)(pc - (bc_buf + RE_HEADER_LEN)));
2025 opcode = *pc++;
2026 switch(opcode) {
2027 case REOP_match:
2028 {
2029 REExecState *rs;
2030 if (no_recurse)
2031 return (intptr_t)cptr;
2032 ret = 1;
2033 goto recurse;
2034 no_match:
2035 if (no_recurse)
2036 return 0;
2037 ret = 0;
2038 recurse:
2039 for(;;) {
2040 if (s->state_stack_len == 0)
2041 return ret;
2042 rs = (REExecState *)(s->state_stack +
2043 (s->state_stack_len - 1) * s->state_size);
2044 if (rs->type == RE_EXEC_STATE_SPLIT) {
2045 if (!ret) {
2046 pop_state:
2047 memcpy(capture, rs->buf,
2048 sizeof(capture[0]) * 2 * s->capture_count);
2049 pop_state1:
2050 pc = rs->pc;
2051 cptr = rs->cptr;
2052 stack_len = rs->stack_len;
2053 memcpy(stack, rs->buf + 2 * s->capture_count,
2054 stack_len * sizeof(stack[0]));
2055 s->state_stack_len--;
2056 break;
2057 }
2058 } else if (rs->type == RE_EXEC_STATE_GREEDY_QUANT) {
2059 if (!ret) {
2060 uint32_t char_count, i;
2061 memcpy(capture, rs->buf,
2062 sizeof(capture[0]) * 2 * s->capture_count);
2063 stack_len = rs->stack_len;
2064 memcpy(stack, rs->buf + 2 * s->capture_count,
2065 stack_len * sizeof(stack[0]));
2066 pc = rs->pc;
2067 cptr = rs->cptr;
2068 /* go backward */
2069 char_count = get_u32(pc + 12);
2070 for(i = 0; i < char_count; i++) {
2071 PREV_CHAR(cptr, s->cbuf);
2072 }
2073 pc = (pc + 16) + (int)get_u32(pc);
2074 rs->cptr = cptr;
2075 rs->count--;
2076 if (rs->count == 0) {
2077 s->state_stack_len--;
2078 }
2079 break;
2080 }
2081 } else {
2082 ret = ((rs->type == RE_EXEC_STATE_LOOKAHEAD && ret) ||
2083 (rs->type == RE_EXEC_STATE_NEGATIVE_LOOKAHEAD && !ret));
2084 if (ret) {
2085 /* keep the capture in case of positive lookahead */
2086 if (rs->type == RE_EXEC_STATE_LOOKAHEAD)
2087 goto pop_state1;
2088 else
2089 goto pop_state;
2090 }
2091 }
2092 s->state_stack_len--;
2093 }
2094 }
2095 break;
2096 case REOP_char32:
2097 val = get_u32(pc);
2098 pc += 4;
2099 goto test_char;
2100 case REOP_char:
2101 val = get_u16(pc);
2102 pc += 2;
2103 test_char:
2104 if (cptr >= cbuf_end)
2105 goto no_match;
2106 GET_CHAR(c, cptr, cbuf_end);
2107 if (s->ignore_case) {
2108 c = lre_canonicalize(c, s->is_utf16);
2109 }
2110 if (val != c)
2111 goto no_match;
2112 break;
2113 case REOP_split_goto_first:
2114 case REOP_split_next_first:
2115 {
2116 const uint8_t *pc1;
2117
2118 val = get_u32(pc);
2119 pc += 4;
2120 if (opcode == REOP_split_next_first) {
2121 pc1 = pc + (int)val;
2122 } else {
2123 pc1 = pc;
2124 pc = pc + (int)val;
2125 }
2126 ret = push_state(s, capture, stack, stack_len,
2127 pc1, cptr, RE_EXEC_STATE_SPLIT, 0);
2128 if (ret < 0)
2129 return -1;
2130 break;
2131 }
2132 case REOP_lookahead:
2133 case REOP_negative_lookahead:
2134 val = get_u32(pc);
2135 pc += 4;
2136 ret = push_state(s, capture, stack, stack_len,
2137 pc + (int)val, cptr,
2138 RE_EXEC_STATE_LOOKAHEAD + opcode - REOP_lookahead,
2139 0);
2140 if (ret < 0)
2141 return -1;
2142 break;
2143
2144 case REOP_goto:
2145 val = get_u32(pc);
2146 pc += 4 + (int)val;
2147 break;
2148 case REOP_line_start:
2149 if (cptr == s->cbuf)
2150 break;
2151 if (!s->multi_line)
2152 goto no_match;
2153 PEEK_PREV_CHAR(c, cptr, s->cbuf);
2154 if (!is_line_terminator(c))
2155 goto no_match;
2156 break;
2157 case REOP_line_end:
2158 if (cptr == cbuf_end)
2159 break;
2160 if (!s->multi_line)
2161 goto no_match;
2162 PEEK_CHAR(c, cptr, cbuf_end);
2163 if (!is_line_terminator(c))
2164 goto no_match;
2165 break;
2166 case REOP_dot:
2167 if (cptr == cbuf_end)
2168 goto no_match;
2169 GET_CHAR(c, cptr, cbuf_end);
2170 if (is_line_terminator(c))
2171 goto no_match;
2172 break;
2173 case REOP_any:
2174 if (cptr == cbuf_end)
2175 goto no_match;
2176 GET_CHAR(c, cptr, cbuf_end);
2177 break;
2178 case REOP_save_start:
2179 case REOP_save_end:
2180 val = *pc++;
2181 assert(val < s->capture_count);
2182 capture[2 * val + opcode - REOP_save_start] = (uint8_t *)cptr;
2183 break;
2184 case REOP_save_reset:
2185 {
2186 uint32_t val2;
2187 val = pc[0];
2188 val2 = pc[1];
2189 pc += 2;
2190 assert(val2 < s->capture_count);
2191 while (val <= val2) {
2192 capture[2 * val] = NULL;
2193 capture[2 * val + 1] = NULL;
2194 val++;
2195 }
2196 }
2197 break;
2198 case REOP_push_i32:
2199 val = get_u32(pc);
2200 pc += 4;
2201 stack[stack_len++] = val;
2202 break;
2203 case REOP_drop:
2204 stack_len--;
2205 break;
2206 case REOP_loop:
2207 val = get_u32(pc);
2208 pc += 4;
2209 if (--stack[stack_len - 1] != 0) {
2210 pc += (int)val;
2211 }
2212 break;
2213 case REOP_push_char_pos:
2214 stack[stack_len++] = (uintptr_t)cptr;
2215 break;
2216 case REOP_check_advance:
2217 if (stack[--stack_len] == (uintptr_t)cptr)
2218 goto no_match;
2219 break;
2220 case REOP_word_boundary:
2221 case REOP_not_word_boundary:
2222 {
2223 BOOL v1, v2;
2224 /* char before */
2225 if (cptr == s->cbuf) {
2226 v1 = FALSE;
2227 } else {
2228 PEEK_PREV_CHAR(c, cptr, s->cbuf);
2229 v1 = is_word_char(c);
2230 }
2231 /* current char */
2232 if (cptr >= cbuf_end) {
2233 v2 = FALSE;
2234 } else {
2235 PEEK_CHAR(c, cptr, cbuf_end);
2236 v2 = is_word_char(c);
2237 }
2238 if (v1 ^ v2 ^ (REOP_not_word_boundary - opcode))
2239 goto no_match;
2240 }
2241 break;
2242 case REOP_back_reference:
2243 case REOP_backward_back_reference:
2244 {
2245 const uint8_t *cptr1, *cptr1_end, *cptr1_start;
2246 uint32_t c1, c2;
2247
2248 val = *pc++;
2249 if (val >= s->capture_count)
2250 goto no_match;
2251 cptr1_start = capture[2 * val];
2252 cptr1_end = capture[2 * val + 1];
2253 if (!cptr1_start || !cptr1_end)
2254 break;
2255 if (opcode == REOP_back_reference) {
2256 cptr1 = cptr1_start;
2257 while (cptr1 < cptr1_end) {
2258 if (cptr >= cbuf_end)
2259 goto no_match;
2260 GET_CHAR(c1, cptr1, cptr1_end);
2261 GET_CHAR(c2, cptr, cbuf_end);
2262 if (s->ignore_case) {
2263 c1 = lre_canonicalize(c1, s->is_utf16);
2264 c2 = lre_canonicalize(c2, s->is_utf16);
2265 }
2266 if (c1 != c2)
2267 goto no_match;
2268 }
2269 } else {
2270 cptr1 = cptr1_end;
2271 while (cptr1 > cptr1_start) {
2272 if (cptr == s->cbuf)
2273 goto no_match;
2274 GET_PREV_CHAR(c1, cptr1, cptr1_start);
2275 GET_PREV_CHAR(c2, cptr, s->cbuf);
2276 if (s->ignore_case) {
2277 c1 = lre_canonicalize(c1, s->is_utf16);
2278 c2 = lre_canonicalize(c2, s->is_utf16);
2279 }
2280 if (c1 != c2)
2281 goto no_match;
2282 }
2283 }
2284 }
2285 break;
2286 case REOP_range:
2287 {
2288 int n;
2289 uint32_t low, high, idx_min, idx_max, idx;
2290
2291 n = get_u16(pc); /* n must be >= 1 */
2292 pc += 2;
2293 if (cptr >= cbuf_end)
2294 goto no_match;
2295 GET_CHAR(c, cptr, cbuf_end);
2296 if (s->ignore_case) {
2297 c = lre_canonicalize(c, s->is_utf16);
2298 }
2299 idx_min = 0;
2300 low = get_u16(pc + 0 * 4);
2301 if (c < low)
2302 goto no_match;
2303 idx_max = n - 1;
2304 high = get_u16(pc + idx_max * 4 + 2);
2305 /* 0xffff in for last value means +infinity */
2306 if (unlikely(c >= 0xffff) && high == 0xffff)
2307 goto range_match;
2308 if (c > high)
2309 goto no_match;
2310 while (idx_min <= idx_max) {
2311 idx = (idx_min + idx_max) / 2;
2312 low = get_u16(pc + idx * 4);
2313 high = get_u16(pc + idx * 4 + 2);
2314 if (c < low)
2315 idx_max = idx - 1;
2316 else if (c > high)
2317 idx_min = idx + 1;
2318 else
2319 goto range_match;
2320 }
2321 goto no_match;
2322 range_match:
2323 pc += 4 * n;
2324 }
2325 break;
2326 case REOP_range32:
2327 {
2328 int n;
2329 uint32_t low, high, idx_min, idx_max, idx;
2330
2331 n = get_u16(pc); /* n must be >= 1 */
2332 pc += 2;
2333 if (cptr >= cbuf_end)
2334 goto no_match;
2335 GET_CHAR(c, cptr, cbuf_end);
2336 if (s->ignore_case) {
2337 c = lre_canonicalize(c, s->is_utf16);
2338 }
2339 idx_min = 0;
2340 low = get_u32(pc + 0 * 8);
2341 if (c < low)
2342 goto no_match;
2343 idx_max = n - 1;
2344 high = get_u32(pc + idx_max * 8 + 4);
2345 if (c > high)
2346 goto no_match;
2347 while (idx_min <= idx_max) {
2348 idx = (idx_min + idx_max) / 2;
2349 low = get_u32(pc + idx * 8);
2350 high = get_u32(pc + idx * 8 + 4);
2351 if (c < low)
2352 idx_max = idx - 1;
2353 else if (c > high)
2354 idx_min = idx + 1;
2355 else
2356 goto range32_match;
2357 }
2358 goto no_match;
2359 range32_match:
2360 pc += 8 * n;
2361 }
2362 break;
2363 case REOP_prev:
2364 /* go to the previous char */
2365 if (cptr == s->cbuf)
2366 goto no_match;
2367 PREV_CHAR(cptr, s->cbuf);
2368 break;
2369 case REOP_simple_greedy_quant:
2370 {
2371 uint32_t next_pos, quant_min, quant_max;
2372 size_t q;
2373 intptr_t res;
2374 const uint8_t *pc1;
2375
2376 next_pos = get_u32(pc);
2377 quant_min = get_u32(pc + 4);
2378 quant_max = get_u32(pc + 8);
2379 pc += 16;
2380 pc1 = pc;
2381 pc += (int)next_pos;
2382
2383 q = 0;
2384 for(;;) {
2385 res = lre_exec_backtrack(s, capture, stack, stack_len,
2386 pc1, cptr, TRUE);
2387 if (res == -1)
2388 return res;
2389 if (!res)
2390 break;
2391 cptr = (uint8_t *)res;
2392 q++;
2393 if (q >= quant_max && quant_max != INT32_MAX)
2394 break;
2395 }
2396 if (q < quant_min)
2397 goto no_match;
2398 if (q > quant_min) {
2399 /* will examine all matches down to quant_min */
2400 ret = push_state(s, capture, stack, stack_len,
2401 pc1 - 16, cptr,
2402 RE_EXEC_STATE_GREEDY_QUANT,
2403 q - quant_min);
2404 if (ret < 0)
2405 return -1;
2406 }
2407 }
2408 break;
2409 default:
2410 abort();
2411 }
2412 }
2413 }
2414
2415 /* Return 1 if match, 0 if not match or -1 if error. cindex is the
2416 starting position of the match and must be such as 0 <= cindex <=
2417 clen. */
2418 int lre_exec(uint8_t **capture,
2419 const uint8_t *bc_buf, const uint8_t *cbuf, int cindex, int clen,
2420 int cbuf_type, void *opaque)
2421 {
2422 REExecContext s_s, *s = &s_s;
2423 int re_flags, i, alloca_size, ret;
2424 StackInt *stack_buf;
2425
2426 re_flags = bc_buf[RE_HEADER_FLAGS];
2427 s->multi_line = (re_flags & LRE_FLAG_MULTILINE) != 0;
2428 s->ignore_case = (re_flags & LRE_FLAG_IGNORECASE) != 0;
2429 s->is_utf16 = (re_flags & LRE_FLAG_UTF16) != 0;
2430 s->capture_count = bc_buf[RE_HEADER_CAPTURE_COUNT];
2431 s->stack_size_max = bc_buf[RE_HEADER_STACK_SIZE];
2432 s->cbuf = cbuf;
2433 s->cbuf_end = cbuf + (clen << cbuf_type);
2434 s->cbuf_type = cbuf_type;
2435 if (s->cbuf_type == 1 && s->is_utf16)
2436 s->cbuf_type = 2;
2437 s->opaque = opaque;
2438
2439 s->state_size = sizeof(REExecState) +
2440 s->capture_count * sizeof(capture[0]) * 2 +
2441 s->stack_size_max * sizeof(stack_buf[0]);
2442 s->state_stack = NULL;
2443 s->state_stack_len = 0;
2444 s->state_stack_size = 0;
2445
2446 for(i = 0; i < s->capture_count * 2; i++)
2447 capture[i] = NULL;
2448 alloca_size = s->stack_size_max * sizeof(stack_buf[0]);
2449 stack_buf = alloca(alloca_size);
2450 ret = lre_exec_backtrack(s, capture, stack_buf, 0, bc_buf + RE_HEADER_LEN,
2451 cbuf + (cindex << cbuf_type), FALSE);
2452 lre_realloc(s->opaque, s->state_stack, 0);
2453 return ret;
2454 }
2455
2456 int lre_get_capture_count(const uint8_t *bc_buf)
2457 {
2458 return bc_buf[RE_HEADER_CAPTURE_COUNT];
2459 }
2460
2461 int lre_get_flags(const uint8_t *bc_buf)
2462 {
2463 return bc_buf[RE_HEADER_FLAGS];
2464 }
2465
2466 /* Return NULL if no group names. Otherwise, return a pointer to
2467 'capture_count - 1' zero terminated UTF-8 strings. */
2468 const char *lre_get_groupnames(const uint8_t *bc_buf)
2469 {
2470 uint32_t re_bytecode_len;
2471 if ((lre_get_flags(bc_buf) & LRE_FLAG_NAMED_GROUPS) == 0)
2472 return NULL;
2473 re_bytecode_len = get_u32(bc_buf + 3);
2474 return (const char *)(bc_buf + 7 + re_bytecode_len);
2475 }
2476
2477 #ifdef TEST
2478
2479 BOOL lre_check_stack_overflow(void *opaque, size_t alloca_size)
2480 {
2481 return FALSE;
2482 }
2483
2484 void *lre_realloc(void *opaque, void *ptr, size_t size)
2485 {
2486 return realloc(ptr, size);
2487 }
2488
2489 int main(int argc, char **argv)
2490 {
2491 int len, ret, i;
2492 uint8_t *bc;
2493 char error_msg[64];
2494 uint8_t *capture[CAPTURE_COUNT_MAX * 2];
2495 const char *input;
2496 int input_len, capture_count;
2497
2498 if (argc < 3) {
2499 printf("usage: %s regexp input\n", argv[0]);
2500 exit(1);
2501 }
2502 bc = lre_compile(&len, error_msg, sizeof(error_msg), argv[1],
2503 strlen(argv[1]), 0, NULL);
2504 if (!bc) {
2505 fprintf(stderr, "error: %s\n", error_msg);
2506 exit(1);
2507 }
2508
2509 input = argv[2];
2510 input_len = strlen(input);
2511
2512 ret = lre_exec(capture, bc, (uint8_t *)input, 0, input_len, 0, NULL);
2513 printf("ret=%d\n", ret);
2514 if (ret == 1) {
2515 capture_count = lre_get_capture_count(bc);
2516 for(i = 0; i < 2 * capture_count; i++) {
2517 uint8_t *ptr;
2518 ptr = capture[i];
2519 printf("%d: ", i);
2520 if (!ptr)
2521 printf("<nil>");
2522 else
2523 printf("%u", (int)(ptr - (uint8_t *)input));
2524 printf("\n");
2525 }
2526 }
2527 return 0;
2528 }
2529 #endif