qr_reader-native 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE-mruby.txt +22 -0
  3. data/LICENSE-spinel.txt +19 -0
  4. data/LICENSE.txt +21 -0
  5. data/README.md +61 -0
  6. data/ext/qr_reader_native/SPINEL_VERSION +1 -0
  7. data/ext/qr_reader_native/extconf.rb +8 -0
  8. data/ext/qr_reader_native/mruby/error.h +13 -0
  9. data/ext/qr_reader_native/mruby/internal.h +145 -0
  10. data/ext/qr_reader_native/mruby/string.h +22 -0
  11. data/ext/qr_reader_native/mruby.h +93 -0
  12. data/ext/qr_reader_native/mruby_shim.h +118 -0
  13. data/ext/qr_reader_native/qr_reader_native.c +13513 -0
  14. data/ext/qr_reader_native/qr_reader_native.h +29 -0
  15. data/ext/qr_reader_native/qr_reader_native_ext.c +598 -0
  16. data/ext/qr_reader_native/re_cased.h +71 -0
  17. data/ext/qr_reader_native/re_compile.c +5784 -0
  18. data/ext/qr_reader_native/re_ctype.h +3540 -0
  19. data/ext/qr_reader_native/re_exec.c +2190 -0
  20. data/ext/qr_reader_native/re_internal.h +671 -0
  21. data/ext/qr_reader_native/re_prop.h +4629 -0
  22. data/ext/qr_reader_native/re_spinel.c +363 -0
  23. data/ext/qr_reader_native/re_spinel.h +22 -0
  24. data/ext/qr_reader_native/re_spinel_utf8.inc +97 -0
  25. data/ext/qr_reader_native/re_utf8.c +156 -0
  26. data/ext/qr_reader_native/sp_alloc.c +1447 -0
  27. data/ext/qr_reader_native/sp_alloc.h +1196 -0
  28. data/ext/qr_reader_native/sp_argf.h +33 -0
  29. data/ext/qr_reader_native/sp_array.c +1052 -0
  30. data/ext/qr_reader_native/sp_array.h +456 -0
  31. data/ext/qr_reader_native/sp_bigint.c +5826 -0
  32. data/ext/qr_reader_native/sp_bigint.h +117 -0
  33. data/ext/qr_reader_native/sp_cold.c +5259 -0
  34. data/ext/qr_reader_native/sp_compat.h +402 -0
  35. data/ext/qr_reader_native/sp_core.c +818 -0
  36. data/ext/qr_reader_native/sp_core.h +56 -0
  37. data/ext/qr_reader_native/sp_crypto.c +877 -0
  38. data/ext/qr_reader_native/sp_crypto.h +169 -0
  39. data/ext/qr_reader_native/sp_dtoa.c +1533 -0
  40. data/ext/qr_reader_native/sp_dtoa.h +29 -0
  41. data/ext/qr_reader_native/sp_encoding_names.h +172 -0
  42. data/ext/qr_reader_native/sp_enum.h +86 -0
  43. data/ext/qr_reader_native/sp_exc.c +1185 -0
  44. data/ext/qr_reader_native/sp_exc.h +186 -0
  45. data/ext/qr_reader_native/sp_exc_ctx.h +56 -0
  46. data/ext/qr_reader_native/sp_fiber.c +889 -0
  47. data/ext/qr_reader_native/sp_fiber.h +162 -0
  48. data/ext/qr_reader_native/sp_fiber_ctx.h +84 -0
  49. data/ext/qr_reader_native/sp_format.c +695 -0
  50. data/ext/qr_reader_native/sp_format.h +83 -0
  51. data/ext/qr_reader_native/sp_gc.c +1793 -0
  52. data/ext/qr_reader_native/sp_gc.h +762 -0
  53. data/ext/qr_reader_native/sp_hash.c +131 -0
  54. data/ext/qr_reader_native/sp_hash.h +131 -0
  55. data/ext/qr_reader_native/sp_inspect.c +215 -0
  56. data/ext/qr_reader_native/sp_inspect.h +128 -0
  57. data/ext/qr_reader_native/sp_io.c +1676 -0
  58. data/ext/qr_reader_native/sp_io.h +272 -0
  59. data/ext/qr_reader_native/sp_iobuffer.c +1014 -0
  60. data/ext/qr_reader_native/sp_iobuffer.h +167 -0
  61. data/ext/qr_reader_native/sp_marshal.c +487 -0
  62. data/ext/qr_reader_native/sp_marshal.h +60 -0
  63. data/ext/qr_reader_native/sp_net.c +1029 -0
  64. data/ext/qr_reader_native/sp_net.h +205 -0
  65. data/ext/qr_reader_native/sp_pack.c +1254 -0
  66. data/ext/qr_reader_native/sp_poly_cold.c +1220 -0
  67. data/ext/qr_reader_native/sp_proc.c +410 -0
  68. data/ext/qr_reader_native/sp_proc.h +327 -0
  69. data/ext/qr_reader_native/sp_process.c +547 -0
  70. data/ext/qr_reader_native/sp_process_status.c +211 -0
  71. data/ext/qr_reader_native/sp_process_status.h +66 -0
  72. data/ext/qr_reader_native/sp_random.c +287 -0
  73. data/ext/qr_reader_native/sp_random.h +52 -0
  74. data/ext/qr_reader_native/sp_range.h +144 -0
  75. data/ext/qr_reader_native/sp_re.c +1379 -0
  76. data/ext/qr_reader_native/sp_re.h +186 -0
  77. data/ext/qr_reader_native/sp_re_names.h +59 -0
  78. data/ext/qr_reader_native/sp_sched.c +4044 -0
  79. data/ext/qr_reader_native/sp_sched.h +295 -0
  80. data/ext/qr_reader_native/sp_slab.c +1507 -0
  81. data/ext/qr_reader_native/sp_str.c +1462 -0
  82. data/ext/qr_reader_native/sp_str.h +306 -0
  83. data/ext/qr_reader_native/sp_str_crypt.c +23 -0
  84. data/ext/qr_reader_native/sp_string.c +92 -0
  85. data/ext/qr_reader_native/sp_string.h +253 -0
  86. data/ext/qr_reader_native/sp_system.c +78 -0
  87. data/ext/qr_reader_native/sp_system.h +18 -0
  88. data/ext/qr_reader_native/sp_time.c +860 -0
  89. data/ext/qr_reader_native/sp_time.h +100 -0
  90. data/ext/qr_reader_native/sp_types.h +292 -0
  91. data/ext/qr_reader_native/spinel_rt.h +19017 -0
  92. data/ext/qr_reader_native/unicase.c +399 -0
  93. data/ext/qr_reader_native/unicase.h +901 -0
  94. data/lib/qr_reader/native.rb +6 -0
  95. metadata +153 -0
@@ -0,0 +1,2190 @@
1
+ /*
2
+ ** re_exec.c - NFA execution engine (Pike VM)
3
+ **
4
+ ** Executes compiled regexp bytecode using Thompson/Pike NFA simulation.
5
+ ** O(pattern * text) time complexity guarantees ReDoS resistance.
6
+ **
7
+ ** See Copyright Notice in mruby.h
8
+ */
9
+
10
+ #include "re_internal.h"
11
+ #include <string.h>
12
+
13
+ /* Whether the rest of a prefix of two bytes or more stands at `p`, whose
14
+ first byte is already known to. The last byte is tested before the ones
15
+ between it and the first, so that a position the scan below is about to
16
+ leave is left on one comparison. */
17
+ static inline mrb_bool
18
+ prefix_rest_at(const uint8_t *prefix, mrb_int plen, const char *p)
19
+ {
20
+ return (uint8_t)p[plen - 1] == prefix[plen - 1] &&
21
+ (plen == 2 || memcmp(p + 1, prefix + 1, (size_t)(plen - 2)) == 0);
22
+ }
23
+
24
+ /*
25
+ * The first position at or after `sp` where a prefix of two bytes or more
26
+ * stands, or NULL when the subject holds none before `str_end`.
27
+ *
28
+ * A scan on the first byte alone proposes a position per occurrence of it, and
29
+ * a subject made mostly of that byte -- /aaaaab/ over a run of `a` -- then
30
+ * costs a rejected comparison per position. The prefix's last byte is scanned
31
+ * for too, at the offset it stands at: where it is not there, the next place
32
+ * it is names the next position worth proposing, and getting there is one
33
+ * scan rather than the occurrences of the first byte one at a time.
34
+ *
35
+ * The second scan runs only where the first byte was found and the last was
36
+ * not, so a subject that holds the first byte nowhere costs what it costs with
37
+ * one scan. Every round leaves `sp` past where it entered, so the two get
38
+ * through the subject once between them whichever of the bytes is the one that
39
+ * keeps being found.
40
+ *
41
+ * It earns its place by skipping positions the first scan would have proposed
42
+ * one at a time, and a subject can be built where it skips none: both bytes
43
+ * all through it, never at the distance the prefix puts them. It is dropped
44
+ * where that shows, leaving the walk the one scan it had before, so no subject
45
+ * pays for it twice over.
46
+ */
47
+ static const char*
48
+ find_prefix_ends(const uint8_t *prefix, mrb_int plen, const char *sp, const char *str_end)
49
+ {
50
+ if (str_end - sp < plen) return NULL;
51
+ /* The last position a match can start at, so the first scan never proposes
52
+ one the subject is too short to hold. */
53
+ const char *limit = str_end - plen;
54
+ mrb_int last = plen - 1;
55
+ mrb_bool scan_last = TRUE;
56
+
57
+ while (sp <= limit) {
58
+ const char *base = sp;
59
+ const char *p0 = (const char*)memchr(sp, prefix[0], (size_t)(limit - sp) + 1);
60
+ if (!p0) return NULL;
61
+ if (prefix_rest_at(prefix, plen, p0)) return p0;
62
+ if (!scan_last || (uint8_t)p0[last] == prefix[last]) {
63
+ /* Nothing to scan for: either the last byte is here too and only the
64
+ bytes between the ends disagree, which says nothing about where the
65
+ next position is, or the scan has been dropped. */
66
+ sp = p0 + 1;
67
+ continue;
68
+ }
69
+ /* Where the last byte stands next names the position a match holding it
70
+ would start at, which is past the one the first byte just named. */
71
+ const char *p1 = (const char*)memchr(p0 + last + 1, prefix[last],
72
+ (size_t)(str_end - (p0 + last + 1)));
73
+ if (!p1) return NULL;
74
+ const char *cand = p1 - last;
75
+ /* Reaching no further than the first scan had just reached is the second
76
+ one proposing the positions it is supposed to be skipping. */
77
+ if (cand - p0 <= p0 - base) scan_last = FALSE;
78
+ sp = cand;
79
+ }
80
+ return NULL;
81
+ }
82
+
83
+ /* The first position at or after `sp` where a prefix of `plen` bytes stands,
84
+ or NULL when the subject holds none. The first scan, and the comparison at
85
+ the position it names, are here rather than behind the walk above: they are
86
+ the whole of the question for a prefix of one byte, and the whole of it
87
+ again wherever the position the scan names is the answer, which is what a
88
+ pattern that matches often asks over and over. The walk is entered only
89
+ where that answer was no. */
90
+ static inline const char*
91
+ find_prefix(const uint8_t *prefix, mrb_int plen, const char *sp, const char *str_end)
92
+ {
93
+ const char *p = (const char*)memchr(sp, prefix[0], (size_t)(str_end - sp));
94
+ if (!p || plen == 1) return p;
95
+ /* A first occurrence of the first byte too near the end settles the whole
96
+ subject, since every later one stands nearer still. */
97
+ if (str_end - p < plen) return NULL;
98
+ if (prefix_rest_at(prefix, plen, p)) return p;
99
+ return find_prefix_ends(prefix, plen, p, str_end);
100
+ }
101
+
102
+ /*
103
+ * Skip to the next position where the pattern's literal prefix could match.
104
+ * Returns the found position, or NULL if no match is possible.
105
+ */
106
+ static const char*
107
+ skip_to_prefix(const mrb_regexp_pattern *pat, const char *sp, const char *str_end)
108
+ {
109
+ if (pat->prefix_len == 0) return sp;
110
+ return find_prefix(pat->prefix, pat->prefix_len, sp, str_end);
111
+ }
112
+
113
+ /* Check if a byte is in the first-byte bitmap */
114
+ #define FIRST_BYTE_OK(pat, ch) \
115
+ ((pat)->first_bytes[(ch) >> 3] & (1 << ((ch) & 7)))
116
+
117
+ /*
118
+ * Skip to the next position a match could start at, per the first-byte set.
119
+ * Returns NULL when no such position remains: the set never holds a byte the
120
+ * pattern can match empty at (first_set_walk() answers FALSE there), so a
121
+ * subject with none of it left holds no match either.
122
+ *
123
+ * A set of up to three bytes is scanned with one bounded memchr per member,
124
+ * each next call bounded by the nearest find so far, so every byte is read at
125
+ * most first_byte_count times and by memchr rather than one test at a time. A
126
+ * wider set walks the bitmap. Either can stop on a member byte inside a
127
+ * character, which the search's interior test refuses as it refuses any
128
+ * position there; see class_first_bytes().
129
+ */
130
+ static const char*
131
+ skip_to_first_byte(const mrb_regexp_pattern *pat, const char *sp, const char *str_end)
132
+ {
133
+ int n = pat->first_byte_count;
134
+ if (n == 0) {
135
+ while (sp < str_end && !FIRST_BYTE_OK(pat, (uint8_t)*sp)) sp++;
136
+ return sp < str_end ? sp : NULL;
137
+ }
138
+ if (sp >= str_end) return NULL;
139
+ /* The caller asks again after every failed attempt, and on a dense subject
140
+ the answer is usually the position it is already at: answer that with the
141
+ member tests alone, keeping the call per byte no dearer than the bitmap
142
+ test it replaces. */
143
+ uint8_t b = (uint8_t)*sp;
144
+ for (int i = 0; i < n; i++) {
145
+ if (b == pat->first_byte[i]) return sp;
146
+ }
147
+ const char *found = NULL;
148
+ size_t span = (size_t)(str_end - sp);
149
+ for (int i = 0; i < n; i++) {
150
+ const char *p = (const char*)memchr(sp, pat->first_byte[i], span);
151
+ if (p) {
152
+ found = p;
153
+ span = (size_t)(p - sp);
154
+ }
155
+ }
156
+ return found;
157
+ }
158
+
159
+ /*
160
+ * Skip to the next position a line-anchored match could start at: the string
161
+ * start, or just after a \n. Everything between fails RE_BOL on its first
162
+ * step, so those positions are gone as candidates, found by memchr rather
163
+ * than proposed one at a time. The tests here are RE_BOL's own: the very end
164
+ * is no line start (a trailing \n opens no final line), except when the
165
+ * string is empty and the end is the start. Returns NULL when no candidate
166
+ * remains.
167
+ */
168
+ static const char*
169
+ skip_to_line_start(const char *str, const char *sp, const char *str_end)
170
+ {
171
+ if (sp == str || (sp != str_end && sp[-1] == '\n')) return sp;
172
+ const char *nl = (const char*)memchr(sp, '\n', (size_t)(str_end - sp));
173
+ if (!nl || nl + 1 == str_end) return NULL;
174
+ return nl + 1;
175
+ }
176
+
177
+ /* Check if the current input character matches a character class. ASCII
178
+ (cp < 128) hits the bitmap; non-ASCII falls back to the inclusive (lo, hi)
179
+ range list, then to the types the class holds by POSIX bracket, then to the
180
+ utf8_any catch-all (used by negated shorthand like \D).
181
+
182
+ `raw` says the input is a byte rather than a character: a byte-indexed
183
+ subject, or one whose byte at this position starts no whole character. It
184
+ picks which half of the range list to read, since a byte member and a
185
+ codepoint member of the same number are different members and arrive here as
186
+ the same number. A byte has no type, so it is in the class through a
187
+ negated bracket and not through a positive one. utf8_any is the answer for
188
+ either, being about the byte being non-ASCII at all. */
189
+ static mrb_bool
190
+ class_match(const re_charclass *cc, uint32_t cp, mrb_bool raw)
191
+ {
192
+ if (cp < 128) {
193
+ return (cc->bitmap[cp >> 3] >> (cp & 7)) & 1;
194
+ }
195
+ if (raw) cp |= RE_CLASS_BYTE;
196
+ for (uint32_t i = 0; i < cc->num_ranges; i++) {
197
+ if (cp >= cc->ranges[2*i] && cp <= cc->ranges[2*i + 1]) return TRUE;
198
+ }
199
+ #ifdef RE_UNICODE_CTYPE
200
+ if (RE_CLASS_HAS_CTYPE(cc)) return mrb_re_class_ctype_match(cc, cp);
201
+ #endif
202
+ return cc->utf8_any;
203
+ }
204
+
205
+ /* The fold of one unit of the subject. A byte-indexed subject hands out
206
+ bytes, and a byte above 127 is not the codepoint of the same value: 0xC0 is
207
+ not U+00C0, so folding it to 0xE0 would pair two bytes that spell no letter
208
+ in common. The letters a byte can spell are the ASCII ones, and those fold
209
+ as they do everywhere. */
210
+ static inline uint32_t
211
+ subject_fold(uint32_t c, mrb_bool binary)
212
+ {
213
+ if (binary && c >= 128) return c;
214
+ return mrb_re_case_fold(c);
215
+ }
216
+
217
+ /* Compare two spans ignoring case. Returns how many bytes of `a` were
218
+ consumed, or -1 when they differ. The count is not always the length of
219
+ `b`: with Unicode folding a counterpart can be a different width (U+212A
220
+ folds to 'k'), so the two spans can match while holding different numbers
221
+ of bytes. */
222
+ static int
223
+ memcmp_ci(const char *a, const char *a_end, const char *b, const char *b_end,
224
+ mrb_bool binary)
225
+ {
226
+ const char *a0 = a;
227
+ while (b < b_end) {
228
+ if (a >= a_end) return -1;
229
+ int alen = 0, blen = 0;
230
+ uint32_t ca = mrb_re_decode_char(a, a_end, &alen, binary);
231
+ uint32_t cb = mrb_re_decode_char(b, b_end, &blen, binary);
232
+ if (subject_fold(ca, binary) != subject_fold(cb, binary)) return -1;
233
+ a += alen;
234
+ b += blen;
235
+ }
236
+ return (int)(a - a0);
237
+ }
238
+
239
+ /*
240
+ * Pike VM with optimized thread storage.
241
+ *
242
+ * Key optimizations vs naive approach:
243
+ * - Captures stored in a flat pool, sized to actual ncap (not RE_MAX_CAPTURES)
244
+ * - Generation counter for visited[] eliminates per-step memset
245
+ * - Threads reference captures by pool index, avoiding 260-byte struct copies
246
+ */
247
+
248
+ typedef re_thread_cache re_thread;
249
+
250
+ typedef struct {
251
+ re_thread *threads;
252
+ int count;
253
+ int capa;
254
+ } re_threadlist;
255
+
256
+ /* A branch of a fork the closure has yet to walk: where it starts and what
257
+ it starts with. The walk carries the higher-priority branch on and keeps
258
+ the other one of these (see add_thread()). The position is not in here
259
+ because a closure stands at one: the walk crosses no instruction that
260
+ consumes, so every branch it keeps begins where the walk began. */
261
+ typedef struct {
262
+ uint32_t pc;
263
+ uint32_t key;
264
+ int cap_slot;
265
+ } re_pending;
266
+
267
+ /* Branches the state holds without asking the allocator for room. A pattern
268
+ whose forks nest no deeper than this spends nothing on them, which is
269
+ every pattern short of the ones written to nest. */
270
+ #define RE_PEND_INLINE 16
271
+
272
+ /* Capture ints the state holds for the pool and for the best match without
273
+ asking the allocator: two allocations a search is otherwise, and a scan or
274
+ a split searches once per match. The pool of a short pattern with few
275
+ groups fits, which is what those run; a larger one starts on the heap. */
276
+ #define RE_POOL_INLINE 128
277
+ #define RE_RESULT_INLINE 32
278
+
279
+ /* All Pike VM state */
280
+ typedef struct {
281
+ mrb_state *mrb;
282
+ const mrb_regexp_pattern *pat;
283
+ int ncap; /* actual capture count (num_captures * 2) */
284
+ int *cap_pool; /* flat: cap_pool[slot * ncap .. (slot+1) * ncap) */
285
+ int pool_next; /* next free slot */
286
+ int pool_capa; /* total slots allocated */
287
+ uint32_t *visited; /* generation-based */
288
+ uint32_t gen; /* visited key this step's first epsilon pass uses */
289
+ uint32_t key_max; /* highest key a further pass may reach this step */
290
+ uint32_t pass_span; /* keys one step reserves: key_max - gen + 1 */
291
+ const char *str;
292
+ const char *str_end;
293
+ mrb_bool matched;
294
+ mrb_bool match_only; /* true: skip capture tracking (match? path) */
295
+ mrb_bool binary; /* true: subject is byte-indexed ASCII-8BIT */
296
+ mrb_bool cut; /* a higher-priority thread matched this step:
297
+ stop adding/processing lower-priority threads */
298
+ mrb_bool nomem; /* the allocator refused the search a buffer it
299
+ needed: it stops and answers RE_NOMEM */
300
+ int *result_caps; /* best match (ncap ints) */
301
+ re_pending *pend; /* branches a closure left for later: pend_inline
302
+ until the nesting outgrows it, the heap after */
303
+ uint32_t pend_top; /* entries in use, the newest at the top */
304
+ uint32_t pend_capa;
305
+ re_pending pend_inline[RE_PEND_INLINE];
306
+ int pool_inline[RE_POOL_INLINE];
307
+ int result_inline[RE_RESULT_INLINE];
308
+ } pike_state;
309
+
310
+ /* Hand out a capture slot, growing the pool where it has none left. TRUE is
311
+ a slot having been handed out, and FALSE is the allocator having refused
312
+ the growth, which is the search stopping: there is no slot to answer with,
313
+ and an index that is not one would be read as a slot all the same. The
314
+ refusal is recorded on the state as well, since the walk that asked for it
315
+ is several frames deep and hands nothing back (see add_thread()).
316
+
317
+ Growing with mrb_realloc_simple() rather than mrb_realloc() is what lets
318
+ the refusal be an answer at all, for the reason pike_vm() gives: a raising
319
+ allocator here jumps past the epilogue that frees the pool and releases
320
+ the cache, and by this point the search holds all of both. */
321
+ static mrb_bool
322
+ pool_grow(pike_state *s)
323
+ {
324
+ int new_capa = s->pool_capa * 2;
325
+ size_t size = sizeof(int) * new_capa * s->ncap;
326
+ int *p;
327
+ if (s->cap_pool == s->pool_inline) {
328
+ /* The pool leaves the state for the heap, taking what it holds. */
329
+ p = (int*)mrb_malloc_simple(s->mrb, size);
330
+ if (p) memcpy(p, s->pool_inline, sizeof(int) * s->pool_capa * s->ncap);
331
+ }
332
+ else {
333
+ p = (int*)mrb_realloc_simple(s->mrb, s->cap_pool, size);
334
+ }
335
+ if (!p) {
336
+ s->nomem = TRUE;
337
+ return FALSE;
338
+ }
339
+ s->cap_pool = p;
340
+ s->pool_capa = new_capa;
341
+ return TRUE;
342
+ }
343
+
344
+ /* The growth is a call of its own so that this, which runs for every slot a
345
+ step hands out, stays small enough to be taken inline. */
346
+ static inline mrb_bool
347
+ pool_alloc(pike_state *s, int *slot)
348
+ {
349
+ if (s->pool_next >= s->pool_capa && !pool_grow(s)) return FALSE;
350
+ *slot = s->pool_next++;
351
+ return TRUE;
352
+ }
353
+
354
+ /* A fresh slot holding what `src_slot` holds. Answers as pool_alloc() does,
355
+ and for the same reason. */
356
+ static mrb_bool
357
+ pool_copy(pike_state *s, int src_slot, int *slot)
358
+ {
359
+ int dst;
360
+ if (!pool_alloc(s, &dst)) return FALSE;
361
+ memcpy(&s->cap_pool[dst * s->ncap],
362
+ &s->cap_pool[src_slot * s->ncap],
363
+ sizeof(int) * s->ncap);
364
+ *slot = dst;
365
+ return TRUE;
366
+ }
367
+
368
+ #define CAP(s, slot) (&(s)->cap_pool[(slot) * (s)->ncap])
369
+
370
+ /* Hand this step's closure a fresh block of visited keys. A step reserves one
371
+ key per epsilon pass, so the counter climbs faster than the single step it
372
+ used to; on a long enough subject it would wrap, leaving marks from earlier
373
+ steps outranking every fresh key and the closure adding nothing. Clear the
374
+ marks and start the keys over when that comes into reach, which also keeps
375
+ a live key below RE_LOOP_STOP. */
376
+ static void
377
+ advance_gen(pike_state *s)
378
+ {
379
+ if (s->key_max > UINT32_MAX - 2 * s->pass_span) {
380
+ memset(s->visited, 0, sizeof(uint32_t) * (s->pat->code_len + 1));
381
+ s->gen = 0;
382
+ s->key_max = s->pass_span - 1;
383
+ }
384
+ s->gen += s->pass_span;
385
+ s->key_max += s->pass_span;
386
+ }
387
+
388
+ /* TRUE once this step's closure has walked the loop head at pc, which means
389
+ the body just ran without consuming: an empty iteration. */
390
+ static mrb_bool
391
+ loop_head_seen(pike_state *s, uint32_t pc)
392
+ {
393
+ return s->visited[pc] >= s->gen;
394
+ }
395
+
396
+ /* A fork also closes e+: the body is laid out before it, so its jump target
397
+ is the body start and pc+1 is the loop's exit. Returns the key the jump
398
+ target's branch walks under, or RE_LOOP_STOP when the body matched empty
399
+ and the repetition therefore has to stop. An ordinary fork, or one closing
400
+ a loop whose body always consumes (`a` is 0, see mark_empty_loops()), has
401
+ no empty iteration to account for and keeps the current key. advance_gen()
402
+ holds every live key below the sentinel. */
403
+ #define RE_LOOP_STOP UINT32_MAX
404
+
405
+ static uint32_t
406
+ re_loop_back(pike_state *s, re_inst inst, uint32_t pc, uint32_t key)
407
+ {
408
+ if (inst.offset > pc || !inst.a) return key;
409
+ if (loop_head_seen(s, inst.offset)) return RE_LOOP_STOP;
410
+ return key < s->key_max ? key + 1 : key;
411
+ }
412
+
413
+ /* Room for one more branch, once the ones the state holds are all in use.
414
+ Answers as pool_alloc() does, and for the same reason: FALSE is the
415
+ allocator having refused the room, which is the search stopping, and the
416
+ refusal is recorded on the state since the walk that asked for it hands
417
+ nothing back. Kept out of pend_push() because a pattern reaching it at all
418
+ is one written to nest. */
419
+ static mrb_bool
420
+ pend_grow(pike_state *s)
421
+ {
422
+ uint32_t capa = s->pend_capa * 2;
423
+ re_pending *p;
424
+ if (s->pend == s->pend_inline) {
425
+ p = (re_pending*)mrb_malloc_simple(s->mrb, sizeof(re_pending) * capa);
426
+ if (p) memcpy(p, s->pend_inline, sizeof(re_pending) * s->pend_capa);
427
+ }
428
+ else {
429
+ p = (re_pending*)mrb_realloc_simple(s->mrb, s->pend,
430
+ sizeof(re_pending) * capa);
431
+ }
432
+ if (!p) {
433
+ s->nomem = TRUE;
434
+ return FALSE;
435
+ }
436
+ s->pend = p;
437
+ s->pend_capa = capa;
438
+ return TRUE;
439
+ }
440
+
441
+ /* Keep a fork's lower-priority branch for the walk to come back to. Inline:
442
+ this stands where the recursive call it replaced stood, in the closure's
443
+ own loop, and a call of its own is what the walk is here to stop making. */
444
+ static inline mrb_bool
445
+ pend_push(pike_state *s, uint32_t pc, int cap_slot, uint32_t key)
446
+ {
447
+ if (s->pend_top == s->pend_capa && !pend_grow(s)) return FALSE;
448
+ re_pending *e = &s->pend[s->pend_top++];
449
+ e->pc = pc;
450
+ e->cap_slot = cap_slot;
451
+ e->key = key;
452
+ return TRUE;
453
+ }
454
+
455
+ /* Add thread following epsilon transitions. `key` is s->gen for the first
456
+ pass over this step's closure and one higher per further pass, and
457
+ visited[pc] holds the key of the pass that last walked pc: a later pass may
458
+ re-walk what an earlier one marked, and no key is ever reused by a later
459
+ step.
460
+
461
+ A fork's branches are walked in priority order: the walk carries the
462
+ higher-priority one on and keeps the other on the state's own stack,
463
+ coming back to the newest of them whenever the branch it followed ends.
464
+ That order is the one walking the higher branch in a call of its own gave,
465
+ and a closure now costs one C frame however deeply the forks it walks
466
+ nest: 1,000 nested `(?:...)?` used to need more C stack than a 128 KiB
467
+ build has, and the 4,095 levels the parse depth limit allows more than
468
+ 256 KiB. */
469
+ static void
470
+ add_thread(pike_state *s, re_threadlist *list,
471
+ uint32_t pc, int cap_slot, const char *sp, uint32_t key)
472
+ {
473
+ s->pend_top = 0;
474
+
475
+ for (;;) {
476
+ for (;;) {
477
+ /* Both of these end the walk without an answer to hand back: a cut is
478
+ this step having been settled by a higher-priority thread, and a
479
+ refused allocation is the search stopping (see pool_alloc()). */
480
+ if (s->cut || s->nomem) goto leave;
481
+ if (pc >= s->pat->code_len) goto next;
482
+ if (s->visited[pc] >= key) goto next;
483
+ s->visited[pc] = key;
484
+
485
+ re_inst inst = s->pat->code[pc];
486
+ switch (inst.op) {
487
+ case RE_JMP:
488
+ /* A backward jump closes a repetition (e*, e{n,}): it returns to the
489
+ RE_SPLIT/RE_SPLITNG head, whose offset is the loop's exit. `a` is set
490
+ only when that body can run empty (see mark_empty_loops()), which is
491
+ the only case with a final empty iteration to account for. */
492
+ if (inst.offset <= pc && inst.a) {
493
+ uint32_t head = inst.offset;
494
+ if (loop_head_seen(s, head)) {
495
+ /* The head was walked at this position, so the iteration that just
496
+ finished consumed nothing. Onigmo stops a repetition on an empty
497
+ iteration and keeps what that iteration captured, so leave the
498
+ loop from here rather than dying on the head's mark: this path
499
+ outranks the exit the head itself queued before the body ran, and
500
+ claims the exit pc first. */
501
+ pc = s->pat->code[head].offset;
502
+ continue;
503
+ }
504
+ /* The head is unmarked, so this closure resumed inside the body and
505
+ the iteration it just finished is a real one. Run the next
506
+ iteration in a fresh pass, past the marks the resumed tail left. */
507
+ if (key < s->key_max) key++;
508
+ pc = head;
509
+ continue;
510
+ }
511
+ pc = inst.offset;
512
+ continue;
513
+
514
+ case RE_SPLIT:
515
+ /* Greedy fork: the fall-through (pc+1) outranks the jump target, the
516
+ same priority order the backtracking engine uses. Follow the
517
+ higher-priority branch first so it claims shared pcs (visited[]) and
518
+ reaches a match before the lower one. Snapshot the captures before
519
+ pc+1's closure can mutate the shared slot; the jump branch then runs
520
+ on that snapshot. */
521
+ {
522
+ uint32_t back = re_loop_back(s, inst, pc, key);
523
+ if (back == RE_LOOP_STOP) { pc++; continue; }
524
+ int cp = 0;
525
+ if (!s->match_only && !pool_copy(s, cap_slot, &cp)) goto leave;
526
+ if (!pend_push(s, inst.offset, cp, back)) goto leave;
527
+ pc = pc + 1;
528
+ }
529
+ continue;
530
+
531
+ case RE_SPLITNG:
532
+ /* Non-greedy fork: the jump target outranks the fall-through. */
533
+ {
534
+ uint32_t back = re_loop_back(s, inst, pc, key);
535
+ if (back == RE_LOOP_STOP) { pc++; continue; }
536
+ int cp = 0;
537
+ if (!s->match_only && !pool_copy(s, cap_slot, &cp)) goto leave;
538
+ if (!pend_push(s, pc + 1, cp, key)) goto leave;
539
+ pc = inst.offset;
540
+ key = back;
541
+ }
542
+ continue;
543
+
544
+ case RE_SAVE:
545
+ /* No test that the position is a character boundary: it is one. A byte
546
+ that spells no character is RE_BYTE and matches only where the subject
547
+ byte stands alone, so no atom stops between two bytes of a character
548
+ and no position a group is recorded at is inside one. The rule used to
549
+ be tested here, on the end of group 0 and then on every slot. */
550
+ if (!s->match_only) {
551
+ CAP(s, cap_slot)[inst.offset] = (int)(sp - s->str);
552
+ }
553
+ pc++;
554
+ continue;
555
+
556
+ case RE_BOL:
557
+ /* ^ always matches at a line start (string start or just after a \n);
558
+ Ruby's /m only affects `.`, not the line anchors. \A is RE_BOT. A
559
+ trailing \n does not open a final line, so ^ does not match at the
560
+ very end. */
561
+ if (sp == s->str || (sp != s->str_end && sp[-1] == '\n')) {
562
+ pc++; continue;
563
+ }
564
+ goto next;
565
+
566
+ case RE_EOL:
567
+ /* $ always matches at a line end (string end or just before a \n). */
568
+ if (sp == s->str_end || *sp == '\n') {
569
+ pc++; continue;
570
+ }
571
+ goto next;
572
+
573
+ case RE_BOT:
574
+ if (sp == s->str) { pc++; continue; }
575
+ goto next;
576
+
577
+ case RE_EOT:
578
+ if (sp == s->str_end) { pc++; continue; }
579
+ goto next;
580
+
581
+ case RE_EOTNL:
582
+ if (sp == s->str_end || (sp + 1 == s->str_end && *sp == '\n')) { pc++; continue; }
583
+ goto next;
584
+
585
+ case RE_WBOUND:
586
+ {
587
+ mrb_bool before = (sp > s->str) && mrb_re_word_before(s->str, sp, s->str_end, s->binary);
588
+ mrb_bool after = (sp < s->str_end) && mrb_re_word_at(sp, s->str_end, s->binary);
589
+ if (before != after) { pc++; continue; }
590
+ }
591
+ goto next;
592
+
593
+ case RE_NWBOUND:
594
+ {
595
+ mrb_bool before = (sp > s->str) && mrb_re_word_before(s->str, sp, s->str_end, s->binary);
596
+ mrb_bool after = (sp < s->str_end) && mrb_re_word_at(sp, s->str_end, s->binary);
597
+ if (before == after) { pc++; continue; }
598
+ }
599
+ goto next;
600
+
601
+ case RE_MATCH:
602
+ s->matched = TRUE;
603
+ if (s->result_caps) {
604
+ memcpy(s->result_caps, CAP(s, cap_slot), sizeof(int) * s->ncap);
605
+ }
606
+ /* Leftmost-first: this is the highest-priority thread to reach a match
607
+ this step (closures run in priority order), so cut every lower one.
608
+ A surviving higher-priority thread can still match later and override
609
+ this in a subsequent step, which is the correct greedy/longest case. */
610
+ s->cut = TRUE;
611
+ goto leave;
612
+
613
+ default:
614
+ break;
615
+ }
616
+ break;
617
+ }
618
+
619
+ if (list->count < list->capa) {
620
+ re_thread *t = &list->threads[list->count++];
621
+ t->pc = pc;
622
+ t->cap_slot = cap_slot;
623
+ t->sp = sp;
624
+ }
625
+
626
+ next:
627
+ /* The branch the walk followed is finished, whether it left a thread
628
+ behind or died on an assertion. What a fork kept is walked newest
629
+ first, which is the order a call of its own gave the higher branch:
630
+ every branch a fork opened below this one has been walked by now. */
631
+ if (s->pend_top == 0) return;
632
+ {
633
+ re_pending *e = &s->pend[--s->pend_top];
634
+ pc = e->pc;
635
+ cap_slot = e->cap_slot;
636
+ key = e->key;
637
+ }
638
+ }
639
+
640
+ leave:
641
+ /* A cut and a refusal both end the closure whole, the branches kept for
642
+ later included: the cut has nothing lower to add and the refusal has
643
+ nowhere to add it. */
644
+ s->pend_top = 0;
645
+ }
646
+
647
+ static int
648
+ pike_vm(mrb_state *mrb, const mrb_regexp_pattern *pat,
649
+ const char *str, mrb_int len, mrb_int start, mrb_int start_limit,
650
+ int *captures, int captures_size, mrb_bool binary)
651
+ {
652
+ const char *start_cap = str + start_limit;
653
+ const char *sp = str + start;
654
+ const char *str_end = str + len;
655
+ /* \A: no position past the string start can begin a match, which is what
656
+ start_cap already bounds, so the anchor costs the scan loop nothing. */
657
+ if (pat->anchor == RE_ANCHOR_BOT) start_cap = str;
658
+ int ncap = pat->num_captures * 2;
659
+ if (ncap == 0) ncap = 2;
660
+
661
+ int list_capa = RE_LIST_CAPA(pat->code_len, pat->loop_depth);
662
+
663
+ mrb_bool match_only = (captures == NULL || captures_size == 0);
664
+
665
+ /* Use cached VM state if available (avoids malloc per call). Whether this
666
+ search may have it is decided here, since it decides what there is left
667
+ to allocate; the claim itself is made below, once nothing is left to
668
+ ask for. */
669
+ mrb_regexp_pattern *mpat = (mrb_regexp_pattern*)pat; /* for cache_in_use flag */
670
+ #ifdef SP_THREADS
671
+ /* spinel: the claim has to be atomic where threads are real, since a
672
+ pattern is shared by every thread matching against it (spinel #4082), so
673
+ it is made here and given back below if the search cannot run */
674
+ mrb_bool use_cache = mpat->cached_visited != NULL &&
675
+ !__atomic_exchange_n(&mpat->cache_in_use, (mrb_bool)TRUE, __ATOMIC_ACQUIRE);
676
+ #else
677
+ mrb_bool use_cache = !mpat->cache_in_use && mpat->cached_visited != NULL;
678
+ #endif
679
+
680
+ pike_state s;
681
+ s.mrb = mrb;
682
+ s.pat = pat;
683
+ s.ncap = ncap;
684
+ s.str = str;
685
+ s.str_end = str_end;
686
+ s.matched = FALSE;
687
+ s.match_only = match_only;
688
+ s.binary = binary;
689
+ s.cut = FALSE;
690
+ s.nomem = FALSE;
691
+ s.pass_span = RE_PASS_SPAN(pat->loop_depth);
692
+ s.gen = 0;
693
+ s.key_max = s.pass_span - 1;
694
+ s.pend = s.pend_inline;
695
+ s.pend_top = 0;
696
+ s.pend_capa = RE_PEND_INLINE;
697
+
698
+ /* Everything this search holds is given back by one epilogue below, which
699
+ an allocator that raises would jump past: what had been taken by then
700
+ would be leaked, and the cache claim made after it would stand for the
701
+ rest of the pattern's life, since nothing but that epilogue clears it.
702
+ The allocator that answers NULL is what lets a refusal be the search's
703
+ own answer (RE_NOMEM) and leave by the same exit as every other one.
704
+ What was not taken is left NULL, which the epilogue frees as readily. */
705
+ size_t vsize = sizeof(uint32_t) * ((size_t)pat->code_len + 1);
706
+ s.pool_next = 0;
707
+ s.result_caps = NULL;
708
+ s.pool_capa = match_only ? 1 : list_capa * 2;
709
+ if ((size_t)s.pool_capa * ncap <= RE_POOL_INLINE) s.cap_pool = s.pool_inline;
710
+ else s.cap_pool = (int*)mrb_malloc_simple(mrb, sizeof(int) * s.pool_capa * ncap);
711
+ if (!match_only) {
712
+ if (ncap <= RE_RESULT_INLINE) s.result_caps = s.result_inline;
713
+ else s.result_caps = (int*)mrb_malloc_simple(mrb, sizeof(int) * ncap);
714
+ }
715
+ if (!s.cap_pool || (!match_only && !s.result_caps)) s.nomem = TRUE;
716
+ else if (s.result_caps) memset(s.result_caps, -1, sizeof(int) * ncap);
717
+
718
+ re_threadlist curr, next;
719
+ s.visited = NULL;
720
+ curr.threads = next.threads = NULL;
721
+ curr.capa = next.capa = 0;
722
+ curr.count = next.count = 0;
723
+ if (s.nomem) {
724
+ /* The search is over before it starts; there is nothing left to take. */
725
+ }
726
+ else if (use_cache) {
727
+ s.visited = mpat->cached_visited;
728
+ memset(s.visited, 0, vsize);
729
+ curr.threads = (re_thread*)mpat->cached_threads[0];
730
+ next.threads = (re_thread*)mpat->cached_threads[1];
731
+ curr.capa = next.capa = mpat->cached_list_capa;
732
+ }
733
+ else {
734
+ s.visited = (uint32_t*)mrb_malloc_simple(mrb, vsize);
735
+ curr.threads = (re_thread*)mrb_malloc_simple(mrb, sizeof(re_thread) * list_capa);
736
+ next.threads = (re_thread*)mrb_malloc_simple(mrb, sizeof(re_thread) * list_capa);
737
+ if (!s.visited || !curr.threads || !next.threads) {
738
+ s.nomem = TRUE;
739
+ }
740
+ else {
741
+ memset(s.visited, 0, vsize);
742
+ curr.capa = next.capa = list_capa;
743
+ }
744
+ }
745
+
746
+ /* Claim the cache last. The claim is on the pattern, which outlives the
747
+ search, so it may not be made where something between it and the
748
+ epilogue could leave without reaching the epilogue, which is what every
749
+ allocation above could do until it stopped raising. A search that
750
+ was refused the memory to run never claims it and never used it, so it
751
+ is not the one to release it either. */
752
+ #ifdef SP_THREADS
753
+ if (s.nomem && use_cache) {
754
+ __atomic_store_n(&mpat->cache_in_use, (mrb_bool)FALSE, __ATOMIC_RELEASE);
755
+ use_cache = FALSE;
756
+ }
757
+ #else
758
+ if (s.nomem) use_cache = FALSE;
759
+ else if (use_cache) mpat->cache_in_use = TRUE;
760
+ #endif
761
+
762
+ for (; !s.nomem && sp <= str_end; sp++) {
763
+ /* Past the last position a match may start at, only the threads already
764
+ running can still answer; once they are gone nothing can. */
765
+ if (!s.matched && sp > start_cap && curr.count == 0) break;
766
+ if (!s.matched && sp <= start_cap) {
767
+ /* Skip ahead when no active threads */
768
+ if (curr.count == 0) {
769
+ /* ^: every branch asserts a line start first, so only those are
770
+ candidates. \A was folded into start_cap on entry; such a pattern
771
+ reaches here at the start alone, where the line-start answer is
772
+ the position unchanged. */
773
+ if (pat->anchor != RE_ANCHOR_NONE) {
774
+ const char *skip = skip_to_line_start(str, sp, str_end);
775
+ if (!skip) break;
776
+ sp = skip;
777
+ }
778
+ if (pat->prefix_len > 0) {
779
+ const char *skip = skip_to_prefix(pat, sp, str_end);
780
+ if (!skip) break;
781
+ sp = skip;
782
+ }
783
+ else if (pat->has_first_bytes) {
784
+ const char *skip = skip_to_first_byte(pat, sp, str_end);
785
+ if (!skip) break;
786
+ sp = skip;
787
+ }
788
+ if (sp > start_cap) break;
789
+ }
790
+ /* Don't seed a new match attempt inside a character. Its interior is
791
+ not a char boundary, and starting a thread there mis-decodes the
792
+ char (e.g. a class match on a stray 0x82 instead of the leader's
793
+ full codepoint). A byte that no lead byte reaches belongs to no
794
+ character and is a boundary of its own.
795
+ Threads seeded earlier are still stepped at this position, so the
796
+ test guards the seeding alone and never skips the iteration. */
797
+ if (s.binary || sp >= str_end ||
798
+ !mrb_re_char_interior_p(str, sp, str_end)) {
799
+ int slot = 0;
800
+ if (!match_only) {
801
+ if (!pool_alloc(&s, &slot)) break;
802
+ memset(CAP(&s, slot), -1, sizeof(int) * ncap);
803
+ }
804
+ advance_gen(&s);
805
+ s.cut = FALSE;
806
+ add_thread(&s, &curr, 0, slot, sp, s.gen);
807
+ if (s.nomem) break;
808
+ if (s.matched && curr.count == 0) break;
809
+ }
810
+ }
811
+
812
+ if (sp >= str_end) break;
813
+
814
+ if (!match_only && curr.count > 0) {
815
+ /* Renumber each live thread's capture slot to its list index so the
816
+ pool can be reset to curr.count. Stage the copies through freshly
817
+ allocated tail slots first: writing straight to CAP(i) would clobber
818
+ a low slot that a later thread (index j > i) still needs to read
819
+ whenever the slot assignment is a non-identity permutation -- which
820
+ happens once alternation reorders threads relative to their slot
821
+ numbers. Tail slots are disjoint from every source slot, and the
822
+ final block copy to the front is disjoint because pool_next >= count. */
823
+ int base = s.pool_next;
824
+ for (int i = 0; i < curr.count; i++) {
825
+ int dst;
826
+ if (!pool_alloc(&s, &dst)) break;
827
+ memcpy(CAP(&s, dst), CAP(&s, curr.threads[i].cap_slot),
828
+ sizeof(int) * ncap);
829
+ curr.threads[i].cap_slot = i;
830
+ }
831
+ /* Leave before the block copy rather than after it: the staging slots
832
+ it reads from are the ones the loop above was refused, and `base` is
833
+ past the end of the pool without them. */
834
+ if (s.nomem) break;
835
+ memcpy(&s.cap_pool[0], &s.cap_pool[base * ncap],
836
+ sizeof(int) * ncap * curr.count);
837
+ }
838
+ /* Every live slot is a thread's, and a match keeps what it found in
839
+ result_caps rather than in the pool (see RE_MATCH in add_thread), so a
840
+ step with no threads left holds no slot either and the pool goes back
841
+ to the front. Reclaiming only where there was something to renumber
842
+ would leave the slot each dead attempt took: a run of positions where
843
+ nothing survives climbs the pool by one a position, and a search over
844
+ a long enough subject asks the allocator for memory in proportion to
845
+ the subject rather than to the pattern. */
846
+ if (!match_only) s.pool_next = curr.count;
847
+
848
+ advance_gen(&s);
849
+ s.cut = FALSE;
850
+ next.count = 0;
851
+
852
+ int ch = (uint8_t)*sp;
853
+ int advance = mrb_re_charlen(sp, str_end, s.binary);
854
+ /* Decoded codepoint of the current input char. Identical to `ch`
855
+ for ASCII; lazily decoded only when the char is multi-byte. */
856
+ uint32_t curr_cp = (uint32_t)ch;
857
+ if (!s.binary && advance > 1) {
858
+ int dlen = 0;
859
+ curr_cp = mrb_re_decode_char(sp, str_end, &dlen, s.binary);
860
+ }
861
+ /* A non-ASCII byte that stands alone is a byte, not the character its
862
+ number spells: every byte of a byte-indexed subject, and a byte that
863
+ starts no whole character in a decoded one. */
864
+ mrb_bool curr_raw = (advance == 1 && ch >= 0x80);
865
+
866
+ for (int i = 0; i < curr.count; i++) {
867
+ re_thread *th = &curr.threads[i];
868
+ if (th->pc >= pat->code_len) continue;
869
+ /* A thread enqueued at sp+advance (RE_CLASS over a multi-byte
870
+ char) waits in the list until the byte-stepped outer sp catches
871
+ up to its own sp. Until then, carry it forward to next
872
+ iteration's curr unchanged. */
873
+ if (th->sp != sp) {
874
+ if (next.count < next.capa) {
875
+ next.threads[next.count++] = *th;
876
+ }
877
+ continue;
878
+ }
879
+
880
+ re_inst inst = pat->code[th->pc];
881
+ switch (inst.op) {
882
+ case RE_CHAR:
883
+ if (ch == inst.a) {
884
+ int cp = 0;
885
+ if (!match_only && !pool_copy(&s, th->cap_slot, &cp)) break;
886
+ add_thread(&s, &next, th->pc + 1, cp, sp + 1, s.gen);
887
+ }
888
+ break;
889
+
890
+ case RE_BYTE:
891
+ /* A byte that spells no character matches only where the subject byte
892
+ spells none either: inside a character the byte belongs to that
893
+ character (see RE_BYTE). `curr_raw` is that question already asked
894
+ for the class path, and a byte-indexed subject answers it for every
895
+ byte, which is where this is RE_CHAR. */
896
+ if (ch == inst.a && curr_raw) {
897
+ int cp = 0;
898
+ if (!match_only && !pool_copy(&s, th->cap_slot, &cp)) break;
899
+ add_thread(&s, &next, th->pc + 1, cp, sp + 1, s.gen);
900
+ }
901
+ break;
902
+
903
+ case RE_ANY:
904
+ if (ch != '\n') {
905
+ int cp = 0;
906
+ if (!match_only && !pool_copy(&s, th->cap_slot, &cp)) break;
907
+ add_thread(&s, &next, th->pc + 1, cp, sp + advance, s.gen);
908
+ }
909
+ break;
910
+
911
+ case RE_ANY_NL:
912
+ {
913
+ int cp = 0;
914
+ if (!match_only && !pool_copy(&s, th->cap_slot, &cp)) break;
915
+ add_thread(&s, &next, th->pc + 1, cp, sp + advance, s.gen);
916
+ }
917
+ break;
918
+
919
+ case RE_CLASS:
920
+ if (class_match(&pat->classes[inst.a], curr_cp, curr_raw)) {
921
+ int cp = 0;
922
+ if (!match_only && !pool_copy(&s, th->cap_slot, &cp)) break;
923
+ add_thread(&s, &next, th->pc + 1, cp, sp + advance, s.gen);
924
+ }
925
+ break;
926
+
927
+ case RE_NCLASS:
928
+ if (!class_match(&pat->classes[inst.a], curr_cp, curr_raw)) {
929
+ int cp = 0;
930
+ if (!match_only && !pool_copy(&s, th->cap_slot, &cp)) break;
931
+ add_thread(&s, &next, th->pc + 1, cp, sp + advance, s.gen);
932
+ }
933
+ break;
934
+
935
+ default:
936
+ break;
937
+ }
938
+
939
+ /* A higher-priority thread reached a match while building `next`; the
940
+ remaining (lower-priority) threads in `curr` are cut for this step.
941
+ A refused allocation stops the whole search rather than this step,
942
+ and the loop above reads it as its own end. */
943
+ if (s.cut || s.nomem) break;
944
+ }
945
+
946
+ /* swap curr and next */
947
+ {
948
+ re_threadlist tmp = curr;
949
+ curr = next;
950
+ next = tmp;
951
+ }
952
+
953
+ if (s.matched && curr.count == 0) break;
954
+ }
955
+
956
+ int ret = 0;
957
+ if (s.nomem) {
958
+ /* The allocator had nothing left for a buffer this search needed. It is
959
+ told apart from a limit all the way out to the caller for the reason
960
+ backtrack_exec() gives: what it asks for is not a knob turned up. */
961
+ ret = RE_NOMEM;
962
+ }
963
+ else if (s.matched) {
964
+ if (captures && s.result_caps) {
965
+ int copy = ncap < captures_size ? ncap : captures_size;
966
+ memcpy(captures, s.result_caps, sizeof(int) * copy);
967
+ }
968
+ ret = ncap > 0 ? ncap : 1;
969
+ }
970
+
971
+ if (use_cache) {
972
+ #ifdef SP_THREADS
973
+ __atomic_store_n(&mpat->cache_in_use, (mrb_bool)FALSE, __ATOMIC_RELEASE);
974
+ #else
975
+ mpat->cache_in_use = FALSE;
976
+ #endif
977
+ }
978
+ else {
979
+ mrb_free(mrb, curr.threads);
980
+ mrb_free(mrb, next.threads);
981
+ mrb_free(mrb, s.visited);
982
+ }
983
+ if (s.cap_pool != s.pool_inline) mrb_free(mrb, s.cap_pool);
984
+ if (s.result_caps != s.result_inline) mrb_free(mrb, s.result_caps);
985
+ if (s.pend != s.pend_inline) mrb_free(mrb, s.pend);
986
+
987
+ return ret;
988
+ }
989
+
990
+ /*
991
+ * Where a lookbehind branch starts matching from: sp rewound by the byte
992
+ * count the RE_LB_WIDTH at its head carries for a binary subject, and
993
+ * otherwise by the character count beside it. The backward walk steps over
994
+ * continuation bytes with mrb_re_char_interior_p(), which keeps it on the
995
+ * boundaries the forward decode uses, broken input included. Returns NULL
996
+ * when the text before sp runs out first.
997
+ */
998
+ static const char*
999
+ lookbehind_start(const char *str, const char *str_end, const char *sp,
1000
+ uint16_t width, mrb_bool binary)
1001
+ {
1002
+ if (binary) {
1003
+ int lb_len = RE_LB_BYTES(width);
1004
+ return (sp - str < lb_len) ? NULL : sp - lb_len;
1005
+ }
1006
+ int nchars = RE_LB_CHARS(width);
1007
+ while (nchars > 0) {
1008
+ if (sp <= str) return NULL;
1009
+ sp--;
1010
+ while (sp > str && mrb_re_char_interior_p(str, sp, str_end)) sp--;
1011
+ nchars--;
1012
+ }
1013
+ return sp;
1014
+ }
1015
+
1016
+ /* What one bt_match() call answers. BT_MATCH is the search having reached
1017
+ RE_MATCH, BT_FAIL is every alternative it held having been tried, BT_LIMIT
1018
+ is the search giving up at one of the limits before it had either, and
1019
+ BT_NOMEM is the allocator having refused the state it needed. Neither of
1020
+ the last two says anything about the text, so neither is read as a branch
1021
+ having failed and answered from the alternatives left: that would be
1022
+ answering a smaller question with whatever they produce: a shorter match, a
1023
+ later one or none, told from the real answer by nothing. backtrack_exec()
1024
+ stops the whole search at either (see there), and tells the two apart
1025
+ there, since what a limit asks of the build is that MRB_REGEXP_STACK_LIMIT
1026
+ be turned up, which is the worst thing it could do about an allocator that
1027
+ had nothing left to give.
1028
+
1029
+ BT_OK is not one of bt_match()'s answers. It is what bt_push(), bt_log()
1030
+ and bt_iter_begin() answer when there is nothing to hand up, so that what
1031
+ they answer otherwise is bt_match()'s answer as it stands. */
1032
+ #define BT_FAIL 0
1033
+ #define BT_MATCH 1
1034
+ #define BT_LIMIT 2
1035
+ #define BT_NOMEM 3
1036
+ #define BT_OK 4
1037
+
1038
+ /* What taking a choice point does beyond resuming where it points. */
1039
+ enum re_cp_kind {
1040
+ RE_CP_FORK, /* nothing: a branch the search has not tried yet */
1041
+ RE_CP_ITER, /* the branch begins an iteration of the loop its `group`
1042
+ keys, whose record is written when the branch is taken
1043
+ rather than when it was pushed (see bt_iter_begin()) */
1044
+ RE_CP_BARRIER,/* not a branch at all: where the group its `group` names was
1045
+ entered. Reaching it while backtracking is that group
1046
+ failing, so it resumes nothing and the search goes on
1047
+ popping; its end drops it and everything above it, which is
1048
+ how an atomic group and a positive lookaround cut (see
1049
+ RE_ATOMIC_END and RE_LOOK_END). */
1050
+ RE_CP_NEG, /* the barrier of a negative lookaround, which is both: its
1051
+ sub-pattern running out of alternatives is the assertion
1052
+ holding, so reaching it resumes the text after the
1053
+ lookaround, at the sp and pc it holds. */
1054
+ RE_CP_CALL, /* not a branch: a call frame, pushed where RE_CALL entered a
1055
+ group's body. `pc` is where the body's RE_RETURN goes on
1056
+ and `sp` is where the input stood, which is where the
1057
+ invocation's capture opens; `group` is the group, for the
1058
+ assert alone. Living on this stack is what makes a call
1059
+ backtrack-safe with no bookkeeping: a failure that goes
1060
+ back past the call pops the frame with everything above
1061
+ it, and MRB_REGEXP_STACK_LIMIT bounds the call depth by
1062
+ bounding the frames. */
1063
+ RE_CP_ABSENT, /* not a branch: the state one absent repeater's scan runs
1064
+ on. `sp` is where the absent began. `pc` is how far it may
1065
+ still reach as an offset into the subject: the whole of
1066
+ what stands after it until a match of the body says
1067
+ otherwise, and below `sp` once the body has matched empty
1068
+ where the absent began, which is the absent matching
1069
+ nothing anywhere. `group` is the end of the subject the
1070
+ text around it runs against, put back when the scan ends.
1071
+ RE_ABSENT pops it at the head of each round and pushes it
1072
+ back for the next, so the scan's state is backtracking
1073
+ state like any other and a failure that goes back past the
1074
+ absent drops it. Reaching it while backtracking resumes
1075
+ nothing: there is no round left to try. */
1076
+ RE_CP_ABSENT_ITER, /* the round after the one now running, pushed directly
1077
+ above the state it belongs to: the body failing at
1078
+ this position is the scan going on at the next.
1079
+ RE_ABSENT_END takes it by hand once the body has
1080
+ matched, which is what drops the alternatives the
1081
+ body left rather than trying them. */
1082
+ RE_CP_ABSENT_BACK, /* the ends an absent repeater has not answered with
1083
+ yet: `sp` is the next one and `group` is where the
1084
+ absent began, which is the last. Taking one pushes
1085
+ the one below it, so a scan of any length leaves one
1086
+ choice point behind rather than one per position. */
1087
+ RE_CP_RET /* not a branch either: the mark RE_RETURN leaves in place of
1088
+ popping the frame it answered, which backtracking may
1089
+ still need. The next RE_RETURN's downward scan counts
1090
+ these against the frames it passes, so each return pairs
1091
+ with the innermost frame no return has answered yet, as
1092
+ Onigmo's STACK_RETURN counts its STK_RETURN marks. */
1093
+ };
1094
+
1095
+ /* A choice point: an alternative the search has not tried yet, as where the
1096
+ input stood (`sp`), which instruction takes the alternative (`pc`) and how
1097
+ tall the undo log was when it was pushed (`undo_top`). Backtracking pops
1098
+ one, takes back every write logged above its `undo_top` and goes on from
1099
+ its `sp` and `pc`. A fork costs one of these rather than the C frame the
1100
+ engine used to recurse into, so the C stack a search spends is the one
1101
+ bt_match() call it makes, whatever the subject: the state that grows is
1102
+ this stack, on the heap.
1103
+
1104
+ MRB_REGEXP_STACK_LIMIT is what bounds it (see there and bt_room()). */
1105
+ typedef struct {
1106
+ const char *sp;
1107
+ uint32_t pc;
1108
+ uint32_t undo_top;
1109
+ uint32_t group; /* what `kind` names, where it names something */
1110
+ int pass; /* the pass it was pushed in, which is the pass the
1111
+ branch it holds runs in; for a lookaround's barrier
1112
+ that is the pass the lookaround was entered from, and
1113
+ the sub-pattern above it runs in one of its own */
1114
+ uint8_t kind;
1115
+ } re_cpoint;
1116
+
1117
+ /* An undo record: one write the search must be able to take back, as the slot
1118
+ written and what stood in it. The records are a stack of their own beside
1119
+ the choice points rather than a field in them, because what a cut does to
1120
+ each differs: the captures a positive lookaround or an atomic group wrote
1121
+ outlive it, so its cut drops the choice points above the barrier and leaves
1122
+ the undo log alone, while a negative lookaround, whose captures do not
1123
+ outlive it, unwinds both. One mixed stack could not truncate at all: it
1124
+ would have to walk the region above the barrier and keep the undo records
1125
+ while dropping the choice points. */
1126
+ typedef struct {
1127
+ int *slot;
1128
+ int old;
1129
+ } re_undo;
1130
+
1131
+ /* Everything one backtrack_exec() call carries: the pattern, the subject,
1132
+ the capture slots being written, the step count, the iteration records and
1133
+ the two stacks the backtracking state stands on. What the search itself
1134
+ holds between instructions is only its position and its pc. */
1135
+ typedef struct {
1136
+ mrb_state *mrb;
1137
+ const mrb_regexp_pattern *pat;
1138
+ const char *str;
1139
+ const char *str_end;
1140
+ int *captures;
1141
+ int ncap;
1142
+ int steps;
1143
+ /* Per pc, the offset the loop that pc keys was entered at, or -1 while
1144
+ none is running; what a record means is what its pc is. For the edge of
1145
+ a repetition whose body can match empty it is where the running
1146
+ iteration began: such a repetition has to stop once an iteration ends
1147
+ where it began, or it would go round at the same position until a limit
1148
+ refused it and answer with whatever the alternatives left inside the
1149
+ limit produce. Onigmo stops it with a null check around the body; this
1150
+ array is that check's memory. The pc that keys a loop is its marked head
1151
+ for e* (the SPLIT/SPLITNG whose offset is the exit; the JMP closing the
1152
+ body reads the record) and its marked back edge for e+ (the
1153
+ SPLIT/SPLITNG at the end of the body, which both writes and reads it);
1154
+ see mark_empty_loops(). */
1155
+ int *entered_at;
1156
+ /* Per pc, the pass that wrote entered_at[pc]. A pass is one run of a
1157
+ lookaround's sub-pattern, numbered from `pass_seq` so that no two runs
1158
+ of one start position's attempt share one, and 0 is the pattern outside
1159
+ every lookaround; `pass` is the one the search is in. A record is read
1160
+ as the running iteration's only by the pass that wrote it: what a
1161
+ positive lookaround captured outlives it, and so do the records of the
1162
+ loops inside it, the undo log not unwinding at its end, so a repetition
1163
+ around the lookaround re-enters the sub-pattern with the records of the
1164
+ run before still live. The first iteration of an e+, which reads its
1165
+ record without having written it, would take one of those for its own
1166
+ where the positions coincide: `(?=(b|)+)+` on "b" re-enters at 0 while
1167
+ the run before left 1 for `(b|)+`, and its first iteration, ending at
1168
+ 1, would stop there with "b" captured, where a fresh pass goes round
1169
+ once more and leaves "". */
1170
+ int *entered_in;
1171
+ int pass;
1172
+ int pass_seq;
1173
+ mrb_bool binary;
1174
+ const char *gpos; /* spinel: where this search started, for \G (RE_GPOS) */
1175
+ /* The choice points not yet tried and the writes not yet taken back, both
1176
+ grown lazily on the heap. A search starts with neither allocated and
1177
+ pays only for the kind of state it holds: a fork is a choice point, a
1178
+ capture or an iteration record is an undo record, and a pattern with
1179
+ none of them in it asks the allocator for nothing. */
1180
+ re_cpoint *cp;
1181
+ uint32_t cp_top;
1182
+ uint32_t cp_capa;
1183
+ re_undo *undo;
1184
+ uint32_t undo_top;
1185
+ uint32_t undo_capa;
1186
+ } bt_state;
1187
+
1188
+ /* Whether the loop `key` keys is at the end of an iteration that began at
1189
+ sp: the record is this pass's and names sp. */
1190
+ #define ITER_EMPTY(m, key, sp) \
1191
+ ((m)->entered_at[key] == (int)((sp) - (m)->str) && (m)->entered_in[key] == (m)->pass)
1192
+
1193
+ /* Whether the search may hold one more entry of backtracking state.
1194
+ MRB_REGEXP_STACK_LIMIT counts the two stacks together: a choice point and
1195
+ an undo record each stand for a branch or a write the search is still able
1196
+ to take back, and bounding their sum is what bounds the state one search
1197
+ holds. */
1198
+ static mrb_bool
1199
+ bt_room(const bt_state *m)
1200
+ {
1201
+ return m->cp_top + m->undo_top < (uint32_t)MRB_REGEXP_STACK_LIMIT;
1202
+ }
1203
+
1204
+ /* What a full stack grows to. Doubling is what makes a push amortised
1205
+ constant; the ceiling is what makes MRB_REGEXP_STACK_LIMIT a bound on the
1206
+ memory a search asks for and not only on the entries it holds at once,
1207
+ since a stack keeps its capacity for the rest of the search and the two of
1208
+ them reach their high-water marks at different times. A stack is grown only
1209
+ where bt_room() has just passed, so its height is below the limit and the
1210
+ ceiling always leaves room for the entry being pushed. */
1211
+ static uint32_t
1212
+ bt_grow_capa(uint32_t capa)
1213
+ {
1214
+ capa = capa ? capa * 2 : 16;
1215
+ return capa < (uint32_t)MRB_REGEXP_STACK_LIMIT ? capa : (uint32_t)MRB_REGEXP_STACK_LIMIT;
1216
+ }
1217
+
1218
+ /* Push a choice point. BT_OK is the push having happened, and anything else
1219
+ is the search stopping, to be handed up as the frame's answer: BT_LIMIT
1220
+ where the stack limit refuses the entry, BT_NOMEM where the allocator
1221
+ refuses the memory for it. Growing with mrb_realloc_simple() rather than
1222
+ mrb_realloc() is what lets a refusal be an answer at all, a raising
1223
+ allocator longjmping past the mrb_free() in backtrack_exec(). */
1224
+ static int
1225
+ bt_push(bt_state *m, const char *sp, uint32_t pc, uint8_t kind, uint32_t group)
1226
+ {
1227
+ if (!bt_room(m)) return BT_LIMIT;
1228
+ if (m->cp_top == m->cp_capa) {
1229
+ uint32_t capa = bt_grow_capa(m->cp_capa);
1230
+ re_cpoint *p = (re_cpoint*)mrb_realloc_simple(m->mrb, m->cp, sizeof(re_cpoint) * capa);
1231
+ if (!p) return BT_NOMEM;
1232
+ m->cp = p;
1233
+ m->cp_capa = capa;
1234
+ }
1235
+ re_cpoint *c = &m->cp[m->cp_top++];
1236
+ c->sp = sp;
1237
+ c->pc = pc;
1238
+ c->undo_top = m->undo_top;
1239
+ c->group = group;
1240
+ c->pass = m->pass;
1241
+ c->kind = kind;
1242
+ return BT_OK;
1243
+ }
1244
+
1245
+ /* Write `val` into `slot`, logging what stood there so that backtracking
1246
+ past this point puts it back. The answer is bt_push()'s, and means what it
1247
+ means there: BT_OK is the write having gone through, and BT_LIMIT or
1248
+ BT_NOMEM is the search stopping, for the same two reasons and told apart
1249
+ for the same one.
1250
+
1251
+ A write of the value already there leaves nothing to put back, so it is not
1252
+ logged. What MRB_REGEXP_STACK_LIMIT counts is then the state a search would
1253
+ have to restore rather than the calls it made, and a search at the limit
1254
+ goes on through such a write rather than stopping at one that would have
1255
+ restored nothing. */
1256
+ static int
1257
+ bt_log(bt_state *m, int *slot, int val)
1258
+ {
1259
+ if (*slot == val) return BT_OK;
1260
+ if (!bt_room(m)) return BT_LIMIT;
1261
+ if (m->undo_top == m->undo_capa) {
1262
+ uint32_t capa = bt_grow_capa(m->undo_capa);
1263
+ re_undo *p = (re_undo*)mrb_realloc_simple(m->mrb, m->undo, sizeof(re_undo) * capa);
1264
+ if (!p) return BT_NOMEM;
1265
+ m->undo = p;
1266
+ m->undo_capa = capa;
1267
+ }
1268
+ re_undo *u = &m->undo[m->undo_top++];
1269
+ u->slot = slot;
1270
+ u->old = *slot;
1271
+ *slot = val;
1272
+ return BT_OK;
1273
+ }
1274
+
1275
+ /* Take back every write logged above `top`. */
1276
+ static void
1277
+ bt_undo_to(bt_state *m, uint32_t top)
1278
+ {
1279
+ while (m->undo_top > top) {
1280
+ re_undo *u = &m->undo[--m->undo_top];
1281
+ *u->slot = u->old;
1282
+ }
1283
+ }
1284
+
1285
+ /* Where the group `group` was entered, as an index into the choice point
1286
+ stack. Barriers nest and a group's end runs while its own is the innermost
1287
+ still standing, so the walk down from the top is over what that end is
1288
+ about to drop in any case. FALSE is a group's end reached without its
1289
+ opener, which a compiled pattern does not hold; the search reads it as a
1290
+ failure rather than trusting an index. */
1291
+ static mrb_bool
1292
+ bt_barrier_find(const bt_state *m, uint32_t group, uint32_t *idx)
1293
+ {
1294
+ uint32_t i = m->cp_top;
1295
+ while (i > 0) {
1296
+ i--;
1297
+ if ((m->cp[i].kind == RE_CP_BARRIER || m->cp[i].kind == RE_CP_NEG) &&
1298
+ m->cp[i].group == group) {
1299
+ *idx = i;
1300
+ return TRUE;
1301
+ }
1302
+ }
1303
+ return FALSE;
1304
+ }
1305
+
1306
+ /* Record that an iteration of the loop `key` keys begins at sp, so that the
1307
+ edge closing the body can tell an iteration that matched empty. The two
1308
+ records go on the undo log, so that backtracking out of an iteration puts
1309
+ back the record of the one it lands in; the branch that begins an
1310
+ iteration is written this way rather than in place when it is taken, so
1311
+ that there is one place that writes them. They go through bt_log() like
1312
+ any other write, so an iteration that begins where the record already
1313
+ says, in the pass it already names, spends nothing on saying so again. */
1314
+ static int
1315
+ bt_iter_begin(bt_state *m, uint32_t key, const char *sp)
1316
+ {
1317
+ int r = bt_log(m, &m->entered_at[key], (int)(sp - m->str));
1318
+ return r != BT_OK ? r : bt_log(m, &m->entered_in[key], m->pass);
1319
+ }
1320
+
1321
+ /*
1322
+ * Backtracking engine for patterns with backreferences.
1323
+ *
1324
+ * A fork pushes a choice point and goes on with its first branch; a failure
1325
+ * pops one and goes on with the alternative it holds, taking back the writes
1326
+ * logged since it was pushed. The whole of a search is this one loop, so what
1327
+ * it costs the C stack is one call however long the subject is and however
1328
+ * deep the pattern nests; what grows instead are the two stacks on the heap,
1329
+ * which MRB_REGEXP_STACK_LIMIT bounds.
1330
+ *
1331
+ * Step-limited to prevent ReDoS.
1332
+ */
1333
+ static int
1334
+ bt_match(bt_state *m, const char *sp, uint32_t pc)
1335
+ {
1336
+ const mrb_regexp_pattern *pat = m->pat;
1337
+ const char *str = m->str;
1338
+ /* Where the subject ends, which is where it really ends except while the
1339
+ body of an absent repeater runs: there it is the furthest the absent may
1340
+ still reach, since a run of text the absent could never take is one the
1341
+ body has no business reading. The whole of the search reads it, an
1342
+ assertion as much as a literal, so `\z` inside such a body holds where
1343
+ the scan stops rather than where the string does, which is CRuby's
1344
+ answer: Onigmo keeps the reach in the same `end` the rest of its
1345
+ executor measures against. RE_ABSENT puts it back at the head of every
1346
+ round. */
1347
+ const char *str_end = m->str_end;
1348
+ int *captures = m->captures;
1349
+ int ncap = m->ncap;
1350
+ mrb_bool binary = m->binary;
1351
+ /* What an operation on the stacks answers, which is this call's answer
1352
+ wherever it is not BT_OK. Outside the loop so that no `goto fail`
1353
+ crosses an initialization: a C++ build refuses a jump that does. */
1354
+ int r;
1355
+ re_inst inst;
1356
+
1357
+ for (;;) {
1358
+ if (pc >= pat->code_len) goto fail;
1359
+ if (++m->steps > MRB_REGEXP_STEP_LIMIT) return BT_LIMIT;
1360
+
1361
+ inst = pat->code[pc];
1362
+ switch (inst.op) {
1363
+ case RE_CHAR:
1364
+ if (sp >= str_end || (uint8_t)*sp != inst.a) goto fail;
1365
+ sp++; pc++;
1366
+ break;
1367
+
1368
+ case RE_BYTE:
1369
+ /* see the Pike VM case */
1370
+ if (sp >= str_end || (uint8_t)*sp != inst.a) goto fail;
1371
+ if (!binary && mrb_re_charlen(sp, str_end, FALSE) != 1) goto fail;
1372
+ sp++; pc++;
1373
+ break;
1374
+
1375
+ case RE_ANY:
1376
+ if (sp >= str_end || *sp == '\n') goto fail;
1377
+ sp += mrb_re_charlen(sp, str_end, binary); pc++;
1378
+ break;
1379
+
1380
+ case RE_ANY_NL:
1381
+ if (sp >= str_end) goto fail;
1382
+ sp += mrb_re_charlen(sp, str_end, binary); pc++;
1383
+ break;
1384
+
1385
+ case RE_CLASS:
1386
+ if (sp >= str_end) goto fail;
1387
+ {
1388
+ int dlen = 0;
1389
+ uint32_t cp_ = mrb_re_decode_char(sp, str_end, &dlen, binary);
1390
+ mrb_bool raw = (dlen == 1 && (uint8_t)*sp >= 0x80);
1391
+ if (!class_match(&pat->classes[inst.a], cp_, raw)) goto fail;
1392
+ sp += mrb_re_charlen(sp, str_end, binary);
1393
+ }
1394
+ pc++;
1395
+ break;
1396
+
1397
+ case RE_NCLASS:
1398
+ if (sp >= str_end) goto fail;
1399
+ {
1400
+ int dlen = 0;
1401
+ uint32_t cp_ = mrb_re_decode_char(sp, str_end, &dlen, binary);
1402
+ mrb_bool raw = (dlen == 1 && (uint8_t)*sp >= 0x80);
1403
+ if (class_match(&pat->classes[inst.a], cp_, raw)) goto fail;
1404
+ sp += mrb_re_charlen(sp, str_end, binary);
1405
+ }
1406
+ pc++;
1407
+ break;
1408
+
1409
+ case RE_MATCH:
1410
+ return BT_MATCH;
1411
+
1412
+ case RE_JMP:
1413
+ /* A backward jump closes e* and returns to its head. When the head is
1414
+ marked, the body can match empty and entered_at[head] holds where
1415
+ the iteration that just ended began (see bt_iter_begin()): an
1416
+ iteration that ended where it began matched empty, and the
1417
+ repetition stops here, taking the head's exit and keeping what the
1418
+ iteration captured, as Onigmo's null check does. */
1419
+ if (inst.a && ITER_EMPTY(m, inst.offset, sp)) {
1420
+ pc = pat->code[inst.offset].offset;
1421
+ break;
1422
+ }
1423
+ pc = inst.offset;
1424
+ break;
1425
+
1426
+ case RE_SPLIT:
1427
+ /* Greedy fork: pc+1 first, then the jump target. A marked one is an
1428
+ edge of a repetition whose body can match empty. Forward, it heads
1429
+ e*, and pc+1 begins an iteration. Backward, it closes e+?, and its
1430
+ target begins the next iteration, unless the one that just ended was
1431
+ empty: then there is only the exit, as at a marked RE_JMP. */
1432
+ if (inst.a) {
1433
+ if (inst.offset > pc) {
1434
+ if ((r = bt_push(m, sp, inst.offset, RE_CP_FORK, 0)) != BT_OK ||
1435
+ (r = bt_iter_begin(m, pc, sp)) != BT_OK) return r;
1436
+ pc++;
1437
+ break;
1438
+ }
1439
+ if (ITER_EMPTY(m, pc, sp)) { pc++; break; }
1440
+ if ((r = bt_push(m, sp, inst.offset, RE_CP_ITER, pc)) != BT_OK) return r;
1441
+ pc++;
1442
+ break;
1443
+ }
1444
+ if ((r = bt_push(m, sp, inst.offset, RE_CP_FORK, 0)) != BT_OK) return r;
1445
+ pc++;
1446
+ break;
1447
+
1448
+ case RE_SPLITNG:
1449
+ /* Non-greedy fork: the jump target first, then pc+1. Marked, forward
1450
+ it heads e*? and backward it closes e+; the iteration-starting branch
1451
+ is the other one from RE_SPLIT's, and the empty-iteration stop is the
1452
+ same. */
1453
+ if (inst.a) {
1454
+ if (inst.offset > pc) {
1455
+ if ((r = bt_push(m, sp, pc + 1, RE_CP_ITER, pc)) != BT_OK) return r;
1456
+ pc = inst.offset;
1457
+ break;
1458
+ }
1459
+ if (ITER_EMPTY(m, pc, sp)) { pc++; break; }
1460
+ if ((r = bt_push(m, sp, pc + 1, RE_CP_FORK, 0)) != BT_OK ||
1461
+ (r = bt_iter_begin(m, pc, sp)) != BT_OK) return r;
1462
+ pc = inst.offset;
1463
+ break;
1464
+ }
1465
+ if ((r = bt_push(m, sp, pc + 1, RE_CP_FORK, 0)) != BT_OK) return r;
1466
+ pc = inst.offset;
1467
+ break;
1468
+
1469
+ case RE_SAVE:
1470
+ {
1471
+ int slot = inst.offset;
1472
+ /* No boundary test: see the Pike VM case. */
1473
+ if (slot >= ncap) goto fail;
1474
+ /* The write is logged rather than recursed over: backtracking past
1475
+ it puts the slot back, which is what undoes what a branch captured
1476
+ before it was abandoned. What a match keeps, and what an atomic
1477
+ group or a positive lookaround keeps once it has matched, is kept
1478
+ by the log not unwinding at all there. */
1479
+ if ((r = bt_log(m, &captures[slot], (int)(sp - str))) != BT_OK) return r;
1480
+ /* An even slot opens its group, and the pair it heads is a span
1481
+ only while the group is closed: clear the end slot with the
1482
+ start, so that RE_BACKREF reads a group a repetition has just
1483
+ re-entered the way it reads one never entered, instead of
1484
+ pairing this iteration's start with the end of the one before:
1485
+ an empty span where the two coincide, and a negative one where
1486
+ the start is past it, which no closed group holds. CRuby
1487
+ reads an open group as unmatched the same way (Onigmo's
1488
+ STACK_PUSH_MEM_START invalidates the end with the start). The
1489
+ end slot exists whenever the start does, ncap being even. The
1490
+ clear is logged too, so backtracking puts back the end the
1491
+ iteration before it left; where there is no such end, the group
1492
+ being one this attempt has not closed yet, the clear writes the
1493
+ -1 that already stands there and bt_log() records nothing. */
1494
+ if ((slot & 1) == 0 && (r = bt_log(m, &captures[slot + 1], -1)) != BT_OK) return r;
1495
+ pc++;
1496
+ }
1497
+ break;
1498
+
1499
+ case RE_BOL:
1500
+ /* ^ always matches at a line start (see the Pike VM case); /m only
1501
+ affects `.`. \A is RE_BOT. A trailing \n opens no final line. */
1502
+ if (sp != str && (sp == str_end || sp[-1] != '\n')) goto fail;
1503
+ pc++;
1504
+ break;
1505
+
1506
+ case RE_EOL:
1507
+ /* $ always matches at a line end. */
1508
+ if (sp != str_end && *sp != '\n') goto fail;
1509
+ pc++;
1510
+ break;
1511
+
1512
+ case RE_BOT:
1513
+ if (sp != str) goto fail;
1514
+ pc++;
1515
+ break;
1516
+
1517
+ case RE_GPOS:
1518
+ /* spinel: \G, only the position this search started from */
1519
+ if (sp != m->gpos) goto fail;
1520
+ pc++;
1521
+ break;
1522
+
1523
+ case RE_EOT:
1524
+ if (sp != str_end) goto fail;
1525
+ pc++;
1526
+ break;
1527
+
1528
+ case RE_EOTNL:
1529
+ if (sp != str_end && !(sp + 1 == str_end && *sp == '\n')) goto fail;
1530
+ pc++;
1531
+ break;
1532
+
1533
+ case RE_WBOUND:
1534
+ {
1535
+ mrb_bool before = (sp > str) && mrb_re_word_before(str, sp, str_end, binary);
1536
+ mrb_bool after = (sp < str_end) && mrb_re_word_at(sp, str_end, binary);
1537
+ if (before == after) goto fail;
1538
+ }
1539
+ pc++;
1540
+ break;
1541
+
1542
+ case RE_NWBOUND:
1543
+ {
1544
+ mrb_bool before = (sp > str) && mrb_re_word_before(str, sp, str_end, binary);
1545
+ mrb_bool after = (sp < str_end) && mrb_re_word_at(sp, str_end, binary);
1546
+ if (before != after) goto fail;
1547
+ }
1548
+ pc++;
1549
+ break;
1550
+
1551
+ case RE_BACKREF:
1552
+ {
1553
+ int group = inst.a;
1554
+ if (group * 2 + 1 >= ncap) goto fail;
1555
+ int gs = captures[group * 2];
1556
+ int ge = captures[group * 2 + 1];
1557
+ if (gs < 0 || ge < 0) goto fail;
1558
+ int blen = ge - gs;
1559
+ if (inst.offset) {
1560
+ /* A folded comparison can consume a different number of bytes than
1561
+ the captured text holds, so the span is measured, not assumed. */
1562
+ int used = memcmp_ci(sp, str_end, str + gs, str + ge, binary);
1563
+ if (used < 0) goto fail;
1564
+ sp += used;
1565
+ }
1566
+ else {
1567
+ if (sp + blen > str_end) goto fail;
1568
+ if (memcmp(sp, str + gs, blen) != 0) goto fail;
1569
+ sp += blen;
1570
+ }
1571
+ pc++;
1572
+ }
1573
+ break;
1574
+
1575
+ case RE_COND:
1576
+ {
1577
+ /* The group has matched when its pair is closed, which is the test
1578
+ RE_BACKREF makes before it reads one: an open group holds a start
1579
+ and no end (see RE_SAVE), and a group nothing has entered holds
1580
+ neither. No choice point: which body runs is settled by the
1581
+ captures as they stand, and a failure inside the body backtracks
1582
+ past this instruction to whatever was pushed before it, which is
1583
+ what may change the captures and bring the search back here with
1584
+ the other answer. */
1585
+ int group = inst.a;
1586
+ if (group * 2 + 1 < ncap &&
1587
+ captures[group * 2] >= 0 && captures[group * 2 + 1] >= 0) {
1588
+ pc++;
1589
+ }
1590
+ else {
1591
+ pc = inst.offset;
1592
+ }
1593
+ }
1594
+ break;
1595
+
1596
+ case RE_LOOKAHEAD:
1597
+ case RE_NEG_LOOKAHEAD:
1598
+ case RE_LOOKBEHIND:
1599
+ case RE_NEG_LOOKBEHIND:
1600
+ {
1601
+ /* The lookaround is entered: a barrier stands where it began, and
1602
+ the sub-pattern goes on from here. What the barrier holds is where
1603
+ the text after the lookaround goes on from and the pass to go on
1604
+ in; for a negative one that is what taking the barrier resumes,
1605
+ its sub-pattern running out of alternatives being the assertion
1606
+ holding. The sub-pattern runs as a pass of its own, one no run
1607
+ before it had, so the records of the loops inside it that an
1608
+ earlier run may have left live are not taken for this run's (see
1609
+ bt_state).
1610
+
1611
+ A lookbehind is entered at the same position as a lookahead: the
1612
+ rewind belongs to the branch, not to the opener, so that the
1613
+ branches of a body whose widths differ each look back their own
1614
+ way and are tried in the order the alternation gives them. The
1615
+ RE_LB_WIDTH at the head of the branch does it (see there). */
1616
+ mrb_bool negated = (inst.op == RE_NEG_LOOKAHEAD || inst.op == RE_NEG_LOOKBEHIND);
1617
+ if ((r = bt_push(m, sp, inst.offset, negated ? RE_CP_NEG : RE_CP_BARRIER,
1618
+ pat->code[inst.offset - 1].offset)) != BT_OK) {
1619
+ return r;
1620
+ }
1621
+ m->pass = ++m->pass_seq;
1622
+ pc++;
1623
+ /* A lookbehind whose body takes one width begins with that rewind,
1624
+ and taking it here rather than through another turn of the loop is
1625
+ what leaves such a lookbehind, every one this engine compiled
1626
+ before a branch could have a width of its own, costing what it
1627
+ did. A body whose branches differ begins with the fork that picks
1628
+ between them, and each branch rewinds when it is reached.
1629
+
1630
+ The opcode alone tells the two apart for a lookahead as well: a
1631
+ rewind stands at the head of a lookbehind branch and nowhere
1632
+ else, so a lookahead's body never begins with one. */
1633
+ if (pat->code[pc].op != RE_LB_WIDTH) break;
1634
+ inst = pat->code[pc];
1635
+ }
1636
+ /* fall through */
1637
+
1638
+ case RE_LB_WIDTH:
1639
+ {
1640
+ /* The branch this heads looks back by the width it carries. Too
1641
+ little text before is this branch failing and nothing more: what
1642
+ the search tries next is the branch after it, and with none left
1643
+ the barrier below answers, a positive lookbehind not holding and
1644
+ a negative one holding with no sub-pattern having run. */
1645
+ const char *from = lookbehind_start(str, str_end, sp, inst.offset, binary);
1646
+ if (!from) goto fail;
1647
+ sp = from;
1648
+ pc++;
1649
+ }
1650
+ break;
1651
+
1652
+ case RE_LOOK_END:
1653
+ {
1654
+ /* The sub-pattern has matched, and that is the whole of what the
1655
+ lookaround asks of it: no alternative inside it may be tried for
1656
+ the text after, so its choice points go, barrier and all, as an
1657
+ atomic group's do. A positive one goes on with the text after from
1658
+ where it was entered, and what the sub-pattern captured stays --
1659
+ the undo log is left alone, and a failure that goes back past
1660
+ where the lookaround began takes it back with everything else
1661
+ logged since. A negative one is the assertion failing: the log
1662
+ unwinds to where the lookaround began, so what the sub-pattern
1663
+ captured goes with it, and the search backtracks. Either way the
1664
+ pass the lookaround was entered from comes back with the
1665
+ barrier. */
1666
+ uint32_t idx;
1667
+ if (!bt_barrier_find(m, inst.offset, &idx)) goto fail;
1668
+ re_cpoint c = m->cp[idx];
1669
+ /* Where the sub-pattern is one whose branches rewind by different
1670
+ widths, it has to have landed back where the lookaround was
1671
+ entered: `(?<=c|ab)` rewound the two characters `ab` asks for can
1672
+ still match `c` and stop a character short, which is a match of
1673
+ the text before the wrong position. The test comes before the cut
1674
+ below, so that a branch that lands short leaves the search the
1675
+ alternatives it has not tried, which are the branches after it,
1676
+ each with its own rewind. Every other lookaround lands where it
1677
+ must by construction and carries no such bit; see RE_LOOK_LANDING.
1678
+ No boundary test either: a sub-pattern reaches the same
1679
+ positions as the rest of the search, so an assertion that used to
1680
+ hold on half a character has no half to hold on. */
1681
+ if ((inst.a & RE_LOOK_LANDING) && sp != c.sp) goto fail;
1682
+ m->cp_top = idx;
1683
+ m->pass = c.pass;
1684
+ if (inst.a & RE_LOOK_NEGATED) {
1685
+ bt_undo_to(m, c.undo_top);
1686
+ goto fail;
1687
+ }
1688
+ sp = c.sp;
1689
+ pc++;
1690
+ }
1691
+ break;
1692
+
1693
+ case RE_ATOMIC:
1694
+ /* The group is entered: a barrier stands where it began, so that a
1695
+ failure inside the body that reaches it is the group failing, and
1696
+ the body goes on from here. */
1697
+ if ((r = bt_push(m, sp, pc + 1, RE_CP_BARRIER, inst.offset)) != BT_OK) return r;
1698
+ pc++;
1699
+ break;
1700
+
1701
+ case RE_ATOMIC_END:
1702
+ {
1703
+ /* The body has matched once, and that is the only way it matches:
1704
+ the alternatives it left are dropped, barrier and all, so that a
1705
+ failure after the group is not answered from inside it. What the
1706
+ body captured stays; the undo log is left as it is, and a
1707
+ failure that goes back past where the group began takes it back
1708
+ along with everything else logged since. */
1709
+ uint32_t idx;
1710
+ if (!bt_barrier_find(m, inst.offset, &idx)) goto fail;
1711
+ m->cp_top = idx;
1712
+ pc++;
1713
+ }
1714
+ break;
1715
+
1716
+ case RE_CALL:
1717
+ {
1718
+ /* The group's body is entered: a frame holds where its RE_RETURN
1719
+ goes on and where the input stands, and the group's end slot is
1720
+ cleared so the group reads as unmatched while the invocation is
1721
+ open -- the same invalidation entering a group inline makes at
1722
+ RE_SAVE, and what makes `(?<a>x|\k<a>y)\g<a>` read \k<a> as
1723
+ unmatched inside the second invocation rather than as the first
1724
+ invocation's text, which is CRuby's answer. The clear is logged,
1725
+ so backtracking out of the call puts back what an earlier
1726
+ invocation captured. */
1727
+ int slot = inst.a * 2 + 1;
1728
+ if (slot < ncap && (r = bt_log(m, &captures[slot], -1)) != BT_OK) return r;
1729
+ if ((r = bt_push(m, sp, pc + 1, RE_CP_CALL, inst.a)) != BT_OK) return r;
1730
+ pc = inst.offset;
1731
+ }
1732
+ break;
1733
+
1734
+ case RE_RETURN:
1735
+ {
1736
+ /* The invocation completed: find its frame -- the innermost one no
1737
+ return has answered yet, the returns already made counting
1738
+ against the frames they answered -- write the group's capture
1739
+ pair from it, leave the mark, and go on where the frame says.
1740
+ The pair is written whole here rather than half at entry: the
1741
+ invocation that completes last is the one the capture names, as
1742
+ in CRuby, where `(?<a>x)\g<a>` leaves the call's text and the
1743
+ recursion this feature exists for leaves the outermost span. */
1744
+ uint32_t i = m->cp_top;
1745
+ uint32_t level = 0;
1746
+ uint32_t idx = 0;
1747
+ mrb_bool found = FALSE;
1748
+ while (i > 0) {
1749
+ i--;
1750
+ if (m->cp[i].kind == RE_CP_RET) level++;
1751
+ else if (m->cp[i].kind == RE_CP_CALL) {
1752
+ if (level == 0) { idx = i; found = TRUE; break; }
1753
+ level--;
1754
+ }
1755
+ }
1756
+ if (!found) goto fail; /* a compiled pattern always has the frame */
1757
+ mrb_assert(m->cp[idx].group == inst.a);
1758
+ /* Group 0 is the whole match, which may not close inside a
1759
+ character; the same rule RE_SAVE applies to slot 1. */
1760
+ if (inst.a == 0 && !binary && sp < str_end &&
1761
+ mrb_re_char_interior_p(str, sp, str_end)) {
1762
+ goto fail;
1763
+ }
1764
+ {
1765
+ int slot = inst.a * 2;
1766
+ if (slot + 1 >= ncap) goto fail;
1767
+ if ((r = bt_log(m, &captures[slot], (int)(m->cp[idx].sp - str))) != BT_OK) return r;
1768
+ if ((r = bt_log(m, &captures[slot + 1], (int)(sp - str))) != BT_OK) return r;
1769
+ }
1770
+ {
1771
+ uint32_t ret = m->cp[idx].pc;
1772
+ if ((r = bt_push(m, sp, 0, RE_CP_RET, inst.a)) != BT_OK) return r;
1773
+ pc = ret;
1774
+ }
1775
+ }
1776
+ break;
1777
+
1778
+ case RE_ABSENT_START:
1779
+ /* The absent repeater is entered. Its scan runs on the state pushed
1780
+ here: it began at sp, it may reach as far as the subject reaches
1781
+ around it, and that same end is what the scan puts back when it is
1782
+ done. The subject an absent inside the body of another one runs
1783
+ against is the one that one has narrowed. */
1784
+ if ((r = bt_push(m, sp, (uint32_t)(str_end - str), RE_CP_ABSENT,
1785
+ (uint32_t)(str_end - str))) != BT_OK) {
1786
+ return r;
1787
+ }
1788
+ pc++;
1789
+ break;
1790
+
1791
+ case RE_ABSENT:
1792
+ {
1793
+ /* One round of the scan, at the position the round before left.
1794
+ Every position from where the absent began to the end it may still
1795
+ reach is an end the absent can take, so the round either takes the
1796
+ furthest of them, leaving the shorter ones to backtracking under
1797
+ one choice point for all of them, or runs the body once here and
1798
+ goes on at the next position.
1799
+
1800
+ The state is popped and pushed back rather than read in place: the
1801
+ round runs the body above it, and a body that fails has to land on
1802
+ the choice point that begins the next round and not inside a state
1803
+ the next round is about to read. */
1804
+ if (m->cp_top == 0 || m->cp[m->cp_top - 1].kind != RE_CP_ABSENT) goto fail;
1805
+ re_cpoint st = m->cp[--m->cp_top];
1806
+ m->pass = st.pass;
1807
+ str_end = str + st.group;
1808
+ int begun = (int)(st.sp - str);
1809
+ int reach = (int32_t)st.pc;
1810
+ /* The body matched empty where the absent began, so every run of
1811
+ text from here holds a match of it, the empty one included. */
1812
+ if (reach < begun) goto fail;
1813
+ if ((int)(sp - str) >= reach) {
1814
+ if (reach > begun) {
1815
+ const char *prev = lookbehind_start(str, str_end, str + reach,
1816
+ RE_LB_PACK(1, 1), binary);
1817
+ if (prev && (r = bt_push(m, prev, inst.offset, RE_CP_ABSENT_BACK,
1818
+ (uint32_t)begun)) != BT_OK) {
1819
+ return r;
1820
+ }
1821
+ }
1822
+ sp = str + reach;
1823
+ pc = inst.offset;
1824
+ break;
1825
+ }
1826
+ {
1827
+ const char *next = sp + mrb_re_charlen(sp, str_end, binary);
1828
+ if ((r = bt_push(m, st.sp, st.pc, RE_CP_ABSENT, st.group)) != BT_OK) return r;
1829
+ if ((r = bt_push(m, next, pc, RE_CP_ABSENT_ITER, 0)) != BT_OK) return r;
1830
+ }
1831
+ /* The body runs against a subject that ends where the absent may
1832
+ still reach, and as a pass of its own, as a lookaround's
1833
+ sub-pattern does, so that the records of the loops inside it are
1834
+ read only by the round that wrote them. */
1835
+ str_end = str + reach;
1836
+ m->pass = ++m->pass_seq;
1837
+ pc++;
1838
+ }
1839
+ break;
1840
+
1841
+ case RE_ABSENT_END:
1842
+ {
1843
+ /* The body has matched, which says how far the absent may still
1844
+ reach: not past the text the body just read, so it stops at the
1845
+ last character of that text, or, where the body matched empty, at
1846
+ the position the body ran at, which the empty match stands after
1847
+ rather than inside. An empty match where the absent began leaves
1848
+ it nothing at all, recorded as a reach below that position and
1849
+ answered at the head of the next round.
1850
+
1851
+ The alternatives the body left are dropped: the scan asks whether
1852
+ the body matches here, and one match is the whole of the answer.
1853
+ So is what it captured. The body is a test the scan runs and no
1854
+ part of the match, so a group inside one is left as the match
1855
+ found it, whether the run of the body matched or failed. */
1856
+ uint32_t idx = m->cp_top;
1857
+ while (idx > 0 && m->cp[idx - 1].kind != RE_CP_ABSENT_ITER) idx--;
1858
+ if (idx == 0) goto fail;
1859
+ idx--;
1860
+ re_cpoint it = m->cp[idx];
1861
+ if (idx == 0 || m->cp[idx - 1].kind != RE_CP_ABSENT) goto fail;
1862
+ re_cpoint *st = &m->cp[idx - 1];
1863
+ int reach;
1864
+ if (sp < it.sp) {
1865
+ reach = (sp == st->sp) ? -1 : (int)(sp - str);
1866
+ }
1867
+ else {
1868
+ const char *prev = lookbehind_start(str, str_end, sp, RE_LB_PACK(1, 1), binary);
1869
+ reach = prev ? (int)(prev - str) : -1;
1870
+ }
1871
+ if (reach < (int32_t)st->pc) st->pc = (uint32_t)reach;
1872
+ m->cp_top = idx;
1873
+ bt_undo_to(m, it.undo_top);
1874
+ m->pass = it.pass;
1875
+ sp = it.sp;
1876
+ pc = it.pc;
1877
+ }
1878
+ break;
1879
+
1880
+ default:
1881
+ goto fail;
1882
+ }
1883
+ continue;
1884
+
1885
+ fail:
1886
+ /* This branch is spent. The next alternative is the choice point on top,
1887
+ with every write since it was pushed taken back; with none left there
1888
+ is nothing more to try from this start position. */
1889
+ for (;;) {
1890
+ if (m->cp_top == 0) return BT_FAIL;
1891
+ re_cpoint c = m->cp[--m->cp_top];
1892
+ bt_undo_to(m, c.undo_top);
1893
+ /* The pass a branch was pushed in is the pass it runs in, and for a
1894
+ lookaround's barrier it is the pass the lookaround was entered
1895
+ from, which is where the search is once the barrier is taken. */
1896
+ m->pass = c.pass;
1897
+ /* A barrier is where a group was entered, not a branch: reaching it is
1898
+ that group failing, and what is left to try is below it. A negative
1899
+ lookaround's is the exception: its sub-pattern having no match
1900
+ left is the assertion holding, and what it resumes is the text after
1901
+ the lookaround. A call frame and a return's mark are not branches
1902
+ either: backtracking past a call is just the call unwinding, and
1903
+ what is left to try is below them. */
1904
+ if (c.kind == RE_CP_BARRIER || c.kind == RE_CP_CALL || c.kind == RE_CP_RET) continue;
1905
+ /* An absent repeater's state is not a branch either: reaching it is
1906
+ the scan having no round left, and the subject the text around it
1907
+ runs against comes back with it. */
1908
+ if (c.kind == RE_CP_ABSENT) { str_end = str + c.group; continue; }
1909
+ /* The ends of an absent repeater are answered longest first, and the
1910
+ one below the end being taken is what is left to try after it. */
1911
+ if (c.kind == RE_CP_ABSENT_BACK && c.sp > str + c.group) {
1912
+ const char *prev = lookbehind_start(str, str_end, c.sp, RE_LB_PACK(1, 1), binary);
1913
+ if (prev && (r = bt_push(m, prev, c.pc, RE_CP_ABSENT_BACK, c.group)) != BT_OK) {
1914
+ return r;
1915
+ }
1916
+ }
1917
+ sp = c.sp;
1918
+ pc = c.pc;
1919
+ if (c.kind == RE_CP_ITER && (r = bt_iter_begin(m, c.group, sp)) != BT_OK) return r;
1920
+ break;
1921
+ }
1922
+ }
1923
+ }
1924
+
1925
+ static int
1926
+ backtrack_exec(mrb_state *mrb, const mrb_regexp_pattern *pat,
1927
+ const char *str, mrb_int len, mrb_int start, mrb_int start_limit,
1928
+ int *captures, int captures_size, mrb_bool binary)
1929
+ {
1930
+ const char *start_cap = str + start_limit;
1931
+ const char *str_end = str + len;
1932
+ /* \A bounds the start positions the way pike_vm's clamp does. */
1933
+ if (pat->anchor == RE_ANCHOR_BOT) start_cap = str;
1934
+ int ncap = pat->num_captures * 2;
1935
+ if (ncap == 0) ncap = 2;
1936
+
1937
+ /* One block: the capture slots, then an entry record per pc and the pass
1938
+ that wrote it. The arrays are filled once here and put back to what they
1939
+ hold by the undo log unwinding between start positions (see there): an
1940
+ iteration's record is written on the log now, which a match does not
1941
+ unwind, so a record left by the attempt before would otherwise be read
1942
+ as this attempt's and stop a repetition that had not gone round yet.
1943
+
1944
+ Taken with mrb_malloc_simple() rather than mrb_malloc(), so that a
1945
+ refusal is answered where the growth reallocs below already answer one.
1946
+ Nothing is held here yet, so raising from this one line would strand
1947
+ nothing; what it would cost is the engine's own answer. Every other
1948
+ refusal inside a search reaches the caller as RE_NOMEM, which
1949
+ re_check_exec_error() turns into the raise, and a search that raised
1950
+ from here instead would be one the caller never saw stop. */
1951
+ int *caps = (int*)mrb_malloc_simple(mrb, sizeof(int) * (ncap + 2 * pat->code_len));
1952
+ if (!caps) return RE_NOMEM;
1953
+ int ret = 0;
1954
+ bt_state m;
1955
+ m.mrb = mrb;
1956
+ m.pat = pat;
1957
+ m.str = str;
1958
+ m.str_end = str_end;
1959
+ m.captures = caps;
1960
+ m.ncap = ncap;
1961
+ m.entered_at = caps + ncap;
1962
+ m.entered_in = m.entered_at + pat->code_len;
1963
+ m.pass = 0;
1964
+ m.pass_seq = 0;
1965
+ m.binary = binary;
1966
+ m.gpos = str + start; /* spinel: \G */
1967
+ m.cp = NULL;
1968
+ m.cp_top = m.cp_capa = 0;
1969
+ m.undo = NULL;
1970
+ m.undo_top = m.undo_capa = 0;
1971
+ memset(m.entered_at, -1, sizeof(int) * pat->code_len);
1972
+ memset(m.entered_in, 0, sizeof(int) * pat->code_len);
1973
+
1974
+ for (const char *sp = str + start; sp <= str_end && sp <= start_cap; sp++) {
1975
+ /* Skip ahead using the anchor, the literal prefix or the first-byte
1976
+ bitmap; the same composition as pike_vm's. */
1977
+ if (pat->anchor != RE_ANCHOR_NONE) {
1978
+ const char *skip = skip_to_line_start(str, sp, str_end);
1979
+ if (!skip) break;
1980
+ sp = skip;
1981
+ }
1982
+ if (pat->prefix_len > 0) {
1983
+ const char *skip = skip_to_prefix(pat, sp, str_end);
1984
+ if (!skip) break;
1985
+ sp = skip;
1986
+ }
1987
+ else if (pat->has_first_bytes) {
1988
+ const char *skip = skip_to_first_byte(pat, sp, str_end);
1989
+ if (!skip) break;
1990
+ sp = skip;
1991
+ }
1992
+ if (sp > start_cap) break;
1993
+ if (!binary && sp < str_end && mrb_re_char_interior_p(str, sp, str_end)) {
1994
+ continue;
1995
+ }
1996
+ memset(caps, -1, sizeof(int) * ncap);
1997
+ m.steps = 0;
1998
+ /* The state of the attempt before, which failed and left nothing to
1999
+ resume, is not this attempt's: the stacks start empty, and the writes
2000
+ still logged are taken back so that the records the arrays hold are
2001
+ what a fresh search finds. The pass numbering starts over with them.
2002
+ Every record a pass wrote is on that log, so once it has unwound
2003
+ there is nothing left for a number to be read against and the numbers
2004
+ need only be unique within the attempt; a counter that ran on across
2005
+ the start positions would climb with the length of the subject
2006
+ instead, until a long enough search overflowed it. */
2007
+ m.cp_top = 0;
2008
+ m.pass = 0;
2009
+ m.pass_seq = 0;
2010
+ bt_undo_to(&m, 0);
2011
+
2012
+ int r = bt_match(&m, sp, 0);
2013
+ if (r == BT_MATCH) {
2014
+ if (captures) {
2015
+ int copy = ncap < captures_size ? ncap : captures_size;
2016
+ memcpy(captures, caps, sizeof(int) * copy);
2017
+ }
2018
+ ret = ncap > 0 ? ncap : 1;
2019
+ break;
2020
+ }
2021
+ if (r == BT_NOMEM) {
2022
+ /* The allocator had nothing left for the state this search needed. The
2023
+ search ends here as it does at a limit, and it is told apart from
2024
+ one all the way out to the caller, since what it asks for is not a
2025
+ knob turned up: raising MRB_REGEXP_STACK_LIMIT in answer to this
2026
+ would only let the next search ask for more. */
2027
+ ret = RE_NOMEM;
2028
+ break;
2029
+ }
2030
+ if (r == BT_LIMIT) {
2031
+ /* The search ends here, not this start position's attempt: the
2032
+ positions after it answer where the first match is only once this
2033
+ one has none, which is what the limit left unanswered. Which limit
2034
+ is read off the step count: nothing but the step check moves it, so
2035
+ it is over the step limit exactly when that check is what gave
2036
+ up. */
2037
+ ret = m.steps > MRB_REGEXP_STEP_LIMIT ? RE_OVER_STEP_LIMIT : RE_OVER_STACK_LIMIT;
2038
+ break;
2039
+ }
2040
+ }
2041
+ mrb_free(mrb, m.undo);
2042
+ mrb_free(mrb, m.cp);
2043
+ mrb_free(mrb, caps);
2044
+ return ret;
2045
+ }
2046
+
2047
+ /* Fast path for pure literal patterns: the whole pattern is the prefix, so
2048
+ the search is the prefix skip itself and there is no NFA to run. */
2049
+ static int
2050
+ literal_exec(const mrb_regexp_pattern *pat,
2051
+ const char *str, mrb_int len, mrb_int start, mrb_int start_limit,
2052
+ int *captures, int captures_size, mrb_bool binary)
2053
+ {
2054
+ const char *start_cap = str + start_limit;
2055
+ const char *sp = str + start;
2056
+ const char *str_end = str + len;
2057
+ mrb_int plen = pat->prefix_len;
2058
+
2059
+ while (sp + plen <= str_end && sp <= start_cap) {
2060
+ const char *found = find_prefix(pat->prefix, plen, sp, str_end);
2061
+ if (!found || found > start_cap) return 0;
2062
+ if (!binary && mrb_re_char_interior_p(str, found, str_end)) {
2063
+ sp = found + 1; /* not a char boundary, same rule as the other engines */
2064
+ continue;
2065
+ }
2066
+ /* No test that the end is a character boundary: a byte that spells no
2067
+ character is RE_BYTE, which this path never holds (the prefix is
2068
+ RE_CHAR only), so the literal is whole characters and a lead byte
2069
+ that matched fixed the length of the one it starts. */
2070
+ if (captures && captures_size >= 2) {
2071
+ captures[0] = (int)(found - str);
2072
+ captures[1] = (int)(found - str) + plen;
2073
+ }
2074
+ return 2; /* group 0 start/end */
2075
+ }
2076
+ return 0;
2077
+ }
2078
+
2079
+ /* The search the three engines make, with the last position a match may
2080
+ start at named. The bound is on where a match may begin and not on how
2081
+ far the subject is read: a match that begins at `start_limit` runs to
2082
+ wherever it ends, which is why this is a separate argument rather than a
2083
+ shorter `len`. Shortening the subject would answer a different question
2084
+ -- `$` and `\z` would assert at the cut, and a match reaching past it
2085
+ would be lost. */
2086
+ static int
2087
+ exec_range(mrb_state *mrb, const mrb_regexp_pattern *pat,
2088
+ const char *str, mrb_int len, mrb_int start, mrb_int start_limit,
2089
+ int *captures, int captures_size, mrb_bool binary)
2090
+ {
2091
+ if (pat->is_literal) {
2092
+ return literal_exec(pat, str, len, start, start_limit, captures, captures_size, binary);
2093
+ }
2094
+ if (pat->has_backref || pat->needs_backtrack) {
2095
+ return backtrack_exec(mrb, pat, str, len, start, start_limit, captures, captures_size, binary);
2096
+ }
2097
+ return pike_vm(mrb, pat, str, len, start, start_limit, captures, captures_size, binary);
2098
+ }
2099
+
2100
+ /* Public entry point */
2101
+ int
2102
+ mrb_re_exec(mrb_state *mrb, const mrb_regexp_pattern *pat,
2103
+ const char *str, mrb_int len, mrb_int start,
2104
+ int *captures, int captures_size, mrb_bool binary)
2105
+ {
2106
+ /* The end of the subject is the last position anything can start at, so
2107
+ the forward search is the unbounded case of the above. */
2108
+ return exec_range(mrb, pat, str, len, start, len, captures, captures_size, binary);
2109
+ }
2110
+
2111
+ /* How far the backward probe below may read before it stops being the cheap
2112
+ question. A search bounded to a window still reads from where the window
2113
+ starts to the end of the subject, so the bound is on that span and not on
2114
+ the window's own width: a narrow window at the end of a long subject is
2115
+ cheap, the same window asked about a position far from the end is the
2116
+ whole search over again. */
2117
+ #define RE_RSEARCH_PROBE_SPAN 256
2118
+
2119
+ /* The last match that starts at or before `limit`, which is what `rindex`,
2120
+ `byterindex` and `rpartition` ask for.
2121
+
2122
+ A forward walk answers this by stepping every match from the front and
2123
+ keeping the last, which costs a search per match: on a subject a pattern
2124
+ matches everywhere that is a search per position, and where one search is
2125
+ itself linear in the subject -- a greedy `/a+b?/` and the like -- the walk
2126
+ is quadratic in it.
2127
+
2128
+ The last match is usually near the end, so ask about the end first: widen
2129
+ a window there until a match starts inside it. A window that catches one
2130
+ costs the window rather than the subject, and the walk that follows has
2131
+ only the window to cross. Widening stops at the span above rather than at
2132
+ the front, so a subject with no match near the end falls through to the
2133
+ single forward search this cost before, instead of paying for the
2134
+ widening as well. */
2135
+ int
2136
+ mrb_re_rexec(mrb_state *mrb, const mrb_regexp_pattern *pat,
2137
+ const char *str, mrb_int len, mrb_int limit,
2138
+ int *captures, int captures_size, mrb_bool binary)
2139
+ {
2140
+ if (limit > len) limit = len;
2141
+ if (limit < 0) return 0;
2142
+
2143
+ int last[RE_MAX_CAPTURES * 2];
2144
+ int last_n = 0;
2145
+
2146
+ for (mrb_int k = 1; ; k *= 2) {
2147
+ mrb_int lo = limit - k + 1;
2148
+ if (lo < 0) lo = 0;
2149
+ if (len - lo > RE_RSEARCH_PROBE_SPAN) break;
2150
+ memset(captures, -1, sizeof(int) * captures_size);
2151
+ last_n = exec_range(mrb, pat, str, len, lo, limit, captures, captures_size, binary);
2152
+ /* A match or an execution error ends the probe. A limit, or an
2153
+ allocation the engine was refused, is the answer to the whole question
2154
+ and not to this window's: a window that gave up is not one with no
2155
+ match in it, and widening would only ask the same search again a size
2156
+ up. */
2157
+ if (last_n) break;
2158
+ /* The window had grown to the whole range, so there is no match to find
2159
+ and the search below would only ask again. */
2160
+ if (lo == 0) return 0;
2161
+ }
2162
+
2163
+ if (last_n == 0) {
2164
+ memset(captures, -1, sizeof(int) * captures_size);
2165
+ last_n = exec_range(mrb, pat, str, len, 0, limit, captures, captures_size, binary);
2166
+ if (last_n == 0) return 0;
2167
+ }
2168
+ if (last_n < 0) return last_n;
2169
+
2170
+ /* Whichever range answered gave its leftmost match; the last one is found
2171
+ by walking forward from it. Each step resumes one byte past the match
2172
+ start and not at the match end, which is what keeps overlapping matches
2173
+ in view: `"aaa"` against `/aa/` answers 1, where resuming at the end
2174
+ would answer 0. A byte inside a character is not a position a match can
2175
+ start at, and the engine steps over one rather than seed an attempt
2176
+ there, so `+ 1` reaches the next character by itself. */
2177
+ memcpy(last, captures, sizeof(int) * captures_size);
2178
+ mrb_int pos = captures[0] + 1;
2179
+ while (pos <= limit) {
2180
+ memset(captures, -1, sizeof(int) * captures_size);
2181
+ int n = exec_range(mrb, pat, str, len, pos, limit, captures, captures_size, binary);
2182
+ if (n == 0) break;
2183
+ if (n < 0) return n;
2184
+ last_n = n;
2185
+ memcpy(last, captures, sizeof(int) * captures_size);
2186
+ pos = captures[0] + 1;
2187
+ }
2188
+ memcpy(captures, last, sizeof(int) * captures_size);
2189
+ return last_n;
2190
+ }