Debian Codegraph @

js/src/vm/RegExpObject.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "vm/RegExpObject.h"
8
9 #include "mozilla/MemoryReporting.h"
10 #include "mozilla/PodOperations.h"
11
12 #include <type_traits>
13
14 #include "builtin/RegExp.h"
15 #include "builtin/SelfHostingDefines.h" // REGEXP_*_FLAG
16 #include "frontend/FrontendContext.h" // AutoReportFrontendContext
17 #include "frontend/TokenStream.h"
18 #include "gc/HashUtil.h"
19 #include "irregexp/RegExpAPI.h"
20 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
21 #include "js/friend/StackLimits.h" // js::ReportOverRecursed
22 #include "js/Object.h" // JS::GetBuiltinClass
23 #include "js/Printer.h" // js::GenericPrinter
24 #include "js/RegExp.h"
25 #include "js/RegExpFlags.h" // JS::RegExpFlags
26 #include "util/StringBuilder.h"
27 #include "util/Unicode.h"
28 #include "vm/JSONPrinter.h" // js::JSONPrinter
29 #include "vm/MatchPairs.h"
30 #include "vm/PlainObject.h"
31 #include "vm/RegExpStatics.h"
32 #include "vm/StringType.h"
33
34 #include "vm/JSContext-inl.h"
35 #include "vm/JSObject-inl.h"
36 #include "vm/NativeObject-inl.h"
37 #include "vm/Shape-inl.h"
38
39 using namespace js;
40
41 using JS::CompileOptions;
42 using JS::RegExpFlag;
43 using JS::RegExpFlags;
44 using mozilla::DebugOnly;
45 using mozilla::PodCopy;
46
47 using JS::AutoCheckCannotGC;
48
49 static_assert(RegExpFlag::HasIndices == REGEXP_HASINDICES_FLAG,
50 "self-hosted JS and /d flag bits must agree");
51 static_assert(RegExpFlag::Global == REGEXP_GLOBAL_FLAG,
52 "self-hosted JS and /g flag bits must agree");
53 static_assert(RegExpFlag::IgnoreCase == REGEXP_IGNORECASE_FLAG,
54 "self-hosted JS and /i flag bits must agree");
55 static_assert(RegExpFlag::Multiline == REGEXP_MULTILINE_FLAG,
56 "self-hosted JS and /m flag bits must agree");
57 static_assert(RegExpFlag::DotAll == REGEXP_DOTALL_FLAG,
58 "self-hosted JS and /s flag bits must agree");
59 static_assert(RegExpFlag::Unicode == REGEXP_UNICODE_FLAG,
60 "self-hosted JS and /u flag bits must agree");
61 static_assert(RegExpFlag::UnicodeSets == REGEXP_UNICODESETS_FLAG,
62 "self-hosted JS and /v flag bits must agree");
63 static_assert(RegExpFlag::Sticky == REGEXP_STICKY_FLAG,
64 "self-hosted JS and /y flag bits must agree");
65
66 RegExpObject* js::RegExpAlloc(JSContext* cx, NewObjectKind newKind,
67 HandleObject proto /* = nullptr */) {
68 Rooted<RegExpObject*> regexp(
69 cx, NewObjectWithClassProtoAndKind<RegExpObject>(cx, proto, newKind));
70 if (!regexp) {
71 return nullptr;
72 }
73
74 if (!SharedShape::ensureInitialCustomShape<RegExpObject>(cx, regexp)) {
75 return nullptr;
76 }
77
78 MOZ_ASSERT(regexp->lookupPure(cx->names().lastIndex)->slot() ==
79 RegExpObject::lastIndexSlot());
80
81 return regexp;
82 }
83
84 /* MatchPairs */
85
86 bool VectorMatchPairs::initArrayFrom(VectorMatchPairs& copyFrom) {
87 MOZ_ASSERT(copyFrom.pairCount() > 0);
88
89 if (!allocOrExpandArray(copyFrom.pairCount())) {
90 return false;
91 }
92
93 PodCopy(pairs_, copyFrom.pairs_, pairCount_);
94
95 return true;
96 }
97
98 bool VectorMatchPairs::allocOrExpandArray(size_t pairCount) {
99 if (!vec_.resizeUninitialized(pairCount)) {
100 return false;
101 }
102
103 pairs_ = &vec_[0];
104 pairCount_ = pairCount;
105 return true;
106 }
107
108 /* RegExpObject */
109
110 /* static */
111 RegExpShared* RegExpObject::getShared(JSContext* cx,
112 Handle<RegExpObject*> regexp) {
113 if (regexp->hasShared()) {
114 return regexp->getShared();
115 }
116
117 return createShared(cx, regexp);
118 }
119
120 /* static */
121 bool RegExpObject::isOriginalFlagGetter(JSNative native, RegExpFlags* mask) {
122 if (native == regexp_hasIndices) {
123 *mask = RegExpFlag::HasIndices;
124 return true;
125 }
126 if (native == regexp_global) {
127 *mask = RegExpFlag::Global;
128 return true;
129 }
130 if (native == regexp_ignoreCase) {
131 *mask = RegExpFlag::IgnoreCase;
132 return true;
133 }
134 if (native == regexp_multiline) {
135 *mask = RegExpFlag::Multiline;
136 return true;
137 }
138 if (native == regexp_dotAll) {
139 *mask = RegExpFlag::DotAll;
140 return true;
141 }
142 if (native == regexp_sticky) {
143 *mask = RegExpFlag::Sticky;
144 return true;
145 }
146 if (native == regexp_unicode) {
147 *mask = RegExpFlag::Unicode;
148 return true;
149 }
150 if (native == regexp_unicodeSets) {
151 *mask = RegExpFlag::UnicodeSets;
152 return true;
153 }
154
155 return false;
156 }
157
158 static const ClassSpec RegExpObjectClassSpec = {
159 GenericCreateConstructor<js::regexp_construct, 2, gc::AllocKind::FUNCTION>,
160 GenericCreatePrototype<RegExpObject>,
161 js::regexp_static_methods,
162 js::regexp_static_props,
163 js::regexp_methods,
164 js::regexp_properties,
165 GenericFinishInit<WhichHasFuseProperty::Proto>,
166 };
167
168 const JSClass RegExpObject::class_ = {
169 "RegExp",
170 JSCLASS_HAS_RESERVED_SLOTS(RegExpObject::RESERVED_SLOTS) |
171 JSCLASS_HAS_CACHED_PROTO(JSProto_RegExp),
172 JS_NULL_CLASS_OPS,
173 &RegExpObjectClassSpec,
174 };
175
176 const JSClass RegExpObject::protoClass_ = {
177 "RegExp.prototype",
178 JSCLASS_HAS_CACHED_PROTO(JSProto_RegExp),
179 JS_NULL_CLASS_OPS,
180 &RegExpObjectClassSpec,
181 };
182
183 template <typename CharT>
184 RegExpObject* RegExpObject::create(JSContext* cx, const CharT* chars,
185 size_t length, RegExpFlags flags,
186 NewObjectKind newKind) {
187 static_assert(std::is_same_v<CharT, char16_t>,
188 "this code may need updating if/when CharT encodes UTF-8");
189
190 Rooted<JSAtom*> source(cx, AtomizeChars(cx, chars, length));
191 if (!source) {
192 return nullptr;
193 }
194
195 return create(cx, source, flags, newKind);
196 }
197
198 template RegExpObject* RegExpObject::create(JSContext* cx,
199 const char16_t* chars,
200 size_t length, RegExpFlags flags,
201 NewObjectKind newKind);
202
203 RegExpObject* RegExpObject::createSyntaxChecked(JSContext* cx,
204 Handle<JSAtom*> source,
205 RegExpFlags flags,
206 NewObjectKind newKind) {
207 Rooted<RegExpObject*> regexp(cx, RegExpAlloc(cx, newKind));
208 if (!regexp) {
209 return nullptr;
210 }
211
212 regexp->initAndZeroLastIndex(source, flags, cx);
213
214 return regexp;
215 }
216
217 RegExpObject* RegExpObject::create(JSContext* cx, Handle<JSAtom*> source,
218 RegExpFlags flags, NewObjectKind newKind) {
219 Rooted<RegExpObject*> regexp(cx);
220 {
221 AutoReportFrontendContext fc(cx);
222 CompileOptions dummyOptions(cx);
223 frontend::DummyTokenStream dummyTokenStream(&fc, dummyOptions);
224
225 LifoAllocScope allocScope(&cx->tempLifoAlloc());
226 if (!irregexp::CheckPatternSyntax(cx, cx->stackLimitForCurrentPrincipal(),
227 dummyTokenStream, source, flags)) {
228 return nullptr;
229 }
230
231 regexp = RegExpAlloc(cx, newKind);
232 if (!regexp) {
233 return nullptr;
234 }
235
236 regexp->initAndZeroLastIndex(source, flags, cx);
237
238 MOZ_ASSERT(!regexp->hasShared());
239 }
240 return regexp;
241 }
242
243 /* static */
244 RegExpShared* RegExpObject::createShared(JSContext* cx,
245 Handle<RegExpObject*> regexp) {
246 MOZ_ASSERT(!regexp->hasShared());
247 Rooted<JSAtom*> source(cx, regexp->getSource());
248 RegExpShared* shared =
249 cx->zone()->regExps().get(cx, source, regexp->getFlags());
250 if (!shared) {
251 return nullptr;
252 }
253
254 regexp->setShared(shared);
255
256 MOZ_ASSERT(regexp->hasShared());
257
258 return shared;
259 }
260
261 SharedShape* RegExpObject::assignInitialShape(JSContext* cx,
262 Handle<RegExpObject*> self) {
263 MOZ_ASSERT(self->empty());
264
265 static_assert(LAST_INDEX_SLOT == 0);
266
267 /* The lastIndex property alone is writable but non-configurable. */
268 if (!NativeObject::addPropertyInReservedSlot(cx, self, cx->names().lastIndex,
269 LAST_INDEX_SLOT,
270 {PropertyFlag::Writable})) {
271 return nullptr;
272 }
273
274 // Cache the initial RegExpObject shape that has RegExp.prototype as proto in
275 // the global object.
276 SharedShape* shape = self->sharedShape();
277 JSObject* proto = cx->global()->maybeGetPrototype(JSProto_RegExp);
278 if (proto && shape->proto() == TaggedProto(proto)) {
279 cx->global()->setRegExpShapeWithDefaultProto(shape);
280 }
281 return shape;
282 }
283
284 void RegExpObject::initIgnoringLastIndex(JSAtom* source, RegExpFlags flags) {
285 // If this is a re-initialization with an existing RegExpShared, 'flags'
286 // may not match getShared()->flags, so forget the RegExpShared.
287 clearShared();
288
289 setSource(source);
290 setFlags(flags);
291 }
292
293 void RegExpObject::initAndZeroLastIndex(JSAtom* source, RegExpFlags flags,
294 JSContext* cx) {
295 initIgnoringLastIndex(source, flags);
296 zeroLastIndex(cx);
297 }
298
299 template <typename KnownF, typename UnknownF>
300 void ForEachRegExpFlag(JS::RegExpFlags flags, KnownF known, UnknownF unknown) {
301 uint8_t raw = flags.value();
302
303 for (uint8_t i = 1; i; i = i << 1) {
304 if (!(raw & i)) {
305 continue;
306 }
307 switch (raw & i) {
308 case RegExpFlag::HasIndices:
309 known("HasIndices", "d");
310 break;
311 case RegExpFlag::Global:
312 known("Global", "g");
313 break;
314 case RegExpFlag::IgnoreCase:
315 known("IgnoreCase", "i");
316 break;
317 case RegExpFlag::Multiline:
318 known("Multiline", "m");
319 break;
320 case RegExpFlag::DotAll:
321 known("DotAll", "s");
322 break;
323 case RegExpFlag::Unicode:
324 known("Unicode", "u");
325 break;
326 case RegExpFlag::UnicodeSets:
327 known("UnicodeSets", "v");
328 break;
329 case RegExpFlag::Sticky:
330 known("Sticky", "y");
331 break;
332 default:
333 unknown(i);
334 break;
335 }
336 }
337 }
338
339 std::ostream& JS::operator<<(std::ostream& os, RegExpFlags flags) {
340 ForEachRegExpFlag(
341 flags, [&](const char* name, const char* c) { os << c; },
342 [&](uint8_t value) { os << '?'; });
343 return os;
344 }
345
346 #if defined(DEBUG) || defined(JS_JITSPEW)
347 void RegExpObject::dumpOwnFields(js::JSONPrinter& json) const {
348 {
349 js::GenericPrinter& out = json.beginStringProperty("source");
350 getSource()->dumpPropertyName(out);
351 json.endStringProperty();
352 }
353
354 json.beginInlineListProperty("flags");
355 ForEachRegExpFlag(
356 getFlags(),
357 [&](const char* name, const char* c) { json.value("%s", name); },
358 [&](uint8_t value) { json.value("Unknown(%02x)", value); });
359 json.endInlineList();
360
361 {
362 js::GenericPrinter& out = json.beginStringProperty("lastIndex");
363 getLastIndex().dumpStringContent(out);
364 json.endStringProperty();
365 }
366 }
367
368 void RegExpObject::dumpOwnStringContent(js::GenericPrinter& out) const {
369 out.put("/");
370
371 getSource()->dumpCharsNoQuote(out);
372
373 out.put("/");
374
375 ForEachRegExpFlag(
376 getFlags(), [&](const char* name, const char* c) { out.put(c); },
377 [&](uint8_t value) {});
378 }
379 #endif /* defined(DEBUG) || defined(JS_JITSPEW) */
380
381 static MOZ_ALWAYS_INLINE bool IsRegExpLineTerminator(const JS::Latin1Char c) {
382 return c == '\n' || c == '\r';
383 }
384
385 static MOZ_ALWAYS_INLINE bool IsRegExpLineTerminator(const char16_t c) {
386 return c == '\n' || c == '\r' || c == 0x2028 || c == 0x2029;
387 }
388
389 static MOZ_ALWAYS_INLINE bool AppendEscapedLineTerminator(
390 StringBuilder& sb, const JS::Latin1Char c) {
391 switch (c) {
392 case '\n':
393 if (!sb.append('n')) {
394 return false;
395 }
396 break;
397 case '\r':
398 if (!sb.append('r')) {
399 return false;
400 }
401 break;
402 default:
403 MOZ_CRASH("Bad LineTerminator");
404 }
405 return true;
406 }
407
408 static MOZ_ALWAYS_INLINE bool AppendEscapedLineTerminator(StringBuilder& sb,
409 const char16_t c) {
410 switch (c) {
411 case '\n':
412 if (!sb.append('n')) {
413 return false;
414 }
415 break;
416 case '\r':
417 if (!sb.append('r')) {
418 return false;
419 }
420 break;
421 case 0x2028:
422 if (!sb.append("u2028")) {
423 return false;
424 }
425 break;
426 case 0x2029:
427 if (!sb.append("u2029")) {
428 return false;
429 }
430 break;
431 default:
432 MOZ_CRASH("Bad LineTerminator");
433 }
434 return true;
435 }
436
437 template <typename CharT>
438 static MOZ_ALWAYS_INLINE bool SetupBuilder(StringBuilder& sb,
439 const CharT* oldChars, size_t oldLen,
440 const CharT* it) {
441 if constexpr (std::is_same_v<CharT, char16_t>) {
442 if (!sb.ensureTwoByteChars()) {
443 return false;
444 }
445 }
446
447 if (!sb.reserve(oldLen + 1)) {
448 return false;
449 }
450
451 sb.infallibleAppend(oldChars, size_t(it - oldChars));
452 return true;
453 }
454
455 // Note: leaves the string builder empty if no escaping need be performed.
456 template <typename CharT>
457 static bool EscapeRegExpPattern(StringBuilder& sb, const CharT* oldChars,
458 size_t oldLen) {
459 bool inBrackets = false;
460 bool previousCharacterWasBackslash = false;
461
462 for (const CharT* it = oldChars; it < oldChars + oldLen; ++it) {
463 CharT ch = *it;
464 if (!previousCharacterWasBackslash) {
465 if (inBrackets) {
466 if (ch == ']') {
467 inBrackets = false;
468 }
469 } else if (ch == '/') {
470 // There's a forward slash that needs escaping.
471 if (sb.empty()) {
472 // This is the first char we've seen that needs escaping,
473 // copy everything up to this point.
474 if (!SetupBuilder(sb, oldChars, oldLen, it)) {
475 return false;
476 }
477 }
478 if (!sb.append('\\')) {
479 return false;
480 }
481 } else if (ch == '[') {
482 inBrackets = true;
483 }
484 }
485
486 if (IsRegExpLineTerminator(ch)) {
487 // There's LineTerminator that needs escaping.
488 if (sb.empty()) {
489 // This is the first char we've seen that needs escaping,
490 // copy everything up to this point.
491 if (!SetupBuilder(sb, oldChars, oldLen, it)) {
492 return false;
493 }
494 }
495 if (!previousCharacterWasBackslash) {
496 if (!sb.append('\\')) {
497 return false;
498 }
499 }
500 if (!AppendEscapedLineTerminator(sb, ch)) {
501 return false;
502 }
503 } else if (!sb.empty()) {
504 if (!sb.append(ch)) {
505 return false;
506 }
507 }
508
509 if (previousCharacterWasBackslash) {
510 previousCharacterWasBackslash = false;
511 } else if (ch == '\\') {
512 previousCharacterWasBackslash = true;
513 }
514 }
515
516 return true;
517 }
518
519 // ES6 draft rev32 21.2.3.2.4.
520 JSLinearString* js::EscapeRegExpPattern(JSContext* cx, Handle<JSAtom*> src) {
521 // Step 2.
522 if (src->length() == 0) {
523 return cx->names().emptyRegExp_;
524 }
525
526 // We may never need to use |sb|. Start using it lazily.
527 JSStringBuilder sb(cx);
528 bool escapeFailed = false;
529 if (src->hasLatin1Chars()) {
530 JS::AutoCheckCannotGC nogc;
531 escapeFailed =
532 !::EscapeRegExpPattern(sb, src->latin1Chars(nogc), src->length());
533 } else {
534 JS::AutoCheckCannotGC nogc;
535 escapeFailed =
536 !::EscapeRegExpPattern(sb, src->twoByteChars(nogc), src->length());
537 }
538 if (escapeFailed) {
539 return nullptr;
540 }
541
542 // Step 3.
543 if (sb.empty()) {
544 return src;
545 }
546 return sb.finishString();
547 }
548
549 // ES6 draft rev32 21.2.5.14. Optimized for RegExpObject.
550 JSLinearString* RegExpObject::toString(JSContext* cx,
551 Handle<RegExpObject*> obj) {
552 // Steps 3-4.
553 Rooted<JSAtom*> src(cx, obj->getSource());
554 if (!src) {
555 return nullptr;
556 }
557 Rooted<JSLinearString*> escapedSrc(cx, EscapeRegExpPattern(cx, src));
558
559 // Step 7.
560 JSStringBuilder sb(cx);
561 size_t len = escapedSrc->length();
562 if (!sb.reserve(len + 2)) {
563 return nullptr;
564 }
565 sb.infallibleAppend('/');
566 if (!sb.append(escapedSrc)) {
567 return nullptr;
568 }
569 sb.infallibleAppend('/');
570
571 // Steps 5-7.
572 if (obj->hasIndices() && !sb.append('d')) {
573 return nullptr;
574 }
575 if (obj->global() && !sb.append('g')) {
576 return nullptr;
577 }
578 if (obj->ignoreCase() && !sb.append('i')) {
579 return nullptr;
580 }
581 if (obj->multiline() && !sb.append('m')) {
582 return nullptr;
583 }
584 if (obj->dotAll() && !sb.append('s')) {
585 return nullptr;
586 }
587 if (obj->unicode() && !sb.append('u')) {
588 return nullptr;
589 }
590 if (obj->unicodeSets() && !sb.append('v')) {
591 return nullptr;
592 }
593 if (obj->sticky() && !sb.append('y')) {
594 return nullptr;
595 }
596
597 return sb.finishString();
598 }
599
600 template <typename CharT>
601 static MOZ_ALWAYS_INLINE bool IsRegExpMetaChar(CharT ch) {
602 switch (ch) {
603 /* ES 2016 draft Mar 25, 2016 21.2.1 SyntaxCharacter. */
604 case '^':
605 case '$':
606 case '\\':
607 case '.':
608 case '*':
609 case '+':
610 case '?':
611 case '(':
612 case ')':
613 case '[':
614 case ']':
615 case '{':
616 case '}':
617 case '|':
618 return true;
619 default:
620 return false;
621 }
622 }
623
624 template <typename CharT>
625 bool js::HasRegExpMetaChars(const CharT* chars, size_t length) {
626 for (size_t i = 0; i < length; ++i) {
627 if (IsRegExpMetaChar<CharT>(chars[i])) {
628 return true;
629 }
630 }
631 return false;
632 }
633
634 template bool js::HasRegExpMetaChars<Latin1Char>(const Latin1Char* chars,
635 size_t length);
636
637 template bool js::HasRegExpMetaChars<char16_t>(const char16_t* chars,
638 size_t length);
639
640 bool js::StringHasRegExpMetaChars(const JSLinearString* str) {
641 AutoCheckCannotGC nogc;
642 if (str->hasLatin1Chars()) {
643 return HasRegExpMetaChars(str->latin1Chars(nogc), str->length());
644 }
645
646 return HasRegExpMetaChars(str->twoByteChars(nogc), str->length());
647 }
648
649 /* RegExpShared */
650
651 RegExpShared::RegExpShared(JSAtom* source, RegExpFlags flags)
652 : CellWithTenuredGCPointer(source), pairCount_(0), flags(flags) {}
653
654 void RegExpShared::traceChildren(JSTracer* trc) {
655 TraceNullableCellHeaderEdge(trc, this, "RegExpShared source");
656 if (kind() == RegExpShared::Kind::Atom) {
657 TraceNullableEdge(trc, &patternAtom_, "RegExpShared pattern atom");
658 } else {
659 for (auto& comp : compilationArray) {
660 TraceNullableEdge(trc, &comp.jitCode, "RegExpShared code");
661 }
662 TraceNullableEdge(trc, &groupsTemplate_, "RegExpShared groups template");
663 }
664 }
665
666 void RegExpShared::discardJitCode() {
667 for (auto& comp : compilationArray) {
668 comp.jitCode = nullptr;
669 }
670
671 // We can also purge the tables used by JIT code.
672 tables.clearAndFree();
673 }
674
675 void RegExpShared::finalize(JS::GCContext* gcx) {
676 for (auto& comp : compilationArray) {
677 if (comp.byteCode) {
678 size_t length = comp.byteCodeLength();
679 gcx->free_(this, comp.byteCode, length, MemoryUse::RegExpSharedBytecode);
680 }
681 }
682 if (namedCaptureIndices_) {
683 size_t length = numNamedCaptures() * sizeof(uint32_t);
684 gcx->free_(this, namedCaptureIndices_, length,
685 MemoryUse::RegExpSharedNamedCaptureData);
686 }
687 if (namedCaptureSliceIndices_) {
688 size_t length = numDistinctNamedCaptures() * sizeof(uint32_t);
689 gcx->free_(this, namedCaptureSliceIndices_, length,
690 MemoryUse::RegExpSharedNamedCaptureSliceData);
691 }
692 tables.~JitCodeTables();
693 }
694
695 /* static */
696 bool RegExpShared::compileIfNecessary(JSContext* cx,
697 MutableHandleRegExpShared re,
698 Handle<JSLinearString*> input,
699 RegExpShared::CodeKind codeKind) {
700 if (codeKind == RegExpShared::CodeKind::Any) {
701 // We start by interpreting regexps, then compile them once they are
702 // sufficiently hot. For very long input strings, we tier up eagerly.
703 codeKind = RegExpShared::CodeKind::Bytecode;
704 if (re->markedForTierUp() || input->length() > 1000) {
705 codeKind = RegExpShared::CodeKind::Jitcode;
706 }
707 }
708
709 // Fall back to bytecode if native codegen is not available.
710 if (!IsNativeRegExpEnabled() && codeKind == RegExpShared::CodeKind::Jitcode) {
711 codeKind = RegExpShared::CodeKind::Bytecode;
712 }
713
714 bool needsCompile = false;
715 if (re->kind() == RegExpShared::Kind::Unparsed) {
716 needsCompile = true;
717 }
718 if (re->kind() == RegExpShared::Kind::RegExp) {
719 if (!re->isCompiled(input->hasLatin1Chars(), codeKind)) {
720 needsCompile = true;
721 }
722 }
723 if (needsCompile) {
724 return irregexp::CompilePattern(cx, re, input, codeKind);
725 }
726 return true;
727 }
728
729 /* static */
730 RegExpRunStatus RegExpShared::execute(JSContext* cx,
731 MutableHandleRegExpShared re,
732 Handle<JSLinearString*> input,
733 size_t start, VectorMatchPairs* matches) {
734 MOZ_ASSERT(matches);
735
736 // TODO: Add tracelogger support
737
738 /* Compile the code at point-of-use. */
739 if (!compileIfNecessary(cx, re, input, RegExpShared::CodeKind::Any)) {
740 return RegExpRunStatus::Error;
741 }
742
743 /*
744 * Ensure sufficient memory for output vector.
745 * No need to initialize it. The RegExp engine fills them in on a match.
746 */
747 if (!matches->allocOrExpandArray(re->pairCount())) {
748 ReportOutOfMemory(cx);
749 return RegExpRunStatus::Error;
750 }
751
752 if (re->kind() == RegExpShared::Kind::Atom) {
753 return RegExpShared::executeAtom(re, input, start, matches);
754 }
755
756 /*
757 * Ensure sufficient memory for output vector.
758 * No need to initialize it. The RegExp engine fills them in on a match.
759 */
760 if (!matches->allocOrExpandArray(re->pairCount())) {
761 ReportOutOfMemory(cx);
762 return RegExpRunStatus::Error;
763 }
764
765 uint32_t interruptRetries = 0;
766 const uint32_t maxInterruptRetries = 4;
767 do {
768 DebugOnly<bool> alreadyThrowing = cx->isExceptionPending();
769 RegExpRunStatus result = irregexp::Execute(cx, re, input, start, matches);
770 #ifdef DEBUG
771 // Check if we must simulate the interruption
772 if (js::irregexp::IsolateShouldSimulateInterrupt(cx->isolate)) {
773 js::irregexp::IsolateClearShouldSimulateInterrupt(cx->isolate);
774 cx->requestInterrupt(InterruptReason::CallbackUrgent);
775 }
776 #endif
777 if (result == RegExpRunStatus::Error) {
778 /* Execute can return RegExpRunStatus::Error:
779 *
780 * 1. If the native stack overflowed
781 * 2. If the backtrack stack overflowed
782 * 3. If an interrupt was requested during execution.
783 *
784 * In the first two cases, we want to throw an error. In the
785 * third case, we want to handle the interrupt and try again.
786 * We cap the number of times we will retry.
787 */
788 if (cx->isExceptionPending()) {
789 // If this regexp is being executed by recovery instructions
790 // while bailing out to handle an exception, there may already
791 // be an exception pending. If so, just return that exception
792 // instead of reporting a new one.
793 MOZ_ASSERT(alreadyThrowing);
794 return RegExpRunStatus::Error;
795 }
796 if (cx->hasAnyPendingInterrupt()) {
797 if (!CheckForInterrupt(cx)) {
798 return RegExpRunStatus::Error;
799 }
800 if (interruptRetries++ < maxInterruptRetries) {
801 // The initial execution may have been interpreted, or the
802 // interrupt may have triggered a GC that discarded jitcode.
803 // To maximize the chance of succeeding before being
804 // interrupted again, we want to ensure we are compiled.
805 if (!compileIfNecessary(cx, re, input,
806 RegExpShared::CodeKind::Jitcode)) {
807 return RegExpRunStatus::Error;
808 }
809 continue;
810 }
811 }
812 // If we have run out of retries, this regexp takes too long to execute.
813 ReportOverRecursed(cx);
814 return RegExpRunStatus::Error;
815 }
816
817 MOZ_ASSERT(result == RegExpRunStatus::Success ||
818 result == RegExpRunStatus::Success_NotFound);
819
820 return result;
821 } while (true);
822
823 MOZ_CRASH("Unreachable");
824 }
825
826 void RegExpShared::useAtomMatch(Handle<JSAtom*> pattern) {
827 MOZ_ASSERT(kind() == RegExpShared::Kind::Unparsed);
828 kind_ = RegExpShared::Kind::Atom;
829 patternAtom_ = pattern;
830 pairCount_ = 1;
831 }
832
833 void RegExpShared::useRegExpMatch(size_t pairCount) {
834 MOZ_ASSERT(kind() == RegExpShared::Kind::Unparsed);
835 kind_ = RegExpShared::Kind::RegExp;
836 pairCount_ = pairCount;
837 ticks_ = jit::JitOptions.regexpWarmUpThreshold;
838 }
839
840 /* static */
841 void RegExpShared::InitializeNamedCaptures(JSContext* cx, HandleRegExpShared re,
842 uint32_t numNamedCaptures,
843 uint32_t numDistinctNamedCaptures,
844 Handle<PlainObject*> templateObject,
845 uint32_t* captureIndices,
846 uint32_t* sliceIndices) {
847 MOZ_ASSERT(!re->groupsTemplate_);
848 MOZ_ASSERT(!re->namedCaptureIndices_);
849 MOZ_ASSERT(!re->namedCaptureSliceIndices_);
850
851 re->numNamedCaptures_ = numNamedCaptures;
852 re->numDistinctNamedCaptures_ = numDistinctNamedCaptures;
853 re->groupsTemplate_ = templateObject;
854 re->namedCaptureIndices_ = captureIndices;
855 re->namedCaptureSliceIndices_ = sliceIndices;
856
857 uint32_t arraySize = numNamedCaptures * sizeof(uint32_t);
858 js::AddCellMemory(re, arraySize, MemoryUse::RegExpSharedNamedCaptureData);
859
860 if (sliceIndices) {
861 arraySize = numDistinctNamedCaptures * sizeof(uint32_t);
862 js::AddCellMemory(re, arraySize,
863 MemoryUse::RegExpSharedNamedCaptureSliceData);
864 }
865 }
866
867 void RegExpShared::tierUpTick() {
868 MOZ_ASSERT(kind() == RegExpShared::Kind::RegExp);
869 if (ticks_ > 0) {
870 ticks_--;
871 }
872 }
873
874 bool RegExpShared::markedForTierUp() const {
875 if (!IsNativeRegExpEnabled()) {
876 return false;
877 }
878 if (kind() != RegExpShared::Kind::RegExp) {
879 return false;
880 }
881 return ticks_ == 0;
882 }
883
884 // When either unicode flag is set and if |index| points to a trail surrogate,
885 // step back to the corresponding lead surrogate.
886 static size_t StepBackToLeadSurrogate(const JSLinearString* input,
887 size_t index) {
888 // |index| must be a position within a two-byte string, otherwise it can't
889 // point to the trail surrogate of a surrogate pair.
890 if (index == 0 || index >= input->length() || input->hasLatin1Chars()) {
891 return index;
892 }
893
894 /*
895 * ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad
896 * 21.2.2.2 step 2.
897 * Let listIndex be the index into Input of the character that was obtained
898 * from element index of str.
899 *
900 * In the spec, pattern match is performed with decoded Unicode code points,
901 * but our implementation performs it with UTF-16 encoded strings. In step 2,
902 * we should decrement lastIndex (index) if it points to a trail surrogate
903 * that has a corresponding lead surrogate.
904 *
905 * var r = /\uD83D\uDC38/ug;
906 * r.lastIndex = 1;
907 * var str = "\uD83D\uDC38";
908 * var result = r.exec(str); // pattern match starts from index 0
909 * print(result.index); // prints 0
910 *
911 * Note: This doesn't match the current spec text and result in different
912 * values for `result.index` under certain conditions. However, the spec will
913 * change to match our implementation's behavior.
914 * See https://github.com/tc39/ecma262/issues/128.
915 */
916 JS::AutoCheckCannotGC nogc;
917 const auto* chars = input->twoByteChars(nogc);
918 if (unicode::IsTrailSurrogate(chars[index]) &&
919 unicode::IsLeadSurrogate(chars[index - 1])) {
920 index--;
921 }
922 return index;
923 }
924
925 static RegExpRunStatus ExecuteAtomImpl(RegExpShared* re,
926 const JSLinearString* input,
927 size_t start, MatchPairs* matches) {
928 MOZ_ASSERT(re->pairCount() == 1);
929 size_t length = input->length();
930 size_t searchLength = re->patternAtom()->length();
931
932 if (re->unicode() || re->unicodeSets()) {
933 start = StepBackToLeadSurrogate(input, start);
934 }
935
936 if (re->sticky()) {
937 // First part checks size_t overflow.
938 if (searchLength + start < searchLength || searchLength + start > length) {
939 return RegExpRunStatus::Success_NotFound;
940 }
941 if (!HasSubstringAt(input, re->patternAtom(), start)) {
942 return RegExpRunStatus::Success_NotFound;
943 }
944
945 (*matches)[0].start = start;
946 (*matches)[0].limit = start + searchLength;
947 matches->checkAgainst(input->length());
948 return RegExpRunStatus::Success;
949 }
950
951 int res = StringFindPattern(input, re->patternAtom(), start);
952 if (res == -1) {
953 return RegExpRunStatus::Success_NotFound;
954 }
955
956 (*matches)[0].start = res;
957 (*matches)[0].limit = res + searchLength;
958 matches->checkAgainst(input->length());
959 return RegExpRunStatus::Success;
960 }
961
962 RegExpRunStatus js::ExecuteRegExpAtomRaw(RegExpShared* re,
963 const JSLinearString* input,
964 size_t start, MatchPairs* matchPairs) {
965 AutoUnsafeCallWithABI unsafe;
966 return ExecuteAtomImpl(re, input, start, matchPairs);
967 }
968
969 /* static */
970 RegExpRunStatus RegExpShared::executeAtom(MutableHandleRegExpShared re,
971 Handle<JSLinearString*> input,
972 size_t start,
973 VectorMatchPairs* matches) {
974 return ExecuteAtomImpl(re, input, start, matches);
975 }
976
977 size_t RegExpShared::sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) {
978 size_t n = 0;
979
980 for (const auto& compilation : compilationArray) {
981 if (compilation.byteCode) {
982 n += mallocSizeOf(compilation.byteCode);
983 }
984 }
985
986 n += tables.sizeOfExcludingThis(mallocSizeOf);
987 for (size_t i = 0; i < tables.length(); i++) {
988 n += mallocSizeOf(tables[i].get());
989 }
990
991 return n;
992 }
993
994 /* RegExpRealm */
995
996 RegExpRealm::RegExpRealm() {
997 for (auto& shape : matchResultShapes_) {
998 shape = nullptr;
999 }
1000 }
1001
1002 SharedShape* RegExpRealm::createMatchResultShape(JSContext* cx,
1003 ResultShapeKind kind) {
1004 MOZ_ASSERT(!matchResultShapes_[kind]);
1005
1006 /* Create template array object */
1007 Rooted<ArrayObject*> templateObject(cx, NewDenseEmptyArray(cx));
1008 if (!templateObject) {
1009 return nullptr;
1010 }
1011
1012 if (kind == ResultShapeKind::Indices) {
1013 /* The |indices| array only has a |groups| property. */
1014 if (!NativeDefineDataProperty(cx, templateObject, cx->names().groups,
1015 UndefinedHandleValue, JSPROP_ENUMERATE)) {
1016 return nullptr;
1017 }
1018 MOZ_ASSERT(templateObject->getLastProperty().slot() == IndicesGroupsSlot);
1019
1020 matchResultShapes_[kind].set(templateObject->sharedShape());
1021 return matchResultShapes_[kind];
1022 }
1023
1024 /* Set dummy index property */
1025 if (!NativeDefineDataProperty(cx, templateObject, cx->names().index,
1026 UndefinedHandleValue, JSPROP_ENUMERATE)) {
1027 return nullptr;
1028 }
1029 MOZ_ASSERT(templateObject->getLastProperty().slot() ==
1030 MatchResultObjectIndexSlot);
1031
1032 /* Set dummy input property */
1033 if (!NativeDefineDataProperty(cx, templateObject, cx->names().input,
1034 UndefinedHandleValue, JSPROP_ENUMERATE)) {
1035 return nullptr;
1036 }
1037 MOZ_ASSERT(templateObject->getLastProperty().slot() ==
1038 MatchResultObjectInputSlot);
1039
1040 /* Set dummy groups property */
1041 if (!NativeDefineDataProperty(cx, templateObject, cx->names().groups,
1042 UndefinedHandleValue, JSPROP_ENUMERATE)) {
1043 return nullptr;
1044 }
1045 MOZ_ASSERT(templateObject->getLastProperty().slot() ==
1046 MatchResultObjectGroupsSlot);
1047
1048 if (kind == ResultShapeKind::WithIndices) {
1049 /* Set dummy indices property */
1050 if (!NativeDefineDataProperty(cx, templateObject, cx->names().indices,
1051 UndefinedHandleValue, JSPROP_ENUMERATE)) {
1052 return nullptr;
1053 }
1054 MOZ_ASSERT(templateObject->getLastProperty().slot() ==
1055 MatchResultObjectIndicesSlot);
1056 }
1057
1058 #ifdef DEBUG
1059 if (kind == ResultShapeKind::Normal) {
1060 MOZ_ASSERT(templateObject->numFixedSlots() == 0);
1061 MOZ_ASSERT(templateObject->numDynamicSlots() ==
1062 MatchResultObjectNumDynamicSlots);
1063 MOZ_ASSERT(templateObject->slotSpan() == MatchResultObjectSlotSpan);
1064 }
1065 #endif
1066
1067 matchResultShapes_[kind].set(templateObject->sharedShape());
1068
1069 return matchResultShapes_[kind];
1070 }
1071
1072 void RegExpRealm::trace(JSTracer* trc) {
1073 if (regExpStatics) {
1074 regExpStatics->trace(trc);
1075 }
1076
1077 for (auto& shape : matchResultShapes_) {
1078 TraceNullableEdge(trc, &shape, "RegExpRealm::matchResultShapes_");
1079 }
1080 }
1081
1082 RegExpShared* RegExpZone::get(JSContext* cx, Handle<JSAtom*> source,
1083 RegExpFlags flags) {
1084 DependentAddPtr<Set> p(cx, set_, Key(source, flags));
1085 if (p) {
1086 return *p;
1087 }
1088
1089 auto* shared = cx->newCell<RegExpShared>(source, flags);
1090 if (!shared) {
1091 return nullptr;
1092 }
1093
1094 if (!p.add(cx, set_, Key(source, flags), shared)) {
1095 return nullptr;
1096 }
1097
1098 return shared;
1099 }
1100
1101 size_t RegExpZone::sizeOfIncludingThis(
1102 mozilla::MallocSizeOf mallocSizeOf) const {
1103 return mallocSizeOf(this) + set_.sizeOfExcludingThis(mallocSizeOf);
1104 }
1105
1106 RegExpZone::RegExpZone(Zone* zone) : set_(zone, zone) {}
1107
1108 /* Functions */
1109
1110 JSObject* js::CloneRegExpObject(JSContext* cx, Handle<RegExpObject*> regex) {
1111 constexpr gc::AllocKind allocKind = RegExpObject::AllocKind;
1112 static_assert(gc::GetGCKindSlots(allocKind) == RegExpObject::RESERVED_SLOTS);
1113 MOZ_ASSERT(regex->asTenured().getAllocKind() == allocKind);
1114
1115 Rooted<SharedShape*> shape(cx, regex->sharedShape());
1116 Rooted<RegExpObject*> clone(cx, NativeObject::create<RegExpObject>(
1117 cx, allocKind, gc::Heap::Default, shape));
1118 if (!clone) {
1119 return nullptr;
1120 }
1121
1122 RegExpShared* shared = RegExpObject::getShared(cx, regex);
1123 if (!shared) {
1124 return nullptr;
1125 }
1126
1127 clone->initAndZeroLastIndex(shared->getSource(), shared->getFlags(), cx);
1128 clone->setShared(shared);
1129
1130 return clone;
1131 }
1132
1133 template <typename CharT>
1134 static bool ParseRegExpFlags(const CharT* chars, size_t length,
1135 RegExpFlags* flagsOut, char16_t* invalidFlag) {
1136 *flagsOut = RegExpFlag::NoFlags;
1137
1138 for (size_t i = 0; i < length; i++) {
1139 uint8_t flag;
1140 if (!JS::MaybeParseRegExpFlag(chars[i], &flag) || *flagsOut & flag) {
1141 *invalidFlag = chars[i];
1142 return false;
1143 }
1144
1145 // /u and /v flags are mutually exclusive.
1146 if (((*flagsOut & RegExpFlag::Unicode) &&
1147 (flag & RegExpFlag::UnicodeSets)) ||
1148 ((*flagsOut & RegExpFlag::UnicodeSets) &&
1149 (flag & RegExpFlag::Unicode))) {
1150 *invalidFlag = chars[i];
1151 return false;
1152 }
1153
1154 *flagsOut |= flag;
1155 }
1156
1157 return true;
1158 }
1159
1160 bool js::ParseRegExpFlags(JSContext* cx, JSString* flagStr,
1161 RegExpFlags* flagsOut) {
1162 JSLinearString* linear = flagStr->ensureLinear(cx);
1163 if (!linear) {
1164 return false;
1165 }
1166
1167 size_t len = linear->length();
1168
1169 bool ok;
1170 char16_t invalidFlag;
1171 if (linear->hasLatin1Chars()) {
1172 AutoCheckCannotGC nogc;
1173 ok = ::ParseRegExpFlags(linear->latin1Chars(nogc), len, flagsOut,
1174 &invalidFlag);
1175 } else {
1176 AutoCheckCannotGC nogc;
1177 ok = ::ParseRegExpFlags(linear->twoByteChars(nogc), len, flagsOut,
1178 &invalidFlag);
1179 }
1180
1181 if (!ok) {
1182 JS::TwoByteChars range(&invalidFlag, 1);
1183 UniqueChars utf8(JS::CharsToNewUTF8CharsZ(cx, range).c_str());
1184 if (!utf8) {
1185 return false;
1186 }
1187 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
1188 JSMSG_BAD_REGEXP_FLAG, utf8.get());
1189 return false;
1190 }
1191
1192 return true;
1193 }
1194
1195 JS::ubi::Node::Size JS::ubi::Concrete<RegExpShared>::size(
1196 mozilla::MallocSizeOf mallocSizeOf) const {
1197 return js::gc::Arena::thingSize(gc::AllocKind::REGEXP_SHARED) +
1198 get().sizeOfExcludingThis(mallocSizeOf);
1199 }
1200
1201 /*
1202 * Regular Expressions.
1203 */
1204 JS_PUBLIC_API JSObject* JS::NewRegExpObject(JSContext* cx, const char* bytes,
1205 size_t length, RegExpFlags flags) {
1206 AssertHeapIsIdle();
1207 CHECK_THREAD(cx);
1208
1209 UniqueTwoByteChars chars(InflateString(cx, bytes, length));
1210 if (!chars) {
1211 return nullptr;
1212 }
1213
1214 return RegExpObject::create(cx, chars.get(), length, flags, GenericObject);
1215 }
1216
1217 JS_PUBLIC_API JSObject* JS::NewUCRegExpObject(JSContext* cx,
1218 const char16_t* chars,
1219 size_t length,
1220 RegExpFlags flags) {
1221 AssertHeapIsIdle();
1222 CHECK_THREAD(cx);
1223
1224 return RegExpObject::create(cx, chars, length, flags, GenericObject);
1225 }
1226
1227 JS_PUBLIC_API bool JS::SetRegExpInput(JSContext* cx, HandleObject obj,
1228 HandleString input) {
1229 AssertHeapIsIdle();
1230 CHECK_THREAD(cx);
1231 cx->check(input);
1232
1233 Handle<GlobalObject*> global = obj.as<GlobalObject>();
1234 RegExpStatics* res = GlobalObject::getRegExpStatics(cx, global);
1235 if (!res) {
1236 return false;
1237 }
1238
1239 res->reset(input);
1240 return true;
1241 }
1242
1243 JS_PUBLIC_API bool JS::ClearRegExpStatics(JSContext* cx, HandleObject obj) {
1244 AssertHeapIsIdle();
1245 CHECK_THREAD(cx);
1246 MOZ_ASSERT(obj);
1247
1248 Handle<GlobalObject*> global = obj.as<GlobalObject>();
1249 RegExpStatics* res = GlobalObject::getRegExpStatics(cx, global);
1250 if (!res) {
1251 return false;
1252 }
1253
1254 res->clear();
1255 return true;
1256 }
1257
1258 JS_PUBLIC_API bool JS::ExecuteRegExp(JSContext* cx, HandleObject obj,
1259 HandleObject reobj, const char16_t* chars,
1260 size_t length, size_t* indexp, bool test,
1261 MutableHandleValue rval) {
1262 AssertHeapIsIdle();
1263 CHECK_THREAD(cx);
1264
1265 Handle<GlobalObject*> global = obj.as<GlobalObject>();
1266 RegExpStatics* res = GlobalObject::getRegExpStatics(cx, global);
1267 if (!res) {
1268 return false;
1269 }
1270
1271 Rooted<JSLinearString*> input(cx, NewStringCopyN<CanGC>(cx, chars, length));
1272 if (!input) {
1273 return false;
1274 }
1275
1276 return ExecuteRegExpLegacy(cx, res, reobj.as<RegExpObject>(), input, indexp,
1277 test, rval);
1278 }
1279
1280 JS_PUBLIC_API bool JS::ExecuteRegExpNoStatics(JSContext* cx, HandleObject obj,
1281 const char16_t* chars,
1282 size_t length, size_t* indexp,
1283 bool test,
1284 MutableHandleValue rval) {
1285 AssertHeapIsIdle();
1286 CHECK_THREAD(cx);
1287
1288 Rooted<JSLinearString*> input(cx, NewStringCopyN<CanGC>(cx, chars, length));
1289 if (!input) {
1290 return false;
1291 }
1292
1293 return ExecuteRegExpLegacy(cx, nullptr, obj.as<RegExpObject>(), input, indexp,
1294 test, rval);
1295 }
1296
1297 JS_PUBLIC_API bool JS::ObjectIsRegExp(JSContext* cx, HandleObject obj,
1298 bool* isRegExp) {
1299 cx->check(obj);
1300
1301 ESClass cls;
1302 if (!GetBuiltinClass(cx, obj, &cls)) {
1303 return false;
1304 }
1305
1306 *isRegExp = cls == ESClass::RegExp;
1307 return true;
1308 }
1309
1310 JS_PUBLIC_API RegExpFlags JS::GetRegExpFlags(JSContext* cx, HandleObject obj) {
1311 AssertHeapIsIdle();
1312 CHECK_THREAD(cx);
1313
1314 RegExpShared* shared = RegExpToShared(cx, obj);
1315 if (!shared) {
1316 return RegExpFlag::NoFlags;
1317 }
1318 return shared->getFlags();
1319 }
1320
1321 JS_PUBLIC_API JSString* JS::GetRegExpSource(JSContext* cx, HandleObject obj) {
1322 AssertHeapIsIdle();
1323 CHECK_THREAD(cx);
1324
1325 RegExpShared* shared = RegExpToShared(cx, obj);
1326 if (!shared) {
1327 return nullptr;
1328 }
1329 return shared->getSource();
1330 }
1331
1332 JS_PUBLIC_API bool JS::CheckRegExpSyntax(JSContext* cx, const char16_t* chars,
1333 size_t length, RegExpFlags flags,
1334 MutableHandleValue error) {
1335 AssertHeapIsIdle();
1336 CHECK_THREAD(cx);
1337
1338 AutoReportFrontendContext fc(cx);
1339 CompileOptions dummyOptions(cx);
1340 frontend::DummyTokenStream dummyTokenStream(&fc, dummyOptions);
1341
1342 LifoAllocScope allocScope(&cx->tempLifoAlloc());
1343
1344 mozilla::Range<const char16_t> source(chars, length);
1345 bool success = irregexp::CheckPatternSyntax(
1346 cx->tempLifoAlloc(), cx->stackLimitForCurrentPrincipal(),
1347 dummyTokenStream, source, flags);
1348 error.set(UndefinedValue());
1349 if (!success) {
1350 if (!fc.convertToRuntimeErrorAndClear()) {
1351 return false;
1352 }
1353 // We can fail because of OOM or over-recursion even if the syntax is valid.
1354 if (cx->isThrowingOutOfMemory() || cx->isThrowingOverRecursed()) {
1355 return false;
1356 }
1357
1358 if (!cx->getPendingException(error)) {
1359 return false;
1360 }
1361 cx->clearPendingException();
1362 }
1363 return true;
1364 }