Debian Codegraph @

js/src/builtin/RegExp.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 "builtin/RegExp.h"
8
9 #include "mozilla/Casting.h"
10 #include "mozilla/CheckedInt.h"
11 #include "mozilla/TextUtils.h"
12
13 #include <algorithm>
14
15 #include "jsapi.h"
16
17 #include "builtin/SelfHostingDefines.h"
18 #include "frontend/FrontendContext.h" // AutoReportFrontendContext
19 #include "frontend/TokenStream.h"
20 #include "irregexp/RegExpAPI.h"
21 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_NEWREGEXP_FLAGGED
22 #include "js/PropertySpec.h"
23 #include "js/RegExpFlags.h" // JS::RegExpFlag, JS::RegExpFlags
24 #include "util/StringBuilder.h"
25 #include "vm/Interpreter.h"
26 #include "vm/JSContext.h"
27 #include "vm/RegExpObject.h"
28 #include "vm/RegExpStatics.h"
29 #include "vm/SelfHosting.h"
30
31 #include "vm/EnvironmentObject-inl.h"
32 #include "vm/GeckoProfiler-inl.h"
33 #include "vm/JSObject-inl.h"
34 #include "vm/NativeObject-inl.h"
35 #include "vm/ObjectOperations-inl.h"
36 #include "vm/PlainObject-inl.h"
37
38 using namespace js;
39
40 using mozilla::AssertedCast;
41 using mozilla::CheckedInt;
42 using mozilla::IsAsciiDigit;
43
44 using JS::CompileOptions;
45 using JS::RegExpFlag;
46 using JS::RegExpFlags;
47
48 // Allocate an object for the |.groups| or |.indices.groups| property
49 // of a regexp match result.
50 static PlainObject* CreateGroupsObject(JSContext* cx,
51 Handle<PlainObject*> groupsTemplate) {
52 if (groupsTemplate->inDictionaryMode()) {
53 return NewPlainObjectWithProto(cx, nullptr);
54 }
55
56 // The groups template object is stored in RegExpShared, which is shared
57 // across compartments and realms. So watch out for the case when the template
58 // object's realm is different from the current realm.
59 if (cx->realm() != groupsTemplate->realm()) {
60 return PlainObject::createWithTemplateFromDifferentRealm(cx,
61 groupsTemplate);
62 }
63
64 return PlainObject::createWithTemplate(cx, groupsTemplate);
65 }
66
67 static inline void getValueAndIndex(HandleRegExpShared re, uint32_t i,
68 Handle<ArrayObject*> arr,
69 MutableHandleValue val,
70 uint32_t& valueIndex) {
71 if (re->numNamedCaptures() == re->numDistinctNamedCaptures()) {
72 valueIndex = re->getNamedCaptureIndex(i);
73 val.set(arr->getDenseElement(valueIndex));
74 } else {
75 mozilla::Span<uint32_t> indicesSlice = re->getNamedCaptureIndices(i);
76 MOZ_ASSERT(!indicesSlice.IsEmpty());
77 valueIndex = indicesSlice[0];
78 for (uint32_t index : indicesSlice) {
79 val.set(arr->getDenseElement(index));
80 if (!val.isUndefined()) {
81 valueIndex = index;
82 break;
83 }
84 }
85 }
86 }
87
88 /*
89 * Implements RegExpBuiltinExec: Steps 18-35
90 * https://tc39.es/ecma262/#sec-regexpbuiltinexec
91 */
92 bool js::CreateRegExpMatchResult(JSContext* cx, HandleRegExpShared re,
93 HandleString input, const MatchPairs& matches,
94 MutableHandleValue rval) {
95 MOZ_ASSERT(re);
96 MOZ_ASSERT(input);
97
98 /*
99 * Create the (slow) result array for a match.
100 *
101 * Array contents:
102 * 0: matched string
103 * 1..pairCount-1: paren matches
104 * input: input string
105 * index: start index for the match
106 * groups: named capture groups for the match
107 * indices: capture indices for the match, if required
108 */
109
110 bool hasIndices = re->hasIndices();
111
112 // Get the shape for the output object.
113 RegExpRealm::ResultShapeKind kind =
114 hasIndices ? RegExpRealm::ResultShapeKind::WithIndices
115 : RegExpRealm::ResultShapeKind::Normal;
116 Rooted<SharedShape*> shape(
117 cx, cx->global()->regExpRealm().getOrCreateMatchResultShape(cx, kind));
118 if (!shape) {
119 return false;
120 }
121
122 // Steps 18-19
123 size_t numPairs = matches.length();
124 MOZ_ASSERT(numPairs > 0);
125
126 // Steps 20-21: Allocate the match result object.
127 Rooted<ArrayObject*> arr(
128 cx, NewDenseFullyAllocatedArrayWithShape(cx, numPairs, shape));
129 if (!arr) {
130 return false;
131 }
132
133 // Steps 28-29 and 33 a-d: Initialize the elements of the match result.
134 // Store a Value for each match pair.
135 for (size_t i = 0; i < numPairs; i++) {
136 const MatchPair& pair = matches[i];
137
138 if (pair.isUndefined()) {
139 MOZ_ASSERT(i != 0); // Since we had a match, first pair must be present.
140 arr->setDenseInitializedLength(i + 1);
141 arr->initDenseElement(i, UndefinedValue());
142 } else {
143 JSLinearString* str =
144 NewDependentString(cx, input, pair.start, pair.length());
145 if (!str) {
146 return false;
147 }
148 arr->setDenseInitializedLength(i + 1);
149 arr->initDenseElement(i, StringValue(str));
150 }
151 }
152
153 // Step 34a (reordered): Allocate and initialize the indices object if needed.
154 // This is an inlined implementation of MakeIndicesArray:
155 // https://tc39.es/ecma262/#sec-makeindicesarray
156 Rooted<ArrayObject*> indices(cx);
157 Rooted<PlainObject*> indicesGroups(cx);
158 if (hasIndices) {
159 // MakeIndicesArray: step 8
160 Rooted<SharedShape*> indicesShape(
161 cx, cx->global()->regExpRealm().getOrCreateMatchResultShape(
162 cx, RegExpRealm::ResultShapeKind::Indices));
163 if (!indicesShape) {
164 return false;
165 }
166 indices = NewDenseFullyAllocatedArrayWithShape(cx, numPairs, indicesShape);
167 if (!indices) {
168 return false;
169 }
170
171 // MakeIndicesArray: steps 10-12
172 if (re->numNamedCaptures() > 0) {
173 Rooted<PlainObject*> groupsTemplate(cx, re->getGroupsTemplate());
174 indicesGroups = CreateGroupsObject(cx, groupsTemplate);
175 if (!indicesGroups) {
176 return false;
177 }
178 indices->initSlot(RegExpRealm::IndicesGroupsSlot,
179 ObjectValue(*indicesGroups));
180 }
181
182 // MakeIndicesArray: step 13 a-d. (Step 13.e is implemented below.)
183 for (size_t i = 0; i < numPairs; i++) {
184 const MatchPair& pair = matches[i];
185
186 if (pair.isUndefined()) {
187 // Since we had a match, first pair must be present.
188 MOZ_ASSERT(i != 0);
189 indices->setDenseInitializedLength(i + 1);
190 indices->initDenseElement(i, UndefinedValue());
191 } else {
192 Rooted<ArrayObject*> indexPair(cx, NewDenseFullyAllocatedArray(cx, 2));
193 if (!indexPair) {
194 return false;
195 }
196 indexPair->setDenseInitializedLength(2);
197 indexPair->initDenseElement(0, Int32Value(pair.start));
198 indexPair->initDenseElement(1, Int32Value(pair.limit));
199
200 indices->setDenseInitializedLength(i + 1);
201 indices->initDenseElement(i, ObjectValue(*indexPair));
202 }
203 }
204 }
205
206 // Steps 30-31 (reordered): Allocate the groups object (if needed).
207 Rooted<PlainObject*> groups(cx);
208 bool groupsInDictionaryMode = false;
209 if (re->numNamedCaptures() > 0) {
210 Rooted<PlainObject*> groupsTemplate(cx, re->getGroupsTemplate());
211 groupsInDictionaryMode = groupsTemplate->inDictionaryMode();
212 groups = CreateGroupsObject(cx, groupsTemplate);
213 if (!groups) {
214 return false;
215 }
216 }
217
218 // Step 33 e-f: Initialize the properties of |groups| and |indices.groups|.
219 // The groups template object stores the names of the named captures
220 // in the the order in which they are defined. The named capture
221 // indices vector stores the corresponding capture indices. In
222 // dictionary mode, we have to define the properties explicitly. If
223 // we are not in dictionary mode, we simply fill in the slots with
224 // the correct values.
225 if (groupsInDictionaryMode) {
226 RootedIdVector keys(cx);
227 Rooted<PlainObject*> groupsTemplate(cx, re->getGroupsTemplate());
228 if (!GetPropertyKeys(cx, groupsTemplate, 0, &keys)) {
229 return false;
230 }
231 MOZ_ASSERT(keys.length() == re->numDistinctNamedCaptures());
232 RootedId key(cx);
233 RootedValue val(cx);
234 uint32_t valueIndex;
235 for (uint32_t i = 0; i < keys.length(); i++) {
236 key = keys[i];
237 getValueAndIndex(re, i, arr, &val, valueIndex);
238 if (!NativeDefineDataProperty(cx, groups, key, val, JSPROP_ENUMERATE)) {
239 return false;
240 }
241
242 // MakeIndicesArray: Step 13.e (reordered)
243 if (hasIndices) {
244 val = indices->getDenseElement(valueIndex);
245 if (!NativeDefineDataProperty(cx, indicesGroups, key, val,
246 JSPROP_ENUMERATE)) {
247 return false;
248 }
249 }
250 }
251 } else {
252 RootedValue val(cx);
253 uint32_t valueIndex;
254
255 for (uint32_t i = 0; i < re->numDistinctNamedCaptures(); i++) {
256 getValueAndIndex(re, i, arr, &val, valueIndex);
257 groups->initSlot(i, val);
258
259 // MakeIndicesArray: Step 13.e (reordered)
260 if (hasIndices) {
261 indicesGroups->initSlot(i, indices->getDenseElement(valueIndex));
262 }
263 }
264 }
265
266 // Step 22 (reordered).
267 // Set the |index| property.
268 arr->initSlot(RegExpRealm::MatchResultObjectIndexSlot,
269 Int32Value(matches[0].start));
270
271 // Step 23 (reordered).
272 // Set the |input| property.
273 arr->initSlot(RegExpRealm::MatchResultObjectInputSlot, StringValue(input));
274
275 // Step 32 (reordered)
276 // Set the |groups| property.
277 if (groups) {
278 arr->initSlot(RegExpRealm::MatchResultObjectGroupsSlot,
279 ObjectValue(*groups));
280 }
281
282 // Step 34b
283 // Set the |indices| property.
284 if (re->hasIndices()) {
285 arr->initSlot(RegExpRealm::MatchResultObjectIndicesSlot,
286 ObjectValue(*indices));
287 }
288
289 #ifdef DEBUG
290 RootedValue test(cx);
291 RootedId id(cx, NameToId(cx->names().index));
292 if (!NativeGetProperty(cx, arr, id, &test)) {
293 return false;
294 }
295 MOZ_ASSERT(test == arr->getSlot(RegExpRealm::MatchResultObjectIndexSlot));
296 id = NameToId(cx->names().input);
297 if (!NativeGetProperty(cx, arr, id, &test)) {
298 return false;
299 }
300 MOZ_ASSERT(test == arr->getSlot(RegExpRealm::MatchResultObjectInputSlot));
301 #endif
302
303 // Step 35.
304 rval.setObject(*arr);
305 return true;
306 }
307
308 static int32_t CreateRegExpSearchResult(JSContext* cx,
309 const MatchPairs& matches) {
310 MOZ_ASSERT(matches[0].start >= 0);
311 MOZ_ASSERT(matches[0].limit >= 0);
312
313 MOZ_ASSERT(cx->regExpSearcherLastLimit == RegExpSearcherLastLimitSentinel);
314
315 #ifdef DEBUG
316 static_assert(JSString::MAX_LENGTH < RegExpSearcherLastLimitSentinel);
317 MOZ_ASSERT(uint32_t(matches[0].limit) < RegExpSearcherLastLimitSentinel);
318 #endif
319
320 cx->regExpSearcherLastLimit = matches[0].limit;
321 return matches[0].start;
322 }
323
324 /*
325 * ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2
326 * steps 3, 9-14, except 12.a.i, 12.c.i.1.
327 */
328 static RegExpRunStatus ExecuteRegExpImpl(JSContext* cx, RegExpStatics* res,
329 MutableHandleRegExpShared re,
330 Handle<JSLinearString*> input,
331 size_t searchIndex,
332 VectorMatchPairs* matches) {
333 RegExpRunStatus status =
334 RegExpShared::execute(cx, re, input, searchIndex, matches);
335
336 /* Out of spec: Update RegExpStatics. */
337 if (status == RegExpRunStatus::Success && res) {
338 if (!res->updateFromMatchPairs(cx, input, *matches)) {
339 return RegExpRunStatus::Error;
340 }
341 }
342 return status;
343 }
344
345 /* Legacy ExecuteRegExp behavior is baked into the JSAPI. */
346 bool js::ExecuteRegExpLegacy(JSContext* cx, RegExpStatics* res,
347 Handle<RegExpObject*> reobj,
348 Handle<JSLinearString*> input, size_t* lastIndex,
349 bool test, MutableHandleValue rval) {
350 cx->check(reobj, input);
351
352 RootedRegExpShared shared(cx, RegExpObject::getShared(cx, reobj));
353 if (!shared) {
354 return false;
355 }
356
357 VectorMatchPairs matches;
358
359 RegExpRunStatus status =
360 ExecuteRegExpImpl(cx, res, &shared, input, *lastIndex, &matches);
361 if (status == RegExpRunStatus::Error) {
362 return false;
363 }
364
365 if (status == RegExpRunStatus::Success_NotFound) {
366 /* ExecuteRegExp() previously returned an array or null. */
367 rval.setNull();
368 return true;
369 }
370
371 *lastIndex = matches[0].limit;
372
373 if (test) {
374 /* Forbid an array, as an optimization. */
375 rval.setBoolean(true);
376 return true;
377 }
378
379 return CreateRegExpMatchResult(cx, shared, input, matches, rval);
380 }
381
382 static bool CheckPatternSyntaxSlow(JSContext* cx, Handle<JSAtom*> pattern,
383 RegExpFlags flags) {
384 LifoAllocScope allocScope(&cx->tempLifoAlloc());
385 AutoReportFrontendContext fc(cx);
386 CompileOptions options(cx);
387 frontend::DummyTokenStream dummyTokenStream(&fc, options);
388 return irregexp::CheckPatternSyntax(cx, cx->stackLimitForCurrentPrincipal(),
389 dummyTokenStream, pattern, flags);
390 }
391
392 static RegExpShared* CheckPatternSyntax(JSContext* cx, Handle<JSAtom*> pattern,
393 RegExpFlags flags) {
394 // If we already have a RegExpShared for this pattern/flags, we can
395 // avoid the much slower CheckPatternSyntaxSlow call.
396
397 RootedRegExpShared shared(cx, cx->zone()->regExps().maybeGet(pattern, flags));
398 if (shared) {
399 #ifdef DEBUG
400 // Assert the pattern is valid.
401 if (!CheckPatternSyntaxSlow(cx, pattern, flags)) {
402 MOZ_ASSERT(cx->isThrowingOutOfMemory() || cx->isThrowingOverRecursed());
403 return nullptr;
404 }
405 #endif
406 return shared;
407 }
408
409 if (!CheckPatternSyntaxSlow(cx, pattern, flags)) {
410 return nullptr;
411 }
412
413 // Allocate and return a new RegExpShared so we will hit the fast path
414 // next time.
415 return cx->zone()->regExps().get(cx, pattern, flags);
416 }
417
418 /*
419 * ES 2016 draft Mar 25, 2016 21.2.3.2.2.
420 *
421 * Steps 14-15 set |obj|'s "lastIndex" property to zero. Some of
422 * RegExpInitialize's callers have a fresh RegExp not yet exposed to script:
423 * in these cases zeroing "lastIndex" is infallible. But others have a RegExp
424 * whose "lastIndex" property might have been made non-writable: here, zeroing
425 * "lastIndex" can fail. We efficiently solve this problem by completely
426 * removing "lastIndex" zeroing from the provided function.
427 *
428 * CALLERS MUST HANDLE "lastIndex" ZEROING THEMSELVES!
429 *
430 * Because this function only ever returns a user-provided |obj| in the spec,
431 * we omit it and just return the usual success/failure.
432 */
433 static bool RegExpInitializeIgnoringLastIndex(JSContext* cx,
434 Handle<RegExpObject*> obj,
435 HandleValue patternValue,
436 HandleValue flagsValue) {
437 Rooted<JSAtom*> pattern(cx);
438 if (patternValue.isUndefined()) {
439 /* Step 1. */
440 pattern = cx->names().empty_;
441 } else {
442 /* Step 2. */
443 pattern = ToAtom<CanGC>(cx, patternValue);
444 if (!pattern) {
445 return false;
446 }
447 }
448
449 /* Step 3. */
450 RegExpFlags flags = RegExpFlag::NoFlags;
451 if (!flagsValue.isUndefined()) {
452 /* Step 4. */
453 RootedString flagStr(cx, ToString<CanGC>(cx, flagsValue));
454 if (!flagStr) {
455 return false;
456 }
457
458 /* Step 5. */
459 if (!ParseRegExpFlags(cx, flagStr, &flags)) {
460 return false;
461 }
462 }
463
464 /* Steps 7-8. */
465 RegExpShared* shared = CheckPatternSyntax(cx, pattern, flags);
466 if (!shared) {
467 return false;
468 }
469
470 /* Steps 9-12. */
471 obj->initIgnoringLastIndex(pattern, flags);
472
473 obj->setShared(shared);
474
475 return true;
476 }
477
478 /* ES 2016 draft Mar 25, 2016 21.2.3.2.3. */
479 bool js::RegExpCreate(JSContext* cx, HandleValue patternValue,
480 HandleValue flagsValue, MutableHandleValue rval) {
481 /* Step 1. */
482 Rooted<RegExpObject*> regexp(cx, RegExpAlloc(cx, GenericObject));
483 if (!regexp) {
484 return false;
485 }
486
487 /* Step 2. */
488 if (!RegExpInitializeIgnoringLastIndex(cx, regexp, patternValue,
489 flagsValue)) {
490 return false;
491 }
492 regexp->zeroLastIndex(cx);
493
494 rval.setObject(*regexp);
495 return true;
496 }
497
498 MOZ_ALWAYS_INLINE bool IsRegExpObject(HandleValue v) {
499 return v.isObject() && v.toObject().is<RegExpObject>();
500 }
501
502 /* ES6 draft rc3 7.2.8. */
503 bool js::IsRegExp(JSContext* cx, HandleValue value, bool* result) {
504 /* Step 1. */
505 if (!value.isObject()) {
506 *result = false;
507 return true;
508 }
509 RootedObject obj(cx, &value.toObject());
510
511 /* Steps 2-3. */
512 RootedValue isRegExp(cx);
513 RootedId matchId(cx, PropertyKey::Symbol(cx->wellKnownSymbols().match));
514 if (!GetProperty(cx, obj, obj, matchId, &isRegExp)) {
515 return false;
516 }
517
518 /* Step 4. */
519 if (!isRegExp.isUndefined()) {
520 *result = ToBoolean(isRegExp);
521 return true;
522 }
523
524 /* Steps 5-6. */
525 ESClass cls;
526 if (!GetClassOfValue(cx, value, &cls)) {
527 return false;
528 }
529
530 *result = cls == ESClass::RegExp;
531 return true;
532 }
533
534 // The "lastIndex" property is non-configurable, but it can be made
535 // non-writable. If CalledFromJit is true, we have emitted guards to ensure it's
536 // writable.
537 template <bool CalledFromJit = false>
538 static bool SetLastIndex(JSContext* cx, Handle<RegExpObject*> regexp,
539 int32_t lastIndex) {
540 MOZ_ASSERT(lastIndex >= 0);
541
542 if (CalledFromJit || MOZ_LIKELY(RegExpObject::isInitialShape(regexp)) ||
543 regexp->lookupPure(cx->names().lastIndex)->writable()) {
544 regexp->setLastIndex(cx, lastIndex);
545 return true;
546 }
547
548 Rooted<Value> val(cx, Int32Value(lastIndex));
549 return SetProperty(cx, regexp, cx->names().lastIndex, val);
550 }
551
552 /* ES6 B.2.5.1. */
553 MOZ_ALWAYS_INLINE bool regexp_compile_impl(JSContext* cx,
554 const CallArgs& args) {
555 MOZ_ASSERT(IsRegExpObject(args.thisv()));
556
557 Rooted<RegExpObject*> regexp(cx, &args.thisv().toObject().as<RegExpObject>());
558
559 // Step 3.
560 RootedValue patternValue(cx, args.get(0));
561 ESClass cls;
562 if (!GetClassOfValue(cx, patternValue, &cls)) {
563 return false;
564 }
565 if (cls == ESClass::RegExp) {
566 // Step 3a.
567 if (args.hasDefined(1)) {
568 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
569 JSMSG_NEWREGEXP_FLAGGED);
570 return false;
571 }
572
573 // Beware! |patternObj| might be a proxy into another compartment, so
574 // don't assume |patternObj.is<RegExpObject>()|. For the same reason,
575 // don't reuse the RegExpShared below.
576 RootedObject patternObj(cx, &patternValue.toObject());
577
578 Rooted<JSAtom*> sourceAtom(cx);
579 RegExpFlags flags = RegExpFlag::NoFlags;
580 {
581 // Step 3b.
582 RegExpShared* shared = RegExpToShared(cx, patternObj);
583 if (!shared) {
584 return false;
585 }
586
587 sourceAtom = shared->getSource();
588 flags = shared->getFlags();
589 }
590
591 // Step 5, minus lastIndex zeroing.
592 regexp->initIgnoringLastIndex(sourceAtom, flags);
593 } else {
594 // Step 4.
595 RootedValue P(cx, patternValue);
596 RootedValue F(cx, args.get(1));
597
598 // Step 5, minus lastIndex zeroing.
599 if (!RegExpInitializeIgnoringLastIndex(cx, regexp, P, F)) {
600 return false;
601 }
602 }
603
604 // The final niggling bit of step 5.
605 //
606 // |regexp| is user-exposed, so its "lastIndex" property might be
607 // non-writable.
608 if (!SetLastIndex(cx, regexp, 0)) {
609 return false;
610 }
611
612 args.rval().setObject(*regexp);
613 return true;
614 }
615
616 static bool regexp_compile(JSContext* cx, unsigned argc, Value* vp) {
617 CallArgs args = CallArgsFromVp(argc, vp);
618
619 /* Steps 1-2. */
620 return CallNonGenericMethod<IsRegExpObject, regexp_compile_impl>(cx, args);
621 }
622
623 /*
624 * ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.3.1.
625 */
626 bool js::regexp_construct(JSContext* cx, unsigned argc, Value* vp) {
627 AutoJSConstructorProfilerEntry pseudoFrame(cx, "RegExp");
628 CallArgs args = CallArgsFromVp(argc, vp);
629
630 // Steps 1.
631 bool patternIsRegExp;
632 if (!IsRegExp(cx, args.get(0), &patternIsRegExp)) {
633 return false;
634 }
635
636 // We can delay step 3 and step 4a until later, during
637 // GetPrototypeFromBuiltinConstructor calls. Accessing the new.target
638 // and the callee from the stack is unobservable.
639 if (!args.isConstructing()) {
640 // Step 3.b.
641 if (patternIsRegExp && !args.hasDefined(1)) {
642 RootedObject patternObj(cx, &args[0].toObject());
643
644 // Step 3.b.i.
645 RootedValue patternConstructor(cx);
646 if (!GetProperty(cx, patternObj, patternObj, cx->names().constructor,
647 &patternConstructor)) {
648 return false;
649 }
650
651 // Step 3.b.ii.
652 if (patternConstructor.isObject() &&
653 patternConstructor.toObject() == args.callee()) {
654 args.rval().set(args[0]);
655 return true;
656 }
657 }
658 }
659
660 RootedValue patternValue(cx, args.get(0));
661
662 // Step 4.
663 ESClass cls;
664 if (!GetClassOfValue(cx, patternValue, &cls)) {
665 return false;
666 }
667 if (cls == ESClass::RegExp) {
668 // Beware! |patternObj| might be a proxy into another compartment, so
669 // don't assume |patternObj.is<RegExpObject>()|.
670 RootedObject patternObj(cx, &patternValue.toObject());
671
672 Rooted<JSAtom*> sourceAtom(cx);
673 RegExpFlags flags;
674 RootedRegExpShared shared(cx);
675 {
676 // Step 4.a.
677 shared = RegExpToShared(cx, patternObj);
678 if (!shared) {
679 return false;
680 }
681 sourceAtom = shared->getSource();
682
683 // Step 4.b.
684 // Get original flags in all cases, to compare with passed flags.
685 flags = shared->getFlags();
686
687 // If the RegExpShared is in another Zone, don't reuse it.
688 if (cx->zone() != shared->zone()) {
689 shared = nullptr;
690 }
691 }
692
693 // Step 7.
694 RootedObject proto(cx);
695 if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_RegExp, &proto)) {
696 return false;
697 }
698
699 Rooted<RegExpObject*> regexp(cx, RegExpAlloc(cx, GenericObject, proto));
700 if (!regexp) {
701 return false;
702 }
703
704 // Step 8.
705 if (args.hasDefined(1)) {
706 // Step 4.c / 21.2.3.2.2 RegExpInitialize step 4.
707 RegExpFlags flagsArg = RegExpFlag::NoFlags;
708 RootedString flagStr(cx, ToString<CanGC>(cx, args[1]));
709 if (!flagStr) {
710 return false;
711 }
712 if (!ParseRegExpFlags(cx, flagStr, &flagsArg)) {
713 return false;
714 }
715
716 // Don't reuse the RegExpShared if we have different flags.
717 if (flags != flagsArg) {
718 shared = nullptr;
719 }
720
721 if (!flags.unicode() && flagsArg.unicode()) {
722 // Have to check syntax again when adding 'u' flag.
723
724 // ES 2017 draft rev 9b49a888e9dfe2667008a01b2754c3662059ae56
725 // 21.2.3.2.2 step 7.
726 shared = CheckPatternSyntax(cx, sourceAtom, flagsArg);
727 if (!shared) {
728 return false;
729 }
730 }
731 flags = flagsArg;
732 }
733
734 regexp->initAndZeroLastIndex(sourceAtom, flags, cx);
735
736 if (shared) {
737 regexp->setShared(shared);
738 }
739
740 args.rval().setObject(*regexp);
741 return true;
742 }
743
744 RootedValue P(cx);
745 RootedValue F(cx);
746
747 // Step 5.
748 if (patternIsRegExp) {
749 RootedObject patternObj(cx, &patternValue.toObject());
750
751 // Step 5.a.
752 if (!GetProperty(cx, patternObj, patternObj, cx->names().source, &P)) {
753 return false;
754 }
755
756 // Step 5.b.
757 F = args.get(1);
758 if (F.isUndefined()) {
759 if (!GetProperty(cx, patternObj, patternObj, cx->names().flags, &F)) {
760 return false;
761 }
762 }
763 } else {
764 // Steps 6.a-b.
765 P = patternValue;
766 F = args.get(1);
767 }
768
769 // Step 7.
770 RootedObject proto(cx);
771 if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_RegExp, &proto)) {
772 return false;
773 }
774
775 Rooted<RegExpObject*> regexp(cx, RegExpAlloc(cx, GenericObject, proto));
776 if (!regexp) {
777 return false;
778 }
779
780 // Step 8.
781 if (!RegExpInitializeIgnoringLastIndex(cx, regexp, P, F)) {
782 return false;
783 }
784 regexp->zeroLastIndex(cx);
785
786 args.rval().setObject(*regexp);
787 return true;
788 }
789
790 /*
791 * ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.3.1
792 * steps 4, 7-8.
793 */
794 bool js::regexp_construct_raw_flags(JSContext* cx, unsigned argc, Value* vp) {
795 CallArgs args = CallArgsFromVp(argc, vp);
796 MOZ_ASSERT(args.length() == 2);
797 MOZ_ASSERT(!args.isConstructing());
798
799 // Step 4.a.
800 Rooted<JSAtom*> sourceAtom(cx, AtomizeString(cx, args[0].toString()));
801 if (!sourceAtom) {
802 return false;
803 }
804
805 // Step 4.c.
806 RegExpFlags flags = AssertedCast<uint8_t>(int32_t(args[1].toNumber()));
807
808 // Step 7.
809 RegExpObject* regexp = RegExpAlloc(cx, GenericObject);
810 if (!regexp) {
811 return false;
812 }
813
814 // Step 8.
815 regexp->initAndZeroLastIndex(sourceAtom, flags, cx);
816 args.rval().setObject(*regexp);
817 return true;
818 }
819
820 // This is a specialized implementation of "UnwrapAndTypeCheckThis" for RegExp
821 // getters that need to return a special value for same-realm
822 // %RegExp.prototype%.
823 template <typename Fn>
824 static bool RegExpGetter(JSContext* cx, CallArgs& args, const char* methodName,
825 Fn&& fn,
826 HandleValue fallbackValue = UndefinedHandleValue) {
827 JSObject* obj = nullptr;
828 if (args.thisv().isObject()) {
829 obj = &args.thisv().toObject();
830 if (IsWrapper(obj)) {
831 obj = CheckedUnwrapStatic(obj);
832 if (!obj) {
833 ReportAccessDenied(cx);
834 return false;
835 }
836 }
837 }
838
839 if (obj) {
840 // Step 4ff
841 if (obj->is<RegExpObject>()) {
842 return fn(&obj->as<RegExpObject>());
843 }
844
845 // Step 3.a. "If SameValue(R, %RegExp.prototype%) is true, return
846 // undefined."
847 // Or `return "(?:)"` for get RegExp.prototype.source.
848 if (obj == cx->global()->maybeGetRegExpPrototype()) {
849 args.rval().set(fallbackValue);
850 return true;
851 }
852
853 // fall-through
854 }
855
856 // Step 2. and Step 3.b.
857 JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
858 JSMSG_INCOMPATIBLE_REGEXP_GETTER, methodName,
859 InformalValueTypeName(args.thisv()));
860 return false;
861 }
862
863 bool js::regexp_hasIndices(JSContext* cx, unsigned argc, JS::Value* vp) {
864 CallArgs args = CallArgsFromVp(argc, vp);
865 return RegExpGetter(cx, args, "hasIndices", [args](RegExpObject* unwrapped) {
866 args.rval().setBoolean(unwrapped->hasIndices());
867 return true;
868 });
869 }
870
871 // ES2021 draft rev 0b3a808af87a9123890767152a26599cc8fde161
872 // 21.2.5.5 get RegExp.prototype.global
873 bool js::regexp_global(JSContext* cx, unsigned argc, JS::Value* vp) {
874 CallArgs args = CallArgsFromVp(argc, vp);
875 return RegExpGetter(cx, args, "global", [args](RegExpObject* unwrapped) {
876 args.rval().setBoolean(unwrapped->global());
877 return true;
878 });
879 }
880
881 // ES2021 draft rev 0b3a808af87a9123890767152a26599cc8fde161
882 // 21.2.5.6 get RegExp.prototype.ignoreCase
883 bool js::regexp_ignoreCase(JSContext* cx, unsigned argc, JS::Value* vp) {
884 CallArgs args = CallArgsFromVp(argc, vp);
885 return RegExpGetter(cx, args, "ignoreCase", [args](RegExpObject* unwrapped) {
886 args.rval().setBoolean(unwrapped->ignoreCase());
887 return true;
888 });
889 }
890
891 // ES2021 draft rev 0b3a808af87a9123890767152a26599cc8fde161
892 // 21.2.5.9 get RegExp.prototype.multiline
893 bool js::regexp_multiline(JSContext* cx, unsigned argc, JS::Value* vp) {
894 CallArgs args = CallArgsFromVp(argc, vp);
895 return RegExpGetter(cx, args, "multiline", [args](RegExpObject* unwrapped) {
896 args.rval().setBoolean(unwrapped->multiline());
897 return true;
898 });
899 }
900
901 // ES2021 draft rev 0b3a808af87a9123890767152a26599cc8fde161
902 // 21.2.5.12 get RegExp.prototype.source
903 static bool regexp_source(JSContext* cx, unsigned argc, JS::Value* vp) {
904 CallArgs args = CallArgsFromVp(argc, vp);
905 // Step 3.a. Return "(?:)" for %RegExp.prototype%.
906 RootedValue fallback(cx, StringValue(cx->names().emptyRegExp_));
907 return RegExpGetter(
908 cx, args, "source",
909 [cx, args](RegExpObject* unwrapped) {
910 Rooted<JSAtom*> src(cx, unwrapped->getSource());
911 MOZ_ASSERT(src);
912 // Mark potentially cross-zone JSAtom.
913 if (cx->zone() != unwrapped->zone()) {
914 cx->markAtom(src);
915 }
916
917 // Step 7.
918 JSString* escaped = EscapeRegExpPattern(cx, src);
919 if (!escaped) {
920 return false;
921 }
922
923 args.rval().setString(escaped);
924 return true;
925 },
926 fallback);
927 }
928
929 // ES2021 draft rev 0b3a808af87a9123890767152a26599cc8fde161
930 // 21.2.5.3 get RegExp.prototype.dotAll
931 bool js::regexp_dotAll(JSContext* cx, unsigned argc, JS::Value* vp) {
932 CallArgs args = CallArgsFromVp(argc, vp);
933 return RegExpGetter(cx, args, "dotAll", [args](RegExpObject* unwrapped) {
934 args.rval().setBoolean(unwrapped->dotAll());
935 return true;
936 });
937 }
938
939 // ES2021 draft rev 0b3a808af87a9123890767152a26599cc8fde161
940 // 21.2.5.14 get RegExp.prototype.sticky
941 bool js::regexp_sticky(JSContext* cx, unsigned argc, JS::Value* vp) {
942 CallArgs args = CallArgsFromVp(argc, vp);
943 return RegExpGetter(cx, args, "sticky", [args](RegExpObject* unwrapped) {
944 args.rval().setBoolean(unwrapped->sticky());
945 return true;
946 });
947 }
948
949 // ES2021 draft rev 0b3a808af87a9123890767152a26599cc8fde161
950 // 21.2.5.17 get RegExp.prototype.unicode
951 bool js::regexp_unicode(JSContext* cx, unsigned argc, JS::Value* vp) {
952 CallArgs args = CallArgsFromVp(argc, vp);
953 return RegExpGetter(cx, args, "unicode", [args](RegExpObject* unwrapped) {
954 args.rval().setBoolean(unwrapped->unicode());
955 return true;
956 });
957 }
958
959 // https://arai-a.github.io/ecma262-compare/?pr=2418&id=sec-get-regexp.prototype.unicodesets
960 // 21.2.6.19 get RegExp.prototype.unicodeSets
961 bool js::regexp_unicodeSets(JSContext* cx, unsigned argc, JS::Value* vp) {
962 CallArgs args = CallArgsFromVp(argc, vp);
963 return RegExpGetter(cx, args, "unicodeSets", [args](RegExpObject* unwrapped) {
964 args.rval().setBoolean(unwrapped->unicodeSets());
965 return true;
966 });
967 }
968
969 const JSPropertySpec js::regexp_properties[] = {
970 JS_SELF_HOSTED_GET("flags", "$RegExpFlagsGetter", 0),
971 JS_PSG("hasIndices", regexp_hasIndices, 0),
972 JS_PSG("global", regexp_global, 0),
973 JS_PSG("ignoreCase", regexp_ignoreCase, 0),
974 JS_PSG("multiline", regexp_multiline, 0),
975 JS_PSG("dotAll", regexp_dotAll, 0),
976 JS_PSG("source", regexp_source, 0),
977 JS_PSG("sticky", regexp_sticky, 0),
978 JS_PSG("unicode", regexp_unicode, 0),
979 JS_PSG("unicodeSets", regexp_unicodeSets, 0),
980 JS_PS_END,
981 };
982
983 const JSFunctionSpec js::regexp_methods[] = {
984 JS_SELF_HOSTED_FN("toSource", "$RegExpToString", 0, 0),
985 JS_SELF_HOSTED_FN("toString", "$RegExpToString", 0, 0),
986 JS_FN("compile", regexp_compile, 2, 0),
987 JS_SELF_HOSTED_FN("exec", "RegExp_prototype_Exec", 1, 0),
988 JS_SELF_HOSTED_FN("test", "RegExpTest", 1, 0),
989 JS_SELF_HOSTED_SYM_FN(match, "RegExpMatch", 1, 0),
990 JS_SELF_HOSTED_SYM_FN(matchAll, "RegExpMatchAll", 1, 0),
991 JS_SELF_HOSTED_SYM_FN(replace, "RegExpReplace", 2, 0),
992 JS_SELF_HOSTED_SYM_FN(search, "RegExpSearch", 1, 0),
993 JS_SELF_HOSTED_SYM_FN(split, "RegExpSplit", 2, 0),
994 JS_FS_END,
995 };
996
997 static constexpr JS::Latin1Char SHOULD_HEX_ESCAPE = JSString::MAX_LATIN1_CHAR;
998
999 /**
1000 * Ascii escape map.
1001 *
1002 * 1. If a character is mapped to zero (0x00), then no escape sequence is used.
1003 * 2. Else,
1004 * a. If a character is mapped to SHOULD_HEX_ESCAPE, then hex-escape.
1005 * b. Else, escape with `\` followed by the mapped value.
1006 */
1007 static constexpr auto AsciiRegExpEscapeMap() {
1008 std::array<JS::Latin1Char, 128> result = {};
1009
1010 // SyntaxCharacter or U+002F (SOLIDUS)
1011 result['^'] = '^';
1012 result['$'] = '$';
1013 result['\\'] = '\\';
1014 result['.'] = '.';
1015 result['*'] = '*';
1016 result['+'] = '+';
1017 result['?'] = '?';
1018 result['('] = '(';
1019 result[')'] = ')';
1020 result['['] = '[';
1021 result[']'] = ']';
1022 result['{'] = '{';
1023 result['}'] = '}';
1024 result['|'] = '|';
1025 result['/'] = '/';
1026
1027 // ControlEscape Code Point Values
1028 result['\t'] = 't';
1029 result['\n'] = 'n';
1030 result['\v'] = 'v';
1031 result['\f'] = 'f';
1032 result['\r'] = 'r';
1033
1034 // Other punctuators ",-=<>#&!%:;@~'`" or 0x0022 (QUOTATION MARK)
1035 result[','] = SHOULD_HEX_ESCAPE;
1036 result['-'] = SHOULD_HEX_ESCAPE;
1037 result['='] = SHOULD_HEX_ESCAPE;
1038 result['<'] = SHOULD_HEX_ESCAPE;
1039 result['>'] = SHOULD_HEX_ESCAPE;
1040 result['#'] = SHOULD_HEX_ESCAPE;
1041 result['&'] = SHOULD_HEX_ESCAPE;
1042 result['!'] = SHOULD_HEX_ESCAPE;
1043 result['%'] = SHOULD_HEX_ESCAPE;
1044 result[':'] = SHOULD_HEX_ESCAPE;
1045 result[';'] = SHOULD_HEX_ESCAPE;
1046 result['@'] = SHOULD_HEX_ESCAPE;
1047 result['~'] = SHOULD_HEX_ESCAPE;
1048 result['\''] = SHOULD_HEX_ESCAPE;
1049 result['`'] = SHOULD_HEX_ESCAPE;
1050 result['"'] = SHOULD_HEX_ESCAPE;
1051
1052 // WhiteSpace or LineTerminator
1053 result[' '] = SHOULD_HEX_ESCAPE;
1054
1055 return result;
1056 }
1057
1058 /**
1059 * EncodeForRegExpEscape ( c )
1060 *
1061 * https://tc39.es/proposal-regex-escaping/#sec-encodeforregexpescape
1062 */
1063 template <typename CharT>
1064 [[nodiscard]] static bool EncodeForRegExpEscape(
1065 JSContext* cx, mozilla::Span<const CharT> chars, JSStringBuilder& sb) {
1066 MOZ_ASSERT(sb.empty());
1067
1068 const size_t length = chars.size();
1069 if (length == 0) {
1070 return true;
1071 }
1072
1073 static constexpr auto asciiEscapeMap = AsciiRegExpEscapeMap();
1074
1075 // Number of characters added when escaping.
1076 static constexpr size_t EscapeAddLength = 2 - 1;
1077 static constexpr size_t HexEscapeAddLength = 4 - 1;
1078 static constexpr size_t UnicodeEscapeAddLength = 6 - 1;
1079
1080 // Initial scan to determine if escape sequences are needed and to compute
1081 // the output length.
1082 mozilla::CheckedInt<size_t> outLength = length;
1083
1084 // Leading Ascii alpha-numeric character is hex-escaped.
1085 size_t scanStart = 0;
1086 if (mozilla::IsAsciiAlphanumeric(chars[0])) {
1087 outLength += HexEscapeAddLength;
1088 scanStart = 1;
1089 }
1090
1091 for (size_t i = scanStart; i < length; i++) {
1092 CharT ch = chars[i];
1093
1094 JS::Latin1Char escape = 0;
1095 if (mozilla::IsAscii(ch)) {
1096 escape = asciiEscapeMap[ch];
1097 } else {
1098 // Surrogate pair.
1099 if (unicode::IsLeadSurrogate(ch) && i + 1 < length &&
1100 unicode::IsTrailSurrogate(chars[i + 1])) {
1101 i += 1;
1102 continue;
1103 }
1104
1105 // WhiteSpace or LineTerminator or unmatched surrogate.
1106 if (unicode::IsSpace(ch) || unicode::IsSurrogate(ch)) {
1107 escape = SHOULD_HEX_ESCAPE;
1108 }
1109 }
1110 if (!escape) {
1111 continue;
1112 }
1113
1114 if (mozilla::IsAscii(escape)) {
1115 outLength += EscapeAddLength;
1116 } else if (ch <= JSString::MAX_LATIN1_CHAR) {
1117 outLength += HexEscapeAddLength;
1118 } else {
1119 outLength += UnicodeEscapeAddLength;
1120 }
1121 }
1122 if (!outLength.isValid()) {
1123 ReportAllocationOverflow(cx);
1124 return false;
1125 }
1126
1127 // Return if no escape sequences are needed.
1128 if (outLength.value() == length) {
1129 return true;
1130 }
1131 MOZ_ASSERT(outLength.value() > length);
1132
1133 // Inflating is fallible, so we have to convert to two-byte upfront.
1134 if constexpr (std::is_same_v<CharT, char16_t>) {
1135 if (!sb.ensureTwoByteChars()) {
1136 return false;
1137 }
1138 }
1139
1140 // Allocate memory for the output using the final length.
1141 if (!sb.reserve(outLength.value())) {
1142 return false;
1143 }
1144
1145 // NB: Lower case hex digits.
1146 static constexpr char HexDigits[] = "0123456789abcdef";
1147 static_assert(std::char_traits<char>::length(HexDigits) == 16);
1148
1149 // Append |ch| as an escaped character.
1150 auto appendEscape = [&](JS::Latin1Char ch) {
1151 MOZ_ASSERT(mozilla::IsAscii(ch));
1152
1153 sb.infallibleAppend('\\');
1154 sb.infallibleAppend(ch);
1155 };
1156
1157 // Append |ch| as a hex-escape sequence.
1158 auto appendHexEscape = [&](CharT ch) {
1159 MOZ_ASSERT(ch <= JSString::MAX_LATIN1_CHAR);
1160
1161 sb.infallibleAppend('\\');
1162 sb.infallibleAppend('x');
1163 sb.infallibleAppend(HexDigits[(ch >> 4) & 0xf]);
1164 sb.infallibleAppend(HexDigits[ch & 0xf]);
1165 };
1166
1167 // Append |ch| as a Unicode-escape sequence.
1168 auto appendUnicodeEscape = [&](char16_t ch) {
1169 MOZ_ASSERT(ch > JSString::MAX_LATIN1_CHAR);
1170
1171 sb.infallibleAppend('\\');
1172 sb.infallibleAppend('u');
1173 sb.infallibleAppend(HexDigits[(ch >> 12) & 0xf]);
1174 sb.infallibleAppend(HexDigits[(ch >> 8) & 0xf]);
1175 sb.infallibleAppend(HexDigits[(ch >> 4) & 0xf]);
1176 sb.infallibleAppend(HexDigits[ch & 0xf]);
1177 };
1178
1179 // Index after the last character which produced an escape sequence.
1180 size_t startUnescaped = 0;
1181
1182 // Append unescaped characters from |startUnescaped| (inclusive) to |end|
1183 // (exclusive).
1184 auto appendUnescaped = [&](size_t end) {
1185 MOZ_ASSERT(startUnescaped <= end && end <= length);
1186
1187 if (startUnescaped < end) {
1188 auto unescaped = chars.FromTo(startUnescaped, end);
1189 sb.infallibleAppend(unescaped.data(), unescaped.size());
1190 }
1191 startUnescaped = end + 1;
1192 };
1193
1194 // Leading Ascii alpha-numeric character is hex-escaped.
1195 size_t start = 0;
1196 if (mozilla::IsAsciiAlphanumeric(chars[0])) {
1197 appendHexEscape(chars[0]);
1198
1199 start = 1;
1200 startUnescaped = 1;
1201 }
1202
1203 for (size_t i = start; i < length; i++) {
1204 CharT ch = chars[i];
1205
1206 JS::Latin1Char escape = 0;
1207 if (mozilla::IsAscii(ch)) {
1208 escape = asciiEscapeMap[ch];
1209 } else {
1210 // Surrogate pair.
1211 if (unicode::IsLeadSurrogate(ch) && i + 1 < length &&
1212 unicode::IsTrailSurrogate(chars[i + 1])) {
1213 i += 1;
1214 continue;
1215 }
1216
1217 // WhiteSpace or LineTerminator or unmatched surrogate.
1218 if (unicode::IsSpace(ch) || unicode::IsSurrogate(ch)) {
1219 escape = SHOULD_HEX_ESCAPE;
1220 }
1221 }
1222 if (!escape) {
1223 continue;
1224 }
1225
1226 appendUnescaped(i);
1227
1228 if (mozilla::IsAscii(escape)) {
1229 appendEscape(escape);
1230 } else if (ch <= JSString::MAX_LATIN1_CHAR) {
1231 appendHexEscape(ch);
1232 } else {
1233 appendUnicodeEscape(ch);
1234 }
1235 }
1236
1237 if (startUnescaped) {
1238 appendUnescaped(length);
1239 }
1240
1241 MOZ_ASSERT(sb.length() == outLength.value(), "all characters were written");
1242 return true;
1243 }
1244
1245 [[nodiscard]] static bool EncodeForRegExpEscape(JSContext* cx,
1246 JSLinearString* string,
1247 JSStringBuilder& sb) {
1248 JS::AutoCheckCannotGC nogc;
1249 if (string->hasLatin1Chars()) {
1250 auto chars = mozilla::Span(string->latin1Range(nogc));
1251 return EncodeForRegExpEscape(cx, chars, sb);
1252 }
1253 auto chars = mozilla::Span(string->twoByteRange(nogc));
1254 return EncodeForRegExpEscape(cx, chars, sb);
1255 }
1256
1257 /**
1258 * RegExp.escape ( S )
1259 *
1260 * https://tc39.es/proposal-regex-escaping/
1261 */
1262 static bool regexp_escape(JSContext* cx, unsigned argc, Value* vp) {
1263 CallArgs args = CallArgsFromVp(argc, vp);
1264
1265 // Step 1.
1266 if (!args.get(0).isString()) {
1267 return ReportValueError(cx, JSMSG_UNEXPECTED_TYPE, JSDVG_SEARCH_STACK,
1268 args.get(0), nullptr, "not a string");
1269 }
1270
1271 Rooted<JSLinearString*> string(cx, args[0].toString()->ensureLinear(cx));
1272 if (!string) {
1273 return false;
1274 }
1275
1276 // Step 2-5.
1277 JSStringBuilder sb(cx);
1278 if (!EncodeForRegExpEscape(cx, string, sb)) {
1279 return false;
1280 }
1281
1282 // Return the input string if no escape sequences were added.
1283 if (sb.empty()) {
1284 args.rval().setString(string);
1285 return true;
1286 }
1287
1288 auto* result = sb.finishString();
1289 if (!result) {
1290 return false;
1291 }
1292
1293 args.rval().setString(result);
1294 return true;
1295 }
1296
1297 #define STATIC_PAREN_GETTER_CODE(parenNum) \
1298 if (!res->createParen(cx, parenNum, args.rval())) return false; \
1299 if (args.rval().isUndefined()) \
1300 args.rval().setString(cx->runtime()->emptyString); \
1301 return true
1302
1303 /*
1304 * RegExp static properties.
1305 *
1306 * RegExp class static properties and their Perl counterparts:
1307 *
1308 * RegExp.input $_
1309 * RegExp.lastMatch $&
1310 * RegExp.lastParen $+
1311 * RegExp.leftContext $`
1312 * RegExp.rightContext $'
1313 */
1314
1315 #define DEFINE_STATIC_GETTER(name, code) \
1316 static bool name(JSContext* cx, unsigned argc, Value* vp) { \
1317 CallArgs args = CallArgsFromVp(argc, vp); \
1318 RegExpStatics* res = GlobalObject::getRegExpStatics(cx, cx->global()); \
1319 if (!res) return false; \
1320 code; \
1321 }
1322
1323 DEFINE_STATIC_GETTER(static_input_getter,
1324 return res->createPendingInput(cx, args.rval()))
1325 DEFINE_STATIC_GETTER(static_lastMatch_getter,
1326 return res->createLastMatch(cx, args.rval()))
1327 DEFINE_STATIC_GETTER(static_lastParen_getter,
1328 return res->createLastParen(cx, args.rval()))
1329 DEFINE_STATIC_GETTER(static_leftContext_getter,
1330 return res->createLeftContext(cx, args.rval()))
1331 DEFINE_STATIC_GETTER(static_rightContext_getter,
1332 return res->createRightContext(cx, args.rval()))
1333
1334 DEFINE_STATIC_GETTER(static_paren1_getter, STATIC_PAREN_GETTER_CODE(1))
1335 DEFINE_STATIC_GETTER(static_paren2_getter, STATIC_PAREN_GETTER_CODE(2))
1336 DEFINE_STATIC_GETTER(static_paren3_getter, STATIC_PAREN_GETTER_CODE(3))
1337 DEFINE_STATIC_GETTER(static_paren4_getter, STATIC_PAREN_GETTER_CODE(4))
1338 DEFINE_STATIC_GETTER(static_paren5_getter, STATIC_PAREN_GETTER_CODE(5))
1339 DEFINE_STATIC_GETTER(static_paren6_getter, STATIC_PAREN_GETTER_CODE(6))
1340 DEFINE_STATIC_GETTER(static_paren7_getter, STATIC_PAREN_GETTER_CODE(7))
1341 DEFINE_STATIC_GETTER(static_paren8_getter, STATIC_PAREN_GETTER_CODE(8))
1342 DEFINE_STATIC_GETTER(static_paren9_getter, STATIC_PAREN_GETTER_CODE(9))
1343
1344 #define DEFINE_STATIC_SETTER(name, code) \
1345 static bool name(JSContext* cx, unsigned argc, Value* vp) { \
1346 RegExpStatics* res = GlobalObject::getRegExpStatics(cx, cx->global()); \
1347 if (!res) return false; \
1348 code; \
1349 return true; \
1350 }
1351
1352 static bool static_input_setter(JSContext* cx, unsigned argc, Value* vp) {
1353 CallArgs args = CallArgsFromVp(argc, vp);
1354 RegExpStatics* res = GlobalObject::getRegExpStatics(cx, cx->global());
1355 if (!res) {
1356 return false;
1357 }
1358
1359 RootedString str(cx, ToString<CanGC>(cx, args.get(0)));
1360 if (!str) {
1361 return false;
1362 }
1363
1364 res->setPendingInput(str);
1365 args.rval().setString(str);
1366 return true;
1367 }
1368
1369 const JSPropertySpec js::regexp_static_props[] = {
1370 JS_PSGS("input", static_input_getter, static_input_setter,
1371 JSPROP_PERMANENT | JSPROP_ENUMERATE),
1372 JS_PSG("lastMatch", static_lastMatch_getter,
1373 JSPROP_PERMANENT | JSPROP_ENUMERATE),
1374 JS_PSG("lastParen", static_lastParen_getter,
1375 JSPROP_PERMANENT | JSPROP_ENUMERATE),
1376 JS_PSG("leftContext", static_leftContext_getter,
1377 JSPROP_PERMANENT | JSPROP_ENUMERATE),
1378 JS_PSG("rightContext", static_rightContext_getter,
1379 JSPROP_PERMANENT | JSPROP_ENUMERATE),
1380 JS_PSG("$1", static_paren1_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
1381 JS_PSG("$2", static_paren2_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
1382 JS_PSG("$3", static_paren3_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
1383 JS_PSG("$4", static_paren4_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
1384 JS_PSG("$5", static_paren5_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
1385 JS_PSG("$6", static_paren6_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
1386 JS_PSG("$7", static_paren7_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
1387 JS_PSG("$8", static_paren8_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
1388 JS_PSG("$9", static_paren9_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
1389 JS_PSGS("$_", static_input_getter, static_input_setter, JSPROP_PERMANENT),
1390 JS_PSG("$&", static_lastMatch_getter, JSPROP_PERMANENT),
1391 JS_PSG("$+", static_lastParen_getter, JSPROP_PERMANENT),
1392 JS_PSG("$`", static_leftContext_getter, JSPROP_PERMANENT),
1393 JS_PSG("$'", static_rightContext_getter, JSPROP_PERMANENT),
1394 JS_SELF_HOSTED_SYM_GET(species, "$RegExpSpecies", 0),
1395 JS_PS_END,
1396 };
1397
1398 const JSFunctionSpec js::regexp_static_methods[] = {
1399 JS_FN("escape", regexp_escape, 1, 0),
1400 JS_FS_END,
1401 };
1402
1403 /*
1404 * ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2
1405 * steps 3, 9-14, except 12.a.i, 12.c.i.1.
1406 */
1407 static RegExpRunStatus ExecuteRegExp(JSContext* cx, HandleObject regexp,
1408 HandleString string, int32_t lastIndex,
1409 VectorMatchPairs* matches) {
1410 /*
1411 * WARNING: Despite the presence of spec step comment numbers, this
1412 * algorithm isn't consistent with any ES6 version, draft or
1413 * otherwise. YOU HAVE BEEN WARNED.
1414 */
1415
1416 /* Steps 1-2 performed by the caller. */
1417 Handle<RegExpObject*> reobj = regexp.as<RegExpObject>();
1418
1419 RootedRegExpShared re(cx, RegExpObject::getShared(cx, reobj));
1420 if (!re) {
1421 return RegExpRunStatus::Error;
1422 }
1423
1424 RegExpStatics* res = GlobalObject::getRegExpStatics(cx, cx->global());
1425 if (!res) {
1426 return RegExpRunStatus::Error;
1427 }
1428
1429 Rooted<JSLinearString*> input(cx, string->ensureLinear(cx));
1430 if (!input) {
1431 return RegExpRunStatus::Error;
1432 }
1433
1434 /* Handled by caller */
1435 MOZ_ASSERT(lastIndex >= 0 && size_t(lastIndex) <= input->length());
1436
1437 /* Steps 4-8 performed by the caller. */
1438
1439 /* Steps 3, 10-14, except 12.a.i, 12.c.i.1. */
1440 RegExpRunStatus status =
1441 ExecuteRegExpImpl(cx, res, &re, input, lastIndex, matches);
1442 if (status == RegExpRunStatus::Error) {
1443 return RegExpRunStatus::Error;
1444 }
1445
1446 /* Steps 12.a.i, 12.c.i.i, 15 are done by Self-hosted function. */
1447
1448 return status;
1449 }
1450
1451 /*
1452 * ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2
1453 * steps 3, 9-25, except 12.a.i, 12.c.i.1, 15.
1454 */
1455 static bool RegExpMatcherImpl(JSContext* cx, HandleObject regexp,
1456 HandleString string, int32_t lastIndex,
1457 MutableHandleValue rval) {
1458 /* Execute regular expression and gather matches. */
1459 VectorMatchPairs matches;
1460
1461 /* Steps 3, 9-14, except 12.a.i, 12.c.i.1. */
1462 RegExpRunStatus status =
1463 ExecuteRegExp(cx, regexp, string, lastIndex, &matches);
1464 if (status == RegExpRunStatus::Error) {
1465 return false;
1466 }
1467
1468 /* Steps 12.a, 12.c. */
1469 if (status == RegExpRunStatus::Success_NotFound) {
1470 rval.setNull();
1471 return true;
1472 }
1473
1474 /* Steps 16-25 */
1475 RootedRegExpShared shared(cx, regexp->as<RegExpObject>().getShared());
1476 return CreateRegExpMatchResult(cx, shared, string, matches, rval);
1477 }
1478
1479 /*
1480 * ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2
1481 * steps 3, 9-25, except 12.a.i, 12.c.i.1, 15.
1482 */
1483 bool js::RegExpMatcher(JSContext* cx, unsigned argc, Value* vp) {
1484 CallArgs args = CallArgsFromVp(argc, vp);
1485 MOZ_ASSERT(args.length() == 3);
1486 MOZ_ASSERT(IsRegExpObject(args[0]));
1487 MOZ_ASSERT(args[1].isString());
1488 MOZ_ASSERT(args[2].isNumber());
1489
1490 RootedObject regexp(cx, &args[0].toObject());
1491 RootedString string(cx, args[1].toString());
1492
1493 int32_t lastIndex;
1494 MOZ_ALWAYS_TRUE(ToInt32(cx, args[2], &lastIndex));
1495
1496 /* Steps 3, 9-25, except 12.a.i, 12.c.i.1, 15. */
1497 return RegExpMatcherImpl(cx, regexp, string, lastIndex, args.rval());
1498 }
1499
1500 /*
1501 * Separate interface for use by the JITs.
1502 * This code cannot re-enter JIT code.
1503 */
1504 bool js::RegExpMatcherRaw(JSContext* cx, HandleObject regexp,
1505 HandleString input, int32_t lastIndex,
1506 MatchPairs* maybeMatches, MutableHandleValue output) {
1507 MOZ_ASSERT(lastIndex >= 0 && size_t(lastIndex) <= input->length());
1508
1509 // RegExp execution was successful only if the pairs have actually been
1510 // filled in. Note that IC code always passes a nullptr maybeMatches.
1511 if (maybeMatches && maybeMatches->pairsRaw()[0] > MatchPair::NoMatch) {
1512 RootedRegExpShared shared(cx, regexp->as<RegExpObject>().getShared());
1513 return CreateRegExpMatchResult(cx, shared, input, *maybeMatches, output);
1514 }
1515 return RegExpMatcherImpl(cx, regexp, input, lastIndex, output);
1516 }
1517
1518 /*
1519 * ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2
1520 * steps 3, 9-25, except 12.a.i, 12.c.i.1, 15.
1521 * This code is inlined in CodeGenerator.cpp generateRegExpSearcherStub,
1522 * changes to this code need to get reflected in there too.
1523 */
1524 static bool RegExpSearcherImpl(JSContext* cx, HandleObject regexp,
1525 HandleString string, int32_t lastIndex,
1526 int32_t* result) {
1527 /* Execute regular expression and gather matches. */
1528 VectorMatchPairs matches;
1529
1530 #ifdef DEBUG
1531 // Ensure we assert if RegExpSearcherLastLimit is called when there's no
1532 // match.
1533 cx->regExpSearcherLastLimit = RegExpSearcherLastLimitSentinel;
1534 #endif
1535
1536 /* Steps 3, 9-14, except 12.a.i, 12.c.i.1. */
1537 RegExpRunStatus status =
1538 ExecuteRegExp(cx, regexp, string, lastIndex, &matches);
1539 if (status == RegExpRunStatus::Error) {
1540 return false;
1541 }
1542
1543 /* Steps 12.a, 12.c. */
1544 if (status == RegExpRunStatus::Success_NotFound) {
1545 *result = -1;
1546 return true;
1547 }
1548
1549 /* Steps 16-25 */
1550 *result = CreateRegExpSearchResult(cx, matches);
1551 return true;
1552 }
1553
1554 /*
1555 * ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2
1556 * steps 3, 9-25, except 12.a.i, 12.c.i.1, 15.
1557 */
1558 bool js::RegExpSearcher(JSContext* cx, unsigned argc, Value* vp) {
1559 CallArgs args = CallArgsFromVp(argc, vp);
1560 MOZ_ASSERT(args.length() == 3);
1561 MOZ_ASSERT(IsRegExpObject(args[0]));
1562 MOZ_ASSERT(args[1].isString());
1563 MOZ_ASSERT(args[2].isNumber());
1564
1565 RootedObject regexp(cx, &args[0].toObject());
1566 RootedString string(cx, args[1].toString());
1567
1568 int32_t lastIndex;
1569 MOZ_ALWAYS_TRUE(ToInt32(cx, args[2], &lastIndex));
1570
1571 /* Steps 3, 9-25, except 12.a.i, 12.c.i.1, 15. */
1572 int32_t result = 0;
1573 if (!RegExpSearcherImpl(cx, regexp, string, lastIndex, &result)) {
1574 return false;
1575 }
1576
1577 args.rval().setInt32(result);
1578 return true;
1579 }
1580
1581 /*
1582 * Separate interface for use by the JITs.
1583 * This code cannot re-enter JIT code.
1584 */
1585 bool js::RegExpSearcherRaw(JSContext* cx, HandleObject regexp,
1586 HandleString input, int32_t lastIndex,
1587 MatchPairs* maybeMatches, int32_t* result) {
1588 MOZ_ASSERT(lastIndex >= 0);
1589
1590 // RegExp execution was successful only if the pairs have actually been
1591 // filled in. Note that IC code always passes a nullptr maybeMatches.
1592 if (maybeMatches && maybeMatches->pairsRaw()[0] > MatchPair::NoMatch) {
1593 *result = CreateRegExpSearchResult(cx, *maybeMatches);
1594 return true;
1595 }
1596 return RegExpSearcherImpl(cx, regexp, input, lastIndex, result);
1597 }
1598
1599 bool js::RegExpSearcherLastLimit(JSContext* cx, unsigned argc, Value* vp) {
1600 CallArgs args = CallArgsFromVp(argc, vp);
1601 MOZ_ASSERT(args.length() == 1);
1602 MOZ_ASSERT(args[0].isString());
1603
1604 // Assert the limit is not the sentinel value and is valid for this string.
1605 MOZ_ASSERT(cx->regExpSearcherLastLimit != RegExpSearcherLastLimitSentinel);
1606 MOZ_ASSERT(cx->regExpSearcherLastLimit <= args[0].toString()->length());
1607
1608 args.rval().setInt32(cx->regExpSearcherLastLimit);
1609
1610 #ifdef DEBUG
1611 // Ensure we assert if this function is called again without a new call to
1612 // RegExpSearcher.
1613 cx->regExpSearcherLastLimit = RegExpSearcherLastLimitSentinel;
1614 #endif
1615 return true;
1616 }
1617
1618 template <bool CalledFromJit>
1619 static bool RegExpBuiltinExecMatchRaw(JSContext* cx,
1620 Handle<RegExpObject*> regexp,
1621 HandleString input, int32_t lastIndex,
1622 MatchPairs* maybeMatches,
1623 MutableHandleValue output) {
1624 MOZ_ASSERT(lastIndex >= 0);
1625 MOZ_ASSERT(size_t(lastIndex) <= input->length());
1626 MOZ_ASSERT_IF(!CalledFromJit, !maybeMatches);
1627
1628 // RegExp execution was successful only if the pairs have actually been
1629 // filled in. Note that IC code always passes a nullptr maybeMatches.
1630 int32_t lastIndexNew = 0;
1631 if (CalledFromJit && maybeMatches &&
1632 maybeMatches->pairsRaw()[0] > MatchPair::NoMatch) {
1633 RootedRegExpShared shared(cx, regexp->as<RegExpObject>().getShared());
1634 if (!CreateRegExpMatchResult(cx, shared, input, *maybeMatches, output)) {
1635 return false;
1636 }
1637 lastIndexNew = (*maybeMatches)[0].limit;
1638 } else {
1639 VectorMatchPairs matches;
1640 RegExpRunStatus status =
1641 ExecuteRegExp(cx, regexp, input, lastIndex, &matches);
1642 if (status == RegExpRunStatus::Error) {
1643 return false;
1644 }
1645 if (status == RegExpRunStatus::Success_NotFound) {
1646 output.setNull();
1647 lastIndexNew = 0;
1648 } else {
1649 RootedRegExpShared shared(cx, regexp->as<RegExpObject>().getShared());
1650 if (!CreateRegExpMatchResult(cx, shared, input, matches, output)) {
1651 return false;
1652 }
1653 lastIndexNew = matches[0].limit;
1654 }
1655 }
1656
1657 RegExpFlags flags = regexp->getFlags();
1658 if (!flags.global() && !flags.sticky()) {
1659 return true;
1660 }
1661
1662 return SetLastIndex<CalledFromJit>(cx, regexp, lastIndexNew);
1663 }
1664
1665 bool js::RegExpBuiltinExecMatchFromJit(JSContext* cx,
1666 Handle<RegExpObject*> regexp,
1667 HandleString input,
1668 MatchPairs* maybeMatches,
1669 MutableHandleValue output) {
1670 int32_t lastIndex = 0;
1671 if (regexp->isGlobalOrSticky()) {
1672 lastIndex = regexp->getLastIndex().toInt32();
1673 MOZ_ASSERT(lastIndex >= 0);
1674 if (size_t(lastIndex) > input->length()) {
1675 output.setNull();
1676 return SetLastIndex<true>(cx, regexp, 0);
1677 }
1678 }
1679 return RegExpBuiltinExecMatchRaw<true>(cx, regexp, input, lastIndex,
1680 maybeMatches, output);
1681 }
1682
1683 template <bool CalledFromJit>
1684 static bool RegExpBuiltinExecTestRaw(JSContext* cx,
1685 Handle<RegExpObject*> regexp,
1686 HandleString input, int32_t lastIndex,
1687 bool* result) {
1688 MOZ_ASSERT(lastIndex >= 0);
1689 MOZ_ASSERT(size_t(lastIndex) <= input->length());
1690
1691 VectorMatchPairs matches;
1692 RegExpRunStatus status =
1693 ExecuteRegExp(cx, regexp, input, lastIndex, &matches);
1694 if (status == RegExpRunStatus::Error) {
1695 return false;
1696 }
1697
1698 *result = (status == RegExpRunStatus::Success);
1699
1700 RegExpFlags flags = regexp->getFlags();
1701 if (!flags.global() && !flags.sticky()) {
1702 return true;
1703 }
1704
1705 int32_t lastIndexNew = *result ? matches[0].limit : 0;
1706 return SetLastIndex<CalledFromJit>(cx, regexp, lastIndexNew);
1707 }
1708
1709 bool js::RegExpBuiltinExecTestFromJit(JSContext* cx,
1710 Handle<RegExpObject*> regexp,
1711 HandleString input, bool* result) {
1712 int32_t lastIndex = 0;
1713 if (regexp->isGlobalOrSticky()) {
1714 lastIndex = regexp->getLastIndex().toInt32();
1715 MOZ_ASSERT(lastIndex >= 0);
1716 if (size_t(lastIndex) > input->length()) {
1717 *result = false;
1718 return SetLastIndex<true>(cx, regexp, 0);
1719 }
1720 }
1721 return RegExpBuiltinExecTestRaw<true>(cx, regexp, input, lastIndex, result);
1722 }
1723
1724 using CapturesVector = GCVector<Value, 4>;
1725
1726 struct JSSubString {
1727 JSLinearString* base = nullptr;
1728 size_t offset = 0;
1729 size_t length = 0;
1730
1731 JSSubString() = default;
1732
1733 void initEmpty(JSLinearString* base) {
1734 this->base = base;
1735 offset = length = 0;
1736 }
1737 void init(JSLinearString* base, size_t offset, size_t length) {
1738 this->base = base;
1739 this->offset = offset;
1740 this->length = length;
1741 }
1742 };
1743
1744 static void GetParen(JSLinearString* matched, const JS::Value& capture,
1745 JSSubString* out) {
1746 if (capture.isUndefined()) {
1747 out->initEmpty(matched);
1748 return;
1749 }
1750 JSLinearString& captureLinear = capture.toString()->asLinear();
1751 out->init(&captureLinear, 0, captureLinear.length());
1752 }
1753
1754 template <typename CharT>
1755 static bool InterpretDollar(JSLinearString* matched, JSLinearString* string,
1756 size_t position, size_t tailPos,
1757 Handle<CapturesVector> captures,
1758 Handle<CapturesVector> namedCaptures,
1759 JSLinearString* replacement,
1760 const CharT* replacementBegin,
1761 const CharT* currentDollar,
1762 const CharT* replacementEnd, JSSubString* out,
1763 size_t* skip, uint32_t* currentNamedCapture) {
1764 MOZ_ASSERT(*currentDollar == '$');
1765
1766 /* If there is only a dollar, bail now. */
1767 if (currentDollar + 1 >= replacementEnd) {
1768 return false;
1769 }
1770
1771 // ES 2021 Table 57: Replacement Text Symbol Substitutions
1772 // https://tc39.es/ecma262/#table-replacement-text-symbol-substitutions
1773 char16_t c = currentDollar[1];
1774 if (IsAsciiDigit(c)) {
1775 /* $n, $nn */
1776 unsigned num = AsciiDigitToNumber(c);
1777 if (num > captures.length()) {
1778 // The result is implementation-defined. Do not substitute.
1779 return false;
1780 }
1781
1782 const CharT* currentChar = currentDollar + 2;
1783 if (currentChar < replacementEnd) {
1784 c = *currentChar;
1785 if (IsAsciiDigit(c)) {
1786 unsigned tmpNum = 10 * num + AsciiDigitToNumber(c);
1787 // If num > captures.length(), the result is implementation-defined.
1788 // Consume next character only if num <= captures.length().
1789 if (tmpNum <= captures.length()) {
1790 currentChar++;
1791 num = tmpNum;
1792 }
1793 }
1794 }
1795
1796 if (num == 0) {
1797 // The result is implementation-defined. Do not substitute.
1798 return false;
1799 }
1800
1801 *skip = currentChar - currentDollar;
1802
1803 MOZ_ASSERT(num <= captures.length());
1804
1805 GetParen(matched, captures[num - 1], out);
1806 return true;
1807 }
1808
1809 // '$<': Named Captures
1810 if (c == '<') {
1811 // Step 1.
1812 if (namedCaptures.length() == 0) {
1813 return false;
1814 }
1815
1816 // Step 2.b
1817 const CharT* nameStart = currentDollar + 2;
1818 const CharT* nameEnd = js_strchr_limit(nameStart, '>', replacementEnd);
1819
1820 // Step 2.c
1821 if (!nameEnd) {
1822 return false;
1823 }
1824
1825 // Step 2.d
1826 // We precompute named capture replacements in InitNamedCaptures.
1827 // They are stored in the order in which we will need them, so here
1828 // we can just take the next one in the list.
1829 size_t nameLength = nameEnd - nameStart;
1830 *skip = nameLength + 3; // $<...>
1831
1832 // Steps 2.d.iii-iv
1833 GetParen(matched, namedCaptures[*currentNamedCapture], out);
1834 *currentNamedCapture += 1;
1835 return true;
1836 }
1837
1838 switch (c) {
1839 default:
1840 return false;
1841 case '$':
1842 out->init(replacement, currentDollar - replacementBegin, 1);
1843 break;
1844 case '&':
1845 out->init(matched, 0, matched->length());
1846 break;
1847 case '`':
1848 out->init(string, 0, position);
1849 break;
1850 case '\'':
1851 if (tailPos >= string->length()) {
1852 out->initEmpty(matched);
1853 } else {
1854 out->init(string, tailPos, string->length() - tailPos);
1855 }
1856 break;
1857 }
1858
1859 *skip = 2;
1860 return true;
1861 }
1862
1863 template <typename CharT>
1864 static bool FindReplaceLengthString(JSContext* cx,
1865 Handle<JSLinearString*> matched,
1866 Handle<JSLinearString*> string,
1867 size_t position, size_t tailPos,
1868 Handle<CapturesVector> captures,
1869 Handle<CapturesVector> namedCaptures,
1870 Handle<JSLinearString*> replacement,
1871 size_t firstDollarIndex, size_t* sizep) {
1872 CheckedInt<uint32_t> replen = replacement->length();
1873
1874 JS::AutoCheckCannotGC nogc;
1875 MOZ_ASSERT(firstDollarIndex < replacement->length());
1876 const CharT* replacementBegin = replacement->chars<CharT>(nogc);
1877 const CharT* currentDollar = replacementBegin + firstDollarIndex;
1878 const CharT* replacementEnd = replacementBegin + replacement->length();
1879 uint32_t currentNamedCapture = 0;
1880 do {
1881 JSSubString sub;
1882 size_t skip;
1883 if (InterpretDollar(matched, string, position, tailPos, captures,
1884 namedCaptures, replacement, replacementBegin,
1885 currentDollar, replacementEnd, &sub, &skip,
1886 &currentNamedCapture)) {
1887 if (sub.length > skip) {
1888 replen += sub.length - skip;
1889 } else {
1890 replen -= skip - sub.length;
1891 }
1892 currentDollar += skip;
1893 } else {
1894 currentDollar++;
1895 }
1896
1897 currentDollar = js_strchr_limit(currentDollar, '$', replacementEnd);
1898 } while (currentDollar);
1899
1900 if (!replen.isValid()) {
1901 ReportAllocationOverflow(cx);
1902 return false;
1903 }
1904
1905 *sizep = replen.value();
1906 return true;
1907 }
1908
1909 static bool FindReplaceLength(JSContext* cx, Handle<JSLinearString*> matched,
1910 Handle<JSLinearString*> string, size_t position,
1911 size_t tailPos, Handle<CapturesVector> captures,
1912 Handle<CapturesVector> namedCaptures,
1913 Handle<JSLinearString*> replacement,
1914 size_t firstDollarIndex, size_t* sizep) {
1915 return replacement->hasLatin1Chars()
1916 ? FindReplaceLengthString<Latin1Char>(
1917 cx, matched, string, position, tailPos, captures,
1918 namedCaptures, replacement, firstDollarIndex, sizep)
1919 : FindReplaceLengthString<char16_t>(
1920 cx, matched, string, position, tailPos, captures,
1921 namedCaptures, replacement, firstDollarIndex, sizep);
1922 }
1923
1924 /*
1925 * Precondition: |sb| already has necessary growth space reserved (as
1926 * derived from FindReplaceLength), and has been inflated to TwoByte if
1927 * necessary.
1928 */
1929 template <typename CharT>
1930 static void DoReplace(Handle<JSLinearString*> matched,
1931 Handle<JSLinearString*> string, size_t position,
1932 size_t tailPos, Handle<CapturesVector> captures,
1933 Handle<CapturesVector> namedCaptures,
1934 Handle<JSLinearString*> replacement,
1935 size_t firstDollarIndex, StringBuilder& sb) {
1936 JS::AutoCheckCannotGC nogc;
1937 const CharT* replacementBegin = replacement->chars<CharT>(nogc);
1938 const CharT* currentChar = replacementBegin;
1939
1940 MOZ_ASSERT(firstDollarIndex < replacement->length());
1941 const CharT* currentDollar = replacementBegin + firstDollarIndex;
1942 const CharT* replacementEnd = replacementBegin + replacement->length();
1943 uint32_t currentNamedCapture = 0;
1944 do {
1945 /* Move one of the constant portions of the replacement value. */
1946 size_t len = currentDollar - currentChar;
1947 sb.infallibleAppend(currentChar, len);
1948 currentChar = currentDollar;
1949
1950 JSSubString sub;
1951 size_t skip;
1952 if (InterpretDollar(matched, string, position, tailPos, captures,
1953 namedCaptures, replacement, replacementBegin,
1954 currentDollar, replacementEnd, &sub, &skip,
1955 &currentNamedCapture)) {
1956 sb.infallibleAppendSubstring(sub.base, sub.offset, sub.length);
1957 currentChar += skip;
1958 currentDollar += skip;
1959 } else {
1960 currentDollar++;
1961 }
1962
1963 currentDollar = js_strchr_limit(currentDollar, '$', replacementEnd);
1964 } while (currentDollar);
1965 sb.infallibleAppend(currentChar,
1966 replacement->length() - (currentChar - replacementBegin));
1967 }
1968
1969 /*
1970 * This function finds the list of named captures of the form
1971 * "$<name>" in a replacement string and converts them into jsids, for
1972 * use in InitNamedReplacements.
1973 */
1974 template <typename CharT>
1975 static bool CollectNames(JSContext* cx, Handle<JSLinearString*> replacement,
1976 size_t firstDollarIndex,
1977 MutableHandle<GCVector<jsid>> names) {
1978 JS::AutoCheckCannotGC nogc;
1979 MOZ_ASSERT(firstDollarIndex < replacement->length());
1980
1981 const CharT* replacementBegin = replacement->chars<CharT>(nogc);
1982 const CharT* currentDollar = replacementBegin + firstDollarIndex;
1983 const CharT* replacementEnd = replacementBegin + replacement->length();
1984
1985 // https://tc39.es/ecma262/#table-45, "$<" section
1986 while (currentDollar && currentDollar + 1 < replacementEnd) {
1987 if (currentDollar[1] == '<') {
1988 // Step 2.b
1989 const CharT* nameStart = currentDollar + 2;
1990 const CharT* nameEnd = js_strchr_limit(nameStart, '>', replacementEnd);
1991
1992 // Step 2.c
1993 if (!nameEnd) {
1994 return true;
1995 }
1996
1997 // Step 2.d.i
1998 size_t nameLength = nameEnd - nameStart;
1999 JSAtom* atom = AtomizeChars(cx, nameStart, nameLength);
2000 if (!atom || !names.append(AtomToId(atom))) {
2001 return false;
2002 }
2003 currentDollar = nameEnd + 1;
2004 } else {
2005 currentDollar += 2;
2006 }
2007 currentDollar = js_strchr_limit(currentDollar, '$', replacementEnd);
2008 }
2009 return true;
2010 }
2011
2012 /*
2013 * When replacing named captures, the spec requires us to perform
2014 * `Get(match.groups, name)` for each "$<name>". These `Get`s can be
2015 * script-visible; for example, RegExp can be extended with an `exec`
2016 * method that wraps `groups` in a proxy. To make sure that we do the
2017 * right thing, if a regexp has named captures, we find the named
2018 * capture replacements before beginning the actual replacement.
2019 * This guarantees that we will call GetProperty once and only once for
2020 * each "$<name>" in the replacement string, in the correct order.
2021 *
2022 * This function precomputes the results of step 2 of the '$<' case
2023 * here: https://tc39.es/proposal-regexp-named-groups/#table-45, so
2024 * that when we need to access the nth named capture in InterpretDollar,
2025 * we can just use the nth value stored in namedCaptures.
2026 */
2027 static bool InitNamedCaptures(JSContext* cx,
2028 Handle<JSLinearString*> replacement,
2029 HandleObject groups, size_t firstDollarIndex,
2030 MutableHandle<CapturesVector> namedCaptures) {
2031 Rooted<GCVector<jsid>> names(cx, cx);
2032 if (replacement->hasLatin1Chars()) {
2033 if (!CollectNames<Latin1Char>(cx, replacement, firstDollarIndex, &names)) {
2034 return false;
2035 }
2036 } else {
2037 if (!CollectNames<char16_t>(cx, replacement, firstDollarIndex, &names)) {
2038 return false;
2039 }
2040 }
2041
2042 // https://tc39.es/ecma262/#table-45, "$<" section
2043 RootedId id(cx);
2044 RootedValue capture(cx);
2045 for (uint32_t i = 0; i < names.length(); i++) {
2046 // Step 2.d.i
2047 id = names[i];
2048
2049 // Step 2.d.ii
2050 if (!GetProperty(cx, groups, groups, id, &capture)) {
2051 return false;
2052 }
2053
2054 // Step 2.d.iii
2055 if (capture.isUndefined()) {
2056 if (!namedCaptures.append(capture)) {
2057 return false;
2058 }
2059 } else {
2060 // Step 2.d.iv
2061 JSString* str = ToString<CanGC>(cx, capture);
2062 if (!str) {
2063 return false;
2064 }
2065 JSLinearString* linear = str->ensureLinear(cx);
2066 if (!linear) {
2067 return false;
2068 }
2069 if (!namedCaptures.append(StringValue(linear))) {
2070 return false;
2071 }
2072 }
2073 }
2074
2075 return true;
2076 }
2077
2078 static bool NeedTwoBytes(Handle<JSLinearString*> string,
2079 Handle<JSLinearString*> replacement,
2080 Handle<JSLinearString*> matched,
2081 Handle<CapturesVector> captures,
2082 Handle<CapturesVector> namedCaptures) {
2083 if (string->hasTwoByteChars()) {
2084 return true;
2085 }
2086 if (replacement->hasTwoByteChars()) {
2087 return true;
2088 }
2089 if (matched->hasTwoByteChars()) {
2090 return true;
2091 }
2092
2093 for (const Value& capture : captures) {
2094 if (capture.isUndefined()) {
2095 continue;
2096 }
2097 if (capture.toString()->hasTwoByteChars()) {
2098 return true;
2099 }
2100 }
2101
2102 for (const Value& capture : namedCaptures) {
2103 if (capture.isUndefined()) {
2104 continue;
2105 }
2106 if (capture.toString()->hasTwoByteChars()) {
2107 return true;
2108 }
2109 }
2110
2111 return false;
2112 }
2113
2114 // ES2024 draft rev d4927f9bc3706484c75dfef4bbcf5ba826d2632e
2115 //
2116 // 22.2.7.2 RegExpBuiltinExec ( R, S )
2117 // https://tc39.es/ecma262/#sec-regexpbuiltinexec
2118 //
2119 // If `forTest` is true, this is called from `RegExp.prototype.test` and we can
2120 // avoid allocating a result object.
2121 bool js::RegExpBuiltinExec(JSContext* cx, Handle<RegExpObject*> regexp,
2122 Handle<JSString*> string, bool forTest,
2123 MutableHandle<Value> rval) {
2124 // Step 2.
2125 uint64_t lastIndex;
2126 if (MOZ_LIKELY(regexp->getLastIndex().isInt32())) {
2127 lastIndex = std::max(regexp->getLastIndex().toInt32(), 0);
2128 } else {
2129 Rooted<Value> lastIndexVal(cx, regexp->getLastIndex());
2130 if (!ToLength(cx, lastIndexVal, &lastIndex)) {
2131 return false;
2132 }
2133 }
2134
2135 // Steps 3-5.
2136 bool globalOrSticky = regexp->isGlobalOrSticky();
2137
2138 // Step 7.
2139 if (!globalOrSticky) {
2140 lastIndex = 0;
2141 } else {
2142 // Steps 1, 13.a.
2143 if (lastIndex > string->length()) {
2144 if (!SetLastIndex(cx, regexp, 0)) {
2145 return false;
2146 }
2147 rval.set(forTest ? BooleanValue(false) : NullValue());
2148 return true;
2149 }
2150 }
2151
2152 MOZ_ASSERT(lastIndex <= string->length());
2153 static_assert(JSString::MAX_LENGTH <= INT32_MAX, "lastIndex fits in int32_t");
2154
2155 // Steps 6, 8-35.
2156
2157 if (forTest) {
2158 bool result;
2159 if (!RegExpBuiltinExecTestRaw<false>(cx, regexp, string, int32_t(lastIndex),
2160 &result)) {
2161 return false;
2162 }
2163 rval.setBoolean(result);
2164 return true;
2165 }
2166
2167 return RegExpBuiltinExecMatchRaw<false>(cx, regexp, string,
2168 int32_t(lastIndex), nullptr, rval);
2169 }
2170
2171 bool js::IsOptimizableRegExpObject(JSObject* obj, JSContext* cx) {
2172 // Check the shape to ensure this is a plain RegExpObject with this realm's
2173 // RegExp.prototype as prototype and without any extra own properties.
2174 // The fuse check ensures RegExp.prototype is optimizable.
2175 bool optimizable =
2176 obj->shape() == cx->global()->maybeRegExpShapeWithDefaultProto() &&
2177 cx->realm()->realmFuses.optimizeRegExpPrototypeFuse.intact();
2178 MOZ_ASSERT_IF(optimizable,
2179 obj->is<RegExpObject>() &&
2180 obj->as<RegExpObject>().realm() == cx->realm());
2181 return optimizable;
2182 }
2183
2184 // ES2024 draft rev d4927f9bc3706484c75dfef4bbcf5ba826d2632e
2185 //
2186 // 22.2.7.1 RegExpExec ( R, S )
2187 // https://tc39.es/ecma262/#sec-regexpexec
2188 //
2189 // If `forTest` is true, this is called from `RegExp.prototype.test` and we can
2190 // avoid allocating a result object.
2191 bool js::RegExpExec(JSContext* cx, Handle<JSObject*> regexp,
2192 Handle<JSString*> string, bool forTest,
2193 MutableHandle<Value> rval) {
2194 // Fast path for the case where `regexp` is a regular expression object with
2195 // the builtin `RegExp.prototype.exec` function.
2196 if (MOZ_LIKELY(IsOptimizableRegExpObject(regexp, cx))) {
2197 return RegExpBuiltinExec(cx, regexp.as<RegExpObject>(), string, forTest,
2198 rval);
2199 }
2200
2201 // Step 1.
2202 Rooted<Value> exec(cx);
2203 Rooted<PropertyKey> execKey(cx, NameToId(cx->names().exec));
2204 if (!GetProperty(cx, regexp, regexp, execKey, &exec)) {
2205 return false;
2206 }
2207
2208 // Step 2.
2209 // If exec is the original RegExp.prototype.exec, use the same, faster,
2210 // path as for the case where exec isn't callable.
2211 PropertyName* execName = cx->names().RegExp_prototype_Exec;
2212 if (IsSelfHostedFunctionWithName(exec, execName) || !IsCallable(exec)) {
2213 // Steps 3-4.
2214 if (MOZ_LIKELY(regexp->is<RegExpObject>())) {
2215 return RegExpBuiltinExec(cx, regexp.as<RegExpObject>(), string, forTest,
2216 rval);
2217 }
2218
2219 // Throw an exception if it's not a wrapped RegExpObject that we can safely
2220 // unwrap.
2221 if (!regexp->canUnwrapAs<RegExpObject>()) {
2222 Rooted<Value> thisv(cx, ObjectValue(*regexp));
2223 return ReportIncompatibleSelfHostedMethod(cx, thisv);
2224 }
2225
2226 // Call RegExpBuiltinExec in the regular expression's realm.
2227 Rooted<RegExpObject*> unwrapped(cx, &regexp->unwrapAs<RegExpObject>());
2228 {
2229 AutoRealm ar(cx, unwrapped);
2230 Rooted<JSString*> wrappedString(cx, string);
2231 if (!cx->compartment()->wrap(cx, &wrappedString)) {
2232 return false;
2233 }
2234 if (!RegExpBuiltinExec(cx, unwrapped, wrappedString, forTest, rval)) {
2235 return false;
2236 }
2237 }
2238 return cx->compartment()->wrap(cx, rval);
2239 }
2240
2241 // Step 2.a.
2242 Rooted<Value> thisv(cx, ObjectValue(*regexp));
2243 FixedInvokeArgs<1> args(cx);
2244 args[0].setString(string);
2245 if (!js::Call(cx, exec, thisv, args, rval, CallReason::CallContent)) {
2246 return false;
2247 }
2248
2249 // Step 2.b.
2250 if (!rval.isObjectOrNull()) {
2251 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2252 JSMSG_EXEC_NOT_OBJORNULL);
2253 return false;
2254 }
2255
2256 // Step 2.c.
2257 if (forTest) {
2258 rval.setBoolean(rval.isObject());
2259 }
2260 return true;
2261 }
2262
2263 bool js::RegExpHasCaptureGroups(JSContext* cx, Handle<RegExpObject*> obj,
2264 Handle<JSString*> input, bool* result) {
2265 // pairCount is only available for compiled regular expressions.
2266 if (!obj->hasShared() ||
2267 obj->getShared()->kind() == RegExpShared::Kind::Unparsed) {
2268 Rooted<RegExpShared*> shared(cx, RegExpObject::getShared(cx, obj));
2269 if (!shared) {
2270 return false;
2271 }
2272 Rooted<JSLinearString*> inputLinear(cx, input->ensureLinear(cx));
2273 if (!inputLinear) {
2274 return false;
2275 }
2276 if (!RegExpShared::compileIfNecessary(cx, &shared, inputLinear,
2277 RegExpShared::CodeKind::Any)) {
2278 return false;
2279 }
2280 }
2281
2282 MOZ_ASSERT(obj->getShared()->pairCount() >= 1);
2283
2284 *result = obj->getShared()->pairCount() > 1;
2285 return true;
2286 }
2287
2288 /* ES 2021 21.1.3.17.1 */
2289 // https://tc39.es/ecma262/#sec-getsubstitution
2290 bool js::RegExpGetSubstitution(JSContext* cx, Handle<ArrayObject*> matchResult,
2291 Handle<JSLinearString*> string, size_t position,
2292 Handle<JSLinearString*> replacement,
2293 size_t firstDollarIndex, HandleValue groups,
2294 MutableHandleValue rval) {
2295 MOZ_ASSERT(firstDollarIndex < replacement->length());
2296
2297 // Step 1 (skipped).
2298
2299 // Step 10 (reordered).
2300 uint32_t matchResultLength = matchResult->length();
2301 MOZ_RELEASE_ASSERT(matchResultLength > 0);
2302 MOZ_RELEASE_ASSERT(IsPackedArray(matchResult));
2303
2304 const Value& matchedValue = matchResult->getDenseElement(0);
2305 Rooted<JSLinearString*> matched(cx,
2306 matchedValue.toString()->ensureLinear(cx));
2307 if (!matched) {
2308 return false;
2309 }
2310
2311 // Step 2.
2312 size_t matchLength = matched->length();
2313
2314 // Steps 3-5 (skipped).
2315
2316 // Step 6.
2317 MOZ_ASSERT(position <= string->length());
2318
2319 // String substitutions can only reference $1 through $99.
2320 uint32_t nCaptures = std::min<uint32_t>(matchResultLength - 1,
2321 REGEXP_MAX_SUBSTITUTION_CAPTURES);
2322 Rooted<CapturesVector> captures(cx, CapturesVector(cx));
2323 if (!captures.reserve(nCaptures)) {
2324 return false;
2325 }
2326
2327 // Step 7.
2328 for (uint32_t i = 1; i <= nCaptures; i++) {
2329 const Value& capture = matchResult->getDenseElement(i);
2330
2331 if (capture.isUndefined()) {
2332 captures.infallibleAppend(capture);
2333 continue;
2334 }
2335
2336 JSLinearString* captureLinear = capture.toString()->ensureLinear(cx);
2337 if (!captureLinear) {
2338 return false;
2339 }
2340 captures.infallibleAppend(StringValue(captureLinear));
2341 }
2342
2343 Rooted<CapturesVector> namedCaptures(cx, cx);
2344 if (groups.isObject()) {
2345 RootedObject groupsObj(cx, &groups.toObject());
2346 if (!InitNamedCaptures(cx, replacement, groupsObj, firstDollarIndex,
2347 &namedCaptures)) {
2348 return false;
2349 }
2350 } else {
2351 MOZ_ASSERT(groups.isUndefined());
2352 }
2353
2354 // Step 8 (skipped).
2355
2356 // Step 9.
2357 CheckedInt<uint32_t> checkedTailPos(0);
2358 checkedTailPos += position;
2359 checkedTailPos += matchLength;
2360 if (!checkedTailPos.isValid()) {
2361 ReportAllocationOverflow(cx);
2362 return false;
2363 }
2364 uint32_t tailPos = checkedTailPos.value();
2365
2366 // Step 11.
2367 size_t reserveLength;
2368 if (!FindReplaceLength(cx, matched, string, position, tailPos, captures,
2369 namedCaptures, replacement, firstDollarIndex,
2370 &reserveLength)) {
2371 return false;
2372 }
2373
2374 JSStringBuilder result(cx);
2375 if (NeedTwoBytes(string, replacement, matched, captures, namedCaptures)) {
2376 if (!result.ensureTwoByteChars()) {
2377 return false;
2378 }
2379 }
2380
2381 if (!result.reserve(reserveLength)) {
2382 return false;
2383 }
2384
2385 if (replacement->hasLatin1Chars()) {
2386 DoReplace<Latin1Char>(matched, string, position, tailPos, captures,
2387 namedCaptures, replacement, firstDollarIndex, result);
2388 } else {
2389 DoReplace<char16_t>(matched, string, position, tailPos, captures,
2390 namedCaptures, replacement, firstDollarIndex, result);
2391 }
2392
2393 // Step 12.
2394 JSString* resultString = result.finishString();
2395 if (!resultString) {
2396 return false;
2397 }
2398
2399 rval.setString(resultString);
2400 return true;
2401 }
2402
2403 bool js::GetFirstDollarIndex(JSContext* cx, unsigned argc, Value* vp) {
2404 CallArgs args = CallArgsFromVp(argc, vp);
2405 MOZ_ASSERT(args.length() == 1);
2406 JSString* str = args[0].toString();
2407
2408 // Should be handled in different path.
2409 MOZ_ASSERT(str->length() != 0);
2410
2411 int32_t index = -1;
2412 if (!GetFirstDollarIndexRaw(cx, str, &index)) {
2413 return false;
2414 }
2415
2416 args.rval().setInt32(index);
2417 return true;
2418 }
2419
2420 template <typename TextChar>
2421 static MOZ_ALWAYS_INLINE int GetFirstDollarIndexImpl(const TextChar* text,
2422 uint32_t textLen) {
2423 const TextChar* end = text + textLen;
2424 for (const TextChar* c = text; c != end; ++c) {
2425 if (*c == '$') {
2426 return c - text;
2427 }
2428 }
2429 return -1;
2430 }
2431
2432 int32_t js::GetFirstDollarIndexRawFlat(const JSLinearString* text) {
2433 uint32_t len = text->length();
2434
2435 JS::AutoCheckCannotGC nogc;
2436 if (text->hasLatin1Chars()) {
2437 return GetFirstDollarIndexImpl(text->latin1Chars(nogc), len);
2438 }
2439
2440 return GetFirstDollarIndexImpl(text->twoByteChars(nogc), len);
2441 }
2442
2443 bool js::GetFirstDollarIndexRaw(JSContext* cx, JSString* str, int32_t* index) {
2444 JSLinearString* text = str->ensureLinear(cx);
2445 if (!text) {
2446 return false;
2447 }
2448
2449 *index = GetFirstDollarIndexRawFlat(text);
2450 return true;
2451 }
2452
2453 bool js::IsRegExpPrototypeOptimizable(JSContext* cx, unsigned argc, Value* vp) {
2454 // This can only be called from self-hosted code.
2455 CallArgs args = CallArgsFromVp(argc, vp);
2456 MOZ_ASSERT(args.length() == 0);
2457
2458 bool optimizable =
2459 cx->realm()->realmFuses.optimizeRegExpPrototypeFuse.intact();
2460 args.rval().setBoolean(optimizable);
2461 return true;
2462 }
2463
2464 bool js::IsOptimizableRegExpObject(JSContext* cx, unsigned argc, Value* vp) {
2465 // This can only be called from self-hosted code.
2466 CallArgs args = CallArgsFromVp(argc, vp);
2467 MOZ_ASSERT(args.length() == 1);
2468 MOZ_ASSERT(args[0].isObject());
2469
2470 JSObject* obj = &args[0].toObject();
2471
2472 bool optimizable = IsOptimizableRegExpObject(obj, cx);
2473 args.rval().setBoolean(optimizable);
2474 return true;
2475 }
2476
2477 /*
2478 * Pattern match the script to check if it is is indexing into a particular
2479 * object, e.g. 'function(a) { return b[a]; }'. Avoid calling the script in
2480 * such cases, which are used by javascript packers (particularly the popular
2481 * Dean Edwards packer) to efficiently encode large scripts. We only handle the
2482 * code patterns generated by such packers here.
2483 */
2484 bool js::intrinsic_GetElemBaseForLambda(JSContext* cx, unsigned argc,
2485 Value* vp) {
2486 // This can only be called from self-hosted code.
2487 CallArgs args = CallArgsFromVp(argc, vp);
2488 MOZ_ASSERT(args.length() == 1);
2489
2490 JSObject& lambda = args[0].toObject();
2491 args.rval().setUndefined();
2492
2493 if (!lambda.is<JSFunction>()) {
2494 return true;
2495 }
2496
2497 RootedFunction fun(cx, &lambda.as<JSFunction>());
2498 if (!fun->isInterpreted() || fun->isClassConstructor()) {
2499 return true;
2500 }
2501
2502 JSScript* script = JSFunction::getOrCreateScript(cx, fun);
2503 if (!script) {
2504 return false;
2505 }
2506
2507 jsbytecode* pc = script->code();
2508
2509 /*
2510 * JSOp::GetAliasedVar tells us exactly where to find the base object 'b'.
2511 * Rule out the (unlikely) possibility of a function with environment
2512 * objects since it would make our environment walk off.
2513 */
2514 if (JSOp(*pc) != JSOp::GetAliasedVar || fun->needsSomeEnvironmentObject()) {
2515 return true;
2516 }
2517 EnvironmentCoordinate ec(pc);
2518 EnvironmentObject* env = &fun->environment()->as<EnvironmentObject>();
2519 for (unsigned i = 0; i < ec.hops(); ++i) {
2520 env = &env->enclosingEnvironment().as<EnvironmentObject>();
2521 }
2522 Value b = env->aliasedBinding(ec);
2523 pc += JSOpLength_GetAliasedVar;
2524
2525 /* Look for 'a' to be the lambda's first argument. */
2526 if (JSOp(*pc) != JSOp::GetArg || GET_ARGNO(pc) != 0) {
2527 return true;
2528 }
2529 pc += JSOpLength_GetArg;
2530
2531 /* 'b[a]' */
2532 if (JSOp(*pc) != JSOp::GetElem) {
2533 return true;
2534 }
2535 pc += JSOpLength_GetElem;
2536
2537 /* 'return b[a]' */
2538 if (JSOp(*pc) != JSOp::Return) {
2539 return true;
2540 }
2541
2542 /* 'b' must behave like a normal object. */
2543 if (!b.isObject()) {
2544 return true;
2545 }
2546
2547 JSObject& bobj = b.toObject();
2548 const JSClass* clasp = bobj.getClass();
2549 if (!clasp->isNativeObject() || clasp->getOpsLookupProperty() ||
2550 clasp->getOpsGetProperty()) {
2551 return true;
2552 }
2553
2554 args.rval().setObject(bobj);
2555 return true;
2556 }
2557
2558 /*
2559 * Emulates `b[a]` property access, that is detected in GetElemBaseForLambda.
2560 * It returns the property value only if the property is data property and the
2561 * property value is a string. Otherwise it returns undefined.
2562 */
2563 bool js::intrinsic_GetStringDataProperty(JSContext* cx, unsigned argc,
2564 Value* vp) {
2565 CallArgs args = CallArgsFromVp(argc, vp);
2566 MOZ_ASSERT(args.length() == 2);
2567
2568 RootedObject obj(cx, &args[0].toObject());
2569 if (!obj->is<NativeObject>()) {
2570 // The object is already checked to be native in GetElemBaseForLambda,
2571 // but it can be swapped to another class that is non-native.
2572 // Return undefined to mark failure to get the property.
2573 args.rval().setUndefined();
2574 return true;
2575 }
2576
2577 JSAtom* atom = AtomizeString(cx, args[1].toString());
2578 if (!atom) {
2579 return false;
2580 }
2581
2582 Value v;
2583 if (GetPropertyPure(cx, obj, AtomToId(atom), &v) && v.isString()) {
2584 args.rval().set(v);
2585 } else {
2586 args.rval().setUndefined();
2587 }
2588
2589 return true;
2590 }