Debian Codegraph @

js/src/builtin/Promise.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/Promise.h"
8
9 #include "mozilla/Atomics.h"
10 #include "mozilla/Maybe.h"
11 #include "mozilla/TimeStamp.h"
12
13 #include "jsapi.h"
14 #include "jsexn.h"
15 #include "jsfriendapi.h"
16
17 #include "js/CallAndConstruct.h" // JS::Construct, JS::IsCallable
18 #include "js/experimental/JitInfo.h" // JSJitGetterOp, JSJitInfo
19 #include "js/ForOfIterator.h" // JS::ForOfIterator
20 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
21 #include "js/PropertySpec.h"
22 #include "js/Stack.h"
23 #include "vm/ArrayObject.h"
24 #include "vm/AsyncFunction.h"
25 #include "vm/AsyncIteration.h"
26 #include "vm/CompletionKind.h"
27 #include "vm/ErrorObject.h"
28 #include "vm/ErrorReporting.h"
29 #include "vm/Iteration.h"
30 #include "vm/JSContext.h"
31 #include "vm/JSObject.h"
32 #include "vm/PlainObject.h" // js::PlainObject
33 #include "vm/PromiseObject.h" // js::PromiseObject, js::PromiseSlot_*
34 #include "vm/SelfHosting.h"
35 #include "vm/Warnings.h" // js::WarnNumberASCII
36
37 #include "debugger/DebugAPI-inl.h"
38 #include "vm/Compartment-inl.h"
39 #include "vm/ErrorObject-inl.h"
40 #include "vm/JSContext-inl.h" // JSContext::check
41 #include "vm/JSObject-inl.h"
42 #include "vm/NativeObject-inl.h"
43
44 using namespace js;
45
46 static double MillisecondsSinceStartup() {
47 auto now = mozilla::TimeStamp::Now();
48 return (now - mozilla::TimeStamp::FirstTimeStamp()).ToMilliseconds();
49 }
50
51 enum ResolutionMode { ResolveMode, RejectMode };
52
53 /**
54 * ES2023 draft rev 714fa3dd1e8237ae9c666146270f81880089eca5
55 *
56 * Promise Resolve Functions
57 * https://tc39.es/ecma262/#sec-promise-resolve-functions
58 */
59 enum ResolveFunctionSlots {
60 // NOTE: All slot represent [[AlreadyResolved]].[[Value]].
61 //
62 // The spec creates single record for [[AlreadyResolved]] and shares it
63 // between Promise Resolve Function and Promise Reject Function.
64 //
65 // Step 1. Let alreadyResolved be the Record { [[Value]]: false }.
66 // ...
67 // Step 6. Set resolve.[[AlreadyResolved]] to alreadyResolved.
68 // ...
69 // Step 11. Set reject.[[AlreadyResolved]] to alreadyResolved.
70 //
71 // We implement it by clearing all slots, both in
72 // Promise Resolve Function and Promise Reject Function at the same time.
73 //
74 // If none of slots are undefined, [[AlreadyResolved]].[[Value]] is false.
75 // If all slot are undefined, [[AlreadyResolved]].[[Value]] is true.
76
77 // [[Promise]] slot.
78 // A possibly-wrapped promise.
79 ResolveFunctionSlot_Promise = 0,
80
81 // The corresponding Promise Reject Function.
82 ResolveFunctionSlot_RejectFunction,
83 };
84
85 /**
86 * ES2023 draft rev 714fa3dd1e8237ae9c666146270f81880089eca5
87 *
88 * Promise Reject Functions
89 * https://tc39.es/ecma262/#sec-promise-reject-functions
90 */
91 enum RejectFunctionSlots {
92 // [[Promise]] slot.
93 // A possibly-wrapped promise.
94 RejectFunctionSlot_Promise = 0,
95
96 // The corresponding Promise Resolve Function.
97 RejectFunctionSlot_ResolveFunction,
98 };
99
100 enum PromiseCombinatorElementFunctionSlots {
101 PromiseCombinatorElementFunctionSlot_Data = 0,
102 PromiseCombinatorElementFunctionSlot_ElementIndexOrResolveFunc,
103 };
104
105 enum ReactionJobSlots {
106 ReactionJobSlot_ReactionRecord = 0,
107 };
108
109 // Extended function slots used to pass arguments through to either
110 // PromiseResolveThenableJob, or PromiseResolveBuiltinThenableJob when calling
111 // the built-in `then`.
112 enum ThenableJobSlots {
113 // The Promise to resolve using the given thenable.
114 //
115 // This can be a CCW when used for PromiseResolveThenableJob, otherwise it is
116 // guaranteed not to be.
117 ThenableJobSlot_Promise = 0,
118
119 // The thenable to use as the receiver when calling the `then` function.
120 //
121 // This can be a CCW when used for PromiseResolveThenableJob, otherwise it is
122 // guaranteed not to be.
123 ThenableJobSlot_Thenable,
124
125 // The handler to use as the Promise reaction, when not calling the built-in
126 // `then`. It is a callable object that's guaranteed to be from the same
127 // compartment as the PromiseReactionJob.
128 ThenableJobSlot_Handler,
129
130 ThenableJobSlot_Count
131 };
132
133 static_assert(size_t(ThenableJobSlot_Count) <=
134 size_t(FunctionExtended::SlotCount));
135
136 struct PromiseCapability {
137 JSObject* promise = nullptr;
138 JSObject* resolve = nullptr;
139 JSObject* reject = nullptr;
140
141 PromiseCapability() = default;
142
143 void trace(JSTracer* trc);
144 };
145
146 void PromiseCapability::trace(JSTracer* trc) {
147 if (promise) {
148 TraceRoot(trc, &promise, "PromiseCapability::promise");
149 }
150 if (resolve) {
151 TraceRoot(trc, &resolve, "PromiseCapability::resolve");
152 }
153 if (reject) {
154 TraceRoot(trc, &reject, "PromiseCapability::reject");
155 }
156 }
157
158 namespace js {
159
160 template <typename Wrapper>
161 class WrappedPtrOperations<PromiseCapability, Wrapper> {
162 const PromiseCapability& capability() const {
163 return static_cast<const Wrapper*>(this)->get();
164 }
165
166 public:
167 HandleObject promise() const {
168 return HandleObject::fromMarkedLocation(&capability().promise);
169 }
170 HandleObject resolve() const {
171 return HandleObject::fromMarkedLocation(&capability().resolve);
172 }
173 HandleObject reject() const {
174 return HandleObject::fromMarkedLocation(&capability().reject);
175 }
176 };
177
178 template <typename Wrapper>
179 class MutableWrappedPtrOperations<PromiseCapability, Wrapper>
180 : public WrappedPtrOperations<PromiseCapability, Wrapper> {
181 PromiseCapability& capability() { return static_cast<Wrapper*>(this)->get(); }
182
183 public:
184 MutableHandleObject promise() {
185 return MutableHandleObject::fromMarkedLocation(&capability().promise);
186 }
187 MutableHandleObject resolve() {
188 return MutableHandleObject::fromMarkedLocation(&capability().resolve);
189 }
190 MutableHandleObject reject() {
191 return MutableHandleObject::fromMarkedLocation(&capability().reject);
192 }
193 };
194
195 } // namespace js
196
197 struct PromiseCombinatorElements;
198
199 class PromiseCombinatorDataHolder : public NativeObject {
200 enum {
201 Slot_Promise = 0,
202 Slot_RemainingElements,
203 Slot_ValuesArray,
204 Slot_ResolveOrRejectFunction,
205 SlotsCount,
206 };
207
208 public:
209 static const JSClass class_;
210 JSObject* promiseObj() { return &getFixedSlot(Slot_Promise).toObject(); }
211 JSObject* resolveOrRejectObj() {
212 return &getFixedSlot(Slot_ResolveOrRejectFunction).toObject();
213 }
214 Value valuesArray() { return getFixedSlot(Slot_ValuesArray); }
215 int32_t remainingCount() {
216 return getFixedSlot(Slot_RemainingElements).toInt32();
217 }
218 int32_t increaseRemainingCount() {
219 int32_t remainingCount = getFixedSlot(Slot_RemainingElements).toInt32();
220 remainingCount++;
221 setFixedSlot(Slot_RemainingElements, Int32Value(remainingCount));
222 return remainingCount;
223 }
224 int32_t decreaseRemainingCount() {
225 int32_t remainingCount = getFixedSlot(Slot_RemainingElements).toInt32();
226 remainingCount--;
227 MOZ_ASSERT(remainingCount >= 0, "unpaired calls to decreaseRemainingCount");
228 setFixedSlot(Slot_RemainingElements, Int32Value(remainingCount));
229 return remainingCount;
230 }
231
232 static PromiseCombinatorDataHolder* New(
233 JSContext* cx, HandleObject resultPromise,
234 Handle<PromiseCombinatorElements> elements, HandleObject resolveOrReject);
235 };
236
237 const JSClass PromiseCombinatorDataHolder::class_ = {
238 "PromiseCombinatorDataHolder",
239 JSCLASS_HAS_RESERVED_SLOTS(SlotsCount),
240 };
241
242 // Smart pointer to the "F.[[Values]]" part of the state of a Promise.all or
243 // Promise.allSettled invocation, or the "F.[[Errors]]" part of the state of a
244 // Promise.any invocation. Copes with compartment issues when setting an
245 // element.
246 struct MOZ_STACK_CLASS PromiseCombinatorElements final {
247 // Object value holding the elements array. The object can be a wrapper.
248 Value value;
249
250 // Unwrapped elements array. May not belong to the current compartment!
251 ArrayObject* unwrappedArray = nullptr;
252
253 // Set to true if the |setElement| method needs to wrap its input value.
254 bool setElementNeedsWrapping = false;
255
256 PromiseCombinatorElements() = default;
257
258 void trace(JSTracer* trc);
259 };
260
261 void PromiseCombinatorElements::trace(JSTracer* trc) {
262 TraceRoot(trc, &value, "PromiseCombinatorElements::value");
263 if (unwrappedArray) {
264 TraceRoot(trc, &unwrappedArray,
265 "PromiseCombinatorElements::unwrappedArray");
266 }
267 }
268
269 namespace js {
270
271 template <typename Wrapper>
272 class WrappedPtrOperations<PromiseCombinatorElements, Wrapper> {
273 const PromiseCombinatorElements& elements() const {
274 return static_cast<const Wrapper*>(this)->get();
275 }
276
277 public:
278 HandleValue value() const {
279 return HandleValue::fromMarkedLocation(&elements().value);
280 }
281
282 Handle<ArrayObject*> unwrappedArray() const {
283 return Handle<ArrayObject*>::fromMarkedLocation(&elements().unwrappedArray);
284 }
285 };
286
287 template <typename Wrapper>
288 class MutableWrappedPtrOperations<PromiseCombinatorElements, Wrapper>
289 : public WrappedPtrOperations<PromiseCombinatorElements, Wrapper> {
290 PromiseCombinatorElements& elements() {
291 return static_cast<Wrapper*>(this)->get();
292 }
293
294 public:
295 MutableHandleValue value() {
296 return MutableHandleValue::fromMarkedLocation(&elements().value);
297 }
298
299 MutableHandle<ArrayObject*> unwrappedArray() {
300 return MutableHandle<ArrayObject*>::fromMarkedLocation(
301 &elements().unwrappedArray);
302 }
303
304 void initialize(ArrayObject* arrayObj) {
305 unwrappedArray().set(arrayObj);
306 value().setObject(*arrayObj);
307
308 // |needsWrapping| isn't tracked here, because all modifications on the
309 // initial elements don't require any wrapping.
310 }
311
312 void initialize(PromiseCombinatorDataHolder* data, ArrayObject* arrayObj,
313 bool needsWrapping) {
314 unwrappedArray().set(arrayObj);
315 value().set(data->valuesArray());
316 elements().setElementNeedsWrapping = needsWrapping;
317 }
318
319 [[nodiscard]] bool pushUndefined(JSContext* cx) {
320 // Helper for the AutoRealm we need to work with |array|. We mostly do this
321 // for performance; we could go ahead and do the define via a cross-
322 // compartment proxy instead...
323 AutoRealm ar(cx, unwrappedArray());
324
325 Handle<ArrayObject*> arrayObj = unwrappedArray();
326 return js::NewbornArrayPush(cx, arrayObj, UndefinedValue());
327 }
328
329 // `Promise.all` Resolve Element Functions
330 // Step 9. Set values[index] to x.
331 //
332 // `Promise.allSettled` Resolve Element Functions
333 // `Promise.allSettled` Reject Element Functions
334 // Step 12. Set values[index] to obj.
335 //
336 // `Promise.any` Reject Element Functions
337 // Step 9. Set errors[index] to x.
338 //
339 // These handler functions are always created in the compartment of the
340 // Promise.all/allSettled/any function, which isn't necessarily the same
341 // compartment as unwrappedArray as explained in NewPromiseCombinatorElements.
342 // So before storing |val| we may need to enter unwrappedArray's compartment.
343 [[nodiscard]] bool setElement(JSContext* cx, uint32_t index,
344 HandleValue val) {
345 // The index is guaranteed to be initialized to `undefined`.
346 MOZ_ASSERT(unwrappedArray()->getDenseElement(index).isUndefined());
347
348 if (elements().setElementNeedsWrapping) {
349 AutoRealm ar(cx, unwrappedArray());
350
351 RootedValue rootedVal(cx, val);
352 if (!cx->compartment()->wrap(cx, &rootedVal)) {
353 return false;
354 }
355 unwrappedArray()->setDenseElement(index, rootedVal);
356 } else {
357 unwrappedArray()->setDenseElement(index, val);
358 }
359 return true;
360 }
361 };
362
363 } // namespace js
364
365 PromiseCombinatorDataHolder* PromiseCombinatorDataHolder::New(
366 JSContext* cx, HandleObject resultPromise,
367 Handle<PromiseCombinatorElements> elements, HandleObject resolveOrReject) {
368 auto* dataHolder = NewBuiltinClassInstance<PromiseCombinatorDataHolder>(cx);
369 if (!dataHolder) {
370 return nullptr;
371 }
372
373 cx->check(resultPromise);
374 cx->check(elements.value());
375 cx->check(resolveOrReject);
376
377 dataHolder->setFixedSlot(Slot_Promise, ObjectValue(*resultPromise));
378 dataHolder->setFixedSlot(Slot_RemainingElements, Int32Value(1));
379 dataHolder->setFixedSlot(Slot_ValuesArray, elements.value());
380 dataHolder->setFixedSlot(Slot_ResolveOrRejectFunction,
381 ObjectValue(*resolveOrReject));
382 return dataHolder;
383 }
384
385 namespace {
386 // Generator used by PromiseObject::getID.
387 mozilla::Atomic<uint64_t> gIDGenerator(0);
388 } // namespace
389
390 // Returns true if the following properties haven't been mutated:
391 // - On the original Promise.prototype object: "constructor" and "then"
392 // - On the original Promise constructor: "resolve" and @@species
393 static bool HasDefaultPromiseProperties(JSContext* cx) {
394 return cx->realm()->realmFuses.optimizePromiseLookupFuse.intact();
395 }
396
397 static bool IsPromiseWithDefaultProperties(PromiseObject* promise,
398 JSContext* cx) {
399 if (!HasDefaultPromiseProperties(cx)) {
400 return false;
401 }
402
403 // Ensure the promise's prototype is the original Promise.prototype object.
404 JSObject* proto = cx->global()->maybeGetPrototype(JSProto_Promise);
405 if (!proto || promise->staticPrototype() != proto) {
406 return false;
407 }
408
409 // Ensure `promise` doesn't define any own properties. This serves as a
410 // quick check to make sure `promise` doesn't define an own "constructor"
411 // or "then" property which may shadow Promise.prototype.constructor or
412 // Promise.prototype.then.
413 return promise->empty();
414 }
415
416 class PromiseDebugInfo : public NativeObject {
417 private:
418 enum Slots {
419 Slot_AllocationSite,
420 Slot_ResolutionSite,
421 Slot_AllocationTime,
422 Slot_ResolutionTime,
423 Slot_Id,
424 SlotCount
425 };
426
427 public:
428 static const JSClass class_;
429 static PromiseDebugInfo* create(JSContext* cx,
430 Handle<PromiseObject*> promise) {
431 Rooted<PromiseDebugInfo*> debugInfo(
432 cx, NewBuiltinClassInstance<PromiseDebugInfo>(cx));
433 if (!debugInfo) {
434 return nullptr;
435 }
436
437 RootedObject stack(cx);
438 if (!JS::CaptureCurrentStack(cx, &stack,
439 JS::StackCapture(JS::AllFrames()))) {
440 return nullptr;
441 }
442 debugInfo->setFixedSlot(Slot_AllocationSite, ObjectOrNullValue(stack));
443 debugInfo->setFixedSlot(Slot_ResolutionSite, NullValue());
444 debugInfo->setFixedSlot(Slot_AllocationTime,
445 DoubleValue(MillisecondsSinceStartup()));
446 debugInfo->setFixedSlot(Slot_ResolutionTime, NumberValue(0));
447 promise->setFixedSlot(PromiseSlot_DebugInfo, ObjectValue(*debugInfo));
448
449 return debugInfo;
450 }
451
452 static PromiseDebugInfo* FromPromise(PromiseObject* promise) {
453 Value val = promise->getFixedSlot(PromiseSlot_DebugInfo);
454 if (val.isObject()) {
455 return &val.toObject().as<PromiseDebugInfo>();
456 }
457 return nullptr;
458 }
459
460 /**
461 * Returns the given PromiseObject's process-unique ID.
462 * The ID is lazily assigned when first queried, and then either stored
463 * in the DebugInfo slot if no debug info was recorded for this Promise,
464 * or in the Id slot of the DebugInfo object.
465 */
466 static uint64_t id(PromiseObject* promise) {
467 Value idVal(promise->getFixedSlot(PromiseSlot_DebugInfo));
468 if (idVal.isUndefined()) {
469 idVal.setDouble(++gIDGenerator);
470 promise->setFixedSlot(PromiseSlot_DebugInfo, idVal);
471 } else if (idVal.isObject()) {
472 PromiseDebugInfo* debugInfo = FromPromise(promise);
473 idVal = debugInfo->getFixedSlot(Slot_Id);
474 if (idVal.isUndefined()) {
475 idVal.setDouble(++gIDGenerator);
476 debugInfo->setFixedSlot(Slot_Id, idVal);
477 }
478 }
479 return uint64_t(idVal.toNumber());
480 }
481
482 double allocationTime() {
483 return getFixedSlot(Slot_AllocationTime).toNumber();
484 }
485 double resolutionTime() {
486 return getFixedSlot(Slot_ResolutionTime).toNumber();
487 }
488 JSObject* allocationSite() {
489 return getFixedSlot(Slot_AllocationSite).toObjectOrNull();
490 }
491 JSObject* resolutionSite() {
492 return getFixedSlot(Slot_ResolutionSite).toObjectOrNull();
493 }
494
495 // The |unwrappedRejectionStack| parameter should only be set on promise
496 // rejections and should be the stack of the exception that caused the promise
497 // to be rejected. If the |unwrappedRejectionStack| is null, the current stack
498 // will be used instead. This is also the default behavior for fulfilled
499 // promises.
500 static void setResolutionInfo(JSContext* cx, Handle<PromiseObject*> promise,
501 Handle<SavedFrame*> unwrappedRejectionStack) {
502 MOZ_ASSERT_IF(unwrappedRejectionStack,
503 promise->state() == JS::PromiseState::Rejected);
504
505 if (!JS::IsAsyncStackCaptureEnabledForRealm(cx)) {
506 return;
507 }
508
509 // If async stacks weren't enabled and the Promise's global wasn't a
510 // debuggee when the Promise was created, we won't have a debugInfo
511 // object. We still want to capture the resolution stack, so we
512 // create the object now and change it's slots' values around a bit.
513 Rooted<PromiseDebugInfo*> debugInfo(cx, FromPromise(promise));
514 if (!debugInfo) {
515 RootedValue idVal(cx, promise->getFixedSlot(PromiseSlot_DebugInfo));
516 debugInfo = create(cx, promise);
517 if (!debugInfo) {
518 cx->clearPendingException();
519 return;
520 }
521
522 // The current stack was stored in the AllocationSite slot, move
523 // it to ResolutionSite as that's what it really is.
524 debugInfo->setFixedSlot(Slot_ResolutionSite,
525 debugInfo->getFixedSlot(Slot_AllocationSite));
526 debugInfo->setFixedSlot(Slot_AllocationSite, NullValue());
527
528 // There's no good default for a missing AllocationTime, so
529 // instead of resetting that, ensure that it's the same as
530 // ResolutionTime, so that the diff shows as 0, which isn't great,
531 // but bearable.
532 debugInfo->setFixedSlot(Slot_ResolutionTime,
533 debugInfo->getFixedSlot(Slot_AllocationTime));
534
535 // The Promise's ID might've been queried earlier, in which case
536 // it's stored in the DebugInfo slot. We saved that earlier, so
537 // now we can store it in the right place (or leave it as
538 // undefined if it wasn't ever initialized.)
539 debugInfo->setFixedSlot(Slot_Id, idVal);
540 return;
541 }
542
543 RootedObject stack(cx, unwrappedRejectionStack);
544 if (stack) {
545 // The exception stack is always unwrapped so it might be in
546 // a different compartment.
547 if (!cx->compartment()->wrap(cx, &stack)) {
548 cx->clearPendingException();
549 return;
550 }
551 } else {
552 if (!JS::CaptureCurrentStack(cx, &stack,
553 JS::StackCapture(JS::AllFrames()))) {
554 cx->clearPendingException();
555 return;
556 }
557 }
558
559 debugInfo->setFixedSlot(Slot_ResolutionSite, ObjectOrNullValue(stack));
560 debugInfo->setFixedSlot(Slot_ResolutionTime,
561 DoubleValue(MillisecondsSinceStartup()));
562 }
563
564 #if defined(DEBUG) || defined(JS_JITSPEW)
565 void dumpOwnFields(js::JSONPrinter& json) const;
566 #endif
567 };
568
569 const JSClass PromiseDebugInfo::class_ = {
570 "PromiseDebugInfo",
571 JSCLASS_HAS_RESERVED_SLOTS(SlotCount),
572 };
573
574 double PromiseObject::allocationTime() {
575 auto debugInfo = PromiseDebugInfo::FromPromise(this);
576 if (debugInfo) {
577 return debugInfo->allocationTime();
578 }
579 return 0;
580 }
581
582 double PromiseObject::resolutionTime() {
583 auto debugInfo = PromiseDebugInfo::FromPromise(this);
584 if (debugInfo) {
585 return debugInfo->resolutionTime();
586 }
587 return 0;
588 }
589
590 JSObject* PromiseObject::allocationSite() {
591 auto debugInfo = PromiseDebugInfo::FromPromise(this);
592 if (debugInfo) {
593 return debugInfo->allocationSite();
594 }
595 return nullptr;
596 }
597
598 JSObject* PromiseObject::resolutionSite() {
599 auto debugInfo = PromiseDebugInfo::FromPromise(this);
600 if (debugInfo) {
601 JSObject* site = debugInfo->resolutionSite();
602 if (site && !JS_IsDeadWrapper(site)) {
603 MOZ_ASSERT(UncheckedUnwrap(site)->is<SavedFrame>());
604 return site;
605 }
606 }
607 return nullptr;
608 }
609
610 /**
611 * Wrapper for GetAndClearExceptionAndStack that handles cases where
612 * no exception is pending, but an error occurred.
613 * This can be the case if an OOM was encountered while throwing the error.
614 */
615 static bool MaybeGetAndClearExceptionAndStack(
616 JSContext* cx, MutableHandleValue rval, MutableHandle<SavedFrame*> stack) {
617 if (!cx->isExceptionPending()) {
618 return false;
619 }
620
621 return GetAndClearExceptionAndStack(cx, rval, stack);
622 }
623
624 [[nodiscard]] static bool CallPromiseRejectFunction(
625 JSContext* cx, HandleObject rejectFun, HandleValue reason,
626 HandleObject promiseObj, Handle<SavedFrame*> unwrappedRejectionStack,
627 UnhandledRejectionBehavior behavior);
628
629 /**
630 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
631 *
632 * IfAbruptRejectPromise ( value, capability )
633 * https://tc39.es/ecma262/#sec-ifabruptrejectpromise
634 *
635 * Steps 1.a-b.
636 *
637 * Extracting all of this internal spec algorithm into a helper function would
638 * be tedious, so the check in step 1 and the entirety of step 2 aren't
639 * included.
640 */
641 bool js::AbruptRejectPromise(JSContext* cx, CallArgs& args,
642 HandleObject promiseObj, HandleObject reject) {
643 // Step 1.a. Perform
644 // ? Call(capability.[[Reject]], undefined, « value.[[Value]] »).
645 RootedValue reason(cx);
646 Rooted<SavedFrame*> stack(cx);
647 if (!MaybeGetAndClearExceptionAndStack(cx, &reason, &stack)) {
648 return false;
649 }
650
651 if (!CallPromiseRejectFunction(cx, reject, reason, promiseObj, stack,
652 UnhandledRejectionBehavior::Report)) {
653 return false;
654 }
655
656 // Step 1.b. Return capability.[[Promise]].
657 args.rval().setObject(*promiseObj);
658 return true;
659 }
660
661 static bool AbruptRejectPromise(JSContext* cx, CallArgs& args,
662 Handle<PromiseCapability> capability) {
663 return AbruptRejectPromise(cx, args, capability.promise(),
664 capability.reject());
665 }
666
667 enum ReactionRecordSlots {
668 // This is the promise-like object that gets resolved with the result of this
669 // reaction, if any. If this reaction record was created with .then or .catch,
670 // this is the promise that .then or .catch returned.
671 //
672 // The spec says that a PromiseReaction record has a [[Capability]] field
673 // whose value is either undefined or a PromiseCapability record, but we just
674 // store the PromiseCapability's fields directly in this object. This is the
675 // capability's [[Promise]] field; its [[Resolve]] and [[Reject]] fields are
676 // stored in ReactionRecordSlot_Resolve and ReactionRecordSlot_Reject.
677 //
678 // This can be 'null' in reaction records created for a few situations:
679 //
680 // - When you resolve one promise to another. When you pass a promise P1 to
681 // the 'fulfill' function of a promise P2, so that resolving P1 resolves P2
682 // in the same way, P1 gets a reaction record with the
683 // REACTION_FLAG_DEFAULT_RESOLVING_HANDLER flag set and whose
684 // ReactionRecordSlot_GeneratorOrPromiseToResolve slot holds P2.
685 //
686 // - When you await a promise. When an async function or generator awaits a
687 // value V, then the await expression generates an internal promise P,
688 // resolves it to V, and then gives P a reaction record with the
689 // REACTION_FLAG_ASYNC_FUNCTION or REACTION_FLAG_ASYNC_GENERATOR flag set
690 // and whose ReactionRecordSlot_GeneratorOrPromiseToResolve slot holds the
691 // generator object. (Typically V is a promise, so resolving P to V gives V
692 // a REACTION_FLAGS_DEFAULT_RESOLVING_HANDLER reaction record as described
693 // above.)
694 //
695 // - When JS::AddPromiseReactions{,IgnoringUnhandledRejection} cause the
696 // reaction to be created. (These functions act as if they had created a
697 // promise to invoke the appropriate provided reaction function, without
698 // actually allocating a promise for them.)
699 ReactionRecordSlot_Promise = 0,
700
701 // The [[Handler]] field(s) of a PromiseReaction record. We create a
702 // single reaction record for fulfillment and rejection, therefore our
703 // PromiseReaction implementation needs two [[Handler]] fields.
704 //
705 // The slot value is either a callable object, an integer constant from
706 // the |PromiseHandler| enum, or null. If the value is null, either the
707 // REACTION_FLAG_DEBUGGER_DUMMY or the
708 // REACTION_FLAG_DEFAULT_RESOLVING_HANDLER flag must be set.
709 //
710 // After setting the target state for a PromiseReaction, the slot of the
711 // no longer used handler gets reused to store the argument of the active
712 // handler.
713 ReactionRecordSlot_OnFulfilled,
714 ReactionRecordSlot_OnRejectedArg = ReactionRecordSlot_OnFulfilled,
715 ReactionRecordSlot_OnRejected,
716 ReactionRecordSlot_OnFulfilledArg = ReactionRecordSlot_OnRejected,
717
718 // The functions to resolve or reject the promise. Matches the
719 // [[Capability]].[[Resolve]] and [[Capability]].[[Reject]] fields from
720 // the spec.
721 //
722 // The slot values are either callable objects or null, but the latter
723 // case is only allowed if the promise is either a built-in Promise object
724 // or null.
725 ReactionRecordSlot_Resolve,
726 ReactionRecordSlot_Reject,
727
728 // The host defined data for this reaction record. Can be null.
729 // See step 5 in https://html.spec.whatwg.org/#hostmakejobcallback
730 ReactionRecordSlot_HostDefinedData,
731
732 // Bitmask of the REACTION_FLAG values.
733 ReactionRecordSlot_Flags,
734
735 // Additional slot to store extra data for specific reaction record types.
736 //
737 // - When the REACTION_FLAG_ASYNC_FUNCTION flag is set, this slot stores
738 // the (internal) generator object for this promise reaction.
739 // - When the REACTION_FLAG_ASYNC_GENERATOR flag is set, this slot stores
740 // the async generator object for this promise reaction.
741 // - When the REACTION_FLAG_DEFAULT_RESOLVING_HANDLER flag is set, this
742 // slot stores the promise to resolve when conceptually "calling" the
743 // OnFulfilled or OnRejected handlers.
744 ReactionRecordSlot_GeneratorOrPromiseToResolve,
745
746 ReactionRecordSlots,
747 };
748
749 /**
750 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
751 *
752 * PromiseReaction Records
753 * https://tc39.es/ecma262/#sec-promisereaction-records
754 */
755 class PromiseReactionRecord : public NativeObject {
756 // If this flag is set, this reaction record is already enqueued to the
757 // job queue, and the spec's [[Type]] field is represented by
758 // REACTION_FLAG_FULFILLED flag.
759 //
760 // If this flag isn't yet set, [[Type]] field is undefined.
761 static constexpr uint32_t REACTION_FLAG_RESOLVED = 0x1;
762
763 // This bit is valid only when REACTION_FLAG_RESOLVED flag is set.
764 //
765 // If this flag is set, [[Type]] field is Fulfill.
766 // If this flag isn't set, [[Type]] field is Reject.
767 static constexpr uint32_t REACTION_FLAG_FULFILLED = 0x2;
768
769 // If this flag is set, this reaction record is created for resolving
770 // one promise P1 to another promise P2, and
771 // ReactionRecordSlot_GeneratorOrPromiseToResolve slot holds P2.
772 static constexpr uint32_t REACTION_FLAG_DEFAULT_RESOLVING_HANDLER = 0x4;
773
774 // If this flag is set, this reaction record is created for async function
775 // and ReactionRecordSlot_GeneratorOrPromiseToResolve slot holds
776 // internal generator object of the async function.
777 static constexpr uint32_t REACTION_FLAG_ASYNC_FUNCTION = 0x8;
778
779 // If this flag is set, this reaction record is created for async generator
780 // and ReactionRecordSlot_GeneratorOrPromiseToResolve slot holds
781 // the async generator object of the async generator.
782 static constexpr uint32_t REACTION_FLAG_ASYNC_GENERATOR = 0x10;
783
784 // If this flag is set, this reaction record is created only for providing
785 // information to debugger.
786 static constexpr uint32_t REACTION_FLAG_DEBUGGER_DUMMY = 0x20;
787
788 // This bit is valid only when the promise object is optimized out
789 // for the reaction.
790 //
791 // If this flag is set, unhandled rejection should be ignored.
792 // Otherwise, promise object should be created on-demand for unhandled
793 // rejection.
794 static constexpr uint32_t REACTION_FLAG_IGNORE_UNHANDLED_REJECTION = 0x40;
795
796 template <typename KnownF, typename UnknownF>
797 static void forEachReactionFlag(uint32_t flags, KnownF known,
798 UnknownF unknown);
799
800 void setFlagOnInitialState(uint32_t flag) {
801 int32_t flags = this->flags();
802 MOZ_ASSERT(flags == 0, "Can't modify with non-default flags");
803 flags |= flag;
804 setFixedSlot(ReactionRecordSlot_Flags, Int32Value(flags));
805 }
806
807 uint32_t handlerSlot() {
808 MOZ_ASSERT(targetState() != JS::PromiseState::Pending);
809 return targetState() == JS::PromiseState::Fulfilled
810 ? ReactionRecordSlot_OnFulfilled
811 : ReactionRecordSlot_OnRejected;
812 }
813
814 uint32_t handlerArgSlot() {
815 MOZ_ASSERT(targetState() != JS::PromiseState::Pending);
816 return targetState() == JS::PromiseState::Fulfilled
817 ? ReactionRecordSlot_OnFulfilledArg
818 : ReactionRecordSlot_OnRejectedArg;
819 }
820
821 public:
822 static const JSClass class_;
823
824 JSObject* promise() const {
825 return getFixedSlot(ReactionRecordSlot_Promise).toObjectOrNull();
826 }
827
828 int32_t flags() const {
829 return getFixedSlot(ReactionRecordSlot_Flags).toInt32();
830 }
831
832 JS::PromiseState targetState() const {
833 int32_t flags = this->flags();
834 if (!(flags & REACTION_FLAG_RESOLVED)) {
835 return JS::PromiseState::Pending;
836 }
837 return flags & REACTION_FLAG_FULFILLED ? JS::PromiseState::Fulfilled
838 : JS::PromiseState::Rejected;
839 }
840 void setTargetStateAndHandlerArg(JS::PromiseState state, const Value& arg) {
841 MOZ_ASSERT(targetState() == JS::PromiseState::Pending);
842 MOZ_ASSERT(state != JS::PromiseState::Pending,
843 "Can't revert a reaction to pending.");
844
845 int32_t flags = this->flags();
846 flags |= REACTION_FLAG_RESOLVED;
847 if (state == JS::PromiseState::Fulfilled) {
848 flags |= REACTION_FLAG_FULFILLED;
849 }
850
851 setFixedSlot(ReactionRecordSlot_Flags, Int32Value(flags));
852 setFixedSlot(handlerArgSlot(), arg);
853 }
854
855 void setShouldIgnoreUnhandledRejection() {
856 setFlagOnInitialState(REACTION_FLAG_IGNORE_UNHANDLED_REJECTION);
857 }
858 UnhandledRejectionBehavior unhandledRejectionBehavior() const {
859 int32_t flags = this->flags();
860 return (flags & REACTION_FLAG_IGNORE_UNHANDLED_REJECTION)
861 ? UnhandledRejectionBehavior::Ignore
862 : UnhandledRejectionBehavior::Report;
863 }
864
865 void setIsDefaultResolvingHandler(PromiseObject* promiseToResolve) {
866 setFlagOnInitialState(REACTION_FLAG_DEFAULT_RESOLVING_HANDLER);
867 setFixedSlot(ReactionRecordSlot_GeneratorOrPromiseToResolve,
868 ObjectValue(*promiseToResolve));
869 }
870 bool isDefaultResolvingHandler() const {
871 int32_t flags = this->flags();
872 return flags & REACTION_FLAG_DEFAULT_RESOLVING_HANDLER;
873 }
874 PromiseObject* defaultResolvingPromise() {
875 MOZ_ASSERT(isDefaultResolvingHandler());
876 const Value& promiseToResolve =
877 getFixedSlot(ReactionRecordSlot_GeneratorOrPromiseToResolve);
878 return &promiseToResolve.toObject().as<PromiseObject>();
879 }
880
881 void setIsAsyncFunction(AsyncFunctionGeneratorObject* genObj) {
882 setFlagOnInitialState(REACTION_FLAG_ASYNC_FUNCTION);
883 setFixedSlot(ReactionRecordSlot_GeneratorOrPromiseToResolve,
884 ObjectValue(*genObj));
885 }
886 bool isAsyncFunction() const {
887 int32_t flags = this->flags();
888 return flags & REACTION_FLAG_ASYNC_FUNCTION;
889 }
890 AsyncFunctionGeneratorObject* asyncFunctionGenerator() {
891 MOZ_ASSERT(isAsyncFunction());
892 const Value& generator =
893 getFixedSlot(ReactionRecordSlot_GeneratorOrPromiseToResolve);
894 return &generator.toObject().as<AsyncFunctionGeneratorObject>();
895 }
896
897 void setIsAsyncGenerator(AsyncGeneratorObject* generator) {
898 setFlagOnInitialState(REACTION_FLAG_ASYNC_GENERATOR);
899 setFixedSlot(ReactionRecordSlot_GeneratorOrPromiseToResolve,
900 ObjectValue(*generator));
901 }
902 bool isAsyncGenerator() const {
903 int32_t flags = this->flags();
904 return flags & REACTION_FLAG_ASYNC_GENERATOR;
905 }
906 AsyncGeneratorObject* asyncGenerator() {
907 MOZ_ASSERT(isAsyncGenerator());
908 const Value& generator =
909 getFixedSlot(ReactionRecordSlot_GeneratorOrPromiseToResolve);
910 return &generator.toObject().as<AsyncGeneratorObject>();
911 }
912
913 void setIsDebuggerDummy() {
914 setFlagOnInitialState(REACTION_FLAG_DEBUGGER_DUMMY);
915 }
916 bool isDebuggerDummy() const {
917 int32_t flags = this->flags();
918 return flags & REACTION_FLAG_DEBUGGER_DUMMY;
919 }
920
921 Value handler() {
922 MOZ_ASSERT(targetState() != JS::PromiseState::Pending);
923 return getFixedSlot(handlerSlot());
924 }
925 Value handlerArg() {
926 MOZ_ASSERT(targetState() != JS::PromiseState::Pending);
927 return getFixedSlot(handlerArgSlot());
928 }
929
930 JSObject* getAndClearHostDefinedData() {
931 JSObject* obj =
932 getFixedSlot(ReactionRecordSlot_HostDefinedData).toObjectOrNull();
933 setFixedSlot(ReactionRecordSlot_HostDefinedData, UndefinedValue());
934 return obj;
935 }
936
937 #if defined(DEBUG) || defined(JS_JITSPEW)
938 void dumpOwnFields(js::JSONPrinter& json) const;
939 #endif
940 };
941
942 const JSClass PromiseReactionRecord::class_ = {
943 "PromiseReactionRecord",
944 JSCLASS_HAS_RESERVED_SLOTS(ReactionRecordSlots),
945 };
946
947 static void AddPromiseFlags(PromiseObject& promise, int32_t flag) {
948 int32_t flags = promise.flags();
949 promise.setFixedSlot(PromiseSlot_Flags, Int32Value(flags | flag));
950 }
951
952 static void RemovePromiseFlags(PromiseObject& promise, int32_t flag) {
953 int32_t flags = promise.flags();
954 promise.setFixedSlot(PromiseSlot_Flags, Int32Value(flags & ~flag));
955 }
956
957 static bool PromiseHasAnyFlag(PromiseObject& promise, int32_t flag) {
958 return promise.flags() & flag;
959 }
960
961 static bool ResolvePromiseFunction(JSContext* cx, unsigned argc, Value* vp);
962 static bool RejectPromiseFunction(JSContext* cx, unsigned argc, Value* vp);
963
964 static JSFunction* GetResolveFunctionFromReject(JSFunction* reject);
965 static JSFunction* GetRejectFunctionFromResolve(JSFunction* resolve);
966
967 #ifdef DEBUG
968
969 /**
970 * Returns Promise Resolve Function's [[AlreadyResolved]].[[Value]].
971 */
972 static bool IsAlreadyResolvedResolveFunction(JSFunction* resolveFun) {
973 MOZ_ASSERT(resolveFun->maybeNative() == ResolvePromiseFunction);
974
975 bool alreadyResolved =
976 resolveFun->getExtendedSlot(ResolveFunctionSlot_Promise).isUndefined();
977
978 // Other slots should agree.
979 if (alreadyResolved) {
980 MOZ_ASSERT(resolveFun->getExtendedSlot(ResolveFunctionSlot_RejectFunction)
981 .isUndefined());
982 } else {
983 JSFunction* rejectFun = GetRejectFunctionFromResolve(resolveFun);
984 MOZ_ASSERT(
985 !rejectFun->getExtendedSlot(RejectFunctionSlot_Promise).isUndefined());
986 MOZ_ASSERT(!rejectFun->getExtendedSlot(RejectFunctionSlot_ResolveFunction)
987 .isUndefined());
988 }
989
990 return alreadyResolved;
991 }
992
993 /**
994 * Returns Promise Reject Function's [[AlreadyResolved]].[[Value]].
995 */
996 static bool IsAlreadyResolvedRejectFunction(JSFunction* rejectFun) {
997 MOZ_ASSERT(rejectFun->maybeNative() == RejectPromiseFunction);
998
999 bool alreadyResolved =
1000 rejectFun->getExtendedSlot(RejectFunctionSlot_Promise).isUndefined();
1001
1002 // Other slots should agree.
1003 if (alreadyResolved) {
1004 MOZ_ASSERT(rejectFun->getExtendedSlot(RejectFunctionSlot_ResolveFunction)
1005 .isUndefined());
1006 } else {
1007 JSFunction* resolveFun = GetResolveFunctionFromReject(rejectFun);
1008 MOZ_ASSERT(!resolveFun->getExtendedSlot(ResolveFunctionSlot_Promise)
1009 .isUndefined());
1010 MOZ_ASSERT(!resolveFun->getExtendedSlot(ResolveFunctionSlot_RejectFunction)
1011 .isUndefined());
1012 }
1013
1014 return alreadyResolved;
1015 }
1016
1017 #endif // DEBUG
1018
1019 /**
1020 * Set Promise Resolve Function's and Promise Reject Function's
1021 * [[AlreadyResolved]].[[Value]] to true.
1022 *
1023 * `resolutionFun` can be either of them.
1024 */
1025 static void SetAlreadyResolvedResolutionFunction(JSFunction* resolutionFun) {
1026 JSFunction* resolve;
1027 JSFunction* reject;
1028 if (resolutionFun->maybeNative() == ResolvePromiseFunction) {
1029 resolve = resolutionFun;
1030 reject = GetRejectFunctionFromResolve(resolutionFun);
1031 } else {
1032 resolve = GetResolveFunctionFromReject(resolutionFun);
1033 reject = resolutionFun;
1034 }
1035
1036 resolve->setExtendedSlot(ResolveFunctionSlot_Promise, UndefinedValue());
1037 resolve->setExtendedSlot(ResolveFunctionSlot_RejectFunction,
1038 UndefinedValue());
1039
1040 reject->setExtendedSlot(RejectFunctionSlot_Promise, UndefinedValue());
1041 reject->setExtendedSlot(RejectFunctionSlot_ResolveFunction, UndefinedValue());
1042
1043 MOZ_ASSERT(IsAlreadyResolvedResolveFunction(resolve));
1044 MOZ_ASSERT(IsAlreadyResolvedRejectFunction(reject));
1045 }
1046
1047 /**
1048 * Returns true if given promise is created by
1049 * CreatePromiseObjectWithoutResolutionFunctions.
1050 */
1051 bool js::IsPromiseWithDefaultResolvingFunction(PromiseObject* promise) {
1052 return PromiseHasAnyFlag(*promise, PROMISE_FLAG_DEFAULT_RESOLVING_FUNCTIONS);
1053 }
1054
1055 /**
1056 * Returns Promise Resolve Function's [[AlreadyResolved]].[[Value]] for
1057 * a promise created by CreatePromiseObjectWithoutResolutionFunctions.
1058 */
1059 static bool IsAlreadyResolvedPromiseWithDefaultResolvingFunction(
1060 PromiseObject* promise) {
1061 MOZ_ASSERT(IsPromiseWithDefaultResolvingFunction(promise));
1062
1063 if (promise->as<PromiseObject>().state() != JS::PromiseState::Pending) {
1064 MOZ_ASSERT(PromiseHasAnyFlag(
1065 *promise, PROMISE_FLAG_DEFAULT_RESOLVING_FUNCTIONS_ALREADY_RESOLVED));
1066 return true;
1067 }
1068
1069 return PromiseHasAnyFlag(
1070 *promise, PROMISE_FLAG_DEFAULT_RESOLVING_FUNCTIONS_ALREADY_RESOLVED);
1071 }
1072
1073 /**
1074 * Set Promise Resolve Function's [[AlreadyResolved]].[[Value]] to true for
1075 * a promise created by CreatePromiseObjectWithoutResolutionFunctions.
1076 */
1077 void js::SetAlreadyResolvedPromiseWithDefaultResolvingFunction(
1078 PromiseObject* promise) {
1079 MOZ_ASSERT(IsPromiseWithDefaultResolvingFunction(promise));
1080
1081 promise->setFixedSlot(
1082 PromiseSlot_Flags,
1083 JS::Int32Value(
1084 promise->flags() |
1085 PROMISE_FLAG_DEFAULT_RESOLVING_FUNCTIONS_ALREADY_RESOLVED));
1086 }
1087
1088 /**
1089 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
1090 *
1091 * CreateResolvingFunctions ( promise )
1092 * https://tc39.es/ecma262/#sec-createresolvingfunctions
1093 */
1094 [[nodiscard]] static MOZ_ALWAYS_INLINE bool CreateResolvingFunctions(
1095 JSContext* cx, HandleObject promise, MutableHandleObject resolveFn,
1096 MutableHandleObject rejectFn) {
1097 // Step 1. Let alreadyResolved be the Record { [[Value]]: false }.
1098 // (implicit, see steps 5-6, 10-11 below)
1099
1100 // Step 2. Let stepsResolve be the algorithm steps defined in Promise Resolve
1101 // Functions.
1102 // Step 3. Let lengthResolve be the number of non-optional parameters of the
1103 // function definition in Promise Resolve Functions.
1104 // Step 4. Let resolve be
1105 // ! CreateBuiltinFunction(stepsResolve, lengthResolve, "",
1106 // « [[Promise]], [[AlreadyResolved]] »).
1107 Handle<PropertyName*> funName = cx->names().empty_;
1108 resolveFn.set(NewNativeFunction(cx, ResolvePromiseFunction, 1, funName,
1109 gc::AllocKind::FUNCTION_EXTENDED,
1110 GenericObject));
1111 if (!resolveFn) {
1112 return false;
1113 }
1114
1115 // Step 7. Let stepsReject be the algorithm steps defined in Promise Reject
1116 // Functions.
1117 // Step 8. Let lengthReject be the number of non-optional parameters of the
1118 // function definition in Promise Reject Functions.
1119 // Step 9. Let reject be
1120 // ! CreateBuiltinFunction(stepsReject, lengthReject, "",
1121 // « [[Promise]], [[AlreadyResolved]] »).
1122 rejectFn.set(NewNativeFunction(cx, RejectPromiseFunction, 1, funName,
1123 gc::AllocKind::FUNCTION_EXTENDED,
1124 GenericObject));
1125 if (!rejectFn) {
1126 return false;
1127 }
1128
1129 JSFunction* resolveFun = &resolveFn->as<JSFunction>();
1130 JSFunction* rejectFun = &rejectFn->as<JSFunction>();
1131
1132 // Step 5. Set resolve.[[Promise]] to promise.
1133 // Step 6. Set resolve.[[AlreadyResolved]] to alreadyResolved.
1134 //
1135 // NOTE: We use these references as [[AlreadyResolved]].[[Value]].
1136 // See the comment in ResolveFunctionSlots for more details.
1137 resolveFun->initExtendedSlot(ResolveFunctionSlot_Promise,
1138 ObjectValue(*promise));
1139 resolveFun->initExtendedSlot(ResolveFunctionSlot_RejectFunction,
1140 ObjectValue(*rejectFun));
1141
1142 // Step 10. Set reject.[[Promise]] to promise.
1143 // Step 11. Set reject.[[AlreadyResolved]] to alreadyResolved.
1144 //
1145 // NOTE: We use these references as [[AlreadyResolved]].[[Value]].
1146 // See the comment in ResolveFunctionSlots for more details.
1147 rejectFun->initExtendedSlot(RejectFunctionSlot_Promise,
1148 ObjectValue(*promise));
1149 rejectFun->initExtendedSlot(RejectFunctionSlot_ResolveFunction,
1150 ObjectValue(*resolveFun));
1151
1152 MOZ_ASSERT(!IsAlreadyResolvedResolveFunction(resolveFun));
1153 MOZ_ASSERT(!IsAlreadyResolvedRejectFunction(rejectFun));
1154
1155 // Step 12. Return the Record { [[Resolve]]: resolve, [[Reject]]: reject }.
1156 return true;
1157 }
1158
1159 static bool IsSettledMaybeWrappedPromise(JSObject* promise) {
1160 if (IsProxy(promise)) {
1161 promise = UncheckedUnwrap(promise);
1162
1163 // Caller needs to handle dead wrappers.
1164 if (JS_IsDeadWrapper(promise)) {
1165 return false;
1166 }
1167 }
1168
1169 return promise->as<PromiseObject>().state() != JS::PromiseState::Pending;
1170 }
1171
1172 [[nodiscard]] static bool RejectMaybeWrappedPromise(
1173 JSContext* cx, HandleObject promiseObj, HandleValue reason,
1174 Handle<SavedFrame*> unwrappedRejectionStack);
1175
1176 /**
1177 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
1178 *
1179 * Promise Reject Functions
1180 * https://tc39.es/ecma262/#sec-promise-reject-functions
1181 */
1182 static bool RejectPromiseFunction(JSContext* cx, unsigned argc, Value* vp) {
1183 CallArgs args = CallArgsFromVp(argc, vp);
1184
1185 JSFunction* reject = &args.callee().as<JSFunction>();
1186 HandleValue reasonVal = args.get(0);
1187
1188 // Step 1. Let F be the active function object.
1189 // Step 2. Assert: F has a [[Promise]] internal slot whose value is an Object.
1190 // (implicit)
1191
1192 // Step 3. Let promise be F.[[Promise]].
1193 const Value& promiseVal = reject->getExtendedSlot(RejectFunctionSlot_Promise);
1194
1195 // Step 4. Let alreadyResolved be F.[[AlreadyResolved]].
1196 // Step 5. If alreadyResolved.[[Value]] is true, return undefined.
1197 //
1198 // If the Promise isn't available anymore, it has been resolved and the
1199 // reference to it removed to make it eligible for collection.
1200 bool alreadyResolved = promiseVal.isUndefined();
1201 MOZ_ASSERT(IsAlreadyResolvedRejectFunction(reject) == alreadyResolved);
1202 if (alreadyResolved) {
1203 args.rval().setUndefined();
1204 return true;
1205 }
1206
1207 RootedObject promise(cx, &promiseVal.toObject());
1208
1209 // Step 6. Set alreadyResolved.[[Value]] to true.
1210 SetAlreadyResolvedResolutionFunction(reject);
1211
1212 // In some cases the Promise reference on the resolution function won't
1213 // have been removed during resolution, so we need to check that here,
1214 // too.
1215 if (IsSettledMaybeWrappedPromise(promise)) {
1216 args.rval().setUndefined();
1217 return true;
1218 }
1219
1220 // Step 7. Return RejectPromise(promise, reason).
1221 if (!RejectMaybeWrappedPromise(cx, promise, reasonVal, nullptr)) {
1222 return false;
1223 }
1224 args.rval().setUndefined();
1225 return true;
1226 }
1227
1228 [[nodiscard]] static bool FulfillMaybeWrappedPromise(JSContext* cx,
1229 HandleObject promiseObj,
1230 HandleValue value_);
1231
1232 [[nodiscard]] static bool EnqueuePromiseResolveThenableJob(
1233 JSContext* cx, HandleValue promiseToResolve, HandleValue thenable,
1234 HandleValue thenVal);
1235
1236 [[nodiscard]] static bool EnqueuePromiseResolveThenableBuiltinJob(
1237 JSContext* cx, HandleObject promiseToResolve, HandleObject thenable);
1238
1239 static bool Promise_then_impl(JSContext* cx, HandleValue promiseVal,
1240 HandleValue onFulfilled, HandleValue onRejected,
1241 MutableHandleValue rval, bool rvalExplicitlyUsed);
1242
1243 // This is used to get the 'then' property off of an object, and report some
1244 // information back for telemetry purposes. When we no longer need this
1245 // telemetry this function can be removed and replaced with GetProperty
1246 bool GetThenValue(JSContext* cx, JS::Handle<JSObject*> obj,
1247 JS::Handle<JS::Value> reciever,
1248 JS::MutableHandle<Value> thenVal, bool* isOnProto,
1249 bool* isOnStandardProto, bool* isOnObjectProto) {
1250 MOZ_ASSERT(isOnProto && *isOnProto == false);
1251 MOZ_ASSERT(isOnStandardProto && *isOnStandardProto == false);
1252 MOZ_ASSERT(isOnObjectProto && *isOnObjectProto == false);
1253
1254 NativeObject* holder;
1255 PropertyResult prop;
1256
1257 // LookupProperty would be observable unforunately. If we can do the lookup,
1258 // then we can produce information, but otherwise we're left blind.
1259 // Fortunately, since this is purely for the purposes of telemetry, let's just
1260 // use Pure.
1261 RootedId thenId(cx, NameToId(cx->names().then));
1262
1263 // If we're doing the lookup on the original promise prototype we want to only
1264 // report telemetry if the value is not the original Promise.prototype.then
1265 //
1266 // We then need to defer until after the lookup to decide this.
1267 bool maybeOnPromiseProto = false;
1268 do {
1269 if (LookupPropertyPure(cx, obj, thenId, &holder, &prop)) {
1270 if (prop.isNotFound()) {
1271 break;
1272 }
1273
1274 if (holder != obj) {
1275 *isOnProto = true;
1276
1277 auto key = JS::IdentifyStandardPrototype(holder);
1278 if (key != JSProto_Null) {
1279 if (key == JSProto_Promise) {
1280 maybeOnPromiseProto = true;
1281 } else {
1282 *isOnStandardProto = true;
1283 if (key == JSProto_Object) {
1284 *isOnObjectProto = true;
1285 }
1286 }
1287 }
1288 }
1289 }
1290 } while (false);
1291
1292 if (!GetProperty(cx, obj, reciever, cx->names().then, thenVal)) {
1293 return false;
1294 }
1295
1296 if (maybeOnPromiseProto) {
1297 *isOnStandardProto = !IsNativeFunction(thenVal, Promise_then);
1298 }
1299
1300 return true;
1301 }
1302
1303 void ReportThenable(JSContext* cx, bool isOnProto, bool isOnStandardProto,
1304 bool isOnObjectProto) {
1305 cx->runtime()->setUseCounter(cx->global(), JSUseCounter::THENABLE_USE);
1306
1307 if (isOnProto) {
1308 cx->runtime()->setUseCounter(cx->global(),
1309 JSUseCounter::THENABLE_USE_PROTO);
1310 JS_LOG(thenable, Debug, "Thenable on proto");
1311 }
1312
1313 if (isOnStandardProto) {
1314 cx->runtime()->setUseCounter(cx->global(),
1315 JSUseCounter::THENABLE_USE_STANDARD_PROTO);
1316 JS_LOG(thenable, Info, "Thenable on standard proto");
1317 }
1318
1319 if (isOnObjectProto) {
1320 cx->runtime()->setUseCounter(cx->global(),
1321 JSUseCounter::THENABLE_USE_OBJECT_PROTO);
1322 JS_LOG(thenable, Info, "Thenable on Object.prototype");
1323 }
1324 }
1325
1326 /**
1327 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
1328 *
1329 * Promise Resolve Functions
1330 * https://tc39.es/ecma262/#sec-promise-resolve-functions
1331 *
1332 * Steps 7-15.
1333 */
1334 [[nodiscard]] bool js::ResolvePromiseInternal(
1335 JSContext* cx, JS::Handle<JSObject*> promise,
1336 JS::Handle<JS::Value> resolutionVal) {
1337 cx->check(promise, resolutionVal);
1338 MOZ_ASSERT(!IsSettledMaybeWrappedPromise(promise));
1339
1340 // (reordered)
1341 // Step 8. If Type(resolution) is not Object, then
1342 if (!resolutionVal.isObject()) {
1343 // Step 8.a. Return FulfillPromise(promise, resolution).
1344 return FulfillMaybeWrappedPromise(cx, promise, resolutionVal);
1345 }
1346
1347 RootedObject resolution(cx, &resolutionVal.toObject());
1348
1349 // Step 7. If SameValue(resolution, promise) is true, then
1350 if (resolution == promise) {
1351 // Step 7.a. Let selfResolutionError be a newly created TypeError object.
1352 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1353 JSMSG_CANNOT_RESOLVE_PROMISE_WITH_ITSELF);
1354 RootedValue selfResolutionError(cx);
1355 Rooted<SavedFrame*> stack(cx);
1356 if (!MaybeGetAndClearExceptionAndStack(cx, &selfResolutionError, &stack)) {
1357 return false;
1358 }
1359
1360 // Step 7.b. Return RejectPromise(promise, selfResolutionError).
1361 return RejectMaybeWrappedPromise(cx, promise, selfResolutionError, stack);
1362 }
1363
1364 // Step 9. Let then be Get(resolution, "then").
1365 RootedValue thenVal(cx);
1366 bool isOnProto = false;
1367 bool isOnStandardProto = false;
1368 bool isOnObjectProto = false;
1369 bool status = GetThenValue(cx, resolution, resolutionVal, &thenVal,
1370 &isOnProto, &isOnStandardProto, &isOnObjectProto);
1371
1372 RootedValue error(cx);
1373 Rooted<SavedFrame*> errorStack(cx);
1374
1375 // Step 10. If then is an abrupt completion, then
1376 if (!status) {
1377 // Get the `then.[[Value]]` value used in the step 10.a.
1378 if (!MaybeGetAndClearExceptionAndStack(cx, &error, &errorStack)) {
1379 return false;
1380 }
1381 }
1382
1383 // Testing functions allow to directly settle a promise without going
1384 // through the resolving functions. In that case the normal bookkeeping to
1385 // ensure only pending promises can be resolved doesn't apply and we need
1386 // to manually check for already settled promises. The exception is simply
1387 // dropped when this case happens.
1388 if (IsSettledMaybeWrappedPromise(promise)) {
1389 return true;
1390 }
1391
1392 // Step 10. If then is an abrupt completion, then
1393 if (!status) {
1394 // Step 10.a. Return RejectPromise(promise, then.[[Value]]).
1395 return RejectMaybeWrappedPromise(cx, promise, error, errorStack);
1396 }
1397
1398 // Step 11. Let thenAction be then.[[Value]].
1399 // (implicit)
1400
1401 // Step 12. If IsCallable(thenAction) is false, then
1402 if (!IsCallable(thenVal)) {
1403 // Step 12.a. Return FulfillPromise(promise, resolution).
1404 return FulfillMaybeWrappedPromise(cx, promise, resolutionVal);
1405 }
1406
1407 // Step 13. Let thenJobCallback be HostMakeJobCallback(thenAction).
1408 // (implicit)
1409
1410 // Step 14. Let job be
1411 // NewPromiseResolveThenableJob(promise, resolution,
1412 // thenJobCallback).
1413 // Step 15. Perform HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]]).
1414
1415 // If the resolution object is a built-in Promise object and the
1416 // `then` property is the original Promise.prototype.then function
1417 // from the current realm, we skip storing/calling it.
1418 // Additionally we require that |promise| itself is also a built-in
1419 // Promise object, so the fast path doesn't need to cope with wrappers.
1420 bool isBuiltinThen = false;
1421 if (resolution->is<PromiseObject>() && promise->is<PromiseObject>() &&
1422 IsNativeFunction(thenVal, Promise_then) &&
1423 thenVal.toObject().as<JSFunction>().realm() == cx->realm()) {
1424 isBuiltinThen = true;
1425 }
1426
1427 if (!isBuiltinThen) {
1428 ReportThenable(cx, isOnProto, isOnStandardProto, isOnObjectProto);
1429
1430 RootedValue promiseVal(cx, ObjectValue(*promise));
1431 if (!EnqueuePromiseResolveThenableJob(cx, promiseVal, resolutionVal,
1432 thenVal)) {
1433 return false;
1434 }
1435 } else {
1436 if (!EnqueuePromiseResolveThenableBuiltinJob(cx, promise, resolution)) {
1437 return false;
1438 }
1439 }
1440
1441 return true;
1442 }
1443
1444 /**
1445 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
1446 *
1447 * Promise Resolve Functions
1448 * https://tc39.es/ecma262/#sec-promise-resolve-functions
1449 */
1450 static bool ResolvePromiseFunction(JSContext* cx, unsigned argc, Value* vp) {
1451 CallArgs args = CallArgsFromVp(argc, vp);
1452
1453 // Step 1. Let F be the active function object.
1454 // Step 2. Assert: F has a [[Promise]] internal slot whose value is an Object.
1455 // (implicit)
1456
1457 JSFunction* resolve = &args.callee().as<JSFunction>();
1458 HandleValue resolutionVal = args.get(0);
1459
1460 // Step 3. Let promise be F.[[Promise]].
1461 const Value& promiseVal =
1462 resolve->getExtendedSlot(ResolveFunctionSlot_Promise);
1463
1464 // Step 4. Let alreadyResolved be F.[[AlreadyResolved]].
1465 // Step 5. If alreadyResolved.[[Value]] is true, return undefined.
1466 //
1467 // NOTE: We use the reference to the reject function as [[AlreadyResolved]].
1468 bool alreadyResolved = promiseVal.isUndefined();
1469 MOZ_ASSERT(IsAlreadyResolvedResolveFunction(resolve) == alreadyResolved);
1470 if (alreadyResolved) {
1471 args.rval().setUndefined();
1472 return true;
1473 }
1474
1475 RootedObject promise(cx, &promiseVal.toObject());
1476
1477 // Step 6. Set alreadyResolved.[[Value]] to true.
1478 SetAlreadyResolvedResolutionFunction(resolve);
1479
1480 // In some cases the Promise reference on the resolution function won't
1481 // have been removed during resolution, so we need to check that here,
1482 // too.
1483 if (IsSettledMaybeWrappedPromise(promise)) {
1484 args.rval().setUndefined();
1485 return true;
1486 }
1487
1488 // Steps 7-15.
1489 if (!ResolvePromiseInternal(cx, promise, resolutionVal)) {
1490 return false;
1491 }
1492
1493 // Step 16. Return undefined.
1494 args.rval().setUndefined();
1495 return true;
1496 }
1497
1498 static bool PromiseReactionJob(JSContext* cx, unsigned argc, Value* vp);
1499
1500 /**
1501 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
1502 *
1503 * NewPromiseReactionJob ( reaction, argument )
1504 * https://tc39.es/ecma262/#sec-newpromisereactionjob
1505 * HostEnqueuePromiseJob ( job, realm )
1506 * https://tc39.es/ecma262/#sec-hostenqueuepromisejob
1507 *
1508 * Tells the embedding to enqueue a Promise reaction job, based on
1509 * three parameters:
1510 * reactionObj - The reaction record.
1511 * handlerArg_ - The first and only argument to pass to the handler invoked by
1512 * the job. This will be stored on the reaction record.
1513 * targetState - The PromiseState this reaction job targets. This decides
1514 * whether the onFulfilled or onRejected handler is called.
1515 */
1516 [[nodiscard]] static bool EnqueuePromiseReactionJob(
1517 JSContext* cx, HandleObject reactionObj, HandleValue handlerArg_,
1518 JS::PromiseState targetState) {
1519 MOZ_ASSERT(targetState == JS::PromiseState::Fulfilled ||
1520 targetState == JS::PromiseState::Rejected);
1521
1522 // The reaction might have been stored on a Promise from another
1523 // compartment, which means it would've been wrapped in a CCW.
1524 // To properly handle that case here, unwrap it and enter its
1525 // compartment, where the job creation should take place anyway.
1526 Rooted<PromiseReactionRecord*> reaction(cx);
1527 RootedValue handlerArg(cx, handlerArg_);
1528 mozilla::Maybe<AutoRealm> ar;
1529 if (!IsProxy(reactionObj)) {
1530 MOZ_RELEASE_ASSERT(reactionObj->is<PromiseReactionRecord>());
1531 reaction = &reactionObj->as<PromiseReactionRecord>();
1532 if (cx->realm() != reaction->realm()) {
1533 // If the compartment has multiple realms, create the job in the
1534 // reaction's realm. This is consistent with the code in the else-branch
1535 // and avoids problems with running jobs against a dying global (Gecko
1536 // drops such jobs).
1537 ar.emplace(cx, reaction);
1538 }
1539 } else {
1540 JSObject* unwrappedReactionObj = UncheckedUnwrap(reactionObj);
1541 if (JS_IsDeadWrapper(unwrappedReactionObj)) {
1542 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1543 JSMSG_DEAD_OBJECT);
1544 return false;
1545 }
1546 reaction = &unwrappedReactionObj->as<PromiseReactionRecord>();
1547 MOZ_RELEASE_ASSERT(reaction->is<PromiseReactionRecord>());
1548 ar.emplace(cx, reaction);
1549 if (!cx->compartment()->wrap(cx, &handlerArg)) {
1550 return false;
1551 }
1552 }
1553
1554 // Must not enqueue a reaction job more than once.
1555 MOZ_ASSERT(reaction->targetState() == JS::PromiseState::Pending);
1556
1557 // NOTE: Instead of capturing reaction and arguments separately in the
1558 // Job Abstract Closure below, store arguments (= handlerArg) in
1559 // reaction object and capture it.
1560 // Also, set reaction.[[Type]] is represented by targetState here.
1561 cx->check(handlerArg);
1562 reaction->setTargetStateAndHandlerArg(targetState, handlerArg);
1563
1564 RootedValue reactionVal(cx, ObjectValue(*reaction));
1565 RootedValue handler(cx, reaction->handler());
1566
1567 // NewPromiseReactionJob
1568 // Step 2. Let handlerRealm be null.
1569 // NOTE: Instead of passing job and realm separately, we use the job's
1570 // JSFunction object's realm as the job's realm.
1571 // So we should enter the handlerRealm before creating the job function.
1572 //
1573 // GetFunctionRealm performed inside AutoFunctionOrCurrentRealm uses checked
1574 // unwrap and it can hit permission error if there's a security wrapper, and
1575 // in that case the reaction job is created in the current realm, instead of
1576 // the target function's realm.
1577 //
1578 // If this reaction crosses chrome/content boundary, and the security
1579 // wrapper would allow "call" operation, it still works inside the
1580 // reaction job.
1581 //
1582 // This behavior is observable only when the job belonging to the content
1583 // realm stops working (*1, *2), and it won't matter in practice.
1584 //
1585 // *1: "we can run script" performed inside HostEnqueuePromiseJob
1586 // in HTML spec
1587 // https://html.spec.whatwg.org/#hostenqueuepromisejob
1588 // https://html.spec.whatwg.org/#check-if-we-can-run-script
1589 // https://html.spec.whatwg.org/#fully-active
1590 // *2: nsIGlobalObject::IsDying performed inside PromiseJobRunnable::Run
1591 // in our implementation
1592 mozilla::Maybe<AutoFunctionOrCurrentRealm> ar2;
1593
1594 // NewPromiseReactionJob
1595 // Step 3. If reaction.[[Handler]] is not empty, then
1596 if (handler.isObject()) {
1597 // Step 3.a. Let getHandlerRealmResult be
1598 // GetFunctionRealm(reaction.[[Handler]].[[Callback]]).
1599 // Step 3.b. If getHandlerRealmResult is a normal completion,
1600 // set handlerRealm to getHandlerRealmResult.[[Value]].
1601 // Step 3.c. Else, set handlerRealm to the current Realm Record.
1602 // Step 3.d. NOTE: handlerRealm is never null unless the handler is
1603 // undefined. When the handler is a revoked Proxy and no
1604 // ECMAScript code runs, handlerRealm is used to create error
1605 // objects.
1606 RootedObject handlerObj(cx, &handler.toObject());
1607 ar2.emplace(cx, handlerObj);
1608
1609 // We need to wrap the reaction to store it on the job function.
1610 if (!cx->compartment()->wrap(cx, &reactionVal)) {
1611 return false;
1612 }
1613 }
1614
1615 // NewPromiseReactionJob
1616 // Step 1. Let job be a new Job Abstract Closure with no parameters that
1617 // captures reaction and argument and performs the following steps
1618 // when called:
1619 Handle<PropertyName*> funName = cx->names().empty_;
1620 RootedFunction job(
1621 cx, NewNativeFunction(cx, PromiseReactionJob, 0, funName,
1622 gc::AllocKind::FUNCTION_EXTENDED, GenericObject));
1623 if (!job) {
1624 return false;
1625 }
1626
1627 job->setExtendedSlot(ReactionJobSlot_ReactionRecord, reactionVal);
1628
1629 // When using JS::AddPromiseReactions{,IgnoringUnHandledRejection}, no actual
1630 // promise is created, so we might not have one here.
1631 // Additionally, we might have an object here that isn't an instance of
1632 // Promise. This can happen if content overrides the value of
1633 // Promise[@@species] (or invokes Promise#then on a Promise subclass
1634 // instance with a non-default @@species value on the constructor) with a
1635 // function that returns objects that're not Promise (subclass) instances.
1636 // In that case, we just pretend we didn't have an object in the first
1637 // place.
1638 // If after all this we do have an object, wrap it in case we entered the
1639 // handler's compartment above, because we should pass objects from a
1640 // single compartment to the enqueuePromiseJob callback.
1641 RootedObject promise(cx, reaction->promise());
1642 if (promise) {
1643 if (promise->is<PromiseObject>()) {
1644 if (!cx->compartment()->wrap(cx, &promise)) {
1645 return false;
1646 }
1647 } else if (IsWrapper(promise)) {
1648 // `promise` can be already-wrapped promise object at this point.
1649 JSObject* unwrappedPromise = UncheckedUnwrap(promise);
1650 if (unwrappedPromise->is<PromiseObject>()) {
1651 if (!cx->compartment()->wrap(cx, &promise)) {
1652 return false;
1653 }
1654 } else {
1655 promise = nullptr;
1656 }
1657 } else {
1658 promise = nullptr;
1659 }
1660 }
1661
1662 JS::Rooted<JSObject*> hostDefinedData(cx);
1663 if (JSObject* hostDefined = reaction->getAndClearHostDefinedData()) {
1664 hostDefined = CheckedUnwrapStatic(hostDefined);
1665 MOZ_ASSERT(hostDefined);
1666 // If the hostDefined object becomes a dead wrapper here, the target
1667 // global has already gone, and the job queue won't run the promise job
1668 // anyway.
1669 if (JS_IsDeadWrapper(hostDefined)) {
1670 return true;
1671 }
1672 hostDefinedData = hostDefined;
1673 }
1674
1675 // HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]]).
1676 return cx->runtime()->enqueuePromiseJob(cx, job, promise, hostDefinedData);
1677 }
1678
1679 [[nodiscard]] static bool TriggerPromiseReactions(JSContext* cx,
1680 HandleValue reactionsVal,
1681 JS::PromiseState state,
1682 HandleValue valueOrReason);
1683
1684 /**
1685 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
1686 *
1687 * FulfillPromise ( promise, value )
1688 * https://tc39.es/ecma262/#sec-fulfillpromise
1689 * RejectPromise ( promise, reason )
1690 * https://tc39.es/ecma262/#sec-rejectpromise
1691 *
1692 * This method takes an additional optional |unwrappedRejectionStack| parameter,
1693 * which is only used for debugging purposes.
1694 * It allows callers to to pass in the stack of some exception which
1695 * triggered the rejection of the promise.
1696 */
1697 [[nodiscard]] static bool ResolvePromise(
1698 JSContext* cx, Handle<PromiseObject*> promise, HandleValue valueOrReason,
1699 JS::PromiseState state,
1700 Handle<SavedFrame*> unwrappedRejectionStack = nullptr) {
1701 // Step 1. Assert: The value of promise.[[PromiseState]] is pending.
1702 MOZ_ASSERT(promise->state() == JS::PromiseState::Pending);
1703 MOZ_ASSERT(state == JS::PromiseState::Fulfilled ||
1704 state == JS::PromiseState::Rejected);
1705 MOZ_ASSERT_IF(unwrappedRejectionStack, state == JS::PromiseState::Rejected);
1706
1707 // FulfillPromise
1708 // Step 2. Let reactions be promise.[[PromiseFulfillReactions]].
1709 // RejectPromise
1710 // Step 2. Let reactions be promise.[[PromiseRejectReactions]].
1711 //
1712 // We only have one list of reactions for both resolution types. So
1713 // instead of getting the right list of reactions, we determine the
1714 // resolution type to retrieve the right information from the
1715 // reaction records.
1716 RootedValue reactionsVal(cx, promise->reactions());
1717
1718 // FulfillPromise
1719 // Step 3. Set promise.[[PromiseResult]] to value.
1720 // RejectPromise
1721 // Step 3. Set promise.[[PromiseResult]] to reason.
1722 //
1723 // Step 4. Set promise.[[PromiseFulfillReactions]] to undefined.
1724 // Step 5. Set promise.[[PromiseRejectReactions]] to undefined.
1725 //
1726 // The same slot is used for the reactions list and the result, so setting
1727 // the result also removes the reactions list.
1728 promise->setFixedSlot(PromiseSlot_ReactionsOrResult, valueOrReason);
1729
1730 // FulfillPromise
1731 // Step 6. Set promise.[[PromiseState]] to fulfilled.
1732 // RejectPromise
1733 // Step 6. Set promise.[[PromiseState]] to rejected.
1734 int32_t flags = promise->flags();
1735 flags |= PROMISE_FLAG_RESOLVED;
1736 if (state == JS::PromiseState::Fulfilled) {
1737 flags |= PROMISE_FLAG_FULFILLED;
1738 }
1739 promise->setFixedSlot(PromiseSlot_Flags, Int32Value(flags));
1740
1741 // Also null out the resolve/reject functions so they can be GC'd.
1742 promise->setFixedSlot(PromiseSlot_RejectFunction, UndefinedValue());
1743
1744 // Now that everything else is done, do the things the debugger needs.
1745
1746 // RejectPromise
1747 // Step 7. If promise.[[PromiseIsHandled]] is false, perform
1748 // HostPromiseRejectionTracker(promise, "reject").
1749 PromiseObject::onSettled(cx, promise, unwrappedRejectionStack);
1750
1751 // FulfillPromise
1752 // Step 7. Return TriggerPromiseReactions(reactions, value).
1753 // RejectPromise
1754 // Step 8. Return TriggerPromiseReactions(reactions, reason).
1755 return TriggerPromiseReactions(cx, reactionsVal, state, valueOrReason);
1756 }
1757
1758 /**
1759 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
1760 *
1761 * RejectPromise ( promise, reason )
1762 * https://tc39.es/ecma262/#sec-rejectpromise
1763 */
1764 [[nodiscard]] bool js::RejectPromiseInternal(
1765 JSContext* cx, JS::Handle<PromiseObject*> promise,
1766 JS::Handle<JS::Value> reason,
1767 JS::Handle<SavedFrame*> unwrappedRejectionStack /* = nullptr */) {
1768 return ResolvePromise(cx, promise, reason, JS::PromiseState::Rejected,
1769 unwrappedRejectionStack);
1770 }
1771
1772 /**
1773 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
1774 *
1775 * FulfillPromise ( promise, value )
1776 * https://tc39.es/ecma262/#sec-fulfillpromise
1777 */
1778 [[nodiscard]] static bool FulfillMaybeWrappedPromise(JSContext* cx,
1779 HandleObject promiseObj,
1780 HandleValue value_) {
1781 Rooted<PromiseObject*> promise(cx);
1782 RootedValue value(cx, value_);
1783
1784 mozilla::Maybe<AutoRealm> ar;
1785 if (!IsProxy(promiseObj)) {
1786 promise = &promiseObj->as<PromiseObject>();
1787 } else {
1788 JSObject* unwrappedPromiseObj = UncheckedUnwrap(promiseObj);
1789 if (JS_IsDeadWrapper(unwrappedPromiseObj)) {
1790 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1791 JSMSG_DEAD_OBJECT);
1792 return false;
1793 }
1794 promise = &unwrappedPromiseObj->as<PromiseObject>();
1795 ar.emplace(cx, promise);
1796 if (!cx->compartment()->wrap(cx, &value)) {
1797 return false;
1798 }
1799 }
1800
1801 return ResolvePromise(cx, promise, value, JS::PromiseState::Fulfilled);
1802 }
1803
1804 static bool GetCapabilitiesExecutor(JSContext* cx, unsigned argc, Value* vp);
1805 static bool PromiseConstructor(JSContext* cx, unsigned argc, Value* vp);
1806 [[nodiscard]] static PromiseObject* CreatePromiseObjectInternal(
1807 JSContext* cx, HandleObject proto = nullptr, bool protoIsWrapped = false,
1808 bool informDebugger = true);
1809
1810 enum GetCapabilitiesExecutorSlots {
1811 GetCapabilitiesExecutorSlots_Resolve,
1812 GetCapabilitiesExecutorSlots_Reject
1813 };
1814
1815 /**
1816 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
1817 *
1818 * Promise ( executor )
1819 * https://tc39.es/ecma262/#sec-promise-executor
1820 */
1821 [[nodiscard]] PromiseObject* js::CreatePromiseObjectWithoutResolutionFunctions(
1822 JSContext* cx, int32_t extraFlags) {
1823 // Steps 3-7.
1824 PromiseObject* promise = CreatePromiseObjectInternal(cx);
1825 if (!promise) {
1826 return nullptr;
1827 }
1828
1829 AddPromiseFlags(*promise,
1830 PROMISE_FLAG_DEFAULT_RESOLVING_FUNCTIONS | extraFlags);
1831
1832 // Step 11. Return promise.
1833 return promise;
1834 }
1835
1836 /**
1837 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
1838 *
1839 * Promise ( executor )
1840 * https://tc39.es/ecma262/#sec-promise-executor
1841 *
1842 * As if called with GetCapabilitiesExecutor as the executor argument.
1843 */
1844 [[nodiscard]] static PromiseObject* CreatePromiseWithDefaultResolutionFunctions(
1845 JSContext* cx, MutableHandleObject resolve, MutableHandleObject reject) {
1846 // Steps 3-7.
1847 Rooted<PromiseObject*> promise(cx, CreatePromiseObjectInternal(cx));
1848 if (!promise) {
1849 return nullptr;
1850 }
1851
1852 // Step 8. Let resolvingFunctions be CreateResolvingFunctions(promise).
1853 if (!CreateResolvingFunctions(cx, promise, resolve, reject)) {
1854 return nullptr;
1855 }
1856
1857 promise->setFixedSlot(PromiseSlot_RejectFunction, ObjectValue(*reject));
1858
1859 // Step 11. Return promise.
1860 return promise;
1861 }
1862
1863 /**
1864 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
1865 *
1866 * NewPromiseCapability ( C )
1867 * https://tc39.es/ecma262/#sec-newpromisecapability
1868 */
1869 [[nodiscard]] static bool NewPromiseCapability(
1870 JSContext* cx, HandleObject C, MutableHandle<PromiseCapability> capability,
1871 bool canOmitResolutionFunctions) {
1872 RootedValue cVal(cx, ObjectValue(*C));
1873
1874 // Step 1. If IsConstructor(C) is false, throw a TypeError exception.
1875 // Step 2. NOTE: C is assumed to be a constructor function that supports the
1876 // parameter conventions of the Promise constructor (see 27.2.3.1).
1877 if (!IsConstructor(C)) {
1878 ReportValueError(cx, JSMSG_NOT_CONSTRUCTOR, JSDVG_SEARCH_STACK, cVal,
1879 nullptr);
1880 return false;
1881 }
1882
1883 // If we'd call the original Promise constructor and know that the
1884 // resolve/reject functions won't ever escape to content, we can skip
1885 // creating and calling the executor function and instead return a Promise
1886 // marked as having default resolve/reject functions.
1887 //
1888 // This can't be used in Promise.all and Promise.race because we have to
1889 // pass the reject (and resolve, in the race case) function to thenables
1890 // in the list passed to all/race, which (potentially) means exposing them
1891 // to content.
1892 //
1893 // For Promise.all and Promise.race we can only optimize away the creation
1894 // of the GetCapabilitiesExecutor function, and directly allocate the
1895 // result promise instead of invoking the Promise constructor.
1896 if (IsNativeFunction(cVal, PromiseConstructor) &&
1897 cVal.toObject().nonCCWRealm() == cx->realm()) {
1898 PromiseObject* promise;
1899 if (canOmitResolutionFunctions) {
1900 promise = CreatePromiseObjectWithoutResolutionFunctions(cx);
1901 } else {
1902 promise = CreatePromiseWithDefaultResolutionFunctions(
1903 cx, capability.resolve(), capability.reject());
1904 }
1905 if (!promise) {
1906 return false;
1907 }
1908
1909 // Step 3. Let promiseCapability be the PromiseCapability Record
1910 // { [[Promise]]: undefined, [[Resolve]]: undefined,
1911 // [[Reject]]: undefined }.
1912 capability.promise().set(promise);
1913
1914 // Step 10. Return promiseCapability.
1915 return true;
1916 }
1917
1918 // Step 4. Let executorClosure be a new Abstract Closure with parameters
1919 // (resolve, reject) that captures promiseCapability and performs the
1920 // following steps when called:
1921 Handle<PropertyName*> funName = cx->names().empty_;
1922 RootedFunction executor(
1923 cx, NewNativeFunction(cx, GetCapabilitiesExecutor, 2, funName,
1924 gc::AllocKind::FUNCTION_EXTENDED, GenericObject));
1925 if (!executor) {
1926 return false;
1927 }
1928
1929 // Step 5. Let executor be
1930 // ! CreateBuiltinFunction(executorClosure, 2, "", « »).
1931 // (omitted)
1932
1933 // Step 6. Let promise be ? Construct(C, « executor »).
1934 // Step 9. Set promiseCapability.[[Promise]] to promise.
1935 FixedConstructArgs<1> cargs(cx);
1936 cargs[0].setObject(*executor);
1937 if (!Construct(cx, cVal, cargs, cVal, capability.promise())) {
1938 return false;
1939 }
1940
1941 // Step 7. If IsCallable(promiseCapability.[[Resolve]]) is false,
1942 // throw a TypeError exception.
1943 const Value& resolveVal =
1944 executor->getExtendedSlot(GetCapabilitiesExecutorSlots_Resolve);
1945 if (!IsCallable(resolveVal)) {
1946 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1947 JSMSG_PROMISE_RESOLVE_FUNCTION_NOT_CALLABLE);
1948 return false;
1949 }
1950
1951 // Step 8. If IsCallable(promiseCapability.[[Reject]]) is false,
1952 // throw a TypeError exception.
1953 const Value& rejectVal =
1954 executor->getExtendedSlot(GetCapabilitiesExecutorSlots_Reject);
1955 if (!IsCallable(rejectVal)) {
1956 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1957 JSMSG_PROMISE_REJECT_FUNCTION_NOT_CALLABLE);
1958 return false;
1959 }
1960
1961 // (reordered)
1962 // Step 3. Let promiseCapability be the PromiseCapability Record
1963 // { [[Promise]]: undefined, [[Resolve]]: undefined,
1964 // [[Reject]]: undefined }.
1965 capability.resolve().set(&resolveVal.toObject());
1966 capability.reject().set(&rejectVal.toObject());
1967
1968 // Step 10. Return promiseCapability.
1969 return true;
1970 }
1971
1972 /**
1973 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
1974 *
1975 * NewPromiseCapability ( C )
1976 * https://tc39.es/ecma262/#sec-newpromisecapability
1977 *
1978 * Steps 4.a-e.
1979 */
1980 static bool GetCapabilitiesExecutor(JSContext* cx, unsigned argc, Value* vp) {
1981 CallArgs args = CallArgsFromVp(argc, vp);
1982 JSFunction* F = &args.callee().as<JSFunction>();
1983
1984 // Step 4.a. If promiseCapability.[[Resolve]] is not undefined,
1985 // throw a TypeError exception.
1986 // Step 4.b. If promiseCapability.[[Reject]] is not undefined,
1987 // throw a TypeError exception.
1988 if (!F->getExtendedSlot(GetCapabilitiesExecutorSlots_Resolve).isUndefined() ||
1989 !F->getExtendedSlot(GetCapabilitiesExecutorSlots_Reject).isUndefined()) {
1990 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1991 JSMSG_PROMISE_CAPABILITY_HAS_SOMETHING_ALREADY);
1992 return false;
1993 }
1994
1995 // Step 4.c. Set promiseCapability.[[Resolve]] to resolve.
1996 F->setExtendedSlot(GetCapabilitiesExecutorSlots_Resolve, args.get(0));
1997
1998 // Step 4.d. Set promiseCapability.[[Reject]] to reject.
1999 F->setExtendedSlot(GetCapabilitiesExecutorSlots_Reject, args.get(1));
2000
2001 // Step 4.e. Return undefined.
2002 args.rval().setUndefined();
2003 return true;
2004 }
2005
2006 /**
2007 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
2008 *
2009 * RejectPromise ( promise, reason )
2010 * https://tc39.es/ecma262/#sec-rejectpromise
2011 */
2012 [[nodiscard]] static bool RejectMaybeWrappedPromise(
2013 JSContext* cx, HandleObject promiseObj, HandleValue reason_,
2014 Handle<SavedFrame*> unwrappedRejectionStack) {
2015 Rooted<PromiseObject*> promise(cx);
2016 RootedValue reason(cx, reason_);
2017
2018 mozilla::Maybe<AutoRealm> ar;
2019 if (!IsProxy(promiseObj)) {
2020 promise = &promiseObj->as<PromiseObject>();
2021 } else {
2022 JSObject* unwrappedPromiseObj = UncheckedUnwrap(promiseObj);
2023 if (JS_IsDeadWrapper(unwrappedPromiseObj)) {
2024 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2025 JSMSG_DEAD_OBJECT);
2026 return false;
2027 }
2028 promise = &unwrappedPromiseObj->as<PromiseObject>();
2029 ar.emplace(cx, promise);
2030
2031 // The rejection reason might've been created in a compartment with higher
2032 // privileges than the Promise's. In that case, object-type rejection
2033 // values might be wrapped into a wrapper that throws whenever the
2034 // Promise's reaction handler wants to do anything useful with it. To
2035 // avoid that situation, we synthesize a generic error that doesn't
2036 // expose any privileged information but can safely be used in the
2037 // rejection handler.
2038 if (!cx->compartment()->wrap(cx, &reason)) {
2039 return false;
2040 }
2041 if (reason.isObject() && !CheckedUnwrapStatic(&reason.toObject())) {
2042 // Report the existing reason, so we don't just drop it on the
2043 // floor.
2044 JSObject* realReason = UncheckedUnwrap(&reason.toObject());
2045 RootedValue realReasonVal(cx, ObjectValue(*realReason));
2046 Rooted<GlobalObject*> realGlobal(cx, &realReason->nonCCWGlobal());
2047 ReportErrorToGlobal(cx, realGlobal, realReasonVal);
2048
2049 // Async stacks are only properly adopted if there's at least one
2050 // interpreter frame active right now. If a thenable job with a
2051 // throwing `then` function got us here, that'll not be the case,
2052 // so we add one by throwing the error from self-hosted code.
2053 if (!GetInternalError(cx, JSMSG_PROMISE_ERROR_IN_WRAPPED_REJECTION_REASON,
2054 &reason)) {
2055 return false;
2056 }
2057 }
2058 }
2059
2060 return ResolvePromise(cx, promise, reason, JS::PromiseState::Rejected,
2061 unwrappedRejectionStack);
2062 }
2063
2064 // Apply f to a mutable handle on each member of a collection of reactions, like
2065 // that stored in PromiseSlot_ReactionsOrResult on a pending promise. When the
2066 // reaction record is wrapped, we pass the wrapper, without dereferencing it. If
2067 // f returns false, then we stop the iteration immediately and return false.
2068 // Otherwise, we return true.
2069 //
2070 // There are several different representations for collections:
2071 //
2072 // - We represent an empty collection of reactions as an 'undefined' value.
2073 //
2074 // - We represent a collection containing a single reaction simply as the given
2075 // PromiseReactionRecord object, possibly wrapped.
2076 //
2077 // - We represent a collection of two or more reactions as a dense array of
2078 // possibly-wrapped PromiseReactionRecords.
2079 //
2080 template <typename F>
2081 static bool ForEachReaction(JSContext* cx, HandleValue reactionsVal, F f) {
2082 if (reactionsVal.isUndefined()) {
2083 return true;
2084 }
2085
2086 RootedObject reactions(cx, &reactionsVal.toObject());
2087 RootedObject reaction(cx);
2088
2089 if (reactions->is<PromiseReactionRecord>() || IsWrapper(reactions) ||
2090 JS_IsDeadWrapper(reactions)) {
2091 return f(&reactions);
2092 }
2093
2094 Handle<NativeObject*> reactionsList = reactions.as<NativeObject>();
2095 uint32_t reactionsCount = reactionsList->getDenseInitializedLength();
2096 MOZ_ASSERT(reactionsCount > 1, "Reactions list should be created lazily");
2097
2098 for (uint32_t i = 0; i < reactionsCount; i++) {
2099 const Value& reactionVal = reactionsList->getDenseElement(i);
2100 MOZ_RELEASE_ASSERT(reactionVal.isObject());
2101 reaction = &reactionVal.toObject();
2102 if (!f(&reaction)) {
2103 return false;
2104 }
2105 }
2106
2107 return true;
2108 }
2109
2110 /**
2111 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
2112 *
2113 * TriggerPromiseReactions ( reactions, argument )
2114 * https://tc39.es/ecma262/#sec-triggerpromisereactions
2115 */
2116 [[nodiscard]] static bool TriggerPromiseReactions(JSContext* cx,
2117 HandleValue reactionsVal,
2118 JS::PromiseState state,
2119 HandleValue valueOrReason) {
2120 MOZ_ASSERT(state == JS::PromiseState::Fulfilled ||
2121 state == JS::PromiseState::Rejected);
2122
2123 // Step 1. For each element reaction of reactions, do
2124 // Step 2. Return undefined.
2125 return ForEachReaction(cx, reactionsVal, [&](MutableHandleObject reaction) {
2126 // Step 1.a. Let job be NewPromiseReactionJob(reaction, argument).
2127 // Step 1.b. Perform HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]]).
2128 return EnqueuePromiseReactionJob(cx, reaction, valueOrReason, state);
2129 });
2130 }
2131
2132 [[nodiscard]] static bool CallPromiseResolveFunction(JSContext* cx,
2133 HandleObject resolveFun,
2134 HandleValue value,
2135 HandleObject promiseObj);
2136
2137 /**
2138 * ES2023 draft rev 714fa3dd1e8237ae9c666146270f81880089eca5
2139 *
2140 * NewPromiseReactionJob ( reaction, argument )
2141 * https://tc39.es/ecma262/#sec-newpromisereactionjob
2142 *
2143 * Step 1.
2144 *
2145 * Implements PromiseReactionJob optimized for the case when the reaction
2146 * handler is one of the default resolving functions as created by the
2147 * CreateResolvingFunctions abstract operation.
2148 */
2149 [[nodiscard]] static bool DefaultResolvingPromiseReactionJob(
2150 JSContext* cx, Handle<PromiseReactionRecord*> reaction) {
2151 MOZ_ASSERT(reaction->targetState() != JS::PromiseState::Pending);
2152
2153 Rooted<PromiseObject*> promiseToResolve(cx,
2154 reaction->defaultResolvingPromise());
2155
2156 // Testing functions allow to directly settle a promise without going
2157 // through the resolving functions. In that case the normal bookkeeping to
2158 // ensure only pending promises can be resolved doesn't apply and we need
2159 // to manually check for already settled promises. We still call
2160 // Run{Fulfill,Reject}Function for consistency with PromiseReactionJob.
2161 ResolutionMode resolutionMode = ResolveMode;
2162 RootedValue handlerResult(cx, UndefinedValue());
2163 Rooted<SavedFrame*> unwrappedRejectionStack(cx);
2164 if (promiseToResolve->state() == JS::PromiseState::Pending) {
2165 RootedValue argument(cx, reaction->handlerArg());
2166
2167 // Step 1.e. Else, let handlerResult be
2168 // Completion(HostCallJobCallback(handler, undefined,
2169 // « argument »)).
2170 bool ok;
2171 if (reaction->targetState() == JS::PromiseState::Fulfilled) {
2172 ok = ResolvePromiseInternal(cx, promiseToResolve, argument);
2173 } else {
2174 ok = RejectPromiseInternal(cx, promiseToResolve, argument);
2175 }
2176
2177 if (!ok) {
2178 resolutionMode = RejectMode;
2179 if (!MaybeGetAndClearExceptionAndStack(cx, &handlerResult,
2180 &unwrappedRejectionStack)) {
2181 return false;
2182 }
2183 }
2184 }
2185
2186 // Steps 1.f-i.
2187 RootedObject promiseObj(cx, reaction->promise());
2188 RootedObject callee(cx);
2189 if (resolutionMode == ResolveMode) {
2190 callee =
2191 reaction->getFixedSlot(ReactionRecordSlot_Resolve).toObjectOrNull();
2192
2193 return CallPromiseResolveFunction(cx, callee, handlerResult, promiseObj);
2194 }
2195
2196 callee = reaction->getFixedSlot(ReactionRecordSlot_Reject).toObjectOrNull();
2197
2198 return CallPromiseRejectFunction(cx, callee, handlerResult, promiseObj,
2199 unwrappedRejectionStack,
2200 reaction->unhandledRejectionBehavior());
2201 }
2202
2203 /**
2204 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
2205 *
2206 * Await in async function
2207 * https://tc39.es/ecma262/#await
2208 *
2209 * Step 3. fulfilledClosure Abstract Closure.
2210 * Step 5. rejectedClosure Abstract Closure.
2211 */
2212 [[nodiscard]] static bool AsyncFunctionPromiseReactionJob(
2213 JSContext* cx, Handle<PromiseReactionRecord*> reaction) {
2214 MOZ_ASSERT(reaction->isAsyncFunction());
2215
2216 auto handler = static_cast<PromiseHandler>(reaction->handler().toInt32());
2217 RootedValue argument(cx, reaction->handlerArg());
2218 Rooted<AsyncFunctionGeneratorObject*> generator(
2219 cx, reaction->asyncFunctionGenerator());
2220
2221 // Await's handlers don't return a value, nor throw any exceptions.
2222 // They fail only on OOM.
2223
2224 if (handler == PromiseHandler::AsyncFunctionAwaitedFulfilled) {
2225 // Step 3. fulfilledClosure Abstract Closure.
2226 return AsyncFunctionAwaitedFulfilled(cx, generator, argument);
2227 }
2228
2229 // Step 5. rejectedClosure Abstract Closure.
2230 MOZ_ASSERT(handler == PromiseHandler::AsyncFunctionAwaitedRejected);
2231 return AsyncFunctionAwaitedRejected(cx, generator, argument);
2232 }
2233
2234 /**
2235 * ES2023 draft rev 714fa3dd1e8237ae9c666146270f81880089eca5
2236 *
2237 * NewPromiseReactionJob ( reaction, argument )
2238 * https://tc39.es/ecma262/#sec-newpromisereactionjob
2239 *
2240 * Step 1.
2241 *
2242 * Callback triggering the fulfill/reject reaction for a resolved Promise,
2243 * to be invoked by the embedding during its processing of the Promise job
2244 * queue.
2245 *
2246 * A PromiseReactionJob is set as the native function of an extended
2247 * JSFunction object, with all information required for the job's
2248 * execution stored in in a reaction record in its first extended slot.
2249 */
2250 static bool PromiseReactionJob(JSContext* cx, unsigned argc, Value* vp) {
2251 CallArgs args = CallArgsFromVp(argc, vp);
2252
2253 RootedFunction job(cx, &args.callee().as<JSFunction>());
2254
2255 // Promise reactions don't return any value.
2256 args.rval().setUndefined();
2257
2258 RootedObject reactionObj(
2259 cx, &job->getExtendedSlot(ReactionJobSlot_ReactionRecord).toObject());
2260
2261 // To ensure that the embedding ends up with the right entry global, we're
2262 // guaranteeing that the reaction job function gets created in the same
2263 // compartment as the handler function. That's not necessarily the global
2264 // that the job was triggered from, though.
2265 // We can find the triggering global via the job's reaction record. To go
2266 // back, we check if the reaction is a wrapper and if so, unwrap it and
2267 // enter its compartment.
2268 mozilla::Maybe<AutoRealm> ar;
2269 if (!IsProxy(reactionObj)) {
2270 MOZ_RELEASE_ASSERT(reactionObj->is<PromiseReactionRecord>());
2271 } else {
2272 reactionObj = UncheckedUnwrap(reactionObj);
2273 if (JS_IsDeadWrapper(reactionObj)) {
2274 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2275 JSMSG_DEAD_OBJECT);
2276 return false;
2277 }
2278 MOZ_RELEASE_ASSERT(reactionObj->is<PromiseReactionRecord>());
2279 ar.emplace(cx, reactionObj);
2280 }
2281
2282 // Optimized/special cases.
2283 Handle<PromiseReactionRecord*> reaction =
2284 reactionObj.as<PromiseReactionRecord>();
2285 if (reaction->isDefaultResolvingHandler()) {
2286 return DefaultResolvingPromiseReactionJob(cx, reaction);
2287 }
2288 if (reaction->isAsyncFunction()) {
2289 return AsyncFunctionPromiseReactionJob(cx, reaction);
2290 }
2291 if (reaction->isAsyncGenerator()) {
2292 RootedValue argument(cx, reaction->handlerArg());
2293 Rooted<AsyncGeneratorObject*> generator(cx, reaction->asyncGenerator());
2294 auto handler = static_cast<PromiseHandler>(reaction->handler().toInt32());
2295 return AsyncGeneratorPromiseReactionJob(cx, handler, generator, argument);
2296 }
2297 if (reaction->isDebuggerDummy()) {
2298 return true;
2299 }
2300
2301 // Step 1.a. Let promiseCapability be reaction.[[Capability]].
2302 // (implicit)
2303
2304 // Step 1.c. Let handler be reaction.[[Handler]].
2305 RootedValue handlerVal(cx, reaction->handler());
2306
2307 RootedValue argument(cx, reaction->handlerArg());
2308
2309 RootedValue handlerResult(cx);
2310 ResolutionMode resolutionMode = ResolveMode;
2311
2312 Rooted<SavedFrame*> unwrappedRejectionStack(cx);
2313
2314 // Step 1.d. If handler is empty, then
2315 if (handlerVal.isInt32()) {
2316 // Step 1.b. Let type be reaction.[[Type]].
2317 // (reordered)
2318 auto handlerNum = static_cast<PromiseHandler>(handlerVal.toInt32());
2319
2320 // Step 1.d.i. If type is Fulfill, let handlerResult be
2321 // NormalCompletion(argument).
2322 if (handlerNum == PromiseHandler::Identity) {
2323 handlerResult = argument;
2324 } else if (handlerNum == PromiseHandler::Thrower) {
2325 // Step 1.d.ii. Else,
2326 // Step 1.d.ii.1. Assert: type is Reject.
2327 // Step 1.d.ii.2. Let handlerResult be ThrowCompletion(argument).
2328 resolutionMode = RejectMode;
2329 handlerResult = argument;
2330 }
2331 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
2332 else if (handlerNum == PromiseHandler::AsyncIteratorDisposeAwaitFulfilled) {
2333 // Explicit Resource Management Proposal
2334 // 27.1.3.1 %AsyncIteratorPrototype% [ @@asyncDispose ] ( )
2335 // https://arai-a.github.io/ecma262-compare/?pr=3000&id=sec-%25asynciteratorprototype%25-%40%40asyncdispose
2336 //
2337 // Step 6.e.i. Return undefined.
2338 handlerResult = JS::UndefinedValue();
2339 }
2340 #endif
2341 else {
2342 // Special case for Async-from-Sync Iterator.
2343
2344 MOZ_ASSERT(handlerNum ==
2345 PromiseHandler::AsyncFromSyncIteratorValueUnwrapDone ||
2346 handlerNum ==
2347 PromiseHandler::AsyncFromSyncIteratorValueUnwrapNotDone);
2348
2349 bool done =
2350 handlerNum == PromiseHandler::AsyncFromSyncIteratorValueUnwrapDone;
2351 // 25.1.4.2.5 Async-from-Sync Iterator Value Unwrap Functions, steps 1-2.
2352 PlainObject* resultObj = CreateIterResultObject(cx, argument, done);
2353 if (!resultObj) {
2354 return false;
2355 }
2356
2357 handlerResult = ObjectValue(*resultObj);
2358 }
2359 } else {
2360 MOZ_ASSERT(handlerVal.isObject());
2361 MOZ_ASSERT(IsCallable(handlerVal));
2362
2363 // Step 1.e. Else, let handlerResult be
2364 // Completion(HostCallJobCallback(handler, undefined,
2365 // « argument »)).
2366 if (!Call(cx, handlerVal, UndefinedHandleValue, argument, &handlerResult)) {
2367 resolutionMode = RejectMode;
2368 if (!MaybeGetAndClearExceptionAndStack(cx, &handlerResult,
2369 &unwrappedRejectionStack)) {
2370 return false;
2371 }
2372 }
2373 }
2374
2375 // Steps 1.f-i.
2376 RootedObject promiseObj(cx, reaction->promise());
2377 RootedObject callee(cx);
2378 if (resolutionMode == ResolveMode) {
2379 callee =
2380 reaction->getFixedSlot(ReactionRecordSlot_Resolve).toObjectOrNull();
2381
2382 return CallPromiseResolveFunction(cx, callee, handlerResult, promiseObj);
2383 }
2384
2385 callee = reaction->getFixedSlot(ReactionRecordSlot_Reject).toObjectOrNull();
2386
2387 return CallPromiseRejectFunction(cx, callee, handlerResult, promiseObj,
2388 unwrappedRejectionStack,
2389 reaction->unhandledRejectionBehavior());
2390 }
2391
2392 /**
2393 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
2394 *
2395 * NewPromiseResolveThenableJob ( promiseToResolve, thenable, then )
2396 * https://tc39.es/ecma262/#sec-newpromiseresolvethenablejob
2397 *
2398 * Steps 1.a-d.
2399 *
2400 * A PromiseResolveThenableJob is set as the native function of an extended
2401 * JSFunction object, with all information required for the job's
2402 * execution stored in the function's extended slots.
2403 *
2404 * Usage of the function's extended slots is described in the ThenableJobSlots
2405 * enum.
2406 */
2407 static bool PromiseResolveThenableJob(JSContext* cx, unsigned argc, Value* vp) {
2408 CallArgs args = CallArgsFromVp(argc, vp);
2409
2410 RootedFunction job(cx, &args.callee().as<JSFunction>());
2411 RootedObject promise(
2412 cx, &job->getExtendedSlot(ThenableJobSlot_Promise).toObject());
2413 RootedValue thenable(cx, job->getExtendedSlot(ThenableJobSlot_Thenable));
2414 RootedValue then(cx, job->getExtendedSlot(ThenableJobSlot_Handler));
2415 MOZ_ASSERT(then.isObject());
2416
2417 // Step 1.a. Let resolvingFunctions be
2418 // CreateResolvingFunctions(promiseToResolve).
2419 RootedObject resolveFn(cx);
2420 RootedObject rejectFn(cx);
2421 if (!CreateResolvingFunctions(cx, promise, &resolveFn, &rejectFn)) {
2422 return false;
2423 }
2424
2425 // Step 1.b. Let thenCallResult be
2426 // HostCallJobCallback(then, thenable,
2427 // « resolvingFunctions.[[Resolve]],
2428 // resolvingFunctions.[[Reject]] »).
2429 FixedInvokeArgs<2> args2(cx);
2430 args2[0].setObject(*resolveFn);
2431 args2[1].setObject(*rejectFn);
2432
2433 // In difference to the usual pattern, we return immediately on success.
2434 RootedValue rval(cx);
2435 if (Call(cx, then, thenable, args2, &rval)) {
2436 // Step 1.d. Return Completion(thenCallResult).
2437 return true;
2438 }
2439
2440 // Step 1.c. If thenCallResult is an abrupt completion, then
2441
2442 Rooted<SavedFrame*> stack(cx);
2443 if (!MaybeGetAndClearExceptionAndStack(cx, &rval, &stack)) {
2444 return false;
2445 }
2446
2447 // Step 1.c.i. Let status be
2448 // Call(resolvingFunctions.[[Reject]], undefined,
2449 // « thenCallResult.[[Value]] »).
2450 // Step 1.c.ii. Return Completion(status).
2451 RootedValue rejectVal(cx, ObjectValue(*rejectFn));
2452 return Call(cx, rejectVal, UndefinedHandleValue, rval, &rval);
2453 }
2454
2455 [[nodiscard]] static bool OriginalPromiseThenWithoutSettleHandlers(
2456 JSContext* cx, Handle<PromiseObject*> promise,
2457 Handle<PromiseObject*> promiseToResolve);
2458
2459 /**
2460 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
2461 *
2462 * NewPromiseResolveThenableJob ( promiseToResolve, thenable, then )
2463 * https://tc39.es/ecma262/#sec-newpromiseresolvethenablejob
2464 *
2465 * Step 1.a-d.
2466 *
2467 * Specialization of PromiseResolveThenableJob when the `thenable` is a
2468 * built-in Promise object and the `then` property is the built-in
2469 * `Promise.prototype.then` function.
2470 *
2471 * A PromiseResolveBuiltinThenableJob is set as the native function of an
2472 * extended JSFunction object, with all information required for the job's
2473 * execution stored in the function's extended slots.
2474 *
2475 * Usage of the function's extended slots is described in the ThenableJobSlots
2476 * enum.
2477 */
2478 static bool PromiseResolveBuiltinThenableJob(JSContext* cx, unsigned argc,
2479 Value* vp) {
2480 CallArgs args = CallArgsFromVp(argc, vp);
2481
2482 RootedFunction job(cx, &args.callee().as<JSFunction>());
2483 RootedObject promise(
2484 cx, &job->getExtendedSlot(ThenableJobSlot_Promise).toObject());
2485 RootedObject thenable(
2486 cx, &job->getExtendedSlot(ThenableJobSlot_Thenable).toObject());
2487 // The handler slot is not used for builtin `then`.
2488 MOZ_ASSERT(job->getExtendedSlot(ThenableJobSlot_Handler).isUndefined());
2489
2490 cx->check(promise, thenable);
2491 MOZ_ASSERT(promise->is<PromiseObject>());
2492 MOZ_ASSERT(thenable->is<PromiseObject>());
2493
2494 // Step 1.a. Let resolvingFunctions be
2495 // CreateResolvingFunctions(promiseToResolve).
2496 // (skipped)
2497
2498 // Step 1.b. Let thenCallResult be HostCallJobCallback(
2499 // then, thenable,
2500 // « resolvingFunctions.[[Resolve]],
2501 // resolvingFunctions.[[Reject]] »).
2502 //
2503 // NOTE: In difference to the usual pattern, we return immediately on success.
2504 if (OriginalPromiseThenWithoutSettleHandlers(cx, thenable.as<PromiseObject>(),
2505 promise.as<PromiseObject>())) {
2506 // Step 1.d. Return Completion(thenCallResult).
2507 return true;
2508 }
2509
2510 // Step 1.c. If thenCallResult is an abrupt completion, then
2511 RootedValue exception(cx);
2512 Rooted<SavedFrame*> stack(cx);
2513 if (!MaybeGetAndClearExceptionAndStack(cx, &exception, &stack)) {
2514 return false;
2515 }
2516
2517 // Testing functions allow to directly settle a promise without going
2518 // through the resolving functions. In that case the normal bookkeeping to
2519 // ensure only pending promises can be resolved doesn't apply and we need
2520 // to manually check for already settled promises. The exception is simply
2521 // dropped when this case happens.
2522 if (promise->as<PromiseObject>().state() != JS::PromiseState::Pending) {
2523 return true;
2524 }
2525
2526 // Step 1.c.i. Let status be
2527 // Call(resolvingFunctions.[[Reject]], undefined,
2528 // « thenCallResult.[[Value]] »).
2529 // Step 1.c.ii. Return Completion(status).
2530 return RejectPromiseInternal(cx, promise.as<PromiseObject>(), exception,
2531 stack);
2532 }
2533
2534 /**
2535 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
2536 *
2537 * NewPromiseResolveThenableJob ( promiseToResolve, thenable, then )
2538 * https://tc39.es/ecma262/#sec-newpromiseresolvethenablejob
2539 * HostEnqueuePromiseJob ( job, realm )
2540 * https://tc39.es/ecma262/#sec-hostenqueuepromisejob
2541 *
2542 * Tells the embedding to enqueue a Promise resolve thenable job, based on
2543 * three parameters:
2544 * promiseToResolve_ - The promise to resolve, obviously.
2545 * thenable_ - The thenable to resolve the Promise with.
2546 * thenVal - The `then` function to invoke with the `thenable` as the receiver.
2547 */
2548 [[nodiscard]] static bool EnqueuePromiseResolveThenableJob(
2549 JSContext* cx, HandleValue promiseToResolve_, HandleValue thenable_,
2550 HandleValue thenVal) {
2551 // Need to re-root these to enable wrapping them below.
2552 RootedValue promiseToResolve(cx, promiseToResolve_);
2553 RootedValue thenable(cx, thenable_);
2554
2555 // Step 2. Let getThenRealmResult be GetFunctionRealm(then.[[Callback]]).
2556 // Step 3. If getThenRealmResult is a normal completion, let thenRealm be
2557 // getThenRealmResult.[[Value]].
2558 // Step 4. Else, let thenRealm be the current Realm Record.
2559 // Step 5. NOTE: thenRealm is never null. When then.[[Callback]] is a revoked
2560 // Proxy and no code runs, thenRealm is used to create error objects.
2561 //
2562 // NOTE: Instead of passing job and realm separately, we use the job's
2563 // JSFunction object's realm as the job's realm.
2564 // So we should enter the thenRealm before creating the job function.
2565 //
2566 // GetFunctionRealm performed inside AutoFunctionOrCurrentRealm uses checked
2567 // unwrap and this is fine given the behavior difference (see the comment
2568 // around AutoFunctionOrCurrentRealm usage in EnqueuePromiseReactionJob for
2569 // more details) is observable only when the `thenable` is from content realm
2570 // and `then` is from chrome realm, that shouldn't happen in practice.
2571 //
2572 // NOTE: If `thenable` is also from chrome realm, accessing `then` silently
2573 // fails and it returns `undefined`, and that case doesn't reach here.
2574 RootedObject then(cx, &thenVal.toObject());
2575 AutoFunctionOrCurrentRealm ar(cx, then);
2576 if (then->maybeCCWRealm() != cx->realm()) {
2577 if (!cx->compartment()->wrap(cx, &then)) {
2578 return false;
2579 }
2580 }
2581
2582 // Wrap the `promiseToResolve` and `thenable` arguments.
2583 if (!cx->compartment()->wrap(cx, &promiseToResolve)) {
2584 return false;
2585 }
2586
2587 MOZ_ASSERT(thenable.isObject());
2588 if (!cx->compartment()->wrap(cx, &thenable)) {
2589 return false;
2590 }
2591
2592 // Step 1. Let job be a new Job Abstract Closure with no parameters that
2593 // captures promiseToResolve, thenable, and then and performs the
2594 // following steps when called:
2595 Handle<PropertyName*> funName = cx->names().empty_;
2596 RootedFunction job(
2597 cx, NewNativeFunction(cx, PromiseResolveThenableJob, 0, funName,
2598 gc::AllocKind::FUNCTION_EXTENDED, GenericObject));
2599 if (!job) {
2600 return false;
2601 }
2602
2603 // Set the `promiseToResolve`, `thenable` and `then` arguments on the
2604 // callback.
2605 job->setExtendedSlot(ThenableJobSlot_Promise, promiseToResolve);
2606 job->setExtendedSlot(ThenableJobSlot_Thenable, thenable);
2607 job->setExtendedSlot(ThenableJobSlot_Handler, ObjectValue(*then));
2608
2609 // At this point the promise is guaranteed to be wrapped into the job's
2610 // compartment.
2611 RootedObject promise(cx, &promiseToResolve.toObject());
2612
2613 Rooted<JSObject*> hostDefinedData(cx);
2614 if (!cx->runtime()->getHostDefinedData(cx, &hostDefinedData)) {
2615 return false;
2616 }
2617
2618 // Step X. HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]]).
2619 return cx->runtime()->enqueuePromiseJob(cx, job, promise, hostDefinedData);
2620 }
2621
2622 /**
2623 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
2624 *
2625 * NewPromiseResolveThenableJob ( promiseToResolve, thenable, then )
2626 * https://tc39.es/ecma262/#sec-newpromiseresolvethenablejob
2627 * HostEnqueuePromiseJob ( job, realm )
2628 * https://tc39.es/ecma262/#sec-hostenqueuepromisejob
2629 *
2630 * Tells the embedding to enqueue a Promise resolve thenable built-in job,
2631 * based on two parameters:
2632 * promiseToResolve - The promise to resolve, obviously.
2633 * thenable - The thenable to resolve the Promise with.
2634 */
2635 [[nodiscard]] static bool EnqueuePromiseResolveThenableBuiltinJob(
2636 JSContext* cx, HandleObject promiseToResolve, HandleObject thenable) {
2637 cx->check(promiseToResolve, thenable);
2638 MOZ_ASSERT(promiseToResolve->is<PromiseObject>());
2639 MOZ_ASSERT(thenable->is<PromiseObject>());
2640
2641 // Step 1. Let job be a new Job Abstract Closure with no parameters that
2642 // captures promiseToResolve, thenable, and then and performs the
2643 // following steps when called:
2644 Handle<PropertyName*> funName = cx->names().empty_;
2645 RootedFunction job(
2646 cx, NewNativeFunction(cx, PromiseResolveBuiltinThenableJob, 0, funName,
2647 gc::AllocKind::FUNCTION_EXTENDED, GenericObject));
2648 if (!job) {
2649 return false;
2650 }
2651
2652 // Steps 2-5.
2653 // (implicit)
2654 // `then` is built-in Promise.prototype.then in the current realm.,
2655 // thus `thenRealm` is also current realm, and we have nothing to do here.
2656
2657 // Store the promise and the thenable on the reaction job.
2658 job->setExtendedSlot(ThenableJobSlot_Promise, ObjectValue(*promiseToResolve));
2659 job->setExtendedSlot(ThenableJobSlot_Thenable, ObjectValue(*thenable));
2660
2661 Rooted<JSObject*> hostDefinedData(cx);
2662 if (!cx->runtime()->getHostDefinedData(cx, &hostDefinedData)) {
2663 return false;
2664 }
2665
2666 // HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]]).
2667 return cx->runtime()->enqueuePromiseJob(cx, job, promiseToResolve,
2668 hostDefinedData);
2669 }
2670
2671 [[nodiscard]] static bool AddDummyPromiseReactionForDebugger(
2672 JSContext* cx, Handle<PromiseObject*> promise,
2673 HandleObject dependentPromise);
2674
2675 [[nodiscard]] static bool AddPromiseReaction(
2676 JSContext* cx, Handle<PromiseObject*> promise,
2677 Handle<PromiseReactionRecord*> reaction);
2678
2679 static JSFunction* GetResolveFunctionFromReject(JSFunction* reject) {
2680 MOZ_ASSERT(reject->maybeNative() == RejectPromiseFunction);
2681 Value resolveFunVal =
2682 reject->getExtendedSlot(RejectFunctionSlot_ResolveFunction);
2683 MOZ_ASSERT(IsNativeFunction(resolveFunVal, ResolvePromiseFunction));
2684 return &resolveFunVal.toObject().as<JSFunction>();
2685 }
2686
2687 static JSFunction* GetRejectFunctionFromResolve(JSFunction* resolve) {
2688 MOZ_ASSERT(resolve->maybeNative() == ResolvePromiseFunction);
2689 Value rejectFunVal =
2690 resolve->getExtendedSlot(ResolveFunctionSlot_RejectFunction);
2691 MOZ_ASSERT(IsNativeFunction(rejectFunVal, RejectPromiseFunction));
2692 return &rejectFunVal.toObject().as<JSFunction>();
2693 }
2694
2695 static JSFunction* GetResolveFunctionFromPromise(PromiseObject* promise) {
2696 Value rejectFunVal = promise->getFixedSlot(PromiseSlot_RejectFunction);
2697 if (rejectFunVal.isUndefined()) {
2698 return nullptr;
2699 }
2700 JSObject* rejectFunObj = &rejectFunVal.toObject();
2701
2702 // We can safely unwrap it because all we want is to get the resolve
2703 // function.
2704 if (IsWrapper(rejectFunObj)) {
2705 rejectFunObj = UncheckedUnwrap(rejectFunObj);
2706 }
2707
2708 if (!rejectFunObj->is<JSFunction>()) {
2709 return nullptr;
2710 }
2711
2712 JSFunction* rejectFun = &rejectFunObj->as<JSFunction>();
2713
2714 // Only the original RejectPromiseFunction has a reference to the resolve
2715 // function.
2716 if (rejectFun->maybeNative() != &RejectPromiseFunction) {
2717 return nullptr;
2718 }
2719
2720 // The reject function was already called and cleared its resolve-function
2721 // extended slot.
2722 if (rejectFun->getExtendedSlot(RejectFunctionSlot_ResolveFunction)
2723 .isUndefined()) {
2724 return nullptr;
2725 }
2726
2727 return GetResolveFunctionFromReject(rejectFun);
2728 }
2729
2730 /**
2731 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
2732 *
2733 * Promise ( executor )
2734 * https://tc39.es/ecma262/#sec-promise-executor
2735 *
2736 * Steps 3-7.
2737 */
2738 [[nodiscard]] static MOZ_ALWAYS_INLINE PromiseObject*
2739 CreatePromiseObjectInternal(JSContext* cx, HandleObject proto /* = nullptr */,
2740 bool protoIsWrapped /* = false */,
2741 bool informDebugger /* = true */) {
2742 // Enter the unwrapped proto's compartment, if that's different from
2743 // the current one.
2744 // All state stored in a Promise's fixed slots must be created in the
2745 // same compartment, so we get all of that out of the way here.
2746 // (Except for the resolution functions, which are created below.)
2747 mozilla::Maybe<AutoRealm> ar;
2748 if (protoIsWrapped) {
2749 ar.emplace(cx, proto);
2750 }
2751
2752 // Step 3. Let promise be
2753 // ? OrdinaryCreateFromConstructor(
2754 // NewTarget, "%Promise.prototype%",
2755 // « [[PromiseState]], [[PromiseResult]],
2756 // [[PromiseFulfillReactions]], [[PromiseRejectReactions]],
2757 // [[PromiseIsHandled]] »).
2758 PromiseObject* promise = NewObjectWithClassProto<PromiseObject>(cx, proto);
2759 if (!promise) {
2760 return nullptr;
2761 }
2762
2763 // Step 4. Set promise.[[PromiseState]] to pending.
2764 promise->initFixedSlot(PromiseSlot_Flags, Int32Value(0));
2765
2766 // Step 5. Set promise.[[PromiseFulfillReactions]] to a new empty List.
2767 // Step 6. Set promise.[[PromiseRejectReactions]] to a new empty List.
2768 // (omitted)
2769 // We allocate our single list of reaction records lazily.
2770
2771 // Step 7. Set promise.[[PromiseIsHandled]] to false.
2772 // (implicit)
2773 // The handled flag is unset by default.
2774
2775 if (MOZ_LIKELY(!JS::IsAsyncStackCaptureEnabledForRealm(cx))) {
2776 return promise;
2777 }
2778
2779 // Store an allocation stack so we can later figure out what the
2780 // control flow was for some unexpected results. Frightfully expensive,
2781 // but oh well.
2782
2783 Rooted<PromiseObject*> promiseRoot(cx, promise);
2784
2785 PromiseDebugInfo* debugInfo = PromiseDebugInfo::create(cx, promiseRoot);
2786 if (!debugInfo) {
2787 return nullptr;
2788 }
2789
2790 // Let the Debugger know about this Promise.
2791 if (informDebugger) {
2792 DebugAPI::onNewPromise(cx, promiseRoot);
2793 }
2794
2795 return promiseRoot;
2796 }
2797
2798 /**
2799 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
2800 *
2801 * Promise ( executor )
2802 * https://tc39.es/ecma262/#sec-promise-executor
2803 */
2804 static bool PromiseConstructor(JSContext* cx, unsigned argc, Value* vp) {
2805 CallArgs args = CallArgsFromVp(argc, vp);
2806
2807 // Step 1. If NewTarget is undefined, throw a TypeError exception.
2808 if (!ThrowIfNotConstructing(cx, args, "Promise")) {
2809 return false;
2810 }
2811
2812 // Step 2. If IsCallable(executor) is false, throw a TypeError exception.
2813 HandleValue executorVal = args.get(0);
2814 if (!IsCallable(executorVal)) {
2815 return ReportIsNotFunction(cx, executorVal);
2816 }
2817 RootedObject executor(cx, &executorVal.toObject());
2818
2819 RootedObject newTarget(cx, &args.newTarget().toObject());
2820
2821 // If the constructor is called via an Xray wrapper, then the newTarget
2822 // hasn't been unwrapped. We want that because, while the actual instance
2823 // should be created in the target compartment, the constructor's code
2824 // should run in the wrapper's compartment.
2825 //
2826 // This is so that the resolve and reject callbacks get created in the
2827 // wrapper's compartment, which is required for code in that compartment
2828 // to freely interact with it, and, e.g., pass objects as arguments, which
2829 // it wouldn't be able to if the callbacks were themselves wrapped in Xray
2830 // wrappers.
2831 //
2832 // At the same time, just creating the Promise itself in the wrapper's
2833 // compartment wouldn't be helpful: if the wrapper forbids interactions
2834 // with objects except for specific actions, such as calling them, then
2835 // the code we want to expose it to can't actually treat it as a Promise:
2836 // calling .then on it would throw, for example.
2837 //
2838 // Another scenario where it's important to create the Promise in a
2839 // different compartment from the resolution functions is when we want to
2840 // give non-privileged code a Promise resolved with the result of a
2841 // Promise from privileged code; as a return value of a JS-implemented
2842 // API, say. If the resolution functions were unprivileged, then resolving
2843 // with a privileged Promise would cause `resolve` to attempt accessing
2844 // .then on the passed Promise, which would throw an exception, so we'd
2845 // just end up with a rejected Promise. Really, we want to chain the two
2846 // Promises, with the unprivileged one resolved with the resolution of the
2847 // privileged one.
2848
2849 bool needsWrapping = false;
2850 RootedObject proto(cx);
2851 if (IsWrapper(newTarget)) {
2852 JSObject* unwrappedNewTarget = CheckedUnwrapStatic(newTarget);
2853 MOZ_ASSERT(unwrappedNewTarget);
2854 MOZ_ASSERT(unwrappedNewTarget != newTarget);
2855
2856 newTarget = unwrappedNewTarget;
2857 {
2858 AutoRealm ar(cx, newTarget);
2859 Handle<GlobalObject*> global = cx->global();
2860 JSObject* promiseCtor =
2861 GlobalObject::getOrCreatePromiseConstructor(cx, global);
2862 if (!promiseCtor) {
2863 return false;
2864 }
2865
2866 // Promise subclasses don't get the special Xray treatment, so
2867 // we only need to do the complex wrapping and unwrapping scheme
2868 // described above for instances of Promise itself.
2869 if (newTarget == promiseCtor) {
2870 needsWrapping = true;
2871 proto = GlobalObject::getOrCreatePromisePrototype(cx, cx->global());
2872 if (!proto) {
2873 return false;
2874 }
2875 }
2876 }
2877 }
2878
2879 if (needsWrapping) {
2880 if (!cx->compartment()->wrap(cx, &proto)) {
2881 return false;
2882 }
2883 } else {
2884 if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_Promise,
2885 &proto)) {
2886 return false;
2887 }
2888 }
2889 PromiseObject* promise =
2890 PromiseObject::create(cx, executor, proto, needsWrapping);
2891 if (!promise) {
2892 return false;
2893 }
2894
2895 // Step 11.
2896 args.rval().setObject(*promise);
2897 if (needsWrapping) {
2898 return cx->compartment()->wrap(cx, args.rval());
2899 }
2900 return true;
2901 }
2902
2903 bool js::IsPromiseConstructor(const JSObject* obj) {
2904 // Note: this also returns true for cross-realm Promise constructors in the
2905 // same compartment.
2906 return IsNativeFunction(obj, PromiseConstructor);
2907 }
2908
2909 /**
2910 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
2911 *
2912 * Promise ( executor )
2913 * https://tc39.es/ecma262/#sec-promise-executor
2914 *
2915 * Steps 3-11.
2916 */
2917 /* static */
2918 PromiseObject* PromiseObject::create(JSContext* cx, HandleObject executor,
2919 HandleObject proto /* = nullptr */,
2920 bool needsWrapping /* = false */) {
2921 MOZ_ASSERT(executor->isCallable());
2922
2923 RootedObject usedProto(cx, proto);
2924 // If the proto is wrapped, that means the current function is running
2925 // with a different compartment active from the one the Promise instance
2926 // is to be created in.
2927 // See the comment in PromiseConstructor for details.
2928 if (needsWrapping) {
2929 MOZ_ASSERT(proto);
2930 usedProto = CheckedUnwrapStatic(proto);
2931 if (!usedProto) {
2932 ReportAccessDenied(cx);
2933 return nullptr;
2934 }
2935 }
2936
2937 // Steps 3-7.
2938 Rooted<PromiseObject*> promise(
2939 cx, CreatePromiseObjectInternal(cx, usedProto, needsWrapping, false));
2940 if (!promise) {
2941 return nullptr;
2942 }
2943
2944 RootedObject promiseObj(cx, promise);
2945 if (needsWrapping && !cx->compartment()->wrap(cx, &promiseObj)) {
2946 return nullptr;
2947 }
2948
2949 // Step 8. Let resolvingFunctions be CreateResolvingFunctions(promise).
2950 //
2951 // The resolving functions are created in the compartment active when the
2952 // (maybe wrapped) Promise constructor was called. They contain checks and
2953 // can unwrap the Promise if required.
2954 RootedObject resolveFn(cx);
2955 RootedObject rejectFn(cx);
2956 if (!CreateResolvingFunctions(cx, promiseObj, &resolveFn, &rejectFn)) {
2957 return nullptr;
2958 }
2959
2960 // Need to wrap the resolution functions before storing them on the Promise.
2961 MOZ_ASSERT(promise->getFixedSlot(PromiseSlot_RejectFunction).isUndefined(),
2962 "Slot must be undefined so initFixedSlot can be used");
2963 if (needsWrapping) {
2964 AutoRealm ar(cx, promise);
2965 RootedObject wrappedRejectFn(cx, rejectFn);
2966 if (!cx->compartment()->wrap(cx, &wrappedRejectFn)) {
2967 return nullptr;
2968 }
2969 promise->initFixedSlot(PromiseSlot_RejectFunction,
2970 ObjectValue(*wrappedRejectFn));
2971 } else {
2972 promise->initFixedSlot(PromiseSlot_RejectFunction, ObjectValue(*rejectFn));
2973 }
2974
2975 // Step 9. Let completion be
2976 // Call(executor, undefined, « resolvingFunctions.[[Resolve]],
2977 // resolvingFunctions.[[Reject]] »).
2978 bool success;
2979 {
2980 FixedInvokeArgs<2> args(cx);
2981 args[0].setObject(*resolveFn);
2982 args[1].setObject(*rejectFn);
2983
2984 RootedValue calleeOrRval(cx, ObjectValue(*executor));
2985 success = Call(cx, calleeOrRval, UndefinedHandleValue, args, &calleeOrRval);
2986 }
2987
2988 // Step 10. If completion is an abrupt completion, then
2989 if (!success) {
2990 RootedValue exceptionVal(cx);
2991 Rooted<SavedFrame*> stack(cx);
2992 if (!MaybeGetAndClearExceptionAndStack(cx, &exceptionVal, &stack)) {
2993 return nullptr;
2994 }
2995
2996 // Step 10.a. Perform
2997 // ? Call(resolvingFunctions.[[Reject]], undefined,
2998 // « completion.[[Value]] »).
2999 RootedValue calleeOrRval(cx, ObjectValue(*rejectFn));
3000 if (!Call(cx, calleeOrRval, UndefinedHandleValue, exceptionVal,
3001 &calleeOrRval)) {
3002 return nullptr;
3003 }
3004 }
3005
3006 // Let the Debugger know about this Promise.
3007 DebugAPI::onNewPromise(cx, promise);
3008
3009 // Step 11. Return promise.
3010 return promise;
3011 }
3012
3013 /**
3014 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
3015 *
3016 * Promise ( executor )
3017 * https://tc39.es/ecma262/#sec-promise-executor
3018 *
3019 * skipping creation of resolution functions and executor function invocation.
3020 */
3021 /* static */
3022 PromiseObject* PromiseObject::createSkippingExecutor(JSContext* cx) {
3023 return CreatePromiseObjectWithoutResolutionFunctions(cx);
3024 }
3025
3026 class MOZ_STACK_CLASS PromiseForOfIterator : public JS::ForOfIterator {
3027 public:
3028 using JS::ForOfIterator::ForOfIterator;
3029
3030 bool isOptimizedDenseArrayIteration() {
3031 MOZ_ASSERT(valueIsIterable());
3032 return index != NOT_ARRAY && IsPackedArray(iterator);
3033 }
3034 };
3035
3036 [[nodiscard]] static bool PerformPromiseAll(
3037 JSContext* cx, PromiseForOfIterator& iterator, HandleObject C,
3038 Handle<PromiseCapability> resultCapability, HandleValue promiseResolve,
3039 bool* done);
3040
3041 [[nodiscard]] static bool PerformPromiseAllSettled(
3042 JSContext* cx, PromiseForOfIterator& iterator, HandleObject C,
3043 Handle<PromiseCapability> resultCapability, HandleValue promiseResolve,
3044 bool* done);
3045
3046 [[nodiscard]] static bool PerformPromiseAny(
3047 JSContext* cx, PromiseForOfIterator& iterator, HandleObject C,
3048 Handle<PromiseCapability> resultCapability, HandleValue promiseResolve,
3049 bool* done);
3050
3051 [[nodiscard]] static bool PerformPromiseRace(
3052 JSContext* cx, PromiseForOfIterator& iterator, HandleObject C,
3053 Handle<PromiseCapability> resultCapability, HandleValue promiseResolve,
3054 bool* done);
3055
3056 enum class CombinatorKind { All, AllSettled, Any, Race };
3057
3058 /**
3059 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
3060 *
3061 * Unified implementation of
3062 *
3063 * Promise.all ( iterable )
3064 * https://tc39.es/ecma262/#sec-promise.all
3065 * Promise.allSettled ( iterable )
3066 * https://tc39.es/ecma262/#sec-promise.allsettled
3067 * Promise.race ( iterable )
3068 * https://tc39.es/ecma262/#sec-promise.race
3069 * Promise.any ( iterable )
3070 * https://tc39.es/ecma262/#sec-promise.any
3071 * GetPromiseResolve ( promiseConstructor )
3072 * https://tc39.es/ecma262/#sec-getpromiseresolve
3073 */
3074 [[nodiscard]] static bool CommonPromiseCombinator(JSContext* cx, CallArgs& args,
3075 CombinatorKind kind) {
3076 HandleValue iterable = args.get(0);
3077
3078 // Step 2. Let promiseCapability be ? NewPromiseCapability(C).
3079 // (moved from NewPromiseCapability, step 1).
3080 HandleValue CVal = args.thisv();
3081 if (!CVal.isObject()) {
3082 const char* message;
3083 switch (kind) {
3084 case CombinatorKind::All:
3085 message = "Receiver of Promise.all call";
3086 break;
3087 case CombinatorKind::AllSettled:
3088 message = "Receiver of Promise.allSettled call";
3089 break;
3090 case CombinatorKind::Any:
3091 message = "Receiver of Promise.any call";
3092 break;
3093 case CombinatorKind::Race:
3094 message = "Receiver of Promise.race call";
3095 break;
3096 }
3097 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3098 JSMSG_OBJECT_REQUIRED, message);
3099 return false;
3100 }
3101
3102 // Step 1. Let C be the this value.
3103 RootedObject C(cx, &CVal.toObject());
3104
3105 // Step 2. Let promiseCapability be ? NewPromiseCapability(C).
3106 Rooted<PromiseCapability> promiseCapability(cx);
3107 if (!NewPromiseCapability(cx, C, &promiseCapability, false)) {
3108 return false;
3109 }
3110
3111 RootedValue promiseResolve(cx, UndefinedValue());
3112 {
3113 JSObject* promiseCtor =
3114 GlobalObject::getOrCreatePromiseConstructor(cx, cx->global());
3115 if (!promiseCtor) {
3116 return false;
3117 }
3118
3119 if (C != promiseCtor || !HasDefaultPromiseProperties(cx)) {
3120 // Step 3. Let promiseResolve be GetPromiseResolve(C).
3121
3122 // GetPromiseResolve
3123 // Step 1. Let promiseResolve be ? Get(promiseConstructor, "resolve").
3124 if (!GetProperty(cx, C, C, cx->names().resolve, &promiseResolve)) {
3125 // Step 4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
3126 return AbruptRejectPromise(cx, args, promiseCapability);
3127 }
3128
3129 // GetPromiseResolve
3130 // Step 2. If IsCallable(promiseResolve) is false,
3131 // throw a TypeError exception.
3132 if (!IsCallable(promiseResolve)) {
3133 ReportIsNotFunction(cx, promiseResolve);
3134
3135 // Step 4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
3136 return AbruptRejectPromise(cx, args, promiseCapability);
3137 }
3138 }
3139 }
3140
3141 // Step 5. Let iteratorRecord be GetIterator(iterable).
3142 PromiseForOfIterator iter(cx);
3143 if (!iter.init(iterable, JS::ForOfIterator::AllowNonIterable)) {
3144 // Step 6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
3145 return AbruptRejectPromise(cx, args, promiseCapability);
3146 }
3147
3148 if (!iter.valueIsIterable()) {
3149 // Step 6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
3150 const char* message;
3151 switch (kind) {
3152 case CombinatorKind::All:
3153 message = "Argument of Promise.all";
3154 break;
3155 case CombinatorKind::AllSettled:
3156 message = "Argument of Promise.allSettled";
3157 break;
3158 case CombinatorKind::Any:
3159 message = "Argument of Promise.any";
3160 break;
3161 case CombinatorKind::Race:
3162 message = "Argument of Promise.race";
3163 break;
3164 }
3165 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_NOT_ITERABLE,
3166 message);
3167 return AbruptRejectPromise(cx, args, promiseCapability);
3168 }
3169
3170 bool done, result;
3171 switch (kind) {
3172 case CombinatorKind::All:
3173 // Promise.all
3174 // Step 7. Let result be
3175 // PerformPromiseAll(iteratorRecord, C, promiseCapability,
3176 // promiseResolve).
3177 result = PerformPromiseAll(cx, iter, C, promiseCapability, promiseResolve,
3178 &done);
3179 break;
3180 case CombinatorKind::AllSettled:
3181 // Promise.allSettled
3182 // Step 7. Let result be
3183 // PerformPromiseAllSettled(iteratorRecord, C, promiseCapability,
3184 // promiseResolve).
3185 result = PerformPromiseAllSettled(cx, iter, C, promiseCapability,
3186 promiseResolve, &done);
3187 break;
3188 case CombinatorKind::Any:
3189 // Promise.any
3190 // Step 7. Let result be
3191 // PerformPromiseAny(iteratorRecord, C, promiseCapability,
3192 // promiseResolve).
3193 result = PerformPromiseAny(cx, iter, C, promiseCapability, promiseResolve,
3194 &done);
3195 break;
3196 case CombinatorKind::Race:
3197 // Promise.race
3198 // Step 7. Let result be
3199 // PerformPromiseRace(iteratorRecord, C, promiseCapability,
3200 // promiseResolve).
3201 result = PerformPromiseRace(cx, iter, C, promiseCapability,
3202 promiseResolve, &done);
3203 break;
3204 }
3205
3206 // Step 8. If result is an abrupt completion, then
3207 if (!result) {
3208 // Step 8.a. If iteratorRecord.[[Done]] is false,
3209 // set result to IteratorClose(iteratorRecord, result).
3210 if (!done) {
3211 iter.closeThrow();
3212 }
3213
3214 // Step 8.b. IfAbruptRejectPromise(result, promiseCapability).
3215 return AbruptRejectPromise(cx, args, promiseCapability);
3216 }
3217
3218 // Step 9. Return Completion(result).
3219 args.rval().setObject(*promiseCapability.promise());
3220 return true;
3221 }
3222
3223 /**
3224 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
3225 *
3226 * Promise.all ( iterable )
3227 * https://tc39.es/ecma262/#sec-promise.all
3228 */
3229 static bool Promise_static_all(JSContext* cx, unsigned argc, Value* vp) {
3230 CallArgs args = CallArgsFromVp(argc, vp);
3231 return CommonPromiseCombinator(cx, args, CombinatorKind::All);
3232 }
3233
3234 [[nodiscard]] static bool PerformPromiseThen(
3235 JSContext* cx, Handle<PromiseObject*> promise, HandleValue onFulfilled_,
3236 HandleValue onRejected_, Handle<PromiseCapability> resultCapability);
3237
3238 [[nodiscard]] static bool PerformPromiseThenWithoutSettleHandlers(
3239 JSContext* cx, Handle<PromiseObject*> promise,
3240 Handle<PromiseObject*> promiseToResolve,
3241 Handle<PromiseCapability> resultCapability);
3242
3243 static JSFunction* NewPromiseCombinatorElementFunction(
3244 JSContext* cx, Native native,
3245 Handle<PromiseCombinatorDataHolder*> dataHolder, uint32_t index,
3246 Handle<Value> maybeResolveFunc);
3247
3248 static bool PromiseAllResolveElementFunction(JSContext* cx, unsigned argc,
3249 Value* vp);
3250
3251 /**
3252 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
3253 *
3254 * Promise.all ( iterable )
3255 * https://tc39.es/ecma262/#sec-promise.all
3256 * PerformPromiseAll ( iteratorRecord, constructor, resultCapability,
3257 * promiseResolve )
3258 * https://tc39.es/ecma262/#sec-performpromiseall
3259 *
3260 * Unforgeable version.
3261 */
3262 [[nodiscard]] JSObject* js::GetWaitForAllPromise(
3263 JSContext* cx, JS::HandleObjectVector promises) {
3264 #ifdef DEBUG
3265 for (size_t i = 0, len = promises.length(); i < len; i++) {
3266 JSObject* obj = promises[i];
3267 cx->check(obj);
3268 JSObject* unwrapped = UncheckedUnwrap(obj);
3269 MOZ_ASSERT(unwrapped->is<PromiseObject>() || JS_IsDeadWrapper(unwrapped));
3270 }
3271 #endif
3272
3273 // Step 1. Let C be the this value.
3274 RootedObject C(cx,
3275 GlobalObject::getOrCreatePromiseConstructor(cx, cx->global()));
3276 if (!C) {
3277 return nullptr;
3278 }
3279
3280 // Step 2. Let promiseCapability be ? NewPromiseCapability(C).
3281 Rooted<PromiseCapability> resultCapability(cx);
3282 if (!NewPromiseCapability(cx, C, &resultCapability, false)) {
3283 return nullptr;
3284 }
3285
3286 // Steps 3-6 for iterator and iteratorRecord.
3287 // (omitted)
3288
3289 // Step 7. Let result be
3290 // PerformPromiseAll(iteratorRecord, C, promiseCapability,
3291 // promiseResolve).
3292 //
3293 // Implemented as an inlined, simplied version of PerformPromiseAll.
3294 {
3295 uint32_t promiseCount = promises.length();
3296 // PerformPromiseAll
3297
3298 // Step 1. Let values be a new empty List.
3299 Rooted<PromiseCombinatorElements> values(cx);
3300 {
3301 auto* valuesArray = NewDenseFullyAllocatedArray(cx, promiseCount);
3302 if (!valuesArray) {
3303 return nullptr;
3304 }
3305 valuesArray->ensureDenseInitializedLength(0, promiseCount);
3306
3307 values.initialize(valuesArray);
3308 }
3309
3310 // Step 2. Let remainingElementsCount be the Record { [[Value]]: 1 }.
3311 //
3312 // Create our data holder that holds all the things shared across
3313 // every step of the iterator. In particular, this holds the
3314 // remainingElementsCount (as an integer reserved slot), the array of
3315 // values, and the resolve function from our PromiseCapability.
3316 Rooted<PromiseCombinatorDataHolder*> dataHolder(cx);
3317 dataHolder = PromiseCombinatorDataHolder::New(
3318 cx, resultCapability.promise(), values, resultCapability.resolve());
3319 if (!dataHolder) {
3320 return nullptr;
3321 }
3322
3323 // Call PerformPromiseThen with resolve and reject set to nullptr.
3324 Rooted<PromiseCapability> resultCapabilityWithoutResolving(cx);
3325 resultCapabilityWithoutResolving.promise().set(resultCapability.promise());
3326
3327 // Step 3. Let index be 0.
3328 // Step 4. Repeat,
3329 // Step 4.t. Set index to index + 1.
3330 for (uint32_t index = 0; index < promiseCount; index++) {
3331 // Steps 4.a-c for IteratorStep.
3332 // (omitted)
3333
3334 // Step 4.d. (implemented after the loop).
3335
3336 // Steps 4.e-g for IteratorValue
3337 // (omitted)
3338
3339 // Step 4.h. Append undefined to values.
3340 values.unwrappedArray()->setDenseElement(index, UndefinedHandleValue);
3341
3342 // Step 4.i. Let nextPromise be
3343 // ? Call(promiseResolve, constructor, « nextValue »).
3344 RootedObject nextPromiseObj(cx, promises[index]);
3345
3346 // Steps 4.j-q.
3347 JSFunction* resolveFunc = NewPromiseCombinatorElementFunction(
3348 cx, PromiseAllResolveElementFunction, dataHolder, index,
3349 UndefinedHandleValue);
3350 if (!resolveFunc) {
3351 return nullptr;
3352 }
3353
3354 // Step 4.r. Set remainingElementsCount.[[Value]] to
3355 // remainingElementsCount.[[Value]] + 1.
3356 dataHolder->increaseRemainingCount();
3357
3358 // Step 4.s. Perform
3359 // ? Invoke(nextPromise, "then",
3360 // « onFulfilled, resultCapability.[[Reject]] »).
3361 RootedValue resolveFunVal(cx, ObjectValue(*resolveFunc));
3362 RootedValue rejectFunVal(cx, ObjectValue(*resultCapability.reject()));
3363 Rooted<PromiseObject*> nextPromise(cx);
3364
3365 // GetWaitForAllPromise is used internally only and must not
3366 // trigger content-observable effects when registering a reaction.
3367 // It's also meant to work on wrapped Promises, potentially from
3368 // compartments with principals inaccessible from the current
3369 // compartment. To make that work, it unwraps promises with
3370 // UncheckedUnwrap,
3371 JSObject* unwrapped = UncheckedUnwrap(nextPromiseObj);
3372 if (JS_IsDeadWrapper(unwrapped)) {
3373 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3374 JSMSG_DEAD_OBJECT);
3375 return nullptr;
3376 }
3377 nextPromise = &unwrapped->as<PromiseObject>();
3378
3379 if (!PerformPromiseThen(cx, nextPromise, resolveFunVal, rejectFunVal,
3380 resultCapabilityWithoutResolving)) {
3381 return nullptr;
3382 }
3383 }
3384
3385 // Step 4.d.i. Set iteratorRecord.[[Done]] to true.
3386 // (implicit)
3387
3388 // Step 4.d.ii. Set remainingElementsCount.[[Value]] to
3389 // remainingElementsCount.[[Value]] - 1.
3390 int32_t remainingCount = dataHolder->decreaseRemainingCount();
3391
3392 // Step 4.d.iii.If remainingElementsCount.[[Value]] is 0, then
3393 if (remainingCount == 0) {
3394 // Step 4.d.iii.1. Let valuesArray be ! CreateArrayFromList(values).
3395 // (already performed)
3396
3397 // Step 4.d.iii.2. Perform
3398 // ? Call(resultCapability.[[Resolve]], undefined,
3399 // « valuesArray »).
3400 if (!ResolvePromiseInternal(cx, resultCapability.promise(),
3401 values.value())) {
3402 return nullptr;
3403 }
3404 }
3405 }
3406
3407 // Step 4.d.iv. Return resultCapability.[[Promise]].
3408 return resultCapability.promise();
3409 }
3410
3411 static bool CallDefaultPromiseResolveFunction(JSContext* cx,
3412 Handle<PromiseObject*> promise,
3413 HandleValue resolutionValue);
3414 static bool CallDefaultPromiseRejectFunction(
3415 JSContext* cx, Handle<PromiseObject*> promise, HandleValue rejectionValue,
3416 JS::Handle<SavedFrame*> unwrappedRejectionStack = nullptr);
3417
3418 /**
3419 * Perform Call(promiseCapability.[[Resolve]], undefined ,« value ») given
3420 * promiseCapability = { promiseObj, resolveFun }.
3421 *
3422 * Also,
3423 *
3424 * ES2023 draft rev 714fa3dd1e8237ae9c666146270f81880089eca5
3425 *
3426 * NewPromiseReactionJob ( reaction, argument )
3427 * https://tc39.es/ecma262/#sec-newpromisereactionjob
3428 *
3429 * Steps 1.f-i. "type is Fulfill" case.
3430 */
3431 [[nodiscard]] static bool CallPromiseResolveFunction(JSContext* cx,
3432 HandleObject resolveFun,
3433 HandleValue value,
3434 HandleObject promiseObj) {
3435 cx->check(resolveFun);
3436 cx->check(value);
3437 cx->check(promiseObj);
3438
3439 // NewPromiseReactionJob
3440 // Step 1.g. Assert: promiseCapability is a PromiseCapability Record.
3441 // (implicit)
3442
3443 if (resolveFun) {
3444 // NewPromiseReactionJob
3445 // Step 1.h. If handlerResult is an abrupt completion, then
3446 // (handled in CallPromiseRejectFunction)
3447 // Step 1.i. Else,
3448 // Step 1.i.i. Return
3449 // ? Call(promiseCapability.[[Resolve]], undefined,
3450 // « handlerResult.[[Value]] »).
3451 RootedValue calleeOrRval(cx, ObjectValue(*resolveFun));
3452 return Call(cx, calleeOrRval, UndefinedHandleValue, value, &calleeOrRval);
3453 }
3454
3455 // `promiseObj` can be optimized away if it's known to be unused.
3456 //
3457 // NewPromiseReactionJob
3458 // Step f. If promiseCapability is undefined, then
3459 // (reordered)
3460 //
3461 // NOTE: "promiseCapability is undefined" case is represented by
3462 // `resolveFun == nullptr && promiseObj == nullptr`.
3463 if (!promiseObj) {
3464 // NewPromiseReactionJob
3465 // Step f.i. Assert: handlerResult is not an abrupt completion.
3466 // (implicit)
3467
3468 // Step f.ii. Return empty.
3469 return true;
3470 }
3471
3472 // NewPromiseReactionJob
3473 // Step 1.h. If handlerResult is an abrupt completion, then
3474 // (handled in CallPromiseRejectFunction)
3475 // Step 1.i. Else,
3476 // Step 1.i.i. Return
3477 // ? Call(promiseCapability.[[Resolve]], undefined,
3478 // « handlerResult.[[Value]] »).
3479 Handle<PromiseObject*> promise = promiseObj.as<PromiseObject>();
3480 if (IsPromiseWithDefaultResolvingFunction(promise)) {
3481 return CallDefaultPromiseResolveFunction(cx, promise, value);
3482 }
3483
3484 // This case is used by resultCapabilityWithoutResolving in
3485 // GetWaitForAllPromise, and nothing should be done.
3486
3487 return true;
3488 }
3489
3490 /**
3491 * Perform Call(promiseCapability.[[Reject]], undefined ,« reason ») given
3492 * promiseCapability = { promiseObj, rejectFun }.
3493 *
3494 * Also,
3495 *
3496 * ES2023 draft rev 714fa3dd1e8237ae9c666146270f81880089eca5
3497 *
3498 * NewPromiseReactionJob ( reaction, argument )
3499 * https://tc39.es/ecma262/#sec-newpromisereactionjob
3500 *
3501 * Steps 1.g-i. "type is Reject" case.
3502 */
3503 [[nodiscard]] static bool CallPromiseRejectFunction(
3504 JSContext* cx, HandleObject rejectFun, HandleValue reason,
3505 HandleObject promiseObj, Handle<SavedFrame*> unwrappedRejectionStack,
3506 UnhandledRejectionBehavior behavior) {
3507 cx->check(rejectFun);
3508 cx->check(reason);
3509 cx->check(promiseObj);
3510
3511 // NewPromiseReactionJob
3512 // Step 1.g. Assert: promiseCapability is a PromiseCapability Record.
3513 // (implicit)
3514
3515 if (rejectFun) {
3516 // NewPromiseReactionJob
3517 // Step 1.h. If handlerResult is an abrupt completion, then
3518 // Step 1.h.i. Return
3519 // ? Call(promiseCapability.[[Reject]], undefined,
3520 // « handlerResult.[[Value]] »).
3521 RootedValue calleeOrRval(cx, ObjectValue(*rejectFun));
3522 return Call(cx, calleeOrRval, UndefinedHandleValue, reason, &calleeOrRval);
3523 }
3524
3525 // NewPromiseReactionJob
3526 // See the comment in CallPromiseResolveFunction for promiseCapability field
3527 //
3528 // Step f. If promiseCapability is undefined, then
3529 // Step f.i. Assert: handlerResult is not an abrupt completion.
3530 //
3531 // The spec doesn't allow promiseCapability to be undefined for reject case,
3532 // but `promiseObj` can be optimized away if it's known to be unused.
3533 if (!promiseObj) {
3534 if (behavior == UnhandledRejectionBehavior::Ignore) {
3535 // Do nothing if unhandled rejections are to be ignored.
3536 return true;
3537 }
3538
3539 // Otherwise create and reject a promise on the fly. The promise's
3540 // allocation time will be wrong. So it goes.
3541 Rooted<PromiseObject*> temporaryPromise(
3542 cx, CreatePromiseObjectWithoutResolutionFunctions(cx));
3543 if (!temporaryPromise) {
3544 cx->clearPendingException();
3545 return true;
3546 }
3547
3548 // NewPromiseReactionJob
3549 // Step 1.h. If handlerResult is an abrupt completion, then
3550 // Step 1.h.i. Return
3551 // ? Call(promiseCapability.[[Reject]], undefined,
3552 // « handlerResult.[[Value]] »).
3553 return RejectPromiseInternal(cx, temporaryPromise, reason,
3554 unwrappedRejectionStack);
3555 }
3556
3557 // NewPromiseReactionJob
3558 // Step 1.h. If handlerResult is an abrupt completion, then
3559 // Step 1.h.i. Return
3560 // ? Call(promiseCapability.[[Reject]], undefined,
3561 // « handlerResult.[[Value]] »).
3562 Handle<PromiseObject*> promise = promiseObj.as<PromiseObject>();
3563 if (IsPromiseWithDefaultResolvingFunction(promise)) {
3564 return CallDefaultPromiseRejectFunction(cx, promise, reason,
3565 unwrappedRejectionStack);
3566 }
3567
3568 // This case is used by resultCapabilityWithoutResolving in
3569 // GetWaitForAllPromise, and nothing should be done.
3570
3571 return true;
3572 }
3573
3574 [[nodiscard]] static JSObject* CommonStaticResolveRejectImpl(
3575 JSContext* cx, HandleValue thisVal, HandleValue argVal,
3576 ResolutionMode mode);
3577
3578 static bool IsPromiseSpecies(JSContext* cx, JSFunction* species);
3579
3580 /**
3581 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
3582 *
3583 * Unified implementation of
3584 *
3585 * PerformPromiseAll ( iteratorRecord, constructor, resultCapability,
3586 * promiseResolve )
3587 * https://tc39.es/ecma262/#sec-performpromiseall
3588 * PerformPromiseAllSettled ( iteratorRecord, constructor, resultCapability,
3589 * promiseResolve )
3590 * https://tc39.es/ecma262/#sec-performpromiseallsettled
3591 * PerformPromiseRace ( iteratorRecord, constructor, resultCapability,
3592 * promiseResolve )
3593 * https://tc39.es/ecma262/#sec-performpromiserace
3594 * PerformPromiseAny ( iteratorRecord, constructor, resultCapability,
3595 * promiseResolve )
3596 * https://tc39.es/ecma262/#sec-performpromiseany
3597 *
3598 * Promise.prototype.then ( onFulfilled, onRejected )
3599 * https://tc39.es/ecma262/#sec-promise.prototype.then
3600 */
3601 template <typename T>
3602 [[nodiscard]] static bool CommonPerformPromiseCombinator(
3603 JSContext* cx, PromiseForOfIterator& iterator, HandleObject C,
3604 HandleObject resultPromise, HandleValue promiseResolve, bool* done,
3605 bool resolveReturnsUndefined, T getResolveAndReject) {
3606 RootedObject promiseCtor(
3607 cx, GlobalObject::getOrCreatePromiseConstructor(cx, cx->global()));
3608 if (!promiseCtor) {
3609 return false;
3610 }
3611
3612 // Optimized dense array iteration ensures no side-effects take place
3613 // during the iteration.
3614 bool iterationMayHaveSideEffects = !iterator.isOptimizedDenseArrayIteration();
3615
3616 // Try to optimize when the Promise object is in its default state, guarded
3617 // by |C == promiseCtor| because we can only perform this optimization
3618 // for the builtin Promise constructor.
3619 bool isDefaultPromiseState =
3620 C == promiseCtor && HasDefaultPromiseProperties(cx);
3621 bool validatePromiseState = iterationMayHaveSideEffects;
3622
3623 RootedValue CVal(cx, ObjectValue(*C));
3624 RootedValue resolveFunVal(cx);
3625 RootedValue rejectFunVal(cx);
3626
3627 // We're reusing rooted variables in the loop below, so we don't need to
3628 // declare a gazillion different rooted variables here. Rooted variables
3629 // which are reused include "Or" in their name.
3630 RootedValue nextValueOrNextPromise(cx);
3631 RootedObject nextPromiseObj(cx);
3632 RootedValue thenVal(cx);
3633 RootedObject thenSpeciesOrBlockedPromise(cx);
3634 Rooted<PromiseCapability> thenCapability(cx);
3635
3636 // PerformPromiseAll, PerformPromiseAllSettled, PerformPromiseAny
3637 // Step 4.
3638 // PerformPromiseRace
3639 // Step 1.
3640 while (true) {
3641 // Step a. Let next be IteratorStep(iteratorRecord).
3642 // Step b. If next is an abrupt completion, set iteratorRecord.[[Done]] to
3643 // true.
3644 // Step c. ReturnIfAbrupt(next).
3645 // Step e. Let nextValue be IteratorValue(next).
3646 // Step f. If nextValue is an abrupt completion, set iteratorRecord.[[Done]]
3647 // to true.
3648 // Step g. ReturnIfAbrupt(nextValue).
3649 RootedValue& nextValue = nextValueOrNextPromise;
3650 if (!iterator.next(&nextValue, done)) {
3651 *done = true;
3652 return false;
3653 }
3654
3655 // Step d. If next is false, then
3656 if (*done) {
3657 return true;
3658 }
3659
3660 // Set to false when we can skip the [[Get]] for "then" and instead
3661 // use the built-in Promise.prototype.then function.
3662 bool getThen = true;
3663
3664 if (isDefaultPromiseState && validatePromiseState) {
3665 isDefaultPromiseState = HasDefaultPromiseProperties(cx);
3666 }
3667
3668 RootedValue& nextPromise = nextValueOrNextPromise;
3669 if (isDefaultPromiseState) {
3670 PromiseObject* nextValuePromise = nullptr;
3671 if (nextValue.isObject() && nextValue.toObject().is<PromiseObject>()) {
3672 nextValuePromise = &nextValue.toObject().as<PromiseObject>();
3673 }
3674
3675 if (nextValuePromise &&
3676 IsPromiseWithDefaultProperties(nextValuePromise, cx)) {
3677 // The below steps don't produce any side-effects, so we can
3678 // skip the Promise state revalidation in the next iteration
3679 // when the iterator itself also doesn't produce any
3680 // side-effects.
3681 validatePromiseState = iterationMayHaveSideEffects;
3682
3683 // Step {i, h}. Let nextPromise be
3684 // ? Call(promiseResolve, constructor, « nextValue »).
3685 // Promise.resolve is a no-op for the default case.
3686 MOZ_ASSERT(&nextPromise.toObject() == nextValuePromise);
3687
3688 // `nextPromise` uses the built-in `then` function.
3689 getThen = false;
3690 } else {
3691 // Need to revalidate the Promise state in the next iteration,
3692 // because CommonStaticResolveRejectImpl may have modified it.
3693 validatePromiseState = true;
3694
3695 // Step {i, h}. Let nextPromise be
3696 // ? Call(promiseResolve, constructor, « nextValue »).
3697 // Inline the call to Promise.resolve.
3698 JSObject* res =
3699 CommonStaticResolveRejectImpl(cx, CVal, nextValue, ResolveMode);
3700 if (!res) {
3701 return false;
3702 }
3703
3704 nextPromise.setObject(*res);
3705 }
3706 } else if (promiseResolve.isUndefined()) {
3707 // |promiseResolve| is undefined when the Promise constructor was
3708 // initially in its default state, i.e. if it had been retrieved, it would
3709 // have been set to |Promise.resolve|.
3710
3711 // Step {i, h}. Let nextPromise be
3712 // ? Call(promiseResolve, constructor, « nextValue »).
3713 // Inline the call to Promise.resolve.
3714 JSObject* res =
3715 CommonStaticResolveRejectImpl(cx, CVal, nextValue, ResolveMode);
3716 if (!res) {
3717 return false;
3718 }
3719
3720 nextPromise.setObject(*res);
3721 } else {
3722 // Step {i, h}. Let nextPromise be
3723 // ? Call(promiseResolve, constructor, « nextValue »).
3724 if (!Call(cx, promiseResolve, CVal, nextValue, &nextPromise)) {
3725 return false;
3726 }
3727 }
3728
3729 // Get the resolving functions for this iteration.
3730 // PerformPromiseAll
3731 // Steps j-r.
3732 // PerformPromiseAllSettled
3733 // Steps j-aa.
3734 // PerformPromiseRace
3735 // Step i.
3736 // PerformPromiseAny
3737 // Steps j-q.
3738 if (!getResolveAndReject(&resolveFunVal, &rejectFunVal)) {
3739 return false;
3740 }
3741
3742 // Call |nextPromise.then| with the provided hooks and add
3743 // |resultPromise| to the list of dependent promises.
3744 //
3745 // If |nextPromise.then| is the original |Promise.prototype.then|
3746 // function and the call to |nextPromise.then| would use the original
3747 // |Promise| constructor to create the resulting promise, we skip the
3748 // call to |nextPromise.then| and thus creating a new promise that
3749 // would not be observable by content.
3750
3751 // PerformPromiseAll
3752 // Step s. Perform
3753 // ? Invoke(nextPromise, "then",
3754 // « onFulfilled, resultCapability.[[Reject]] »).
3755 // PerformPromiseAllSettled
3756 // Step ab. Perform
3757 // ? Invoke(nextPromise, "then", « onFulfilled, onRejected »).
3758 // PerformPromiseRace
3759 // Step i. Perform
3760 // ? Invoke(nextPromise, "then",
3761 // « resultCapability.[[Resolve]],
3762 // resultCapability.[[Reject]] »).
3763 // PerformPromiseAny
3764 // Step s. Perform
3765 // ? Invoke(nextPromise, "then",
3766 // « resultCapability.[[Resolve]], onRejected »).
3767 nextPromiseObj = ToObject(cx, nextPromise);
3768 if (!nextPromiseObj) {
3769 return false;
3770 }
3771
3772 bool isBuiltinThen;
3773 bool isOnProto = false;
3774 bool isOnStandardProto = false;
3775 bool isOnObjectProto = false;
3776 if (getThen) {
3777 // We don't use the Promise lookup cache here, because this code
3778 // is only called when we had a lookup cache miss, so it's likely
3779 // we'd get another cache miss when trying to use the cache here.
3780 if (!GetThenValue(cx, nextPromiseObj, nextPromise, &thenVal, &isOnProto,
3781 &isOnStandardProto, &isOnObjectProto)) {
3782 return false;
3783 }
3784
3785 // |nextPromise| is an unwrapped Promise, and |then| is the
3786 // original |Promise.prototype.then|, inline it here.
3787 isBuiltinThen = nextPromiseObj->is<PromiseObject>() &&
3788 IsNativeFunction(thenVal, Promise_then);
3789 } else {
3790 isBuiltinThen = true;
3791 }
3792
3793 // By default, the blocked promise is added as an extra entry to the
3794 // rejected promises list.
3795 bool addToDependent = true;
3796
3797 if (isBuiltinThen) {
3798 MOZ_ASSERT(nextPromise.isObject());
3799 MOZ_ASSERT(&nextPromise.toObject() == nextPromiseObj);
3800
3801 // Promise.prototype.then
3802 // Step 3. Let C be ? SpeciesConstructor(promise, %Promise%).
3803 RootedObject& thenSpecies = thenSpeciesOrBlockedPromise;
3804 if (getThen) {
3805 thenSpecies = SpeciesConstructor(cx, nextPromiseObj, JSProto_Promise,
3806 IsPromiseSpecies);
3807 if (!thenSpecies) {
3808 return false;
3809 }
3810 } else {
3811 thenSpecies = promiseCtor;
3812 }
3813
3814 // The fast path here and the one in NewPromiseCapability may not
3815 // set the resolve and reject handlers, so we need to clear the
3816 // fields in case they were set in the previous iteration.
3817 thenCapability.resolve().set(nullptr);
3818 thenCapability.reject().set(nullptr);
3819
3820 // Skip the creation of a built-in Promise object if:
3821 // 1. `thenSpecies` is the built-in Promise constructor.
3822 // 2. `resolveFun` doesn't return an object, which ensures no side effects
3823 // occur in ResolvePromiseInternal.
3824 // 3. The result promise is a built-in Promise object.
3825 // 4. The result promise doesn't use the default resolving functions,
3826 // which in turn means Run{Fulfill,Reject}Function when called from
3827 // PromiseReactionJob won't try to resolve the promise.
3828 if (thenSpecies == promiseCtor && resolveReturnsUndefined &&
3829 resultPromise->is<PromiseObject>() &&
3830 !IsPromiseWithDefaultResolvingFunction(
3831 &resultPromise->as<PromiseObject>())) {
3832 thenCapability.promise().set(resultPromise);
3833 addToDependent = false;
3834 } else {
3835 // Promise.prototype.then
3836 // Step 4. Let resultCapability be ? NewPromiseCapability(C).
3837 if (!NewPromiseCapability(cx, thenSpecies, &thenCapability, true)) {
3838 return false;
3839 }
3840 }
3841
3842 // Promise.prototype.then
3843 // Step 5. Return
3844 // PerformPromiseThen(promise, onFulfilled, onRejected,
3845 // resultCapability).
3846 Handle<PromiseObject*> promise = nextPromiseObj.as<PromiseObject>();
3847 if (!PerformPromiseThen(cx, promise, resolveFunVal, rejectFunVal,
3848 thenCapability)) {
3849 return false;
3850 }
3851 } else {
3852 ReportThenable(cx, isOnProto, isOnStandardProto, isOnObjectProto);
3853
3854 RootedValue& ignored = thenVal;
3855 if (!Call(cx, thenVal, nextPromise, resolveFunVal, rejectFunVal,
3856 &ignored)) {
3857 return false;
3858 }
3859
3860 // In case the value to depend on isn't an object at all, there's
3861 // nothing more to do here: we can only add reactions to Promise
3862 // objects (potentially after unwrapping them), and non-object
3863 // values can't be Promise objects. This can happen if Promise.all
3864 // is called on an object with a `resolve` method that returns
3865 // primitives.
3866 if (!nextPromise.isObject()) {
3867 addToDependent = false;
3868 }
3869 }
3870
3871 // Adds |resultPromise| to the list of dependent promises.
3872 if (addToDependent) {
3873 // The object created by the |promise.then| call or the inlined
3874 // version of it above is visible to content (either because
3875 // |promise.then| was overridden by content and could leak it,
3876 // or because a constructor other than the original value of
3877 // |Promise| was used to create it). To have both that object and
3878 // |resultPromise| show up as dependent promises in the debugger,
3879 // add a dummy reaction to the list of reject reactions that
3880 // contains |resultPromise|, but otherwise does nothing.
3881 RootedObject& blockedPromise = thenSpeciesOrBlockedPromise;
3882 blockedPromise = resultPromise;
3883
3884 mozilla::Maybe<AutoRealm> ar;
3885 if (IsProxy(nextPromiseObj)) {
3886 nextPromiseObj = CheckedUnwrapStatic(nextPromiseObj);
3887 if (!nextPromiseObj) {
3888 ReportAccessDenied(cx);
3889 return false;
3890 }
3891 if (JS_IsDeadWrapper(nextPromiseObj)) {
3892 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3893 JSMSG_DEAD_OBJECT);
3894 return false;
3895 }
3896 ar.emplace(cx, nextPromiseObj);
3897 if (!cx->compartment()->wrap(cx, &blockedPromise)) {
3898 return false;
3899 }
3900 }
3901
3902 // If either the object to depend on (`nextPromiseObj`) or the
3903 // object that gets blocked (`resultPromise`) isn't a,
3904 // maybe-wrapped, Promise instance, we ignore it. All this does is
3905 // lose some small amount of debug information in scenarios that
3906 // are highly unlikely to occur in useful code.
3907 if (nextPromiseObj->is<PromiseObject>() &&
3908 resultPromise->is<PromiseObject>()) {
3909 Handle<PromiseObject*> promise = nextPromiseObj.as<PromiseObject>();
3910 if (!AddDummyPromiseReactionForDebugger(cx, promise, blockedPromise)) {
3911 return false;
3912 }
3913 }
3914 }
3915 }
3916 }
3917
3918 // Create the elements for the Promise combinators Promise.all and
3919 // Promise.allSettled.
3920 [[nodiscard]] static bool NewPromiseCombinatorElements(
3921 JSContext* cx, Handle<PromiseCapability> resultCapability,
3922 MutableHandle<PromiseCombinatorElements> elements) {
3923 // We have to be very careful about which compartments we create things for
3924 // the Promise combinators. In particular, we have to maintain the invariant
3925 // that anything stored in a reserved slot is same-compartment with the object
3926 // whose reserved slot it's in. But we want to create the values array in the
3927 // compartment of the result capability's Promise, because that array can get
3928 // exposed as the Promise's resolution value to code that has access to the
3929 // Promise (in particular code from that compartment), and that should work,
3930 // even if the Promise compartment is less-privileged than our caller
3931 // compartment.
3932 //
3933 // So the plan is as follows: Create the values array in the promise
3934 // compartment. Create the promise resolving functions and the data holder in
3935 // our current compartment, i.e. the compartment of the Promise combinator
3936 // function. Store a cross-compartment wrapper to the values array in the
3937 // holder. This should be OK because the only things we hand the promise
3938 // resolving functions to are the "then" calls we do and in the case when the
3939 // Promise's compartment is not the current compartment those are happening
3940 // over Xrays anyway, which means they get the canonical "then" function and
3941 // content can't see our promise resolving functions.
3942
3943 if (IsWrapper(resultCapability.promise())) {
3944 JSObject* unwrappedPromiseObj =
3945 CheckedUnwrapStatic(resultCapability.promise());
3946 MOZ_ASSERT(unwrappedPromiseObj);
3947
3948 {
3949 AutoRealm ar(cx, unwrappedPromiseObj);
3950 auto* array = NewDenseEmptyArray(cx);
3951 if (!array) {
3952 return false;
3953 }
3954 elements.initialize(array);
3955 }
3956
3957 if (!cx->compartment()->wrap(cx, elements.value())) {
3958 return false;
3959 }
3960 } else {
3961 auto* array = NewDenseEmptyArray(cx);
3962 if (!array) {
3963 return false;
3964 }
3965
3966 elements.initialize(array);
3967 }
3968 return true;
3969 }
3970
3971 // Retrieve the combinator elements from the data holder.
3972 [[nodiscard]] static bool GetPromiseCombinatorElements(
3973 JSContext* cx, Handle<PromiseCombinatorDataHolder*> data,
3974 MutableHandle<PromiseCombinatorElements> elements) {
3975 bool needsWrapping = false;
3976 JSObject* valuesObj = &data->valuesArray().toObject();
3977 if (IsProxy(valuesObj)) {
3978 // See comment for NewPromiseCombinatorElements for why we unwrap here.
3979 valuesObj = UncheckedUnwrap(valuesObj);
3980
3981 if (JS_IsDeadWrapper(valuesObj)) {
3982 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3983 JSMSG_DEAD_OBJECT);
3984 return false;
3985 }
3986
3987 needsWrapping = true;
3988 }
3989
3990 elements.initialize(data, &valuesObj->as<ArrayObject>(), needsWrapping);
3991 return true;
3992 }
3993
3994 static JSFunction* NewPromiseCombinatorElementFunction(
3995 JSContext* cx, Native native,
3996 Handle<PromiseCombinatorDataHolder*> dataHolder, uint32_t index,
3997 Handle<Value> maybeResolveFunc) {
3998 JSFunction* fn = NewNativeFunction(
3999 cx, native, 1, nullptr, gc::AllocKind::FUNCTION_EXTENDED, GenericObject);
4000 if (!fn) {
4001 return nullptr;
4002 }
4003
4004 fn->setExtendedSlot(PromiseCombinatorElementFunctionSlot_Data,
4005 ObjectValue(*dataHolder));
4006 if (maybeResolveFunc.isObject()) {
4007 fn->setExtendedSlot(
4008 PromiseCombinatorElementFunctionSlot_ElementIndexOrResolveFunc,
4009 maybeResolveFunc);
4010 } else {
4011 fn->setExtendedSlot(
4012 PromiseCombinatorElementFunctionSlot_ElementIndexOrResolveFunc,
4013 Int32Value(index));
4014 }
4015 return fn;
4016 }
4017
4018 /**
4019 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
4020 *
4021 * Unified implementation of
4022 *
4023 * Promise.all Resolve Element Functions
4024 * https://tc39.es/ecma262/#sec-promise.all-resolve-element-functions
4025 *
4026 * Steps 1-4.
4027 *
4028 * Promise.allSettled Resolve Element Functions
4029 * https://tc39.es/ecma262/#sec-promise.allsettled-resolve-element-functions
4030 *
4031 * Steps 1-5.
4032 *
4033 * Promise.allSettled Reject Element Functions
4034 * https://tc39.es/ecma262/#sec-promise.allsettled-reject-element-functions
4035 *
4036 * Steps 1-5.
4037 *
4038 * Common implementation for Promise combinator element functions to check if
4039 * they've already been called.
4040 */
4041 static bool PromiseCombinatorElementFunctionAlreadyCalled(
4042 const CallArgs& args, MutableHandle<PromiseCombinatorDataHolder*> data,
4043 uint32_t* index) {
4044 // Step 1. Let F be the active function object.
4045 JSFunction* fn = &args.callee().as<JSFunction>();
4046
4047 constexpr size_t indexOrResolveFuncSlot =
4048 PromiseCombinatorElementFunctionSlot_ElementIndexOrResolveFunc;
4049 if (fn->getExtendedSlot(indexOrResolveFuncSlot).isObject()) {
4050 Value slotVal = fn->getExtendedSlot(indexOrResolveFuncSlot);
4051 fn = &slotVal.toObject().as<JSFunction>();
4052 }
4053 MOZ_RELEASE_ASSERT(fn->getExtendedSlot(indexOrResolveFuncSlot).isInt32());
4054
4055 // Promise.all functions
4056 // Step 2. If F.[[AlreadyCalled]] is true, return undefined.
4057 // Promise.allSettled functions
4058 // Step 2. Let alreadyCalled be F.[[AlreadyCalled]].
4059 // Step 3. If alreadyCalled.[[Value]] is true, return undefined.
4060 //
4061 // We use the existence of the data holder as a signal for whether the Promise
4062 // combinator element function was already called. Upon resolution, it's reset
4063 // to `undefined`.
4064 const Value& dataVal =
4065 fn->getExtendedSlot(PromiseCombinatorElementFunctionSlot_Data);
4066 if (dataVal.isUndefined()) {
4067 return true;
4068 }
4069
4070 data.set(&dataVal.toObject().as<PromiseCombinatorDataHolder>());
4071
4072 // Promise.all functions
4073 // Step 3. Set F.[[AlreadyCalled]] to true.
4074 // Promise.allSettled functions
4075 // Step 4. Set alreadyCalled.[[Value]] to true.
4076 fn->setExtendedSlot(PromiseCombinatorElementFunctionSlot_Data,
4077 UndefinedValue());
4078
4079 // Promise.all functions
4080 // Step 4. Let index be F.[[Index]].
4081 // Promise.allSettled functions
4082 // Step 5. Let index be F.[[Index]].
4083 int32_t idx = fn->getExtendedSlot(indexOrResolveFuncSlot).toInt32();
4084 MOZ_ASSERT(idx >= 0);
4085 *index = uint32_t(idx);
4086
4087 return false;
4088 }
4089
4090 /**
4091 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
4092 *
4093 * PerformPromiseAll ( iteratorRecord, constructor, resultCapability,
4094 * promiseResolve )
4095 * https://tc39.es/ecma262/#sec-performpromiseall
4096 */
4097 [[nodiscard]] static bool PerformPromiseAll(
4098 JSContext* cx, PromiseForOfIterator& iterator, HandleObject C,
4099 Handle<PromiseCapability> resultCapability, HandleValue promiseResolve,
4100 bool* done) {
4101 *done = false;
4102
4103 MOZ_ASSERT(C->isConstructor());
4104
4105 // Step 1. Let values be a new empty List.
4106 Rooted<PromiseCombinatorElements> values(cx);
4107 if (!NewPromiseCombinatorElements(cx, resultCapability, &values)) {
4108 return false;
4109 }
4110
4111 // Step 2. Let remainingElementsCount be the Record { [[Value]]: 1 }.
4112 //
4113 // Create our data holder that holds all the things shared across
4114 // every step of the iterator. In particular, this holds the
4115 // remainingElementsCount (as an integer reserved slot), the array of
4116 // values, and the resolve function from our PromiseCapability.
4117 Rooted<PromiseCombinatorDataHolder*> dataHolder(cx);
4118 dataHolder = PromiseCombinatorDataHolder::New(
4119 cx, resultCapability.promise(), values, resultCapability.resolve());
4120 if (!dataHolder) {
4121 return false;
4122 }
4123
4124 // Step 3. Let index be 0.
4125 uint32_t index = 0;
4126
4127 auto getResolveAndReject = [cx, &resultCapability, &values, &dataHolder,
4128 &index](MutableHandleValue resolveFunVal,
4129 MutableHandleValue rejectFunVal) {
4130 // Step 4.h. Append undefined to values.
4131 if (!values.pushUndefined(cx)) {
4132 return false;
4133 }
4134
4135 // Steps 4.j-q.
4136 JSFunction* resolveFunc = NewPromiseCombinatorElementFunction(
4137 cx, PromiseAllResolveElementFunction, dataHolder, index,
4138 UndefinedHandleValue);
4139 if (!resolveFunc) {
4140 return false;
4141 }
4142
4143 // Step 4.r. Set remainingElementsCount.[[Value]] to
4144 // remainingElementsCount.[[Value]] + 1.
4145 dataHolder->increaseRemainingCount();
4146
4147 // Step 4.t. Set index to index + 1.
4148 index++;
4149 MOZ_ASSERT(index > 0);
4150
4151 resolveFunVal.setObject(*resolveFunc);
4152 rejectFunVal.setObject(*resultCapability.reject());
4153 return true;
4154 };
4155
4156 // Steps 4.
4157 if (!CommonPerformPromiseCombinator(
4158 cx, iterator, C, resultCapability.promise(), promiseResolve, done,
4159 true, getResolveAndReject)) {
4160 return false;
4161 }
4162
4163 // Step 4.d.ii. Set remainingElementsCount.[[Value]] to
4164 // remainingElementsCount.[[Value]] - 1.
4165 int32_t remainingCount = dataHolder->decreaseRemainingCount();
4166
4167 // Step 4.d.iii. If remainingElementsCount.[[Value]] is 0, then
4168 if (remainingCount == 0) {
4169 // Step 4.d.iii.1. Let valuesArray be ! CreateArrayFromList(values).
4170 // (already performed)
4171
4172 // Step 4.d.iii.2. Perform
4173 // ? Call(resultCapability.[[Resolve]], undefined,
4174 // « valuesArray »).
4175 return CallPromiseResolveFunction(cx, resultCapability.resolve(),
4176 values.value(),
4177 resultCapability.promise());
4178 }
4179
4180 // Step 4.d.iv. Return resultCapability.[[Promise]].
4181 return true;
4182 }
4183
4184 /**
4185 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
4186 *
4187 * Promise.all Resolve Element Functions
4188 * https://tc39.es/ecma262/#sec-promise.all-resolve-element-functions
4189 */
4190 static bool PromiseAllResolveElementFunction(JSContext* cx, unsigned argc,
4191 Value* vp) {
4192 CallArgs args = CallArgsFromVp(argc, vp);
4193 HandleValue xVal = args.get(0);
4194
4195 // Steps 1-4.
4196 Rooted<PromiseCombinatorDataHolder*> data(cx);
4197 uint32_t index;
4198 if (PromiseCombinatorElementFunctionAlreadyCalled(args, &data, &index)) {
4199 args.rval().setUndefined();
4200 return true;
4201 }
4202
4203 // Step 5. Let values be F.[[Values]].
4204 Rooted<PromiseCombinatorElements> values(cx);
4205 if (!GetPromiseCombinatorElements(cx, data, &values)) {
4206 return false;
4207 }
4208
4209 // Step 8. Set values[index] to x.
4210 if (!values.setElement(cx, index, xVal)) {
4211 return false;
4212 }
4213
4214 // (reordered)
4215 // Step 7. Let remainingElementsCount be F.[[RemainingElements]].
4216 //
4217 // Step 9. Set remainingElementsCount.[[Value]] to
4218 // remainingElementsCount.[[Value]] - 1.
4219 uint32_t remainingCount = data->decreaseRemainingCount();
4220
4221 // Step 10. If remainingElementsCount.[[Value]] is 0, then
4222 if (remainingCount == 0) {
4223 // Step 10.a. Let valuesArray be ! CreateArrayFromList(values).
4224 // (already performed)
4225
4226 // (reordered)
4227 // Step 6. Let promiseCapability be F.[[Capability]].
4228 //
4229 // Step 10.b. Return
4230 // ? Call(promiseCapability.[[Resolve]], undefined,
4231 // « valuesArray »).
4232 RootedObject resolveAllFun(cx, data->resolveOrRejectObj());
4233 RootedObject promiseObj(cx, data->promiseObj());
4234 if (!CallPromiseResolveFunction(cx, resolveAllFun, values.value(),
4235 promiseObj)) {
4236 return false;
4237 }
4238 }
4239
4240 // Step 11. Return undefined.
4241 args.rval().setUndefined();
4242 return true;
4243 }
4244
4245 /**
4246 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
4247 *
4248 * Promise.race ( iterable )
4249 * https://tc39.es/ecma262/#sec-promise.race
4250 */
4251 static bool Promise_static_race(JSContext* cx, unsigned argc, Value* vp) {
4252 CallArgs args = CallArgsFromVp(argc, vp);
4253 return CommonPromiseCombinator(cx, args, CombinatorKind::Race);
4254 }
4255
4256 /**
4257 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
4258 *
4259 * PerformPromiseRace ( iteratorRecord, constructor, resultCapability,
4260 * promiseResolve )
4261 * https://tc39.es/ecma262/#sec-performpromiserace
4262 */
4263 [[nodiscard]] static bool PerformPromiseRace(
4264 JSContext* cx, PromiseForOfIterator& iterator, HandleObject C,
4265 Handle<PromiseCapability> resultCapability, HandleValue promiseResolve,
4266 bool* done) {
4267 *done = false;
4268
4269 MOZ_ASSERT(C->isConstructor());
4270
4271 // BlockOnPromise fast path requires the passed onFulfilled function
4272 // doesn't return an object value, because otherwise the skipped promise
4273 // creation is detectable due to missing property lookups.
4274 bool isDefaultResolveFn =
4275 IsNativeFunction(resultCapability.resolve(), ResolvePromiseFunction);
4276
4277 auto getResolveAndReject = [&resultCapability](
4278 MutableHandleValue resolveFunVal,
4279 MutableHandleValue rejectFunVal) {
4280 resolveFunVal.setObject(*resultCapability.resolve());
4281 rejectFunVal.setObject(*resultCapability.reject());
4282 return true;
4283 };
4284
4285 // Step 1.
4286 return CommonPerformPromiseCombinator(
4287 cx, iterator, C, resultCapability.promise(), promiseResolve, done,
4288 isDefaultResolveFn, getResolveAndReject);
4289 }
4290
4291 enum class PromiseAllSettledElementFunctionKind { Resolve, Reject };
4292
4293 template <PromiseAllSettledElementFunctionKind Kind>
4294 static bool PromiseAllSettledElementFunction(JSContext* cx, unsigned argc,
4295 Value* vp);
4296
4297 /**
4298 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
4299 *
4300 * Promise.allSettled ( iterable )
4301 * https://tc39.es/ecma262/#sec-promise.allsettled
4302 */
4303 static bool Promise_static_allSettled(JSContext* cx, unsigned argc, Value* vp) {
4304 CallArgs args = CallArgsFromVp(argc, vp);
4305 return CommonPromiseCombinator(cx, args, CombinatorKind::AllSettled);
4306 }
4307
4308 /**
4309 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
4310 *
4311 * PerformPromiseAllSettled ( iteratorRecord, constructor, resultCapability,
4312 * promiseResolve )
4313 * https://tc39.es/ecma262/#sec-performpromiseallsettled
4314 */
4315 [[nodiscard]] static bool PerformPromiseAllSettled(
4316 JSContext* cx, PromiseForOfIterator& iterator, HandleObject C,
4317 Handle<PromiseCapability> resultCapability, HandleValue promiseResolve,
4318 bool* done) {
4319 *done = false;
4320
4321 MOZ_ASSERT(C->isConstructor());
4322
4323 // Step 1. Let values be a new empty List.
4324 Rooted<PromiseCombinatorElements> values(cx);
4325 if (!NewPromiseCombinatorElements(cx, resultCapability, &values)) {
4326 return false;
4327 }
4328
4329 // Step 2. Let remainingElementsCount be the Record { [[Value]]: 1 }.
4330 //
4331 // Create our data holder that holds all the things shared across every step
4332 // of the iterator. In particular, this holds the remainingElementsCount
4333 // (as an integer reserved slot), the array of values, and the resolve
4334 // function from our PromiseCapability.
4335 Rooted<PromiseCombinatorDataHolder*> dataHolder(cx);
4336 dataHolder = PromiseCombinatorDataHolder::New(
4337 cx, resultCapability.promise(), values, resultCapability.resolve());
4338 if (!dataHolder) {
4339 return false;
4340 }
4341
4342 // Step 3. Let index be 0.
4343 uint32_t index = 0;
4344
4345 auto getResolveAndReject = [cx, &values, &dataHolder, &index](
4346 MutableHandleValue resolveFunVal,
4347 MutableHandleValue rejectFunVal) {
4348 // Step 4.h. Append undefined to values.
4349 if (!values.pushUndefined(cx)) {
4350 return false;
4351 }
4352
4353 auto PromiseAllSettledResolveElementFunction =
4354 PromiseAllSettledElementFunction<
4355 PromiseAllSettledElementFunctionKind::Resolve>;
4356 auto PromiseAllSettledRejectElementFunction =
4357 PromiseAllSettledElementFunction<
4358 PromiseAllSettledElementFunctionKind::Reject>;
4359
4360 // Steps 4.j-r.
4361 JSFunction* resolveFunc = NewPromiseCombinatorElementFunction(
4362 cx, PromiseAllSettledResolveElementFunction, dataHolder, index,
4363 UndefinedHandleValue);
4364 if (!resolveFunc) {
4365 return false;
4366 }
4367 resolveFunVal.setObject(*resolveFunc);
4368
4369 // Steps 4.s-z.
4370 JSFunction* rejectFunc = NewPromiseCombinatorElementFunction(
4371 cx, PromiseAllSettledRejectElementFunction, dataHolder, index,
4372 resolveFunVal);
4373 if (!rejectFunc) {
4374 return false;
4375 }
4376 rejectFunVal.setObject(*rejectFunc);
4377
4378 // Step 4.aa. Set remainingElementsCount.[[Value]] to
4379 // remainingElementsCount.[[Value]] + 1.
4380 dataHolder->increaseRemainingCount();
4381
4382 // Step 4.ac. Set index to index + 1.
4383 index++;
4384 MOZ_ASSERT(index > 0);
4385
4386 return true;
4387 };
4388
4389 // Steps 4.
4390 if (!CommonPerformPromiseCombinator(
4391 cx, iterator, C, resultCapability.promise(), promiseResolve, done,
4392 true, getResolveAndReject)) {
4393 return false;
4394 }
4395
4396 // Step 4.d.ii. Set remainingElementsCount.[[Value]] to
4397 // remainingElementsCount.[[Value]] - 1.
4398 int32_t remainingCount = dataHolder->decreaseRemainingCount();
4399
4400 // Step 4.d.iii. If remainingElementsCount.[[Value]] is 0, then
4401 if (remainingCount == 0) {
4402 // Step 4.d.iii.1. Let valuesArray be ! CreateArrayFromList(values).
4403 // (already performed)
4404
4405 // Step 4.d.iii.2. Perform
4406 // ? Call(resultCapability.[[Resolve]], undefined,
4407 // « valuesArray »).
4408 return CallPromiseResolveFunction(cx, resultCapability.resolve(),
4409 values.value(),
4410 resultCapability.promise());
4411 }
4412
4413 return true;
4414 }
4415
4416 /**
4417 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
4418 *
4419 * Unified implementation of
4420 *
4421 * Promise.allSettled Resolve Element Functions
4422 * https://tc39.es/ecma262/#sec-promise.allsettled-resolve-element-functions
4423 * Promise.allSettled Reject Element Functions
4424 * https://tc39.es/ecma262/#sec-promise.allsettled-reject-element-functions
4425 */
4426 template <PromiseAllSettledElementFunctionKind Kind>
4427 static bool PromiseAllSettledElementFunction(JSContext* cx, unsigned argc,
4428 Value* vp) {
4429 CallArgs args = CallArgsFromVp(argc, vp);
4430 HandleValue valueOrReason = args.get(0);
4431
4432 // Steps 1-5.
4433 Rooted<PromiseCombinatorDataHolder*> data(cx);
4434 uint32_t index;
4435 if (PromiseCombinatorElementFunctionAlreadyCalled(args, &data, &index)) {
4436 args.rval().setUndefined();
4437 return true;
4438 }
4439
4440 // Step 6. Let values be F.[[Values]].
4441 Rooted<PromiseCombinatorElements> values(cx);
4442 if (!GetPromiseCombinatorElements(cx, data, &values)) {
4443 return false;
4444 }
4445
4446 // Step 2. Let alreadyCalled be F.[[AlreadyCalled]].
4447 // Step 3. If alreadyCalled.[[Value]] is true, return undefined.
4448 //
4449 // The already-called check above only handles the case when |this| function
4450 // is called repeatedly, so we still need to check if the other pair of this
4451 // resolving function was already called:
4452 // We use the element value as a signal for whether the Promise was already
4453 // fulfilled. Upon resolution, it's set to the result object created below.
4454 if (!values.unwrappedArray()->getDenseElement(index).isUndefined()) {
4455 args.rval().setUndefined();
4456 return true;
4457 }
4458
4459 // Step 9. Let obj be ! OrdinaryObjectCreate(%Object.prototype%).
4460 Rooted<PlainObject*> obj(cx, NewPlainObject(cx));
4461 if (!obj) {
4462 return false;
4463 }
4464
4465 // Promise.allSettled Resolve Element Functions
4466 // Step 10. Perform ! CreateDataPropertyOrThrow(obj, "status", "fulfilled").
4467 // Promise.allSettled Reject Element Functions
4468 // Step 10. Perform ! CreateDataPropertyOrThrow(obj, "status", "rejected").
4469 RootedId id(cx, NameToId(cx->names().status));
4470 RootedValue statusValue(cx);
4471 if (Kind == PromiseAllSettledElementFunctionKind::Resolve) {
4472 statusValue.setString(cx->names().fulfilled);
4473 } else {
4474 statusValue.setString(cx->names().rejected);
4475 }
4476 if (!NativeDefineDataProperty(cx, obj, id, statusValue, JSPROP_ENUMERATE)) {
4477 return false;
4478 }
4479
4480 // Promise.allSettled Resolve Element Functions
4481 // Step 11. Perform ! CreateDataPropertyOrThrow(obj, "value", x).
4482 // Promise.allSettled Reject Element Functions
4483 // Step 11. Perform ! CreateDataPropertyOrThrow(obj, "reason", x).
4484 if (Kind == PromiseAllSettledElementFunctionKind::Resolve) {
4485 id = NameToId(cx->names().value);
4486 } else {
4487 id = NameToId(cx->names().reason);
4488 }
4489 if (!NativeDefineDataProperty(cx, obj, id, valueOrReason, JSPROP_ENUMERATE)) {
4490 return false;
4491 }
4492
4493 // Step 12. Set values[index] to obj.
4494 RootedValue objVal(cx, ObjectValue(*obj));
4495 if (!values.setElement(cx, index, objVal)) {
4496 return false;
4497 }
4498
4499 // (reordered)
4500 // Step 8. Let remainingElementsCount be F.[[RemainingElements]].
4501 //
4502 // Step 13. Set remainingElementsCount.[[Value]] to
4503 // remainingElementsCount.[[Value]] - 1.
4504 uint32_t remainingCount = data->decreaseRemainingCount();
4505
4506 // Step 14. If remainingElementsCount.[[Value]] is 0, then
4507 if (remainingCount == 0) {
4508 // Step 14.a. Let valuesArray be ! CreateArrayFromList(values).
4509 // (already performed)
4510
4511 // (reordered)
4512 // Step 7. Let promiseCapability be F.[[Capability]].
4513 //
4514 // Step 14.b. Return
4515 // ? Call(promiseCapability.[[Resolve]], undefined,
4516 // « valuesArray »).
4517 RootedObject resolveAllFun(cx, data->resolveOrRejectObj());
4518 RootedObject promiseObj(cx, data->promiseObj());
4519 if (!CallPromiseResolveFunction(cx, resolveAllFun, values.value(),
4520 promiseObj)) {
4521 return false;
4522 }
4523 }
4524
4525 // Step 15. Return undefined.
4526 args.rval().setUndefined();
4527 return true;
4528 }
4529
4530 /**
4531 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
4532 *
4533 * Promise.any ( iterable )
4534 * https://tc39.es/ecma262/#sec-promise.any
4535 */
4536 static bool Promise_static_any(JSContext* cx, unsigned argc, Value* vp) {
4537 CallArgs args = CallArgsFromVp(argc, vp);
4538 return CommonPromiseCombinator(cx, args, CombinatorKind::Any);
4539 }
4540
4541 static bool PromiseAnyRejectElementFunction(JSContext* cx, unsigned argc,
4542 Value* vp);
4543
4544 static void ThrowAggregateError(JSContext* cx,
4545 Handle<PromiseCombinatorElements> errors,
4546 HandleObject promise);
4547
4548 /**
4549 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
4550 *
4551 * Promise.any ( iterable )
4552 * https://tc39.es/ecma262/#sec-promise.any
4553 * PerformPromiseAny ( iteratorRecord, constructor, resultCapability,
4554 * promiseResolve )
4555 * https://tc39.es/ecma262/#sec-performpromiseany
4556 */
4557 [[nodiscard]] static bool PerformPromiseAny(
4558 JSContext* cx, PromiseForOfIterator& iterator, HandleObject C,
4559 Handle<PromiseCapability> resultCapability, HandleValue promiseResolve,
4560 bool* done) {
4561 *done = false;
4562
4563 // Step 1. Let C be the this value.
4564 MOZ_ASSERT(C->isConstructor());
4565
4566 // Step 2. Let promiseCapability be ? NewPromiseCapability(C).
4567 // (omitted).
4568
4569 // Step 3. Let promiseResolve be GetPromiseResolve(C).
4570 Rooted<PromiseCombinatorElements> errors(cx);
4571 if (!NewPromiseCombinatorElements(cx, resultCapability, &errors)) {
4572 return false;
4573 }
4574
4575 // Step 4.
4576 // Create our data holder that holds all the things shared across every step
4577 // of the iterator. In particular, this holds the remainingElementsCount (as
4578 // an integer reserved slot), the array of errors, and the reject function
4579 // from our PromiseCapability.
4580 Rooted<PromiseCombinatorDataHolder*> dataHolder(cx);
4581 dataHolder = PromiseCombinatorDataHolder::New(
4582 cx, resultCapability.promise(), errors, resultCapability.reject());
4583 if (!dataHolder) {
4584 return false;
4585 }
4586
4587 // PerformPromiseAny
4588 // Step 3. Let index be 0.
4589 uint32_t index = 0;
4590
4591 auto getResolveAndReject = [cx, &resultCapability, &errors, &dataHolder,
4592 &index](MutableHandleValue resolveFunVal,
4593 MutableHandleValue rejectFunVal) {
4594 // Step 4.h. Append undefined to errors.
4595 if (!errors.pushUndefined(cx)) {
4596 return false;
4597 }
4598
4599 // Steps 4.j-q.
4600 JSFunction* rejectFunc = NewPromiseCombinatorElementFunction(
4601 cx, PromiseAnyRejectElementFunction, dataHolder, index,
4602 UndefinedHandleValue);
4603 if (!rejectFunc) {
4604 return false;
4605 }
4606
4607 // Step 4.r. Set remainingElementsCount.[[Value]] to
4608 // remainingElementsCount.[[Value]] + 1.
4609 dataHolder->increaseRemainingCount();
4610
4611 // Step 4.t. Set index to index + 1.
4612 index++;
4613 MOZ_ASSERT(index > 0);
4614
4615 resolveFunVal.setObject(*resultCapability.resolve());
4616 rejectFunVal.setObject(*rejectFunc);
4617 return true;
4618 };
4619
4620 // BlockOnPromise fast path requires the passed onFulfilled function doesn't
4621 // return an object value, because otherwise the skipped promise creation is
4622 // detectable due to missing property lookups.
4623 bool isDefaultResolveFn =
4624 IsNativeFunction(resultCapability.resolve(), ResolvePromiseFunction);
4625
4626 // Steps 4.
4627 if (!CommonPerformPromiseCombinator(
4628 cx, iterator, C, resultCapability.promise(), promiseResolve, done,
4629 isDefaultResolveFn, getResolveAndReject)) {
4630 return false;
4631 }
4632
4633 // Step 4.d.ii. Set remainingElementsCount.[[Value]] to
4634 // remainingElementsCount.[[Value]] - 1.
4635 int32_t remainingCount = dataHolder->decreaseRemainingCount();
4636
4637 // Step 4.d.iii. If remainingElementsCount.[[Value]] is 0, then
4638 if (remainingCount == 0) {
4639 ThrowAggregateError(cx, errors, resultCapability.promise());
4640 return false;
4641 }
4642
4643 // Step 4.d.iv. Return resultCapability.[[Promise]].
4644 return true;
4645 }
4646
4647 /**
4648 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
4649 *
4650 * Promise.any Reject Element Functions
4651 * https://tc39.es/ecma262/#sec-promise.any-reject-element-functions
4652 */
4653 static bool PromiseAnyRejectElementFunction(JSContext* cx, unsigned argc,
4654 Value* vp) {
4655 CallArgs args = CallArgsFromVp(argc, vp);
4656 HandleValue xVal = args.get(0);
4657
4658 // Steps 1-5.
4659 Rooted<PromiseCombinatorDataHolder*> data(cx);
4660 uint32_t index;
4661 if (PromiseCombinatorElementFunctionAlreadyCalled(args, &data, &index)) {
4662 args.rval().setUndefined();
4663 return true;
4664 }
4665
4666 // Step 6.
4667 Rooted<PromiseCombinatorElements> errors(cx);
4668 if (!GetPromiseCombinatorElements(cx, data, &errors)) {
4669 return false;
4670 }
4671
4672 // Step 9.
4673 if (!errors.setElement(cx, index, xVal)) {
4674 return false;
4675 }
4676
4677 // Steps 8, 10.
4678 uint32_t remainingCount = data->decreaseRemainingCount();
4679
4680 // Step 11.
4681 if (remainingCount == 0) {
4682 // Step 7 (Adapted to work with PromiseCombinatorDataHolder's layout).
4683 RootedObject rejectFun(cx, data->resolveOrRejectObj());
4684 RootedObject promiseObj(cx, data->promiseObj());
4685
4686 ThrowAggregateError(cx, errors, promiseObj);
4687
4688 RootedValue reason(cx);
4689 Rooted<SavedFrame*> stack(cx);
4690 if (!MaybeGetAndClearExceptionAndStack(cx, &reason, &stack)) {
4691 return false;
4692 }
4693
4694 if (!CallPromiseRejectFunction(cx, rejectFun, reason, promiseObj, stack,
4695 UnhandledRejectionBehavior::Report)) {
4696 return false;
4697 }
4698 }
4699
4700 // Step 12.
4701 args.rval().setUndefined();
4702 return true;
4703 }
4704
4705 /**
4706 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
4707 *
4708 * PerformPromiseAny ( iteratorRecord, constructor, resultCapability,
4709 * promiseResolve )
4710 * https://tc39.es/ecma262/#sec-performpromiseany
4711 *
4712 * Steps 4.d.iii.1-3
4713 */
4714 static void ThrowAggregateError(JSContext* cx,
4715 Handle<PromiseCombinatorElements> errors,
4716 HandleObject promise) {
4717 MOZ_ASSERT(!cx->isExceptionPending());
4718
4719 // Create the AggregateError in the same realm as the array object.
4720 AutoRealm ar(cx, errors.unwrappedArray());
4721
4722 RootedObject allocationSite(cx);
4723 mozilla::Maybe<JS::AutoSetAsyncStackForNewCalls> asyncStack;
4724
4725 // Provide a more useful error stack if possible: This function is typically
4726 // called from Promise job queue, which doesn't have any JS frames on the
4727 // stack. So when we create the AggregateError below, its stack property will
4728 // be set to the empty string, which makes it harder to debug the error cause.
4729 // To avoid this situation set-up an async stack based on the Promise
4730 // allocation site, which should point to calling site of |Promise.any|.
4731 if (promise->is<PromiseObject>()) {
4732 allocationSite = promise->as<PromiseObject>().allocationSite();
4733 if (allocationSite) {
4734 asyncStack.emplace(
4735 cx, allocationSite, "Promise.any",
4736 JS::AutoSetAsyncStackForNewCalls::AsyncCallKind::IMPLICIT);
4737 }
4738 }
4739
4740 // Step 4.d.iii.1. Let error be a newly created AggregateError object.
4741 //
4742 // AutoSetAsyncStackForNewCalls requires a new activation before it takes
4743 // effect, so call into the self-hosting helper to set-up new call frames.
4744 RootedValue error(cx);
4745 if (!GetAggregateError(cx, JSMSG_PROMISE_ANY_REJECTION, &error)) {
4746 return;
4747 }
4748
4749 // Step 4.d.iii.2. Perform ! DefinePropertyOrThrow(
4750 // error, "errors", PropertyDescriptor {
4751 // [[Configurable]]: true, [[Enumerable]]: false,
4752 // [[Writable]]: true,
4753 // [[Value]]: ! CreateArrayFromList(errors) }).
4754 //
4755 // |error| isn't guaranteed to be an AggregateError in case of OOM or stack
4756 // overflow.
4757 Rooted<SavedFrame*> stack(cx);
4758 if (error.isObject() && error.toObject().is<ErrorObject>()) {
4759 Rooted<ErrorObject*> errorObj(cx, &error.toObject().as<ErrorObject>());
4760 if (errorObj->type() == JSEXN_AGGREGATEERR) {
4761 RootedValue errorsVal(cx, JS::ObjectValue(*errors.unwrappedArray()));
4762 if (!NativeDefineDataProperty(cx, errorObj, cx->names().errors, errorsVal,
4763 0)) {
4764 return;
4765 }
4766
4767 // Adopt the existing saved frames when present.
4768 if (JSObject* errorStack = errorObj->stack()) {
4769 stack = &errorStack->as<SavedFrame>();
4770 }
4771 }
4772 }
4773
4774 // Step 4.d.iii.3. Return ThrowCompletion(error).
4775 cx->setPendingException(error, stack);
4776 }
4777
4778 /**
4779 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
4780 *
4781 * Unified implementation of
4782 *
4783 * Promise.reject ( r )
4784 * https://tc39.es/ecma262/#sec-promise.reject
4785 * NewPromiseCapability ( C )
4786 * https://tc39.es/ecma262/#sec-newpromisecapability
4787 * Promise.resolve ( x )
4788 * https://tc39.es/ecma262/#sec-promise.resolve
4789 * PromiseResolve ( C, x )
4790 * https://tc39.es/ecma262/#sec-promise-resolve
4791 */
4792 [[nodiscard]] static JSObject* CommonStaticResolveRejectImpl(
4793 JSContext* cx, HandleValue thisVal, HandleValue argVal,
4794 ResolutionMode mode) {
4795 // Promise.reject
4796 // Step 1. Let C be the this value.
4797 // Step 2. Let promiseCapability be ? NewPromiseCapability(C).
4798 //
4799 // Promise.reject => NewPromiseCapability
4800 // Step 1. If IsConstructor(C) is false, throw a TypeError exception.
4801 //
4802 // Promise.resolve
4803 // Step 1. Let C be the this value.
4804 // Step 2. If Type(C) is not Object, throw a TypeError exception.
4805 if (!thisVal.isObject()) {
4806 const char* msg = mode == ResolveMode ? "Receiver of Promise.resolve call"
4807 : "Receiver of Promise.reject call";
4808 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
4809 JSMSG_OBJECT_REQUIRED, msg);
4810 return nullptr;
4811 }
4812 RootedObject C(cx, &thisVal.toObject());
4813
4814 // Promise.resolve
4815 // Step 3. Return ? PromiseResolve(C, x).
4816 //
4817 // PromiseResolve
4818 // Step 1. Assert: Type(C) is Object.
4819 // (implicit)
4820 if (mode == ResolveMode && argVal.isObject()) {
4821 RootedObject xObj(cx, &argVal.toObject());
4822 bool isPromise = false;
4823 if (xObj->is<PromiseObject>()) {
4824 isPromise = true;
4825 } else if (IsWrapper(xObj)) {
4826 // Treat instances of Promise from other compartments as Promises
4827 // here, too.
4828 // It's important to do the GetProperty for the `constructor`
4829 // below through the wrapper, because wrappers can change the
4830 // outcome, so instead of unwrapping and then performing the
4831 // GetProperty, just check here and then operate on the original
4832 // object again.
4833 if (xObj->canUnwrapAs<PromiseObject>()) {
4834 isPromise = true;
4835 }
4836 }
4837
4838 // PromiseResolve
4839 // Step 2. If IsPromise(x) is true, then
4840 if (isPromise) {
4841 // Step 2.a. Let xConstructor be ? Get(x, "constructor").
4842 RootedValue ctorVal(cx);
4843 if (!GetProperty(cx, xObj, xObj, cx->names().constructor, &ctorVal)) {
4844 return nullptr;
4845 }
4846
4847 // Step 2.b. If SameValue(xConstructor, C) is true, return x.
4848 if (ctorVal == thisVal) {
4849 return xObj;
4850 }
4851 }
4852 }
4853
4854 // Promise.reject
4855 // Step 2. Let promiseCapability be ? NewPromiseCapability(C).
4856 // PromiseResolve
4857 // Step 3. Let promiseCapability be ? NewPromiseCapability(C).
4858 Rooted<PromiseCapability> capability(cx);
4859 if (!NewPromiseCapability(cx, C, &capability, true)) {
4860 return nullptr;
4861 }
4862
4863 HandleObject promise = capability.promise();
4864 if (mode == ResolveMode) {
4865 // PromiseResolve
4866 // Step 4. Perform ? Call(promiseCapability.[[Resolve]], undefined, « x »).
4867 if (!CallPromiseResolveFunction(cx, capability.resolve(), argVal,
4868 promise)) {
4869 return nullptr;
4870 }
4871 } else {
4872 // Promise.reject
4873 // Step 3. Perform ? Call(promiseCapability.[[Reject]], undefined, « r »).
4874 if (!CallPromiseRejectFunction(cx, capability.reject(), argVal, promise,
4875 nullptr,
4876 UnhandledRejectionBehavior::Report)) {
4877 return nullptr;
4878 }
4879 }
4880
4881 // Promise.reject
4882 // Step 4. Return promiseCapability.[[Promise]].
4883 // PromiseResolve
4884 // Step 5. Return promiseCapability.[[Promise]].
4885 return promise;
4886 }
4887
4888 [[nodiscard]] JSObject* js::PromiseResolve(JSContext* cx,
4889 HandleObject constructor,
4890 HandleValue value) {
4891 RootedValue C(cx, ObjectValue(*constructor));
4892 return CommonStaticResolveRejectImpl(cx, C, value, ResolveMode);
4893 }
4894
4895 /**
4896 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
4897 *
4898 * Promise.reject ( r )
4899 * https://tc39.es/ecma262/#sec-promise.reject
4900 */
4901 static bool Promise_reject(JSContext* cx, unsigned argc, Value* vp) {
4902 CallArgs args = CallArgsFromVp(argc, vp);
4903 HandleValue thisVal = args.thisv();
4904 HandleValue argVal = args.get(0);
4905 JSObject* result =
4906 CommonStaticResolveRejectImpl(cx, thisVal, argVal, RejectMode);
4907 if (!result) {
4908 return false;
4909 }
4910 args.rval().setObject(*result);
4911 return true;
4912 }
4913
4914 /**
4915 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
4916 *
4917 * Promise.reject ( r )
4918 * https://tc39.es/ecma262/#sec-promise.reject
4919 *
4920 * Unforgeable version.
4921 */
4922 /* static */
4923 PromiseObject* PromiseObject::unforgeableReject(JSContext* cx,
4924 HandleValue value) {
4925 cx->check(value);
4926
4927 // Step 1. Let C be the this value.
4928 // Step 2. Let promiseCapability be ? NewPromiseCapability(C).
4929 Rooted<PromiseObject*> promise(
4930 cx, CreatePromiseObjectWithoutResolutionFunctions(cx));
4931 if (!promise) {
4932 return nullptr;
4933 }
4934
4935 MOZ_ASSERT(promise->state() == JS::PromiseState::Pending);
4936 MOZ_ASSERT(IsPromiseWithDefaultResolvingFunction(promise));
4937
4938 // Step 3. Perform ? Call(promiseCapability.[[Reject]], undefined, « r »).
4939 if (!RejectPromiseInternal(cx, promise, value)) {
4940 return nullptr;
4941 }
4942
4943 // Step 4. Return promiseCapability.[[Promise]].
4944 return promise;
4945 }
4946
4947 /**
4948 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
4949 *
4950 * Promise.resolve ( x )
4951 * https://tc39.es/ecma262/#sec-promise.resolve
4952 */
4953 bool js::Promise_static_resolve(JSContext* cx, unsigned argc, Value* vp) {
4954 CallArgs args = CallArgsFromVp(argc, vp);
4955 HandleValue thisVal = args.thisv();
4956 HandleValue argVal = args.get(0);
4957 JSObject* result =
4958 CommonStaticResolveRejectImpl(cx, thisVal, argVal, ResolveMode);
4959 if (!result) {
4960 return false;
4961 }
4962 args.rval().setObject(*result);
4963 return true;
4964 }
4965
4966 /**
4967 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
4968 *
4969 * Promise.resolve ( x )
4970 * https://tc39.es/ecma262/#sec-promise.resolve
4971 *
4972 * Unforgeable version.
4973 */
4974 /* static */
4975 JSObject* PromiseObject::unforgeableResolve(JSContext* cx, HandleValue value) {
4976 JSObject* promiseCtor = JS::GetPromiseConstructor(cx);
4977 if (!promiseCtor) {
4978 return nullptr;
4979 }
4980 RootedValue cVal(cx, ObjectValue(*promiseCtor));
4981 return CommonStaticResolveRejectImpl(cx, cVal, value, ResolveMode);
4982 }
4983
4984 /**
4985 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
4986 *
4987 * Promise.resolve ( x )
4988 * https://tc39.es/ecma262/#sec-promise.resolve
4989 * PromiseResolve ( C, x )
4990 * https://tc39.es/ecma262/#sec-promise-resolve
4991 *
4992 * Unforgeable version, where `x` is guaranteed not to be a promise.
4993 */
4994 /* static */
4995 PromiseObject* PromiseObject::unforgeableResolveWithNonPromise(
4996 JSContext* cx, HandleValue value) {
4997 cx->check(value);
4998
4999 #ifdef DEBUG
5000 auto IsPromise = [](HandleValue value) {
5001 if (!value.isObject()) {
5002 return false;
5003 }
5004
5005 JSObject* obj = &value.toObject();
5006 if (obj->is<PromiseObject>()) {
5007 return true;
5008 }
5009
5010 if (!IsWrapper(obj)) {
5011 return false;
5012 }
5013
5014 return obj->canUnwrapAs<PromiseObject>();
5015 };
5016 MOZ_ASSERT(!IsPromise(value), "must use unforgeableResolve with this value");
5017 #endif
5018
5019 // Promise.resolve
5020 // Step 3. Return ? PromiseResolve(C, x).
5021
5022 // PromiseResolve
5023 // Step 2. Let promiseCapability be ? NewPromiseCapability(C).
5024 Rooted<PromiseObject*> promise(
5025 cx, CreatePromiseObjectWithoutResolutionFunctions(cx));
5026 if (!promise) {
5027 return nullptr;
5028 }
5029
5030 MOZ_ASSERT(promise->state() == JS::PromiseState::Pending);
5031 MOZ_ASSERT(IsPromiseWithDefaultResolvingFunction(promise));
5032
5033 // PromiseResolve
5034 // Step 3. Perform ? Call(promiseCapability.[[Resolve]], undefined, « x »).
5035 if (!ResolvePromiseInternal(cx, promise, value)) {
5036 return nullptr;
5037 }
5038
5039 // PromiseResolve
5040 // Step 4. Return promiseCapability.[[Promise]].
5041 return promise;
5042 }
5043
5044 /**
5045 * https://tc39.es/proposal-promise-try/
5046 *
5047 * Promise.try ( )
5048 */
5049 static bool Promise_static_try(JSContext* cx, unsigned argc, Value* vp) {
5050 CallArgs args = CallArgsFromVp(argc, vp);
5051
5052 // 1. Let C be the this value.
5053 RootedValue cVal(cx, args.thisv());
5054
5055 // 2. If C is not an Object, throw a TypeError exception.
5056 if (!cVal.isObject()) {
5057 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5058 JSMSG_OBJECT_REQUIRED,
5059 "Receiver of Promise.try call");
5060 return false;
5061 }
5062
5063 // 3. Let promiseCapability be ? NewPromiseCapability(C).
5064 RootedObject c(cx, &cVal.toObject());
5065 Rooted<PromiseCapability> promiseCapability(cx);
5066 if (!NewPromiseCapability(cx, c, &promiseCapability, false)) {
5067 return false;
5068 }
5069 HandleObject promiseObject = promiseCapability.promise();
5070
5071 // 4. Let status be Completion(Call(callbackfn, undefined, args)).
5072 size_t argCount = args.length();
5073 if (argCount > 0) {
5074 argCount--;
5075 }
5076
5077 InvokeArgs iargs(cx);
5078 if (!iargs.init(cx, argCount)) {
5079 return false;
5080 }
5081
5082 for (size_t i = 0; i < argCount; i++) {
5083 iargs[i].set(args[i + 1]);
5084 }
5085
5086 HandleValue callbackfn = args.get(0);
5087 RootedValue rval(cx);
5088 bool ok = Call(cx, callbackfn, UndefinedHandleValue, iargs, &rval);
5089
5090 // 5. If status is an abrupt completion, then
5091 if (!ok) {
5092 RootedValue reason(cx);
5093 Rooted<SavedFrame*> stack(cx);
5094
5095 if (!MaybeGetAndClearExceptionAndStack(cx, &reason, &stack)) {
5096 return false;
5097 }
5098
5099 // 5.a. Perform ? Call(promiseCapability.[[Reject]], undefined, «
5100 // status.[[Value]] »).
5101 if (!CallPromiseRejectFunction(cx, promiseCapability.reject(), reason,
5102 promiseObject, stack,
5103 UnhandledRejectionBehavior::Report)) {
5104 return false;
5105 }
5106 } else {
5107 // 6. Else,
5108 // 6.a. Perform ? Call(promiseCapability.[[Resolve]], undefined, «
5109 // status.[[Value]] »).
5110 if (!CallPromiseResolveFunction(cx, promiseCapability.resolve(), rval,
5111 promiseObject)) {
5112 return false;
5113 }
5114 }
5115
5116 // 7. Return promiseCapability.[[Promise]].
5117 args.rval().setObject(*promiseObject);
5118 return true;
5119 }
5120
5121 /**
5122 * https://tc39.es/proposal-promise-with-resolvers/
5123 *
5124 * Promise.withResolvers ( )
5125 */
5126 static bool Promise_static_withResolvers(JSContext* cx, unsigned argc,
5127 Value* vp) {
5128 CallArgs args = CallArgsFromVp(argc, vp);
5129
5130 // Step 1. Let C be the this value.
5131 RootedValue cVal(cx, args.thisv());
5132
5133 // Step 2. Let promiseCapability be ? NewPromiseCapability(C).
5134 if (!cVal.isObject()) {
5135 ReportValueError(cx, JSMSG_NOT_CONSTRUCTOR, JSDVG_SEARCH_STACK, cVal,
5136 nullptr);
5137 return false;
5138 }
5139 RootedObject c(cx, &cVal.toObject());
5140 Rooted<PromiseCapability> promiseCapability(cx);
5141 if (!NewPromiseCapability(cx, c, &promiseCapability, false)) {
5142 return false;
5143 }
5144
5145 // Step 3. Let obj be OrdinaryObjectCreate(%Object.prototype%).
5146 Rooted<PlainObject*> obj(cx, NewPlainObject(cx));
5147 if (!obj) {
5148 return false;
5149 }
5150
5151 // Step 4. Perform ! CreateDataPropertyOrThrow(obj, "promise",
5152 // promiseCapability.[[Promise]]).
5153 RootedValue v(cx, ObjectValue(*promiseCapability.promise()));
5154 if (!NativeDefineDataProperty(cx, obj, cx->names().promise, v,
5155 JSPROP_ENUMERATE)) {
5156 return false;
5157 }
5158
5159 // Step 5. Perform ! CreateDataPropertyOrThrow(obj, "resolve",
5160 // promiseCapability.[[Resolve]]).
5161 v.setObject(*promiseCapability.resolve());
5162 if (!NativeDefineDataProperty(cx, obj, cx->names().resolve, v,
5163 JSPROP_ENUMERATE)) {
5164 return false;
5165 }
5166
5167 // Step 6. Perform ! CreateDataPropertyOrThrow(obj, "reject",
5168 // promiseCapability.[[Reject]]).
5169 v.setObject(*promiseCapability.reject());
5170 if (!NativeDefineDataProperty(cx, obj, cx->names().reject, v,
5171 JSPROP_ENUMERATE)) {
5172 return false;
5173 }
5174
5175 // Step 7. Return obj.
5176 args.rval().setObject(*obj);
5177 return true;
5178 }
5179
5180 /**
5181 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
5182 *
5183 * get Promise [ @@species ]
5184 * https://tc39.es/ecma262/#sec-get-promise-@@species
5185 */
5186 bool js::Promise_static_species(JSContext* cx, unsigned argc, Value* vp) {
5187 CallArgs args = CallArgsFromVp(argc, vp);
5188
5189 // Step 1. Return the this value.
5190 args.rval().set(args.thisv());
5191 return true;
5192 }
5193
5194 enum class HostDefinedDataObject {
5195 // Do not use the host defined data object, this is a special case used by the
5196 // debugger.
5197 No,
5198
5199 // Use host defined data object, this is the normal operation.
5200 Yes
5201 };
5202
5203 /**
5204 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
5205 *
5206 * PerformPromiseThen ( promise, onFulfilled, onRejected
5207 * [ , resultCapability ] )
5208 * https://tc39.es/ecma262/#sec-performpromisethen
5209 *
5210 * Steps 7-8 for creating PromiseReaction record.
5211 * We use single object for both fulfillReaction and rejectReaction.
5212 */
5213 static PromiseReactionRecord* NewReactionRecord(
5214 JSContext* cx, Handle<PromiseCapability> resultCapability,
5215 HandleValue onFulfilled, HandleValue onRejected,
5216 HostDefinedDataObject hostDefinedDataObjectOption) {
5217 #ifdef DEBUG
5218 if (resultCapability.promise()) {
5219 if (hostDefinedDataObjectOption == HostDefinedDataObject::Yes) {
5220 if (resultCapability.promise()->is<PromiseObject>()) {
5221 // If `resultCapability.promise` is a Promise object,
5222 // `resultCapability.{resolve,reject}` may be optimized out,
5223 // but if they're not, they should be callable.
5224 MOZ_ASSERT_IF(resultCapability.resolve(),
5225 IsCallable(resultCapability.resolve()));
5226 MOZ_ASSERT_IF(resultCapability.reject(),
5227 IsCallable(resultCapability.reject()));
5228 } else {
5229 // If `resultCapability.promise` is a non-Promise object
5230 // (including wrapped Promise object),
5231 // `resultCapability.{resolve,reject}` should be callable.
5232 MOZ_ASSERT(resultCapability.resolve());
5233 MOZ_ASSERT(IsCallable(resultCapability.resolve()));
5234 MOZ_ASSERT(resultCapability.reject());
5235 MOZ_ASSERT(IsCallable(resultCapability.reject()));
5236 }
5237 } else {
5238 // For debugger usage, `resultCapability.promise` should be a
5239 // maybe-wrapped Promise object. The other fields are not used.
5240 //
5241 // This is the only case where we allow `resolve` and `reject` to
5242 // be null when the `promise` field is not a PromiseObject.
5243 JSObject* unwrappedPromise = UncheckedUnwrap(resultCapability.promise());
5244 MOZ_ASSERT(unwrappedPromise->is<PromiseObject>() ||
5245 JS_IsDeadWrapper(unwrappedPromise));
5246 MOZ_ASSERT(!resultCapability.resolve());
5247 MOZ_ASSERT(!resultCapability.reject());
5248 }
5249 } else {
5250 // `resultCapability.promise` is null for the following cases:
5251 // * resulting Promise is known to be unused
5252 // * Async Function
5253 // * Async Generator
5254 // In any case, other fields are also not used.
5255 MOZ_ASSERT(!resultCapability.resolve());
5256 MOZ_ASSERT(!resultCapability.reject());
5257 MOZ_ASSERT(hostDefinedDataObjectOption == HostDefinedDataObject::Yes);
5258 }
5259 #endif
5260
5261 // Ensure the onFulfilled handler has the expected type.
5262 MOZ_ASSERT(onFulfilled.isInt32() || onFulfilled.isObjectOrNull());
5263 MOZ_ASSERT_IF(onFulfilled.isObject(), IsCallable(onFulfilled));
5264 MOZ_ASSERT_IF(onFulfilled.isInt32(),
5265 0 <= onFulfilled.toInt32() &&
5266 onFulfilled.toInt32() < int32_t(PromiseHandler::Limit));
5267
5268 // Ensure the onRejected handler has the expected type.
5269 MOZ_ASSERT(onRejected.isInt32() || onRejected.isObjectOrNull());
5270 MOZ_ASSERT_IF(onRejected.isObject(), IsCallable(onRejected));
5271 MOZ_ASSERT_IF(onRejected.isInt32(),
5272 0 <= onRejected.toInt32() &&
5273 onRejected.toInt32() < int32_t(PromiseHandler::Limit));
5274
5275 // Handlers must either both be present or both be absent.
5276 MOZ_ASSERT(onFulfilled.isNull() == onRejected.isNull());
5277
5278 RootedObject hostDefinedData(cx);
5279 if (hostDefinedDataObjectOption == HostDefinedDataObject::Yes) {
5280 if (!GetObjectFromHostDefinedData(cx, &hostDefinedData)) {
5281 return nullptr;
5282 }
5283 }
5284
5285 PromiseReactionRecord* reaction =
5286 NewBuiltinClassInstance<PromiseReactionRecord>(cx);
5287 if (!reaction) {
5288 return nullptr;
5289 }
5290
5291 cx->check(resultCapability.promise());
5292 cx->check(onFulfilled);
5293 cx->check(onRejected);
5294 cx->check(resultCapability.resolve());
5295 cx->check(resultCapability.reject());
5296 cx->check(hostDefinedData);
5297
5298 // Step 7. Let fulfillReaction be the PromiseReaction
5299 // { [[Capability]]: resultCapability, [[Type]]: Fulfill,
5300 // [[Handler]]: onFulfilledJobCallback }.
5301 // Step 8. Let rejectReaction be the PromiseReaction
5302 // { [[Capability]]: resultCapability, [[Type]]: Reject,
5303 // [[Handler]]: onRejectedJobCallback }.
5304
5305 // See comments for ReactionRecordSlots for the relation between
5306 // spec record fields and PromiseReactionRecord slots.
5307 reaction->setFixedSlot(ReactionRecordSlot_Promise,
5308 ObjectOrNullValue(resultCapability.promise()));
5309 // We set [[Type]] in EnqueuePromiseReactionJob, by calling
5310 // setTargetStateAndHandlerArg.
5311 reaction->setFixedSlot(ReactionRecordSlot_Flags, Int32Value(0));
5312 reaction->setFixedSlot(ReactionRecordSlot_OnFulfilled, onFulfilled);
5313 reaction->setFixedSlot(ReactionRecordSlot_OnRejected, onRejected);
5314 reaction->setFixedSlot(ReactionRecordSlot_Resolve,
5315 ObjectOrNullValue(resultCapability.resolve()));
5316 reaction->setFixedSlot(ReactionRecordSlot_Reject,
5317 ObjectOrNullValue(resultCapability.reject()));
5318 reaction->setFixedSlot(ReactionRecordSlot_HostDefinedData,
5319 ObjectOrNullValue(hostDefinedData));
5320
5321 return reaction;
5322 }
5323
5324 static bool IsPromiseSpecies(JSContext* cx, JSFunction* species) {
5325 return species->maybeNative() == Promise_static_species;
5326 }
5327
5328 // Whether to create a promise as the return value of Promise#{then,catch}.
5329 // If the return value is known to be unused, and if the operation is known
5330 // to be unobservable, we can skip creating the promise.
5331 enum class CreateDependentPromise { Always, SkipIfCtorUnobservable };
5332
5333 /**
5334 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
5335 *
5336 * Promise.prototype.then ( onFulfilled, onRejected )
5337 * https://tc39.es/ecma262/#sec-promise.prototype.then
5338 *
5339 * Steps 3-4.
5340 */
5341 static bool PromiseThenNewPromiseCapability(
5342 JSContext* cx, HandleObject promiseObj,
5343 CreateDependentPromise createDependent,
5344 MutableHandle<PromiseCapability> resultCapability) {
5345 // Step 3. Let C be ? SpeciesConstructor(promise, %Promise%).
5346 RootedObject C(cx, SpeciesConstructor(cx, promiseObj, JSProto_Promise,
5347 IsPromiseSpecies));
5348 if (!C) {
5349 return false;
5350 }
5351
5352 if (createDependent != CreateDependentPromise::Always &&
5353 IsNativeFunction(C, PromiseConstructor)) {
5354 return true;
5355 }
5356
5357 // Step 4. Let resultCapability be ? NewPromiseCapability(C).
5358 if (!NewPromiseCapability(cx, C, resultCapability, true)) {
5359 return false;
5360 }
5361
5362 RootedObject unwrappedPromise(cx, promiseObj);
5363 if (IsWrapper(promiseObj)) {
5364 unwrappedPromise = UncheckedUnwrap(promiseObj);
5365 }
5366 RootedObject unwrappedNewPromise(cx, resultCapability.promise());
5367 if (IsWrapper(resultCapability.promise())) {
5368 unwrappedNewPromise = UncheckedUnwrap(resultCapability.promise());
5369 }
5370 if (unwrappedPromise->is<PromiseObject>() &&
5371 unwrappedNewPromise->is<PromiseObject>()) {
5372 unwrappedNewPromise->as<PromiseObject>().copyUserInteractionFlagsFrom(
5373 *unwrappedPromise.as<PromiseObject>());
5374 }
5375
5376 return true;
5377 }
5378
5379 /**
5380 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
5381 *
5382 * Promise.prototype.then ( onFulfilled, onRejected )
5383 * https://tc39.es/ecma262/#sec-promise.prototype.then
5384 *
5385 * Steps 3-5.
5386 */
5387 [[nodiscard]] PromiseObject* js::OriginalPromiseThen(JSContext* cx,
5388 HandleObject promiseObj,
5389 HandleObject onFulfilled,
5390 HandleObject onRejected) {
5391 cx->check(promiseObj);
5392 cx->check(onFulfilled);
5393 cx->check(onRejected);
5394
5395 RootedValue promiseVal(cx, ObjectValue(*promiseObj));
5396 Rooted<PromiseObject*> unwrappedPromise(
5397 cx,
5398 UnwrapAndTypeCheckValue<PromiseObject>(cx, promiseVal, [cx, promiseObj] {
5399 JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
5400 JSMSG_INCOMPATIBLE_PROTO, "Promise", "then",
5401 promiseObj->getClass()->name);
5402 }));
5403 if (!unwrappedPromise) {
5404 return nullptr;
5405 }
5406
5407 // Step 3. Let C be ? SpeciesConstructor(promise, %Promise%).
5408 // Step 4. Let resultCapability be ? NewPromiseCapability(C).
5409 Rooted<PromiseObject*> newPromise(
5410 cx, CreatePromiseObjectWithoutResolutionFunctions(cx));
5411 if (!newPromise) {
5412 return nullptr;
5413 }
5414 newPromise->copyUserInteractionFlagsFrom(*unwrappedPromise);
5415
5416 Rooted<PromiseCapability> resultCapability(cx);
5417 resultCapability.promise().set(newPromise);
5418
5419 // Step 5. Return PerformPromiseThen(promise, onFulfilled, onRejected,
5420 // resultCapability).
5421 {
5422 RootedValue onFulfilledVal(cx, ObjectOrNullValue(onFulfilled));
5423 RootedValue onRejectedVal(cx, ObjectOrNullValue(onRejected));
5424 if (!PerformPromiseThen(cx, unwrappedPromise, onFulfilledVal, onRejectedVal,
5425 resultCapability)) {
5426 return nullptr;
5427 }
5428 }
5429
5430 return newPromise;
5431 }
5432
5433 /**
5434 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
5435 *
5436 * Promise.prototype.then ( onFulfilled, onRejected )
5437 * https://tc39.es/ecma262/#sec-promise.prototype.then
5438 *
5439 * Steps 3-5.
5440 */
5441 [[nodiscard]] static bool OriginalPromiseThenWithoutSettleHandlers(
5442 JSContext* cx, Handle<PromiseObject*> promise,
5443 Handle<PromiseObject*> promiseToResolve) {
5444 cx->check(promise);
5445
5446 // Step 3. Let C be ? SpeciesConstructor(promise, %Promise%).
5447 // Step 4. Let resultCapability be ? NewPromiseCapability(C).
5448 Rooted<PromiseCapability> resultCapability(cx);
5449 if (!PromiseThenNewPromiseCapability(
5450 cx, promise, CreateDependentPromise::SkipIfCtorUnobservable,
5451 &resultCapability)) {
5452 return false;
5453 }
5454
5455 // Step 5. Return PerformPromiseThen(promise, onFulfilled, onRejected,
5456 // resultCapability).
5457 return PerformPromiseThenWithoutSettleHandlers(cx, promise, promiseToResolve,
5458 resultCapability);
5459 }
5460
5461 [[nodiscard]] static bool PerformPromiseThenWithReaction(
5462 JSContext* cx, Handle<PromiseObject*> promise,
5463 Handle<PromiseReactionRecord*> reaction);
5464
5465 [[nodiscard]] bool js::ReactToUnwrappedPromise(
5466 JSContext* cx, Handle<PromiseObject*> unwrappedPromise,
5467 HandleObject onFulfilled_, HandleObject onRejected_,
5468 UnhandledRejectionBehavior behavior) {
5469 cx->check(onFulfilled_);
5470 cx->check(onRejected_);
5471
5472 MOZ_ASSERT_IF(onFulfilled_, IsCallable(onFulfilled_));
5473 MOZ_ASSERT_IF(onRejected_, IsCallable(onRejected_));
5474
5475 RootedValue onFulfilled(
5476 cx, onFulfilled_ ? ObjectValue(*onFulfilled_)
5477 : Int32Value(int32_t(PromiseHandler::Identity)));
5478
5479 RootedValue onRejected(
5480 cx, onRejected_ ? ObjectValue(*onRejected_)
5481 : Int32Value(int32_t(PromiseHandler::Thrower)));
5482
5483 Rooted<PromiseCapability> resultCapability(cx);
5484 MOZ_ASSERT(!resultCapability.promise());
5485
5486 Rooted<PromiseReactionRecord*> reaction(
5487 cx, NewReactionRecord(cx, resultCapability, onFulfilled, onRejected,
5488 HostDefinedDataObject::Yes));
5489 if (!reaction) {
5490 return false;
5491 }
5492
5493 if (behavior == UnhandledRejectionBehavior::Ignore) {
5494 reaction->setShouldIgnoreUnhandledRejection();
5495 }
5496
5497 return PerformPromiseThenWithReaction(cx, unwrappedPromise, reaction);
5498 }
5499
5500 static bool CanCallOriginalPromiseThenBuiltin(JSContext* cx,
5501 HandleValue promise) {
5502 return promise.isObject() && promise.toObject().is<PromiseObject>() &&
5503 IsPromiseWithDefaultProperties(&promise.toObject().as<PromiseObject>(),
5504 cx);
5505 }
5506
5507 static MOZ_ALWAYS_INLINE bool IsPromiseThenOrCatchRetValImplicitlyUsed(
5508 JSContext* cx, PromiseObject* promise) {
5509 // Embedding requires the return value of then/catch as
5510 // `enqueuePromiseJob` parameter, to propaggate the user-interaction.
5511 // We cannot optimize out the return value if the flag is set by embedding.
5512 if (promise->requiresUserInteractionHandling()) {
5513 return true;
5514 }
5515
5516 // The returned promise of Promise#then and Promise#catch contains
5517 // stack info if async stack is enabled. Even if their return value is not
5518 // used explicitly in the script, the stack info is observable in devtools
5519 // and profilers. We shouldn't apply the optimization not to allocate the
5520 // returned Promise object if the it's implicitly used by them.
5521 if (!cx->options().asyncStack()) {
5522 return false;
5523 }
5524
5525 // If devtools is opened, the current realm will become debuggee.
5526 if (cx->realm()->isDebuggee()) {
5527 return true;
5528 }
5529
5530 // There are 2 profilers, and they can be independently enabled.
5531 if (cx->runtime()->geckoProfiler().enabled()) {
5532 return true;
5533 }
5534 if (JS::IsProfileTimelineRecordingEnabled()) {
5535 return true;
5536 }
5537
5538 // The stack is also observable from Error#stack, but we don't care since
5539 // it's nonstandard feature.
5540 return false;
5541 }
5542
5543 /**
5544 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
5545 *
5546 * Promise.prototype.then ( onFulfilled, onRejected )
5547 * https://tc39.es/ecma262/#sec-promise.prototype.then
5548 *
5549 * Steps 3-5.
5550 */
5551 static bool OriginalPromiseThenBuiltin(JSContext* cx, HandleValue promiseVal,
5552 HandleValue onFulfilled,
5553 HandleValue onRejected,
5554 MutableHandleValue rval,
5555 bool rvalExplicitlyUsed) {
5556 cx->check(promiseVal, onFulfilled, onRejected);
5557 MOZ_ASSERT(CanCallOriginalPromiseThenBuiltin(cx, promiseVal));
5558
5559 Rooted<PromiseObject*> promise(cx,
5560 &promiseVal.toObject().as<PromiseObject>());
5561
5562 bool rvalUsed = rvalExplicitlyUsed ||
5563 IsPromiseThenOrCatchRetValImplicitlyUsed(cx, promise);
5564
5565 // Step 3. Let C be ? SpeciesConstructor(promise, %Promise%).
5566 // Step 4. Let resultCapability be ? NewPromiseCapability(C).
5567 Rooted<PromiseCapability> resultCapability(cx);
5568 if (rvalUsed) {
5569 PromiseObject* resultPromise =
5570 CreatePromiseObjectWithoutResolutionFunctions(cx);
5571 if (!resultPromise) {
5572 return false;
5573 }
5574
5575 resultPromise->copyUserInteractionFlagsFrom(
5576 promiseVal.toObject().as<PromiseObject>());
5577 resultCapability.promise().set(resultPromise);
5578 }
5579
5580 // Step 5. Return PerformPromiseThen(promise, onFulfilled, onRejected,
5581 // resultCapability).
5582 if (!PerformPromiseThen(cx, promise, onFulfilled, onRejected,
5583 resultCapability)) {
5584 return false;
5585 }
5586
5587 if (rvalUsed) {
5588 rval.setObject(*resultCapability.promise());
5589 } else {
5590 rval.setUndefined();
5591 }
5592 return true;
5593 }
5594
5595 [[nodiscard]] bool js::RejectPromiseWithPendingError(
5596 JSContext* cx, Handle<PromiseObject*> promise) {
5597 cx->check(promise);
5598
5599 if (!cx->isExceptionPending()) {
5600 // Reject the promise, but also propagate this uncatchable error.
5601 (void)PromiseObject::reject(cx, promise, UndefinedHandleValue);
5602 return false;
5603 }
5604
5605 RootedValue exn(cx);
5606 if (!GetAndClearException(cx, &exn)) {
5607 return false;
5608 }
5609 return PromiseObject::reject(cx, promise, exn);
5610 }
5611
5612 // Some async/await functions are implemented here instead of
5613 // js/src/builtin/AsyncFunction.cpp, to call Promise internal functions.
5614
5615 /**
5616 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
5617 *
5618 * Runtime Semantics: EvaluateAsyncFunctionBody
5619 * AsyncFunctionBody : FunctionBody
5620 * https://tc39.es/ecma262/#sec-runtime-semantics-evaluateasyncfunctionbody
5621 *
5622 * Runtime Semantics: EvaluateAsyncConciseBody
5623 * AsyncConciseBody : ExpressionBody
5624 * https://tc39.es/ecma262/#sec-runtime-semantics-evaluateasyncconcisebody
5625 */
5626 [[nodiscard]] PromiseObject* js::CreatePromiseObjectForAsync(JSContext* cx) {
5627 // Step 1. Let promiseCapability be ! NewPromiseCapability(%Promise%).
5628 PromiseObject* promise =
5629 CreatePromiseObjectWithoutResolutionFunctions(cx, PROMISE_FLAG_ASYNC);
5630 if (!promise) {
5631 return nullptr;
5632 }
5633
5634 return promise;
5635 }
5636
5637 bool js::IsPromiseForAsyncFunctionOrGenerator(JSObject* promise) {
5638 return promise->is<PromiseObject>() &&
5639 PromiseHasAnyFlag(promise->as<PromiseObject>(), PROMISE_FLAG_ASYNC);
5640 }
5641
5642 [[nodiscard]] PromiseObject* js::CreatePromiseObjectForAsyncGenerator(
5643 JSContext* cx) {
5644 PromiseObject* promise =
5645 CreatePromiseObjectWithoutResolutionFunctions(cx, PROMISE_FLAG_ASYNC);
5646 if (!promise) {
5647 return nullptr;
5648 }
5649
5650 return promise;
5651 }
5652
5653 /**
5654 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
5655 *
5656 * AsyncFunctionStart ( promiseCapability, asyncFunctionBody )
5657 * https://tc39.es/ecma262/#sec-async-functions-abstract-operations-async-function-start
5658 *
5659 * Steps 4.f-g.
5660 */
5661 [[nodiscard]] bool js::AsyncFunctionThrown(
5662 JSContext* cx, Handle<PromiseObject*> resultPromise, HandleValue reason,
5663 JS::Handle<SavedFrame*> unwrappedRejectionStack) {
5664 if (resultPromise->state() != JS::PromiseState::Pending) {
5665 // OOM after resolving promise.
5666 // Report a warning and ignore the result.
5667 if (!WarnNumberASCII(cx, JSMSG_UNHANDLABLE_PROMISE_REJECTION_WARNING)) {
5668 if (cx->isExceptionPending()) {
5669 cx->clearPendingException();
5670 }
5671 }
5672 return true;
5673 }
5674
5675 // Step 4.f. Else,
5676 // Step 4.f.i. Assert: result.[[Type]] is throw.
5677 // Step 4.f.ii. Perform
5678 // ! Call(promiseCapability.[[Reject]], undefined,
5679 // « result.[[Value]] »).
5680 // Step 4.g. Return.
5681 return RejectPromiseInternal(cx, resultPromise, reason,
5682 unwrappedRejectionStack);
5683 }
5684
5685 /**
5686 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
5687 *
5688 * AsyncFunctionStart ( promiseCapability, asyncFunctionBody )
5689 * https://tc39.es/ecma262/#sec-async-functions-abstract-operations-async-function-start
5690 *
5691 * Steps 4.e, 4.g.
5692 */
5693 [[nodiscard]] bool js::AsyncFunctionReturned(
5694 JSContext* cx, Handle<PromiseObject*> resultPromise, HandleValue value) {
5695 if (resultPromise->state() != JS::PromiseState::Pending) {
5696 if (!WarnNumberASCII(cx, JSMSG_UNHANDLABLE_PROMISE_RESOLUTION_WARNING)) {
5697 if (cx->isExceptionPending()) {
5698 cx->clearPendingException();
5699 }
5700 }
5701 return true;
5702 }
5703
5704 // Step 4.e. Else if result.[[Type]] is return, then
5705 // Step 4.e.i. Perform
5706 // ! Call(promiseCapability.[[Resolve]], undefined,
5707 // « result.[[Value]] »).
5708 return ResolvePromiseInternal(cx, resultPromise, value);
5709 }
5710
5711 /**
5712 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
5713 *
5714 * Await
5715 * https://tc39.github.io/ecma262/#await
5716 *
5717 * Helper function that performs Await(promise) steps 2-7.
5718 * The same steps are also used in a few other places in the spec.
5719 */
5720 template <typename T>
5721 [[nodiscard]] static bool InternalAwait(JSContext* cx, HandleValue value,
5722 HandleObject resultPromise,
5723 PromiseHandler onFulfilled,
5724 PromiseHandler onRejected,
5725 T extraStep) {
5726 // Step 2. Let promise be ? PromiseResolve(%Promise%, value).
5727 RootedObject promise(cx, PromiseObject::unforgeableResolve(cx, value));
5728 if (!promise) {
5729 return false;
5730 }
5731
5732 // This downcast is safe because unforgeableResolve either returns `value`
5733 // (only if it is already a possibly-wrapped promise) or creates a new
5734 // promise using the Promise constructor.
5735 Rooted<PromiseObject*> unwrappedPromise(
5736 cx, UnwrapAndDowncastObject<PromiseObject>(cx, promise));
5737 if (!unwrappedPromise) {
5738 return false;
5739 }
5740
5741 // Steps 3-6 for creating onFulfilled/onRejected are done by caller.
5742
5743 // Step 7. Perform ! PerformPromiseThen(promise, onFulfilled, onRejected).
5744 RootedValue onFulfilledValue(cx, Int32Value(int32_t(onFulfilled)));
5745 RootedValue onRejectedValue(cx, Int32Value(int32_t(onRejected)));
5746 Rooted<PromiseCapability> resultCapability(cx);
5747 resultCapability.promise().set(resultPromise);
5748 Rooted<PromiseReactionRecord*> reaction(
5749 cx, NewReactionRecord(cx, resultCapability, onFulfilledValue,
5750 onRejectedValue, HostDefinedDataObject::Yes));
5751 if (!reaction) {
5752 return false;
5753 }
5754 extraStep(reaction);
5755 return PerformPromiseThenWithReaction(cx, unwrappedPromise, reaction);
5756 }
5757
5758 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
5759 // Explicit Resource Management Proposal
5760 // 27.1.3.1 %AsyncIteratorPrototype% [ @@asyncDispose ] ( )
5761 // Steps 6.c-g
5762 // https://arai-a.github.io/ecma262-compare/?pr=3000&id=sec-%25asynciteratorprototype%25-%40%40asyncdispose
5763 // The steps mentioned above are almost identical to the steps 3-7 of
5764 // https://tc39.es/ecma262/#await we have a utility function InternalAwait which
5765 // covers these steps thus this following function wraps around the utility
5766 // and implements the steps of %AsyncIteratorPrototype% [ @@asyncDispose ] ( ).
5767 [[nodiscard]] bool js::InternalAsyncIteratorDisposeAwait(
5768 JSContext* cx, JS::Handle<JS::Value> value,
5769 JS::Handle<JSObject*> resultPromise) {
5770 auto extra = [](JS::Handle<PromiseReactionRecord*> reaction) {};
5771 return InternalAwait(cx, value, resultPromise,
5772 PromiseHandler::AsyncIteratorDisposeAwaitFulfilled,
5773 PromiseHandler::Thrower, extra);
5774 }
5775 #endif
5776
5777 [[nodiscard]] bool js::InternalAsyncGeneratorAwait(
5778 JSContext* cx, JS::Handle<AsyncGeneratorObject*> generator,
5779 JS::Handle<JS::Value> value, PromiseHandler onFulfilled,
5780 PromiseHandler onRejected) {
5781 auto extra = [&](Handle<PromiseReactionRecord*> reaction) {
5782 reaction->setIsAsyncGenerator(generator);
5783 };
5784 return InternalAwait(cx, value, nullptr, onFulfilled, onRejected, extra);
5785 }
5786
5787 /**
5788 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
5789 *
5790 * Await
5791 * https://tc39.es/ecma262/#await
5792 */
5793 [[nodiscard]] JSObject* js::AsyncFunctionAwait(
5794 JSContext* cx, Handle<AsyncFunctionGeneratorObject*> genObj,
5795 HandleValue value) {
5796 auto extra = [&](Handle<PromiseReactionRecord*> reaction) {
5797 reaction->setIsAsyncFunction(genObj);
5798 };
5799 if (!InternalAwait(cx, value, nullptr,
5800 PromiseHandler::AsyncFunctionAwaitedFulfilled,
5801 PromiseHandler::AsyncFunctionAwaitedRejected, extra)) {
5802 return nullptr;
5803 }
5804 return genObj->promise();
5805 }
5806
5807 /**
5808 * ES2024 draft rev 53454a9a596d90473d2152ef04656d605162cd4c
5809 *
5810 * %AsyncFromSyncIteratorPrototype%.next ( [ value ] )
5811 * https://tc39.es/ecma262/#sec-%asyncfromsynciteratorprototype%.next
5812 *
5813 * %AsyncFromSyncIteratorPrototype%.return ( [ value ] )
5814 * https://tc39.es/ecma262/#sec-%asyncfromsynciteratorprototype%.return
5815 *
5816 * %AsyncFromSyncIteratorPrototype%.throw ( [ value ] )
5817 * https://tc39.es/ecma262/#sec-%asyncfromsynciteratorprototype%.throw
5818 *
5819 * AsyncFromSyncIteratorContinuation ( result, promiseCapability )
5820 * https://tc39.es/ecma262/#sec-asyncfromsynciteratorcontinuation
5821 */
5822 bool js::AsyncFromSyncIteratorMethod(JSContext* cx, CallArgs& args,
5823 CompletionKind completionKind) {
5824 // Step 1. Let O be the this value.
5825 HandleValue thisVal = args.thisv();
5826
5827 // Step 2. Assert: O is an Object that has a [[SyncIteratorRecord]] internal
5828 // slot.
5829 MOZ_ASSERT(thisVal.isObject());
5830 MOZ_ASSERT(thisVal.toObject().is<AsyncFromSyncIteratorObject>());
5831
5832 // Step 3. Let promiseCapability be ! NewPromiseCapability(%Promise%).
5833 Rooted<PromiseObject*> resultPromise(
5834 cx, CreatePromiseObjectWithoutResolutionFunctions(cx));
5835 if (!resultPromise) {
5836 return false;
5837 }
5838
5839 Rooted<AsyncFromSyncIteratorObject*> asyncIter(
5840 cx, &thisVal.toObject().as<AsyncFromSyncIteratorObject>());
5841
5842 // next():
5843 // Step 4. Let syncIteratorRecord be O.[[SyncIteratorRecord]].
5844 //
5845 // or
5846 //
5847 // return() / throw():
5848 // Step 4. Let syncIterator be O.[[SyncIteratorRecord]].[[Iterator]].
5849 RootedObject iter(cx, asyncIter->iterator());
5850
5851 RootedValue func(cx);
5852 if (completionKind == CompletionKind::Normal) {
5853 // next() preparing for steps 5-6.
5854 func.set(asyncIter->nextMethod());
5855 } else if (completionKind == CompletionKind::Return) {
5856 // return() steps 5-7.
5857 // Step 5. Let return be Completion(GetMethod(syncIterator, "return")).
5858 // Step 6. IfAbruptRejectPromise(return, promiseCapability).
5859 if (!GetProperty(cx, iter, iter, cx->names().return_, &func)) {
5860 return AbruptRejectPromise(cx, args, resultPromise, nullptr);
5861 }
5862
5863 // Step 7. If return is undefined, then
5864 // (Note: GetMethod contains a step that changes `null` to `undefined`;
5865 // we omit that step above, and check for `null` here instead.)
5866 if (func.isNullOrUndefined()) {
5867 // Step 7.a. Let iterResult be CreateIterResultObject(value, true).
5868 PlainObject* resultObj = CreateIterResultObject(cx, args.get(0), true);
5869 if (!resultObj) {
5870 return AbruptRejectPromise(cx, args, resultPromise, nullptr);
5871 }
5872
5873 RootedValue resultVal(cx, ObjectValue(*resultObj));
5874
5875 // Step 7.b. Perform ! Call(promiseCapability.[[Resolve]], undefined,
5876 // « iterResult »).
5877 if (!ResolvePromiseInternal(cx, resultPromise, resultVal)) {
5878 return AbruptRejectPromise(cx, args, resultPromise, nullptr);
5879 }
5880
5881 // Step 7.c. Return promiseCapability.[[Promise]].
5882 args.rval().setObject(*resultPromise);
5883 return true;
5884 }
5885 } else {
5886 // throw() steps 5-7.
5887 MOZ_ASSERT(completionKind == CompletionKind::Throw);
5888
5889 // Step 5. Let throw be Completion(GetMethod(syncIterator, "throw")).
5890 // Step 6. IfAbruptRejectPromise(throw, promiseCapability).
5891 if (!GetProperty(cx, iter, iter, cx->names().throw_, &func)) {
5892 return AbruptRejectPromise(cx, args, resultPromise, nullptr);
5893 }
5894
5895 // Step 7. If throw is undefined, then
5896 // (Note: GetMethod contains a step that changes `null` to `undefined`;
5897 // we omit that step above, and check for `null` here instead.)
5898 if (func.isNullOrUndefined()) {
5899 // Step 7.a. Perform ! Call(promiseCapability.[[Reject]], undefined,
5900 // « value »).
5901 if (!RejectPromiseInternal(cx, resultPromise, args.get(0))) {
5902 return AbruptRejectPromise(cx, args, resultPromise, nullptr);
5903 }
5904
5905 // Step 7.b. Return promiseCapability.[[Promise]].
5906 args.rval().setObject(*resultPromise);
5907 return true;
5908 }
5909 }
5910
5911 // next():
5912 // Step 5. If value is present, then
5913 // Step 5.a. Let result be Completion(IteratorNext(syncIteratorRecord,
5914 // value)).
5915 // Step 6. Else,
5916 // Step 6.a. Let result be Completion(IteratorNext(syncIteratorRecord)).
5917 //
5918 // or
5919 //
5920 // return():
5921 // Step 8. If value is present, then
5922 // Step 8.a. Let result be Completion(Call(return, syncIterator,
5923 // « value »)).
5924 // Step 9. Else,
5925 // Step 9.a. Let result be Completion(Call(return, syncIterator)).
5926 //
5927 // throw():
5928 // Step 8. If value is present, then
5929 // Step 8.a. Let result be Completion(Call(throw, syncIterator,
5930 // « value »)).
5931 // Step 9. Else,
5932 // Step 9.a. Let result be Completion(Call(throw, syncIterator)).
5933 RootedValue iterVal(cx, ObjectValue(*iter));
5934 RootedValue resultVal(cx);
5935 bool ok;
5936 if (args.length() == 0) {
5937 ok = Call(cx, func, iterVal, &resultVal);
5938 } else {
5939 ok = Call(cx, func, iterVal, args[0], &resultVal);
5940 }
5941 if (!ok) {
5942 // next():
5943 // Step 7. IfAbruptRejectPromise(result, promiseCapability).
5944 //
5945 // return() / throw():
5946 // Step 10. IfAbruptRejectPromise(result, promiseCapability).
5947 return AbruptRejectPromise(cx, args, resultPromise, nullptr);
5948 }
5949
5950 // next() steps 5-6 -> IteratorNext:
5951 // Step 3. If result is not an Object, throw a TypeError exception.
5952 // next():
5953 // Step 7. IfAbruptRejectPromise(result, promiseCapability).
5954 //
5955 // or
5956 //
5957 // return() / throw():
5958 // Step 11. If result is not an Object, then
5959 // Step 11.a. Perform ! Call(promiseCapability.[[Reject]], undefined,
5960 // « a newly created TypeError object »).
5961 // Step 11.b. Return promiseCapability.[[Promise]].
5962 if (!resultVal.isObject()) {
5963 CheckIsObjectKind kind;
5964 switch (completionKind) {
5965 case CompletionKind::Normal:
5966 kind = CheckIsObjectKind::IteratorNext;
5967 break;
5968 case CompletionKind::Throw:
5969 kind = CheckIsObjectKind::IteratorThrow;
5970 break;
5971 case CompletionKind::Return:
5972 kind = CheckIsObjectKind::IteratorReturn;
5973 break;
5974 }
5975 MOZ_ALWAYS_FALSE(ThrowCheckIsObject(cx, kind));
5976 return AbruptRejectPromise(cx, args, resultPromise, nullptr);
5977 }
5978
5979 RootedObject resultObj(cx, &resultVal.toObject());
5980
5981 // next():
5982 // Step 8. Return AsyncFromSyncIteratorContinuation(result,
5983 // promiseCapability).
5984 //
5985 // return() / throw():
5986 // Step 12. Return AsyncFromSyncIteratorContinuation(result,
5987 // promiseCapability).
5988
5989 // The step numbers below are for AsyncFromSyncIteratorContinuation().
5990 //
5991 // Step 1. NOTE: Because promiseCapability is derived from the intrinsic
5992 // %Promise%, the calls to promiseCapability.[[Reject]] entailed by
5993 // the use IfAbruptRejectPromise below are guaranteed not to throw.
5994 // Step 2. Let done be Completion(IteratorComplete(result)).
5995 // Step 3. IfAbruptRejectPromise(done, promiseCapability).
5996 RootedValue doneVal(cx);
5997 if (!GetProperty(cx, resultObj, resultObj, cx->names().done, &doneVal)) {
5998 return AbruptRejectPromise(cx, args, resultPromise, nullptr);
5999 }
6000 bool done = ToBoolean(doneVal);
6001
6002 // Step 4. Let value be Completion(IteratorValue(result)).
6003 // Step 5. IfAbruptRejectPromise(value, promiseCapability).
6004 RootedValue value(cx);
6005 if (!GetProperty(cx, resultObj, resultObj, cx->names().value, &value)) {
6006 return AbruptRejectPromise(cx, args, resultPromise, nullptr);
6007 }
6008
6009 // Step 8. Let unwrap be a new Abstract Closure with parameters (v) that
6010 // captures done and performs the following steps when called:
6011 // Step 8.a. Return CreateIterResultObject(v, done).
6012 // Step 9. Let onFulfilled be CreateBuiltinFunction(unwrap, 1, "", « »).
6013 // Step 10. NOTE: onFulfilled is used when processing the "value" property
6014 // of an IteratorResult object in order to wait for its value if it
6015 // is a promise and re-package the result in a new "unwrapped"
6016 // IteratorResult object.
6017 PromiseHandler onFulfilled =
6018 done ? PromiseHandler::AsyncFromSyncIteratorValueUnwrapDone
6019 : PromiseHandler::AsyncFromSyncIteratorValueUnwrapNotDone;
6020 PromiseHandler onRejected = PromiseHandler::Thrower;
6021
6022 // Steps 6-7 and 11 are identical to some steps in Await; we have a utility
6023 // function InternalAwait() that implements the idiom.
6024 //
6025 // Step 6. Let valueWrapper be Completion(PromiseResolve(%Promise%, value)).
6026 // Step 7. IfAbruptRejectPromise(valueWrapper, promiseCapability).
6027 // Step 11. Perform PerformPromiseThen(valueWrapper, onFulfilled,
6028 // undefined, promiseCapability).
6029 auto extra = [](Handle<PromiseReactionRecord*> reaction) {};
6030 if (!InternalAwait(cx, value, resultPromise, onFulfilled, onRejected,
6031 extra)) {
6032 return AbruptRejectPromise(cx, args, resultPromise, nullptr);
6033 }
6034
6035 // Step 12. Return promiseCapability.[[Promise]].
6036 args.rval().setObject(*resultPromise);
6037 return true;
6038 }
6039
6040 /**
6041 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
6042 *
6043 * Promise.prototype.catch ( onRejected )
6044 * https://tc39.es/ecma262/#sec-promise.prototype.catch
6045 */
6046 static bool Promise_catch_impl(JSContext* cx, unsigned argc, Value* vp,
6047 bool rvalExplicitlyUsed) {
6048 CallArgs args = CallArgsFromVp(argc, vp);
6049
6050 // Step 1. Let promise be the this value.
6051 HandleValue thisVal = args.thisv();
6052 HandleValue onFulfilled = UndefinedHandleValue;
6053 HandleValue onRejected = args.get(0);
6054
6055 // Fast path when the default Promise state is intact.
6056 if (CanCallOriginalPromiseThenBuiltin(cx, thisVal)) {
6057 return OriginalPromiseThenBuiltin(cx, thisVal, onFulfilled, onRejected,
6058 args.rval(), rvalExplicitlyUsed);
6059 }
6060
6061 // Step 2. Return ? Invoke(promise, "then", « undefined, onRejected »).
6062 RootedValue thenVal(cx);
6063 RootedObject thisObj(cx, ToObject(cx, thisVal));
6064 bool isOnProto = false;
6065 bool isOnStandardProto = false;
6066 bool isOnObjectProto = false;
6067 if (!thisObj) {
6068 return false;
6069 }
6070 if (!GetThenValue(cx, thisObj, thisVal, &thenVal, &isOnProto,
6071 &isOnStandardProto, &isOnObjectProto)) {
6072 return false;
6073 }
6074
6075 if (IsNativeFunction(thenVal, &Promise_then) &&
6076 thenVal.toObject().nonCCWRealm() == cx->realm()) {
6077 return Promise_then_impl(cx, thisVal, onFulfilled, onRejected, args.rval(),
6078 rvalExplicitlyUsed);
6079 }
6080
6081 ReportThenable(cx, isOnProto, isOnStandardProto, isOnObjectProto);
6082 return Call(cx, thenVal, thisVal, UndefinedHandleValue, onRejected,
6083 args.rval());
6084 }
6085
6086 /**
6087 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
6088 *
6089 * Promise.prototype.catch ( onRejected )
6090 * https://tc39.es/ecma262/#sec-promise.prototype.catch
6091 */
6092 static bool Promise_catch_noRetVal(JSContext* cx, unsigned argc, Value* vp) {
6093 return Promise_catch_impl(cx, argc, vp, false);
6094 }
6095
6096 /**
6097 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
6098 *
6099 * Promise.prototype.catch ( onRejected )
6100 * https://tc39.es/ecma262/#sec-promise.prototype.catch
6101 */
6102 static bool Promise_catch(JSContext* cx, unsigned argc, Value* vp) {
6103 return Promise_catch_impl(cx, argc, vp, true);
6104 }
6105
6106 /**
6107 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
6108 *
6109 * Promise.prototype.then ( onFulfilled, onRejected )
6110 * https://tc39.es/ecma262/#sec-promise.prototype.then
6111 */
6112 static bool Promise_then_impl(JSContext* cx, HandleValue promiseVal,
6113 HandleValue onFulfilled, HandleValue onRejected,
6114 MutableHandleValue rval,
6115 bool rvalExplicitlyUsed) {
6116 // Step 1. Let promise be the this value.
6117 // (implicit)
6118
6119 // Step 2. If IsPromise(promise) is false, throw a TypeError exception.
6120 if (!promiseVal.isObject()) {
6121 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
6122 JSMSG_OBJECT_REQUIRED,
6123 "Receiver of Promise.prototype.then call");
6124 return false;
6125 }
6126
6127 // Fast path when the default Promise state is intact.
6128 if (CanCallOriginalPromiseThenBuiltin(cx, promiseVal)) {
6129 // Steps 3-5.
6130 return OriginalPromiseThenBuiltin(cx, promiseVal, onFulfilled, onRejected,
6131 rval, rvalExplicitlyUsed);
6132 }
6133
6134 RootedObject promiseObj(cx, &promiseVal.toObject());
6135 Rooted<PromiseObject*> unwrappedPromise(
6136 cx,
6137 UnwrapAndTypeCheckValue<PromiseObject>(cx, promiseVal, [cx, &promiseVal] {
6138 JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
6139 JSMSG_INCOMPATIBLE_PROTO, "Promise", "then",
6140 InformalValueTypeName(promiseVal));
6141 }));
6142 if (!unwrappedPromise) {
6143 return false;
6144 }
6145
6146 bool rvalUsed =
6147 rvalExplicitlyUsed ||
6148 IsPromiseThenOrCatchRetValImplicitlyUsed(cx, unwrappedPromise);
6149
6150 // Step 3. Let C be ? SpeciesConstructor(promise, %Promise%).
6151 // Step 4. Let resultCapability be ? NewPromiseCapability(C).
6152 CreateDependentPromise createDependent =
6153 rvalUsed ? CreateDependentPromise::Always
6154 : CreateDependentPromise::SkipIfCtorUnobservable;
6155 Rooted<PromiseCapability> resultCapability(cx);
6156 if (!PromiseThenNewPromiseCapability(cx, promiseObj, createDependent,
6157 &resultCapability)) {
6158 return false;
6159 }
6160
6161 // Step 5. Return PerformPromiseThen(promise, onFulfilled, onRejected,
6162 // resultCapability).
6163 if (!PerformPromiseThen(cx, unwrappedPromise, onFulfilled, onRejected,
6164 resultCapability)) {
6165 return false;
6166 }
6167
6168 if (rvalUsed) {
6169 rval.setObject(*resultCapability.promise());
6170 } else {
6171 rval.setUndefined();
6172 }
6173 return true;
6174 }
6175
6176 /**
6177 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
6178 *
6179 * Promise.prototype.then ( onFulfilled, onRejected )
6180 * https://tc39.es/ecma262/#sec-promise.prototype.then
6181 */
6182 bool Promise_then_noRetVal(JSContext* cx, unsigned argc, Value* vp) {
6183 CallArgs args = CallArgsFromVp(argc, vp);
6184 return Promise_then_impl(cx, args.thisv(), args.get(0), args.get(1),
6185 args.rval(), false);
6186 }
6187
6188 /**
6189 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
6190 *
6191 * Promise.prototype.then ( onFulfilled, onRejected )
6192 * https://tc39.es/ecma262/#sec-promise.prototype.then
6193 */
6194 bool js::Promise_then(JSContext* cx, unsigned argc, Value* vp) {
6195 CallArgs args = CallArgsFromVp(argc, vp);
6196 return Promise_then_impl(cx, args.thisv(), args.get(0), args.get(1),
6197 args.rval(), true);
6198 }
6199
6200 /**
6201 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
6202 *
6203 * PerformPromiseThen ( promise, onFulfilled, onRejected
6204 * [ , resultCapability ] )
6205 * https://tc39.es/ecma262/#sec-performpromisethen
6206 *
6207 * Steps 1-12.
6208 */
6209 [[nodiscard]] static bool PerformPromiseThen(
6210 JSContext* cx, Handle<PromiseObject*> promise, HandleValue onFulfilled_,
6211 HandleValue onRejected_, Handle<PromiseCapability> resultCapability) {
6212 // Step 1. Assert: IsPromise(promise) is true.
6213 // Step 2. If resultCapability is not present, then
6214 // Step 2. a. Set resultCapability to undefined.
6215 // (implicit)
6216
6217 // (reordered)
6218 // Step 4. Else,
6219 // Step 4. a. Let onFulfilledJobCallback be HostMakeJobCallback(onFulfilled).
6220 RootedValue onFulfilled(cx, onFulfilled_);
6221
6222 // Step 3. If IsCallable(onFulfilled) is false, then
6223 if (!IsCallable(onFulfilled)) {
6224 // Step 3. a. Let onFulfilledJobCallback be empty.
6225 onFulfilled = Int32Value(int32_t(PromiseHandler::Identity));
6226 }
6227
6228 // (reordered)
6229 // Step 6. Else,
6230 // Step 6. a. Let onRejectedJobCallback be HostMakeJobCallback(onRejected).
6231 RootedValue onRejected(cx, onRejected_);
6232
6233 // Step 5. If IsCallable(onRejected) is false, then
6234 if (!IsCallable(onRejected)) {
6235 // Step 5. a. Let onRejectedJobCallback be empty.
6236 onRejected = Int32Value(int32_t(PromiseHandler::Thrower));
6237 }
6238
6239 // Step 7. Let fulfillReaction be the PromiseReaction
6240 // { [[Capability]]: resultCapability, [[Type]]: Fulfill,
6241 // [[Handler]]: onFulfilledJobCallback }.
6242 // Step 8. Let rejectReaction be the PromiseReaction
6243 // { [[Capability]]: resultCapability, [[Type]]: Reject,
6244 // [[Handler]]: onRejectedJobCallback }.
6245 //
6246 // NOTE: We use single object for both reactions.
6247 Rooted<PromiseReactionRecord*> reaction(
6248 cx, NewReactionRecord(cx, resultCapability, onFulfilled, onRejected,
6249 HostDefinedDataObject::Yes));
6250 if (!reaction) {
6251 return false;
6252 }
6253
6254 // Steps 9-14.
6255 return PerformPromiseThenWithReaction(cx, promise, reaction);
6256 }
6257
6258 /**
6259 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
6260 *
6261 * PerformPromiseThen ( promise, onFulfilled, onRejected
6262 * [ , resultCapability ] )
6263 * https://tc39.es/ecma262/#sec-performpromisethen
6264 */
6265 [[nodiscard]] static bool PerformPromiseThenWithoutSettleHandlers(
6266 JSContext* cx, Handle<PromiseObject*> promise,
6267 Handle<PromiseObject*> promiseToResolve,
6268 Handle<PromiseCapability> resultCapability) {
6269 // Step 1. Assert: IsPromise(promise) is true.
6270 // Step 2. If resultCapability is not present, then
6271 // (implicit)
6272
6273 // Step 3. If IsCallable(onFulfilled) is false, then
6274 // Step 3.a. Let onFulfilledJobCallback be empty.
6275 HandleValue onFulfilled = NullHandleValue;
6276
6277 // Step 5. If IsCallable(onRejected) is false, then
6278 // Step 5.a. Let onRejectedJobCallback be empty.
6279 HandleValue onRejected = NullHandleValue;
6280
6281 // Step 7. Let fulfillReaction be the PromiseReaction
6282 // { [[Capability]]: resultCapability, [[Type]]: Fulfill,
6283 // [[Handler]]: onFulfilledJobCallback }.
6284 // Step 8. Let rejectReaction be the PromiseReaction
6285 // { [[Capability]]: resultCapability, [[Type]]: Reject,
6286 // [[Handler]]: onRejectedJobCallback }.
6287 Rooted<PromiseReactionRecord*> reaction(
6288 cx, NewReactionRecord(cx, resultCapability, onFulfilled, onRejected,
6289 HostDefinedDataObject::Yes));
6290 if (!reaction) {
6291 return false;
6292 }
6293
6294 reaction->setIsDefaultResolvingHandler(promiseToResolve);
6295
6296 // Steps 9-12.
6297 return PerformPromiseThenWithReaction(cx, promise, reaction);
6298 }
6299
6300 /**
6301 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
6302 *
6303 * PerformPromiseThen ( promise, onFulfilled, onRejected
6304 * [ , resultCapability ] )
6305 * https://tc39.github.io/ecma262/#sec-performpromisethen
6306 *
6307 * Steps 9-12.
6308 */
6309 [[nodiscard]] static bool PerformPromiseThenWithReaction(
6310 JSContext* cx, Handle<PromiseObject*> unwrappedPromise,
6311 Handle<PromiseReactionRecord*> reaction) {
6312 // Step 9. If promise.[[PromiseState]] is pending, then
6313 JS::PromiseState state = unwrappedPromise->state();
6314 int32_t flags = unwrappedPromise->flags();
6315 if (state == JS::PromiseState::Pending) {
6316 // Step 9.a. Append fulfillReaction as the last element of the List that is
6317 // promise.[[PromiseFulfillReactions]].
6318 // Step 9.b. Append rejectReaction as the last element of the List that is
6319 // promise.[[PromiseRejectReactions]].
6320 //
6321 // Instead of creating separate reaction records for fulfillment and
6322 // rejection, we create a combined record. All places we use the record
6323 // can handle that.
6324 if (!AddPromiseReaction(cx, unwrappedPromise, reaction)) {
6325 return false;
6326 }
6327 }
6328
6329 // Steps 10-11.
6330 else {
6331 // Step 11.a. Assert: The value of promise.[[PromiseState]] is rejected.
6332 MOZ_ASSERT_IF(state != JS::PromiseState::Fulfilled,
6333 state == JS::PromiseState::Rejected);
6334
6335 // Step 10.a. Let value be promise.[[PromiseResult]].
6336 // Step 11.b. Let reason be promise.[[PromiseResult]].
6337 RootedValue valueOrReason(cx, unwrappedPromise->valueOrReason());
6338
6339 // We might be operating on a promise from another compartment. In that
6340 // case, we need to wrap the result/reason value before using it.
6341 if (!cx->compartment()->wrap(cx, &valueOrReason)) {
6342 return false;
6343 }
6344
6345 // Step 11.c. If promise.[[PromiseIsHandled]] is false,
6346 // perform HostPromiseRejectionTracker(promise, "handle").
6347 if (state == JS::PromiseState::Rejected &&
6348 !(flags & PROMISE_FLAG_HANDLED)) {
6349 cx->runtime()->removeUnhandledRejectedPromise(cx, unwrappedPromise);
6350 }
6351
6352 // Step 10.b. Let fulfillJob be
6353 // NewPromiseReactionJob(fulfillReaction, value).
6354 // Step 10.c. Perform HostEnqueuePromiseJob(fulfillJob.[[Job]],
6355 // fulfillJob.[[Realm]]).
6356 // Step 11.d. Let rejectJob be
6357 // NewPromiseReactionJob(rejectReaction, reason).
6358 // Step 11.e. Perform HostEnqueuePromiseJob(rejectJob.[[Job]],
6359 // rejectJob.[[Realm]]).
6360 if (!EnqueuePromiseReactionJob(cx, reaction, valueOrReason, state)) {
6361 return false;
6362 }
6363 }
6364
6365 // Step 12. Set promise.[[PromiseIsHandled]] to true.
6366 unwrappedPromise->setHandled();
6367
6368 return true;
6369 }
6370
6371 /**
6372 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
6373 *
6374 * PerformPromiseThen ( promise, onFulfilled, onRejected
6375 * [ , resultCapability ] )
6376 * https://tc39.github.io/ecma262/#sec-performpromisethen
6377 *
6378 * Steps 9.a-b.
6379 */
6380 [[nodiscard]] static bool AddPromiseReaction(
6381 JSContext* cx, Handle<PromiseObject*> unwrappedPromise,
6382 Handle<PromiseReactionRecord*> reaction) {
6383 MOZ_RELEASE_ASSERT(reaction->is<PromiseReactionRecord>());
6384 RootedValue reactionVal(cx, ObjectValue(*reaction));
6385
6386 // The code that creates Promise reactions can handle wrapped Promises,
6387 // unwrapping them as needed. That means that the `promise` and `reaction`
6388 // objects we have here aren't necessarily from the same compartment. In
6389 // order to store the reaction on the promise, we have to ensure that it
6390 // is properly wrapped.
6391 mozilla::Maybe<AutoRealm> ar;
6392 if (unwrappedPromise->compartment() != cx->compartment()) {
6393 ar.emplace(cx, unwrappedPromise);
6394 if (!cx->compartment()->wrap(cx, &reactionVal)) {
6395 return false;
6396 }
6397 }
6398 Handle<PromiseObject*> promise = unwrappedPromise;
6399
6400 // Step 9.a. Append fulfillReaction as the last element of the List that is
6401 // promise.[[PromiseFulfillReactions]].
6402 // Step 9.b. Append rejectReaction as the last element of the List that is
6403 // promise.[[PromiseRejectReactions]].
6404 RootedValue reactionsVal(cx, promise->reactions());
6405
6406 if (reactionsVal.isUndefined()) {
6407 // If no reactions existed so far, just store the reaction record directly.
6408 promise->setFixedSlot(PromiseSlot_ReactionsOrResult, reactionVal);
6409 return true;
6410 }
6411
6412 RootedObject reactionsObj(cx, &reactionsVal.toObject());
6413
6414 // If only a single reaction exists, it's stored directly instead of in a
6415 // list. In that case, `reactionsObj` might be a wrapper, which we can
6416 // always safely unwrap.
6417 if (IsProxy(reactionsObj)) {
6418 reactionsObj = UncheckedUnwrap(reactionsObj);
6419 if (JS_IsDeadWrapper(reactionsObj)) {
6420 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
6421 JSMSG_DEAD_OBJECT);
6422 return false;
6423 }
6424 MOZ_RELEASE_ASSERT(reactionsObj->is<PromiseReactionRecord>());
6425 }
6426
6427 if (reactionsObj->is<PromiseReactionRecord>()) {
6428 // If a single reaction existed so far, create a list and store the
6429 // old and the new reaction in it.
6430 ArrayObject* reactions = NewDenseFullyAllocatedArray(cx, 2);
6431 if (!reactions) {
6432 return false;
6433 }
6434
6435 reactions->setDenseInitializedLength(2);
6436 reactions->initDenseElement(0, reactionsVal);
6437 reactions->initDenseElement(1, reactionVal);
6438
6439 promise->setFixedSlot(PromiseSlot_ReactionsOrResult,
6440 ObjectValue(*reactions));
6441 } else {
6442 // Otherwise, just store the new reaction.
6443 MOZ_RELEASE_ASSERT(reactionsObj->is<NativeObject>());
6444 Handle<NativeObject*> reactions = reactionsObj.as<NativeObject>();
6445 uint32_t len = reactions->getDenseInitializedLength();
6446 DenseElementResult result = reactions->ensureDenseElements(cx, len, 1);
6447 if (result != DenseElementResult::Success) {
6448 MOZ_ASSERT(result == DenseElementResult::Failure);
6449 return false;
6450 }
6451 reactions->setDenseElement(len, reactionVal);
6452 }
6453
6454 return true;
6455 }
6456
6457 [[nodiscard]] static bool AddDummyPromiseReactionForDebugger(
6458 JSContext* cx, Handle<PromiseObject*> promise,
6459 HandleObject dependentPromise) {
6460 if (promise->state() != JS::PromiseState::Pending) {
6461 return true;
6462 }
6463
6464 if (JS_IsDeadWrapper(UncheckedUnwrap(dependentPromise))) {
6465 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_DEAD_OBJECT);
6466 return false;
6467 }
6468
6469 // `dependentPromise` should be a maybe-wrapped Promise.
6470 MOZ_ASSERT(UncheckedUnwrap(dependentPromise)->is<PromiseObject>());
6471
6472 // Leave resolve and reject as null.
6473 Rooted<PromiseCapability> capability(cx);
6474 capability.promise().set(dependentPromise);
6475
6476 Rooted<PromiseReactionRecord*> reaction(
6477 cx, NewReactionRecord(cx, capability, NullHandleValue, NullHandleValue,
6478 HostDefinedDataObject::No));
6479 if (!reaction) {
6480 return false;
6481 }
6482
6483 reaction->setIsDebuggerDummy();
6484
6485 return AddPromiseReaction(cx, promise, reaction);
6486 }
6487
6488 uint64_t PromiseObject::getID() { return PromiseDebugInfo::id(this); }
6489
6490 double PromiseObject::lifetime() {
6491 return MillisecondsSinceStartup() - allocationTime();
6492 }
6493
6494 /**
6495 * Returns all promises that directly depend on this one. That means those
6496 * created by calling `then` on this promise, or the promise returned by
6497 * `Promise.all(iterable)` or `Promise.race(iterable)`, with this promise
6498 * being a member of the passed-in `iterable`.
6499 *
6500 * Per spec, we should have separate lists of reaction records for the
6501 * fulfill and reject cases. As an optimization, we have only one of those,
6502 * containing the required data for both cases. So we just walk that list
6503 * and extract the dependent promises from all reaction records.
6504 */
6505 bool PromiseObject::dependentPromises(JSContext* cx,
6506 MutableHandle<GCVector<Value>> values) {
6507 if (state() != JS::PromiseState::Pending) {
6508 return true;
6509 }
6510
6511 uint32_t valuesIndex = 0;
6512 RootedValue reactionsVal(cx, reactions());
6513
6514 return ForEachReaction(cx, reactionsVal, [&](MutableHandleObject obj) {
6515 if (IsProxy(obj)) {
6516 obj.set(UncheckedUnwrap(obj));
6517 }
6518
6519 if (JS_IsDeadWrapper(obj)) {
6520 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
6521 JSMSG_DEAD_OBJECT);
6522 return false;
6523 }
6524
6525 MOZ_RELEASE_ASSERT(obj->is<PromiseReactionRecord>());
6526 Rooted<PromiseReactionRecord*> reaction(cx,
6527 &obj->as<PromiseReactionRecord>());
6528
6529 // Not all reactions have a Promise on them.
6530 RootedObject promiseObj(cx, reaction->promise());
6531 if (promiseObj) {
6532 if (!values.growBy(1)) {
6533 return false;
6534 }
6535
6536 values[valuesIndex++].setObject(*promiseObj);
6537 }
6538 return true;
6539 });
6540 }
6541
6542 bool PromiseObject::forEachReactionRecord(
6543 JSContext* cx, PromiseReactionRecordBuilder& builder) {
6544 if (state() != JS::PromiseState::Pending) {
6545 // Promise was resolved, so no reaction records are present.
6546 return true;
6547 }
6548
6549 RootedValue reactionsVal(cx, reactions());
6550 if (reactionsVal.isNullOrUndefined()) {
6551 // No reaction records are attached to this promise.
6552 return true;
6553 }
6554
6555 return ForEachReaction(cx, reactionsVal, [&](MutableHandleObject obj) {
6556 if (IsProxy(obj)) {
6557 obj.set(UncheckedUnwrap(obj));
6558 }
6559
6560 if (JS_IsDeadWrapper(obj)) {
6561 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
6562 JSMSG_DEAD_OBJECT);
6563 return false;
6564 }
6565
6566 Rooted<PromiseReactionRecord*> reaction(cx,
6567 &obj->as<PromiseReactionRecord>());
6568 MOZ_ASSERT(reaction->targetState() == JS::PromiseState::Pending);
6569
6570 if (reaction->isAsyncFunction()) {
6571 Rooted<AsyncFunctionGeneratorObject*> generator(
6572 cx, reaction->asyncFunctionGenerator());
6573 if (!builder.asyncFunction(cx, generator)) {
6574 return false;
6575 }
6576 } else if (reaction->isAsyncGenerator()) {
6577 Rooted<AsyncGeneratorObject*> generator(cx, reaction->asyncGenerator());
6578 if (!builder.asyncGenerator(cx, generator)) {
6579 return false;
6580 }
6581 } else if (reaction->isDefaultResolvingHandler()) {
6582 Rooted<PromiseObject*> promise(cx, reaction->defaultResolvingPromise());
6583 if (!builder.direct(cx, promise)) {
6584 return false;
6585 }
6586 } else {
6587 RootedObject resolve(cx);
6588 RootedObject reject(cx);
6589 RootedObject result(cx, reaction->promise());
6590
6591 Value v = reaction->getFixedSlot(ReactionRecordSlot_OnFulfilled);
6592 if (v.isObject()) {
6593 resolve = &v.toObject();
6594 }
6595
6596 v = reaction->getFixedSlot(ReactionRecordSlot_OnRejected);
6597 if (v.isObject()) {
6598 reject = &v.toObject();
6599 }
6600
6601 if (!builder.then(cx, resolve, reject, result)) {
6602 return false;
6603 }
6604 }
6605
6606 return true;
6607 });
6608 }
6609
6610 /**
6611 * ES2023 draft rev 714fa3dd1e8237ae9c666146270f81880089eca5
6612 *
6613 * Promise Reject Functions
6614 * https://tc39.es/ecma262/#sec-promise-reject-functions
6615 */
6616 static bool CallDefaultPromiseResolveFunction(JSContext* cx,
6617 Handle<PromiseObject*> promise,
6618 HandleValue resolutionValue) {
6619 MOZ_ASSERT(IsPromiseWithDefaultResolvingFunction(promise));
6620
6621 // Steps 1-3.
6622 // (implicit)
6623
6624 // Step 4. Let alreadyResolved be F.[[AlreadyResolved]].
6625 // Step 5. If alreadyResolved.[[Value]] is true, return undefined.
6626 if (IsAlreadyResolvedPromiseWithDefaultResolvingFunction(promise)) {
6627 return true;
6628 }
6629
6630 // Step 6. Set alreadyResolved.[[Value]] to true.
6631 SetAlreadyResolvedPromiseWithDefaultResolvingFunction(promise);
6632
6633 // Steps 7-15.
6634 // (implicit) Step 16. Return undefined.
6635 return ResolvePromiseInternal(cx, promise, resolutionValue);
6636 }
6637
6638 /* static */
6639 bool PromiseObject::resolve(JSContext* cx, Handle<PromiseObject*> promise,
6640 HandleValue resolutionValue) {
6641 MOZ_ASSERT(!PromiseHasAnyFlag(*promise, PROMISE_FLAG_ASYNC));
6642 if (promise->state() != JS::PromiseState::Pending) {
6643 return true;
6644 }
6645
6646 if (IsPromiseWithDefaultResolvingFunction(promise)) {
6647 return CallDefaultPromiseResolveFunction(cx, promise, resolutionValue);
6648 }
6649
6650 JSFunction* resolveFun = GetResolveFunctionFromPromise(promise);
6651 if (!resolveFun) {
6652 return true;
6653 }
6654
6655 RootedValue funVal(cx, ObjectValue(*resolveFun));
6656
6657 // For xray'd Promises, the resolve fun may have been created in another
6658 // compartment. For the call below to work in that case, wrap the
6659 // function into the current compartment.
6660 if (!cx->compartment()->wrap(cx, &funVal)) {
6661 return false;
6662 }
6663
6664 RootedValue dummy(cx);
6665 return Call(cx, funVal, UndefinedHandleValue, resolutionValue, &dummy);
6666 }
6667
6668 /**
6669 * ES2023 draft rev 714fa3dd1e8237ae9c666146270f81880089eca5
6670 *
6671 * Promise Reject Functions
6672 * https://tc39.es/ecma262/#sec-promise-reject-functions
6673 */
6674 static bool CallDefaultPromiseRejectFunction(
6675 JSContext* cx, Handle<PromiseObject*> promise, HandleValue rejectionValue,
6676 JS::Handle<SavedFrame*> unwrappedRejectionStack /* = nullptr */) {
6677 MOZ_ASSERT(IsPromiseWithDefaultResolvingFunction(promise));
6678
6679 // Steps 1-3.
6680 // (implicit)
6681
6682 // Step 4. Let alreadyResolved be F.[[AlreadyResolved]].
6683 // Step 5. If alreadyResolved.[[Value]] is true, return undefined.
6684 if (IsAlreadyResolvedPromiseWithDefaultResolvingFunction(promise)) {
6685 return true;
6686 }
6687
6688 // Step 6. Set alreadyResolved.[[Value]] to true.
6689 SetAlreadyResolvedPromiseWithDefaultResolvingFunction(promise);
6690
6691 return RejectPromiseInternal(cx, promise, rejectionValue,
6692 unwrappedRejectionStack);
6693 }
6694
6695 /* static */
6696 bool PromiseObject::reject(JSContext* cx, Handle<PromiseObject*> promise,
6697 HandleValue rejectionValue) {
6698 MOZ_ASSERT(!PromiseHasAnyFlag(*promise, PROMISE_FLAG_ASYNC));
6699 if (promise->state() != JS::PromiseState::Pending) {
6700 return true;
6701 }
6702
6703 if (IsPromiseWithDefaultResolvingFunction(promise)) {
6704 return CallDefaultPromiseRejectFunction(cx, promise, rejectionValue);
6705 }
6706
6707 RootedValue funVal(cx, promise->getFixedSlot(PromiseSlot_RejectFunction));
6708 MOZ_ASSERT(IsCallable(funVal));
6709
6710 RootedValue dummy(cx);
6711 return Call(cx, funVal, UndefinedHandleValue, rejectionValue, &dummy);
6712 }
6713
6714 /**
6715 * ES2022 draft rev d03c1ec6e235a5180fa772b6178727c17974cb14
6716 *
6717 * RejectPromise ( promise, reason )
6718 * https://tc39.es/ecma262/#sec-rejectpromise
6719 *
6720 * Step 7.
6721 */
6722 /* static */
6723 void PromiseObject::onSettled(JSContext* cx, Handle<PromiseObject*> promise,
6724 Handle<SavedFrame*> unwrappedRejectionStack) {
6725 PromiseDebugInfo::setResolutionInfo(cx, promise, unwrappedRejectionStack);
6726
6727 // Step 7. If promise.[[PromiseIsHandled]] is false, perform
6728 // HostPromiseRejectionTracker(promise, "reject").
6729 if (promise->state() == JS::PromiseState::Rejected &&
6730 promise->isUnhandled()) {
6731 cx->runtime()->addUnhandledRejectedPromise(cx, promise);
6732 }
6733
6734 DebugAPI::onPromiseSettled(cx, promise);
6735 }
6736
6737 void PromiseObject::setRequiresUserInteractionHandling(bool state) {
6738 if (state) {
6739 AddPromiseFlags(*this, PROMISE_FLAG_REQUIRES_USER_INTERACTION_HANDLING);
6740 } else {
6741 RemovePromiseFlags(*this, PROMISE_FLAG_REQUIRES_USER_INTERACTION_HANDLING);
6742 }
6743 }
6744
6745 void PromiseObject::setHadUserInteractionUponCreation(bool state) {
6746 if (state) {
6747 AddPromiseFlags(*this, PROMISE_FLAG_HAD_USER_INTERACTION_UPON_CREATION);
6748 } else {
6749 RemovePromiseFlags(*this, PROMISE_FLAG_HAD_USER_INTERACTION_UPON_CREATION);
6750 }
6751 }
6752
6753 void PromiseObject::copyUserInteractionFlagsFrom(PromiseObject& rhs) {
6754 setRequiresUserInteractionHandling(rhs.requiresUserInteractionHandling());
6755 setHadUserInteractionUponCreation(rhs.hadUserInteractionUponCreation());
6756 }
6757
6758 #if defined(DEBUG) || defined(JS_JITSPEW)
6759 void PromiseDebugInfo::dumpOwnFields(js::JSONPrinter& json) const {
6760 if (getFixedSlot(Slot_Id).isNumber()) {
6761 json.formatProperty("id", "%lf", getFixedSlot(Slot_Id).toNumber());
6762 }
6763
6764 if (getFixedSlot(Slot_AllocationTime).isNumber()) {
6765 json.formatProperty("allocationTime", "%lf",
6766 getFixedSlot(Slot_AllocationTime).toNumber());
6767 }
6768
6769 {
6770 js::GenericPrinter& out = json.beginStringProperty("allocationSite");
6771 getFixedSlot(Slot_AllocationSite).dumpStringContent(out);
6772 json.endStringProperty();
6773 }
6774
6775 if (getFixedSlot(Slot_ResolutionTime).isNumber()) {
6776 json.formatProperty("resolutionTime", "%lf",
6777 getFixedSlot(Slot_ResolutionTime).toNumber());
6778 }
6779
6780 {
6781 js::GenericPrinter& out = json.beginStringProperty("resolutionSite");
6782 getFixedSlot(Slot_ResolutionSite).dumpStringContent(out);
6783 json.endStringProperty();
6784 }
6785 }
6786
6787 template <typename KnownF, typename UnknownF>
6788 /* static */
6789 void PromiseReactionRecord::forEachReactionFlag(uint32_t flags, KnownF known,
6790 UnknownF unknown) {
6791 for (uint32_t i = 1; i; i = i << 1) {
6792 if (!(flags & i)) {
6793 continue;
6794 }
6795 switch (flags & i) {
6796 case REACTION_FLAG_RESOLVED:
6797 known("RESOLVED");
6798 break;
6799 case REACTION_FLAG_FULFILLED:
6800 known("FULFILLED");
6801 break;
6802 case REACTION_FLAG_DEFAULT_RESOLVING_HANDLER:
6803 known("DEFAULT_RESOLVING_HANDLER");
6804 break;
6805 case REACTION_FLAG_ASYNC_FUNCTION:
6806 known("ASYNC_FUNCTION");
6807 break;
6808 case REACTION_FLAG_ASYNC_GENERATOR:
6809 known("ASYNC_GENERATOR");
6810 break;
6811 case REACTION_FLAG_DEBUGGER_DUMMY:
6812 known("DEBUGGER_DUMMY");
6813 break;
6814 case REACTION_FLAG_IGNORE_UNHANDLED_REJECTION:
6815 known("IGNORE_UNHANDLED_REJECTION");
6816 break;
6817 default:
6818 unknown(i);
6819 break;
6820 }
6821 }
6822 }
6823
6824 void PromiseReactionRecord::dumpOwnFields(js::JSONPrinter& json) const {
6825 if (promise()) {
6826 js::GenericPrinter& out = json.beginStringProperty("promise");
6827 promise()->dumpStringContent(out);
6828 json.endStringProperty();
6829 }
6830
6831 if (targetState() == JS::PromiseState::Fulfilled) {
6832 {
6833 js::GenericPrinter& out = json.beginStringProperty("onFulfilled");
6834 getFixedSlot(ReactionRecordSlot_OnFulfilled).dumpStringContent(out);
6835 json.endStringProperty();
6836 }
6837 {
6838 js::GenericPrinter& out = json.beginStringProperty("onFulfilledArg");
6839 getFixedSlot(ReactionRecordSlot_OnFulfilledArg).dumpStringContent(out);
6840 json.endStringProperty();
6841 }
6842 }
6843
6844 if (targetState() == JS::PromiseState::Rejected) {
6845 {
6846 js::GenericPrinter& out = json.beginStringProperty("onRejected");
6847 getFixedSlot(ReactionRecordSlot_OnRejected).dumpStringContent(out);
6848 json.endStringProperty();
6849 }
6850 {
6851 js::GenericPrinter& out = json.beginStringProperty("onRejectedArg");
6852 getFixedSlot(ReactionRecordSlot_OnRejectedArg).dumpStringContent(out);
6853 json.endStringProperty();
6854 }
6855 }
6856
6857 if (!getFixedSlot(ReactionRecordSlot_Resolve).isNull()) {
6858 js::GenericPrinter& out = json.beginStringProperty("resolve");
6859 getFixedSlot(ReactionRecordSlot_Resolve).dumpStringContent(out);
6860 json.endStringProperty();
6861 }
6862
6863 if (!getFixedSlot(ReactionRecordSlot_Reject).isNull()) {
6864 js::GenericPrinter& out = json.beginStringProperty("reject");
6865 getFixedSlot(ReactionRecordSlot_Reject).dumpStringContent(out);
6866 json.endStringProperty();
6867 }
6868
6869 {
6870 js::GenericPrinter& out = json.beginStringProperty("hostDefinedData");
6871 getFixedSlot(ReactionRecordSlot_HostDefinedData).dumpStringContent(out);
6872 json.endStringProperty();
6873 }
6874
6875 json.beginInlineListProperty("flags");
6876 forEachReactionFlag(
6877 flags(), [&](const char* name) { json.value("%s", name); },
6878 [&](uint32_t value) { json.value("Unknown(%08x)", value); });
6879 json.endInlineList();
6880
6881 if (isDefaultResolvingHandler()) {
6882 js::GenericPrinter& out = json.beginStringProperty("promiseToResolve");
6883 getFixedSlot(ReactionRecordSlot_GeneratorOrPromiseToResolve)
6884 .dumpStringContent(out);
6885 json.endStringProperty();
6886 }
6887
6888 if (isAsyncFunction()) {
6889 js::GenericPrinter& out = json.beginStringProperty("generator");
6890 getFixedSlot(ReactionRecordSlot_GeneratorOrPromiseToResolve)
6891 .dumpStringContent(out);
6892 json.endStringProperty();
6893 }
6894
6895 if (isAsyncGenerator()) {
6896 js::GenericPrinter& out = json.beginStringProperty("generator");
6897 getFixedSlot(ReactionRecordSlot_GeneratorOrPromiseToResolve)
6898 .dumpStringContent(out);
6899 json.endStringProperty();
6900 }
6901 }
6902
6903 void DumpReactions(js::JSONPrinter& json, const JS::Value& reactionsVal) {
6904 if (reactionsVal.isUndefined()) {
6905 return;
6906 }
6907
6908 if (reactionsVal.isObject()) {
6909 JSObject* reactionsObj = &reactionsVal.toObject();
6910 if (IsProxy(reactionsObj)) {
6911 reactionsObj = UncheckedUnwrap(reactionsObj);
6912 }
6913
6914 if (reactionsObj->is<PromiseReactionRecord>()) {
6915 json.beginObject();
6916 reactionsObj->as<PromiseReactionRecord>().dumpOwnFields(json);
6917 json.endObject();
6918 return;
6919 }
6920
6921 if (reactionsObj->is<NativeObject>()) {
6922 NativeObject* reactionsList = &reactionsObj->as<NativeObject>();
6923 uint32_t len = reactionsList->getDenseInitializedLength();
6924 for (uint32_t i = 0; i < len; i++) {
6925 const JS::Value& reactionVal = reactionsList->getDenseElement(i);
6926 if (reactionVal.isObject()) {
6927 JSObject* reactionsObj = &reactionVal.toObject();
6928 if (IsProxy(reactionsObj)) {
6929 reactionsObj = UncheckedUnwrap(reactionsObj);
6930 }
6931
6932 if (reactionsObj->is<PromiseReactionRecord>()) {
6933 json.beginObject();
6934 reactionsObj->as<PromiseReactionRecord>().dumpOwnFields(json);
6935 json.endObject();
6936 continue;
6937 }
6938 }
6939
6940 js::GenericPrinter& out = json.beginString();
6941 out.put("Unknown(");
6942 reactionVal.dumpStringContent(out);
6943 out.put(")");
6944 json.endString();
6945 }
6946 return;
6947 }
6948 }
6949
6950 js::GenericPrinter& out = json.beginString();
6951 out.put("Unknown(");
6952 reactionsVal.dumpStringContent(out);
6953 out.put(")");
6954 json.endString();
6955 }
6956
6957 template <typename KnownF, typename UnknownF>
6958 void ForEachPromiseFlag(uint32_t flags, KnownF known, UnknownF unknown) {
6959 for (uint32_t i = 1; i; i = i << 1) {
6960 if (!(flags & i)) {
6961 continue;
6962 }
6963 switch (flags & i) {
6964 case PROMISE_FLAG_RESOLVED:
6965 known("RESOLVED");
6966 break;
6967 case PROMISE_FLAG_FULFILLED:
6968 known("FULFILLED");
6969 break;
6970 case PROMISE_FLAG_HANDLED:
6971 known("HANDLED");
6972 break;
6973 case PROMISE_FLAG_DEFAULT_RESOLVING_FUNCTIONS:
6974 known("DEFAULT_RESOLVING_FUNCTIONS");
6975 break;
6976 case PROMISE_FLAG_DEFAULT_RESOLVING_FUNCTIONS_ALREADY_RESOLVED:
6977 known("DEFAULT_RESOLVING_FUNCTIONS_ALREADY_RESOLVED");
6978 break;
6979 case PROMISE_FLAG_ASYNC:
6980 known("ASYNC");
6981 break;
6982 case PROMISE_FLAG_REQUIRES_USER_INTERACTION_HANDLING:
6983 known("REQUIRES_USER_INTERACTION_HANDLING");
6984 break;
6985 case PROMISE_FLAG_HAD_USER_INTERACTION_UPON_CREATION:
6986 known("HAD_USER_INTERACTION_UPON_CREATION");
6987 break;
6988 default:
6989 unknown(i);
6990 break;
6991 }
6992 }
6993 }
6994
6995 void PromiseObject::dumpOwnFields(js::JSONPrinter& json) const {
6996 json.beginInlineListProperty("flags");
6997 ForEachPromiseFlag(
6998 flags(), [&](const char* name) { json.value("%s", name); },
6999 [&](uint32_t value) { json.value("Unknown(%08x)", value); });
7000 json.endInlineList();
7001
7002 if (state() == JS::PromiseState::Pending) {
7003 json.property("state", "pending");
7004
7005 json.beginListProperty("reactions");
7006 DumpReactions(json, reactions());
7007 json.endList();
7008 } else if (state() == JS::PromiseState::Fulfilled) {
7009 json.property("state", "fulfilled");
7010
7011 json.beginObjectProperty("value");
7012 value().dumpFields(json);
7013 json.endObject();
7014 } else if (state() == JS::PromiseState::Rejected) {
7015 json.property("state", "rejected");
7016
7017 json.beginObjectProperty("reason");
7018 reason().dumpFields(json);
7019 json.endObject();
7020 }
7021
7022 JS::Value debugInfo = getFixedSlot(PromiseSlot_DebugInfo);
7023 if (debugInfo.isNumber()) {
7024 json.formatProperty("id", "%lf", debugInfo.toNumber());
7025 } else if (debugInfo.isObject() &&
7026 debugInfo.toObject().is<PromiseDebugInfo>()) {
7027 debugInfo.toObject().as<PromiseDebugInfo>().dumpOwnFields(json);
7028 }
7029 }
7030
7031 void PromiseObject::dumpOwnStringContent(js::GenericPrinter& out) const {}
7032 #endif
7033
7034 // We can skip `await` with an already resolved value only if the current frame
7035 // is the topmost JS frame and the current job is the last job in the job queue.
7036 // This guarantees that any new job enqueued in the current turn will be
7037 // executed immediately after the current job.
7038 //
7039 // Currently we only support skipping jobs when the async function is resumed
7040 // at least once.
7041 [[nodiscard]] static bool IsTopMostAsyncFunctionCall(JSContext* cx) {
7042 FrameIter iter(cx);
7043
7044 // The current frame should be the async function.
7045 if (iter.done()) {
7046 return false;
7047 }
7048
7049 if (!iter.isFunctionFrame() && iter.isModuleFrame()) {
7050 // The iterator is not a function frame, it is a module frame.
7051 // Ignore this optimization for now.
7052 return true;
7053 }
7054
7055 MOZ_ASSERT(iter.calleeTemplate()->isAsync());
7056
7057 #ifdef DEBUG
7058 bool isGenerator = iter.calleeTemplate()->isGenerator();
7059 #endif
7060
7061 ++iter;
7062
7063 // The parent frame should be the `next` function of the generator that is
7064 // internally called in AsyncFunctionResume resp. AsyncGeneratorResume.
7065 if (iter.done()) {
7066 return false;
7067 }
7068 // The initial call into an async function can happen from top-level code, so
7069 // the parent frame isn't required to be a function frame. Contrary to that,
7070 // the parent frame for an async generator function is always a function
7071 // frame, because async generators can't directly fall through to an `await`
7072 // expression from their initial call.
7073 if (!iter.isFunctionFrame()) {
7074 MOZ_ASSERT(!isGenerator);
7075 return false;
7076 }
7077
7078 // Always skip InterpretGeneratorResume if present.
7079 JSFunction* fun = iter.calleeTemplate();
7080 if (IsSelfHostedFunctionWithName(fun, cx->names().InterpretGeneratorResume)) {
7081 ++iter;
7082
7083 if (iter.done()) {
7084 return false;
7085 }
7086
7087 MOZ_ASSERT(iter.isFunctionFrame());
7088 fun = iter.calleeTemplate();
7089 }
7090
7091 if (!IsSelfHostedFunctionWithName(fun, cx->names().AsyncFunctionNext) &&
7092 !IsSelfHostedFunctionWithName(fun, cx->names().AsyncGeneratorNext)) {
7093 return false;
7094 }
7095
7096 ++iter;
7097
7098 // There should be no more frames.
7099 if (iter.done()) {
7100 return true;
7101 }
7102
7103 return false;
7104 }
7105
7106 [[nodiscard]] bool js::CanSkipAwait(JSContext* cx, HandleValue val,
7107 bool* canSkip) {
7108 if (!cx->canSkipEnqueuingJobs) {
7109 *canSkip = false;
7110 return true;
7111 }
7112
7113 if (!IsTopMostAsyncFunctionCall(cx)) {
7114 *canSkip = false;
7115 return true;
7116 }
7117
7118 // Primitive values cannot be 'thenables', so we can trivially skip the
7119 // await operation.
7120 if (!val.isObject()) {
7121 *canSkip = true;
7122 return true;
7123 }
7124
7125 JSObject* obj = &val.toObject();
7126 if (!obj->is<PromiseObject>()) {
7127 *canSkip = false;
7128 return true;
7129 }
7130
7131 PromiseObject* promise = &obj->as<PromiseObject>();
7132
7133 if (promise->state() == JS::PromiseState::Pending) {
7134 *canSkip = false;
7135 return true;
7136 }
7137
7138 if (!IsPromiseWithDefaultProperties(promise, cx)) {
7139 *canSkip = false;
7140 return true;
7141 }
7142
7143 if (promise->state() == JS::PromiseState::Rejected) {
7144 // We don't optimize rejected Promises for now.
7145 *canSkip = false;
7146 return true;
7147 }
7148
7149 *canSkip = true;
7150 return true;
7151 }
7152
7153 [[nodiscard]] bool js::ExtractAwaitValue(JSContext* cx, HandleValue val,
7154 MutableHandleValue resolved) {
7155 // Ensure all callers of this are jumping past the
7156 // extract if it's not possible to extract.
7157 #ifdef DEBUG
7158 bool canSkip;
7159 if (!CanSkipAwait(cx, val, &canSkip)) {
7160 return false;
7161 }
7162 MOZ_ASSERT(canSkip == true);
7163 #endif
7164
7165 // Primitive values cannot be 'thenables', so we can trivially skip the
7166 // await operation.
7167 if (!val.isObject()) {
7168 resolved.set(val);
7169 return true;
7170 }
7171
7172 JSObject* obj = &val.toObject();
7173 PromiseObject* promise = &obj->as<PromiseObject>();
7174 resolved.set(promise->value());
7175
7176 return true;
7177 }
7178
7179 JS::AutoDebuggerJobQueueInterruption::AutoDebuggerJobQueueInterruption()
7180 : cx(nullptr) {}
7181
7182 JS::AutoDebuggerJobQueueInterruption::~AutoDebuggerJobQueueInterruption() {
7183 MOZ_ASSERT_IF(initialized() && !cx->jobQueue->isDrainingStopped(),
7184 cx->jobQueue->empty());
7185 }
7186
7187 bool JS::AutoDebuggerJobQueueInterruption::init(JSContext* cx) {
7188 MOZ_ASSERT(cx->jobQueue);
7189 this->cx = cx;
7190 saved = cx->jobQueue->saveJobQueue(cx);
7191 return !!saved;
7192 }
7193
7194 void JS::AutoDebuggerJobQueueInterruption::runJobs() {
7195 JS::AutoSaveExceptionState ases(cx);
7196 cx->jobQueue->runJobs(cx);
7197 }
7198
7199 const JSJitInfo promise_then_info = {
7200 {(JSJitGetterOp)Promise_then_noRetVal},
7201 {0}, /* unused */
7202 {0}, /* unused */
7203 JSJitInfo::IgnoresReturnValueNative,
7204 JSJitInfo::AliasEverything,
7205 JSVAL_TYPE_UNDEFINED,
7206 };
7207
7208 const JSJitInfo promise_catch_info = {
7209 {(JSJitGetterOp)Promise_catch_noRetVal},
7210 {0}, /* unused */
7211 {0}, /* unused */
7212 JSJitInfo::IgnoresReturnValueNative,
7213 JSJitInfo::AliasEverything,
7214 JSVAL_TYPE_UNDEFINED,
7215 };
7216
7217 static const JSFunctionSpec promise_methods[] = {
7218 JS_FNINFO("then", js::Promise_then, &promise_then_info, 2, 0),
7219 JS_FNINFO("catch", Promise_catch, &promise_catch_info, 1, 0),
7220 JS_SELF_HOSTED_FN("finally", "Promise_finally", 1, 0),
7221 JS_FS_END,
7222 };
7223
7224 static const JSPropertySpec promise_properties[] = {
7225 JS_STRING_SYM_PS(toStringTag, "Promise", JSPROP_READONLY),
7226 JS_PS_END,
7227 };
7228
7229 static const JSFunctionSpec promise_static_methods[] = {
7230 JS_FN("all", Promise_static_all, 1, 0),
7231 JS_FN("allSettled", Promise_static_allSettled, 1, 0),
7232 JS_FN("any", Promise_static_any, 1, 0),
7233 JS_FN("race", Promise_static_race, 1, 0),
7234 JS_FN("reject", Promise_reject, 1, 0),
7235 JS_FN("resolve", js::Promise_static_resolve, 1, 0),
7236 JS_FN("withResolvers", Promise_static_withResolvers, 0, 0),
7237 JS_FN("try", Promise_static_try, 1, 0),
7238 JS_FS_END,
7239 };
7240
7241 static const JSPropertySpec promise_static_properties[] = {
7242 JS_SYM_GET(species, js::Promise_static_species, 0),
7243 JS_PS_END,
7244 };
7245
7246 static const ClassSpec PromiseObjectClassSpec = {
7247 GenericCreateConstructor<PromiseConstructor, 1, gc::AllocKind::FUNCTION>,
7248 GenericCreatePrototype<PromiseObject>,
7249 promise_static_methods,
7250 promise_static_properties,
7251 promise_methods,
7252 promise_properties,
7253 GenericFinishInit<WhichHasFuseProperty::ProtoAndCtor>,
7254 };
7255
7256 const JSClass PromiseObject::class_ = {
7257 "Promise",
7258 JSCLASS_HAS_RESERVED_SLOTS(RESERVED_SLOTS) |
7259 JSCLASS_HAS_CACHED_PROTO(JSProto_Promise) |
7260 JSCLASS_HAS_XRAYED_CONSTRUCTOR,
7261 JS_NULL_CLASS_OPS,
7262 &PromiseObjectClassSpec,
7263 };
7264
7265 const JSClass PromiseObject::protoClass_ = {
7266 "Promise.prototype",
7267 JSCLASS_HAS_CACHED_PROTO(JSProto_Promise),
7268 JS_NULL_CLASS_OPS,
7269 &PromiseObjectClassSpec,
7270 };