Debian Codegraph @

js/src/wasm/WasmPI.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 *
4 * Copyright 2016 Mozilla Foundation
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 #include "wasm/WasmPI.h"
20
21 #include "builtin/Promise.h"
22 #include "debugger/DebugAPI.h"
23 #include "debugger/Debugger.h"
24 #include "jit/arm/Simulator-arm.h"
25 #include "jit/JitRuntime.h"
26 #include "jit/MIRGenerator.h"
27 #include "js/CallAndConstruct.h"
28 #include "js/Printf.h"
29 #include "vm/Iteration.h"
30 #include "vm/JSContext.h"
31 #include "vm/JSObject.h"
32 #include "vm/NativeObject.h"
33 #include "vm/PromiseObject.h"
34 #include "wasm/WasmConstants.h"
35 #include "wasm/WasmContext.h"
36 #include "wasm/WasmFeatures.h"
37 #include "wasm/WasmGenerator.h"
38 #include "wasm/WasmIonCompile.h" // IonPlatformSupport
39 #include "wasm/WasmValidate.h"
40
41 #include "vm/JSObject-inl.h"
42 #include "wasm/WasmGcObject-inl.h"
43 #include "wasm/WasmInstance-inl.h"
44
45 #ifdef JS_CODEGEN_ARM64
46 # include "jit/arm64/vixl/Simulator-vixl.h"
47 #endif
48
49 #ifdef XP_WIN
50 # include "util/WindowsWrapper.h"
51 #endif
52
53 using namespace js;
54 using namespace js::jit;
55
56 #ifdef ENABLE_WASM_JSPI
57 namespace js::wasm {
58
59 SuspenderObjectData::SuspenderObjectData(void* stackMemory)
60 : stackMemory_(stackMemory),
61 suspendableFP_(nullptr),
62 suspendableSP_(static_cast<uint8_t*>(stackMemory) +
63 SuspendableStackPlusRedZoneSize),
64 state_(SuspenderState::Initial),
65 suspendedBy_(nullptr) {}
66
67 void SuspenderObjectData::releaseStackMemory() {
68 js_free(stackMemory_);
69 stackMemory_ = nullptr;
70 }
71
72 # if defined(_WIN32)
73 // On WIN64, the Thread Information Block stack limits has to be modified to
74 // avoid failures on SP checks.
75 void SuspenderObjectData::updateTIBStackFields() {
76 _NT_TIB* tib = reinterpret_cast<_NT_TIB*>(::NtCurrentTeb());
77 savedStackBase_ = tib->StackBase;
78 savedStackLimit_ = tib->StackLimit;
79 uintptr_t stack_limit = (uintptr_t)stackMemory_;
80 uintptr_t stack_base = stack_limit + SuspendableStackPlusRedZoneSize;
81 tib->StackBase = (void*)stack_base;
82 tib->StackLimit = (void*)stack_limit;
83 }
84
85 void SuspenderObjectData::restoreTIBStackFields() {
86 _NT_TIB* tib = reinterpret_cast<_NT_TIB*>(::NtCurrentTeb());
87 tib->StackBase = savedStackBase_;
88 tib->StackLimit = savedStackLimit_;
89 }
90 # endif
91
92 # ifdef JS_SIMULATOR_ARM64
93 void SuspenderObjectData::switchSimulatorToMain() {
94 auto* sim = Simulator::Current();
95 suspendableSP_ = (void*)sim->xreg(Registers::sp, vixl::Reg31IsStackPointer);
96 suspendableFP_ = (void*)sim->xreg(Registers::fp);
97 sim->set_xreg(Registers::sp, (int64_t)mainSP_, vixl::Debugger::LogRegWrites,
98 vixl::Reg31IsStackPointer);
99 sim->set_xreg(Registers::fp, (int64_t)mainFP_);
100 }
101
102 void SuspenderObjectData::switchSimulatorToSuspendable() {
103 auto* sim = Simulator::Current();
104 mainSP_ = (void*)sim->xreg(Registers::sp, vixl::Reg31IsStackPointer);
105 mainFP_ = (void*)sim->xreg(Registers::fp);
106 sim->set_xreg(Registers::sp, (int64_t)suspendableSP_,
107 vixl::Debugger::LogRegWrites, vixl::Reg31IsStackPointer);
108 sim->set_xreg(Registers::fp, (int64_t)suspendableFP_);
109 }
110 # endif
111
112 # ifdef JS_SIMULATOR_ARM
113 void SuspenderObjectData::switchSimulatorToMain() {
114 suspendableSP_ = (void*)Simulator::Current()->get_register(Simulator::sp);
115 suspendableFP_ = (void*)Simulator::Current()->get_register(Simulator::fp);
116 Simulator::Current()->set_register(Simulator::sp, (int)mainSP_);
117 Simulator::Current()->set_register(Simulator::fp, (int)mainFP_);
118 }
119
120 void SuspenderObjectData::switchSimulatorToSuspendable() {
121 mainSP_ = (void*)Simulator::Current()->get_register(Simulator::sp);
122 mainFP_ = (void*)Simulator::Current()->get_register(Simulator::fp);
123 Simulator::Current()->set_register(Simulator::sp, (int)suspendableSP_);
124 Simulator::Current()->set_register(Simulator::fp, (int)suspendableFP_);
125 }
126 # endif
127
128 // Slots that used in various JSFunctionExtended below.
129 const size_t SUSPENDER_SLOT = 0;
130 const size_t WRAPPED_FN_SLOT = 1;
131 const size_t CONTINUE_ON_SUSPENDABLE_SLOT = 1;
132 const size_t PROMISE_SLOT = 2;
133
134 SuspenderContext::SuspenderContext()
135 : activeSuspender_(nullptr), suspendedStacks_() {}
136
137 SuspenderContext::~SuspenderContext() {
138 MOZ_ASSERT(activeSuspender_ == nullptr);
139 MOZ_ASSERT(suspendedStacks_.isEmpty());
140 }
141
142 SuspenderObject* SuspenderContext::activeSuspender() {
143 return activeSuspender_;
144 }
145
146 void SuspenderContext::setActiveSuspender(SuspenderObject* obj) {
147 activeSuspender_.set(obj);
148 }
149
150 void SuspenderContext::trace(JSTracer* trc) {
151 if (activeSuspender_) {
152 TraceEdge(trc, &activeSuspender_, "suspender");
153 }
154 }
155
156 static void TraceSuspendableStack(JSTracer* trc,
157 const SuspenderObjectData& data) {
158 void* startFP = data.suspendableFP();
159 void* returnAddress = data.suspendedReturnAddress();
160 void* exitFP = data.suspendableExitFP();
161 MOZ_ASSERT(startFP != exitFP);
162
163 WasmFrameIter iter(static_cast<FrameWithInstances*>(startFP), returnAddress);
164 MOZ_ASSERT(iter.currentFrameStackSwitched());
165 uintptr_t highestByteVisitedInPrevWasmFrame = 0;
166 while (true) {
167 MOZ_ASSERT(!iter.done());
168 uint8_t* nextPC = iter.resumePCinCurrentFrame();
169 Instance* instance = iter.instance();
170 TraceInstanceEdge(trc, instance, "WasmFrameIter instance");
171 highestByteVisitedInPrevWasmFrame = instance->traceFrame(
172 trc, iter, nextPC, highestByteVisitedInPrevWasmFrame);
173 if (iter.frame() == exitFP) {
174 break;
175 }
176 ++iter;
177 if (iter.currentFrameStackSwitched()) {
178 highestByteVisitedInPrevWasmFrame = 0;
179 }
180 }
181 }
182
183 void SuspenderContext::traceRoots(JSTracer* trc) {
184 // The suspendedStacks_ contains suspended stacks frames that need to be
185 // traced only during minor GC. The major GC tracing is happening via
186 // SuspenderObject::trace.
187 // Non-suspended stack frames are traced as part of TraceJitActivations.
188 if (!trc->isTenuringTracer()) {
189 return;
190 }
191 gc::AssertRootMarkingPhase(trc);
192 for (const SuspenderObjectData& data : suspendedStacks_) {
193 TraceSuspendableStack(trc, data);
194 }
195 }
196
197 static_assert(JS_STACK_GROWTH_DIRECTION < 0,
198 "JS-PI implemented only for native stacks that grows towards 0");
199
200 static void DecrementSuspendableStacksCount(JSContext* cx) {
201 for (;;) {
202 uint32_t currentCount = cx->wasm().suspendableStacksCount;
203 MOZ_ASSERT(currentCount > 0);
204 if (cx->wasm().suspendableStacksCount.compareExchange(currentCount,
205 currentCount - 1)) {
206 break;
207 }
208 // Failed to decrement suspendableStacksCount, repeat.
209 }
210 }
211
212 class SuspenderObject : public NativeObject {
213 public:
214 static const JSClass class_;
215
216 enum { DataSlot, PromisingPromiseSlot, SuspendingReturnTypeSlot, SlotCount };
217
218 enum class ReturnType : int32_t { Unknown, Promise, Exception };
219
220 static SuspenderObject* create(JSContext* cx) {
221 for (;;) {
222 uint32_t currentCount = cx->wasm().suspendableStacksCount;
223 if (currentCount >= SuspendableStacksMaxCount) {
224 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
225 JSMSG_JSPI_SUSPENDER_LIMIT);
226 return nullptr;
227 }
228 if (cx->wasm().suspendableStacksCount.compareExchange(currentCount,
229 currentCount + 1)) {
230 break;
231 }
232 // Failed to increment suspendableStacksCount, repeat.
233 }
234
235 Rooted<SuspenderObject*> suspender(
236 cx, NewBuiltinClassInstance<SuspenderObject>(cx));
237 if (!suspender) {
238 DecrementSuspendableStacksCount(cx);
239 return nullptr;
240 }
241
242 void* stackMemory = js_malloc(SuspendableStackPlusRedZoneSize);
243 if (!stackMemory) {
244 DecrementSuspendableStacksCount(cx);
245 ReportOutOfMemory(cx);
246 return nullptr;
247 }
248
249 SuspenderObjectData* data = js_new<SuspenderObjectData>(stackMemory);
250 if (!data) {
251 js_free(stackMemory);
252 DecrementSuspendableStacksCount(cx);
253 ReportOutOfMemory(cx);
254 return nullptr;
255 }
256 MOZ_RELEASE_ASSERT(data->state() != SuspenderState::Moribund);
257
258 suspender->initReservedSlot(DataSlot, PrivateValue(data));
259 suspender->initReservedSlot(PromisingPromiseSlot, NullValue());
260 suspender->initReservedSlot(SuspendingReturnTypeSlot,
261 Int32Value(int32_t(ReturnType::Unknown)));
262 return suspender;
263 }
264
265 PromiseObject* promisingPromise() const {
266 return &getReservedSlot(PromisingPromiseSlot)
267 .toObject()
268 .as<PromiseObject>();
269 }
270
271 void setPromisingPromise(Handle<PromiseObject*> promise) {
272 setReservedSlot(PromisingPromiseSlot, ObjectOrNullValue(promise));
273 }
274
275 ReturnType suspendingReturnType() const {
276 return ReturnType(getReservedSlot(SuspendingReturnTypeSlot).toInt32());
277 }
278
279 void setSuspendingReturnType(ReturnType type) {
280 // The SuspendingReturnTypeSlot will change after result is defined,
281 // and becomes invalid after GetSuspendingPromiseResult. The assert is
282 // checking if the result was processed by GetSuspendingPromiseResult.
283 MOZ_ASSERT((type == ReturnType::Unknown) !=
284 (suspendingReturnType() == ReturnType::Unknown));
285
286 setReservedSlot(SuspendingReturnTypeSlot, Int32Value(int32_t(type)));
287 }
288
289 JS::NativeStackLimit getStackMemoryLimit() {
290 return JS::NativeStackLimit(data()->stackMemory()) + SuspendableRedZoneSize;
291 }
292
293 SuspenderState state() { return data()->state(); }
294
295 inline bool hasData() { return !getReservedSlot(DataSlot).isUndefined(); }
296
297 inline SuspenderObjectData* data() {
298 return static_cast<SuspenderObjectData*>(
299 getReservedSlot(DataSlot).toPrivate());
300 }
301
302 void setMoribund(JSContext* cx);
303 void setActive(JSContext* cx);
304 void setSuspended(JSContext* cx);
305
306 void enter(JSContext* cx);
307 void suspend(JSContext* cx);
308 void resume(JSContext* cx);
309 void leave(JSContext* cx);
310
311 // Modifies frames to inject the suspendable stack back into the main one.
312 void forwardToSuspendable();
313
314 private:
315 static const JSClassOps classOps_;
316
317 static void finalize(JS::GCContext* gcx, JSObject* obj);
318 static void trace(JSTracer* trc, JSObject* obj);
319 };
320
321 static_assert(SuspenderObjectDataSlot == SuspenderObject::DataSlot);
322
323 const JSClass SuspenderObject::class_ = {
324 "SuspenderObject",
325 JSCLASS_HAS_RESERVED_SLOTS(SlotCount) | JSCLASS_FOREGROUND_FINALIZE,
326 &SuspenderObject::classOps_,
327 };
328
329 const JSClassOps SuspenderObject::classOps_ = {
330 nullptr, // addProperty
331 nullptr, // delProperty
332 nullptr, // enumerate
333 nullptr, // newEnumerate
334 nullptr, // resolve
335 nullptr, // mayResolve
336 finalize, // finalize
337 nullptr, // call
338 nullptr, // construct
339 trace, // trace
340 };
341
342 /* static */
343 void SuspenderObject::finalize(JS::GCContext* gcx, JSObject* obj) {
344 SuspenderObject& suspender = obj->as<SuspenderObject>();
345 if (!suspender.hasData()) {
346 return;
347 }
348 SuspenderObjectData* data = suspender.data();
349 if (data->state() == SuspenderState::Moribund) {
350 MOZ_RELEASE_ASSERT(!data->stackMemory());
351 } else {
352 // Cleaning stack memory and removing from suspendableStacks_.
353 data->releaseStackMemory();
354 if (SuspenderContext* scx = data->suspendedBy()) {
355 scx->suspendedStacks_.remove(data);
356 }
357 }
358 js_free(data);
359 }
360
361 /* static */
362 void SuspenderObject::trace(JSTracer* trc, JSObject* obj) {
363 SuspenderObject& suspender = obj->as<SuspenderObject>();
364 if (!suspender.hasData()) {
365 return;
366 }
367 SuspenderObjectData& data = *suspender.data();
368 // The SuspenderObjectData refers stacks frames that need to be traced
369 // only during major GC to determine if SuspenderObject content is
370 // reachable from JS. The frames must be suspended -- non-suspended
371 // stack frames are traced as part of TraceJitActivations.
372 if (!data.traceable() || trc->isTenuringTracer()) {
373 return;
374 }
375 TraceSuspendableStack(trc, data);
376 }
377
378 void SuspenderObject::setMoribund(JSContext* cx) {
379 MOZ_ASSERT(state() == SuspenderState::Active);
380 ResetInstanceStackLimits(cx);
381 # if defined(_WIN32)
382 data()->restoreTIBStackFields();
383 # endif
384 SuspenderObjectData* data = this->data();
385 data->setState(SuspenderState::Moribund);
386 data->releaseStackMemory();
387 DecrementSuspendableStacksCount(cx);
388 MOZ_ASSERT(
389 !cx->wasm().promiseIntegration.suspendedStacks_.ElementProbablyInList(
390 data));
391 }
392
393 void SuspenderObject::setActive(JSContext* cx) {
394 data()->setState(SuspenderState::Active);
395 UpdateInstanceStackLimitsForSuspendableStack(cx, getStackMemoryLimit());
396 # if defined(_WIN32)
397 data()->updateTIBStackFields();
398 # endif
399 }
400
401 void SuspenderObject::setSuspended(JSContext* cx) {
402 data()->setState(SuspenderState::Suspended);
403 ResetInstanceStackLimits(cx);
404 # if defined(_WIN32)
405 data()->restoreTIBStackFields();
406 # endif
407 }
408
409 void SuspenderObject::enter(JSContext* cx) {
410 MOZ_ASSERT(state() == SuspenderState::Initial);
411 cx->wasm().promiseIntegration.setActiveSuspender(this);
412 setActive(cx);
413 # ifdef DEBUG
414 cx->runtime()->jitRuntime()->disallowArbitraryCode();
415 # endif
416 }
417
418 void SuspenderObject::suspend(JSContext* cx) {
419 MOZ_ASSERT(state() == SuspenderState::Active);
420 setSuspended(cx);
421 cx->wasm().promiseIntegration.suspendedStacks_.pushFront(data());
422 data()->setSuspendedBy(&cx->wasm().promiseIntegration);
423 cx->wasm().promiseIntegration.setActiveSuspender(nullptr);
424 # ifdef DEBUG
425 cx->runtime()->jitRuntime()->clearDisallowArbitraryCode();
426 # endif
427
428 if (cx->realm()->isDebuggee()) {
429 WasmFrameIter iter(cx->activation()->asJit());
430 while (true) {
431 MOZ_ASSERT(!iter.done());
432 if (iter.debugEnabled()) {
433 DebugAPI::onSuspendWasmFrame(cx, iter.debugFrame());
434 }
435 ++iter;
436 if (iter.currentFrameStackSwitched()) {
437 break;
438 }
439 }
440 }
441 }
442
443 void SuspenderObject::resume(JSContext* cx) {
444 MOZ_ASSERT(state() == SuspenderState::Suspended);
445 cx->wasm().promiseIntegration.setActiveSuspender(this);
446 setActive(cx);
447 data()->setSuspendedBy(nullptr);
448 cx->wasm().promiseIntegration.suspendedStacks_.remove(data());
449 # ifdef DEBUG
450 cx->runtime()->jitRuntime()->disallowArbitraryCode();
451 # endif
452
453 if (cx->realm()->isDebuggee()) {
454 for (FrameIter iter(cx);; ++iter) {
455 MOZ_RELEASE_ASSERT(!iter.done(), "expecting stackSwitched()");
456 if (iter.isWasm()) {
457 WasmFrameIter& wasmIter = iter.wasmFrame();
458 if (wasmIter.currentFrameStackSwitched()) {
459 break;
460 }
461 if (wasmIter.debugEnabled()) {
462 DebugAPI::onResumeWasmFrame(cx, iter);
463 }
464 }
465 }
466 }
467 }
468
469 void SuspenderObject::leave(JSContext* cx) {
470 cx->wasm().promiseIntegration.setActiveSuspender(nullptr);
471 # ifdef DEBUG
472 cx->runtime()->jitRuntime()->clearDisallowArbitraryCode();
473 # endif
474 // We are exiting alternative stack if state is active,
475 // otherwise the stack was just suspended.
476 switch (state()) {
477 case SuspenderState::Active:
478 setMoribund(cx);
479 break;
480 case SuspenderState::Suspended:
481 break;
482 case SuspenderState::Initial:
483 case SuspenderState::Moribund:
484 MOZ_CRASH();
485 }
486 }
487
488 void SuspenderObject::forwardToSuspendable() {
489 // Injecting suspendable stack back into main one at the exit frame.
490 SuspenderObjectData* data = this->data();
491 uint8_t* mainExitFP = (uint8_t*)data->mainExitFP();
492 *reinterpret_cast<void**>(mainExitFP + Frame::callerFPOffset()) =
493 data->suspendableFP();
494 *reinterpret_cast<void**>(mainExitFP + Frame::returnAddressOffset()) =
495 data->suspendedReturnAddress();
496 }
497
498 bool CallOnMainStack(JSContext* cx, CallOnMainStackFn fn, void* data) {
499 Rooted<SuspenderObject*> suspender(
500 cx, cx->wasm().promiseIntegration.activeSuspender());
501 SuspenderObjectData* stacks = suspender->data();
502
503 cx->wasm().promiseIntegration.setActiveSuspender(nullptr);
504
505 MOZ_ASSERT(suspender->state() == SuspenderState::Active);
506 suspender->setSuspended(cx);
507
508 # ifdef JS_SIMULATOR
509 # if defined(JS_SIMULATOR_ARM64) || defined(JS_SIMULATOR_ARM)
510 // The simulator is using its own stack, however switching is needed for
511 // virtual registers.
512 stacks->switchSimulatorToMain();
513 bool res = fn(data);
514 stacks->switchSimulatorToSuspendable();
515 # else
516 # error "not supported"
517 # endif
518 # else
519 // The platform specific code below inserts offsets as strings into inline
520 // assembly. CHECK_OFFSETS verifies the specified literals in macros below.
521 # define CHECK_OFFSETS(MAIN_FP_OFFSET, MAIN_SP_OFFSET, \
522 SUSPENDABLE_FP_OFFSET, SUSPENDABLE_SP_OFFSET) \
523 static_assert( \
524 (MAIN_FP_OFFSET) == SuspenderObjectData::offsetOfMainFP() && \
525 (MAIN_SP_OFFSET) == SuspenderObjectData::offsetOfMainSP() && \
526 (SUSPENDABLE_FP_OFFSET) == \
527 SuspenderObjectData::offsetOfSuspendableFP() && \
528 (SUSPENDABLE_SP_OFFSET) == \
529 SuspenderObjectData::offsetOfSuspendableSP());
530
531 // The following assembly code temporarily switches FP/SP pointers to be on
532 // main stack, while maintaining frames linking. After
533 // `CallImportData::Call` execution suspendable stack FP/SP will be restored.
534 //
535 // Because the assembly sequences contain a call, the trashed-register list
536 // must contain all the caller saved registers. They must also contain "cc"
537 // and "memory" since both of those state elements could be modified by the
538 // call. They also need a "volatile" qualifier to ensure that the they don't
539 // get optimised out or otherwise messed with by clang/gcc.
540 //
541 // `Registers::VolatileMask` (in the assembler complex) is useful in that it
542 // lists the caller-saved registers.
543
544 uintptr_t res;
545
546 // clang-format off
547 #if defined(_M_ARM64) || defined(__aarch64__)
548 # define CALLER_SAVED_REGS \
549 "x0", "x1", "x2", "x3","x4", "x5", "x6", "x7", "x8", "x9", "x10", \
550 "x11", "x12", "x13", "x14", "x15", "x16", "x17", /* "x18", */ \
551 "x19", "x20", /* it's unclear who saves these two, so be safe */ \
552 /* claim that all the vector regs are caller-saved, for safety */ \
553 "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", \
554 "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", \
555 "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", \
556 "v29", "v30", "v31"
557 # define INLINED_ASM(MAIN_FP, MAIN_SP, SUSPENDABLE_FP, SUSPENDABLE_SP) \
558 CHECK_OFFSETS(MAIN_FP, MAIN_SP, SUSPENDABLE_FP, SUSPENDABLE_SP); \
559 asm volatile( \
560 "\n mov x0, %1" \
561 "\n mov x27, sp " \
562 "\n str x29, [x0, #" #SUSPENDABLE_FP "] " \
563 "\n str x27, [x0, #" #SUSPENDABLE_SP "] " \
564 \
565 "\n ldr x29, [x0, #" #MAIN_FP "] " \
566 "\n ldr x27, [x0, #" #MAIN_SP "] " \
567 "\n mov sp, x27 " \
568 \
569 "\n stp x0, x27, [sp, #-16]! " \
570 \
571 "\n mov x0, %3" \
572 "\n blr %2 " \
573 \
574 "\n ldp x3, x27, [sp], #16 " \
575 \
576 "\n mov x27, sp " \
577 "\n str x29, [x3, #" #MAIN_FP "] " \
578 "\n str x27, [x3, #" #MAIN_SP "] " \
579 \
580 "\n ldr x29, [x3, #" #SUSPENDABLE_FP "] " \
581 "\n ldr x27, [x3, #" #SUSPENDABLE_SP "] " \
582 "\n mov sp, x27 " \
583 "\n mov %0, x0" \
584 : "=r"(res) \
585 : "r"(stacks), "r"(fn), "r"(data) \
586 : "x0", "x3", "x27", CALLER_SAVED_REGS, "cc", "memory")
587 INLINED_ASM(24, 32, 40, 48);
588
589 # elif defined(_WIN64) && defined(_M_X64)
590 # define INLINED_ASM(MAIN_FP, MAIN_SP, SUSPENDABLE_FP, SUSPENDABLE_SP) \
591 CHECK_OFFSETS(MAIN_FP, MAIN_SP, SUSPENDABLE_FP, SUSPENDABLE_SP); \
592 asm("\n mov %1, %%rcx" \
593 "\n mov %%rbp, " #SUSPENDABLE_FP "(%%rcx)" \
594 "\n mov %%rsp, " #SUSPENDABLE_SP "(%%rcx)" \
595 \
596 "\n mov " #MAIN_FP "(%%rcx), %%rbp" \
597 "\n mov " #MAIN_SP "(%%rcx), %%rsp" \
598 \
599 "\n push %%rcx" \
600 "\n push %%rdx" \
601 \
602 "\n mov %3, %%rcx" \
603 "\n call *%2" \
604 \
605 "\n pop %%rdx" \
606 "\n pop %%rcx" \
607 \
608 "\n mov %%rbp, " #MAIN_FP "(%%rcx)" \
609 "\n mov %%rsp, " #MAIN_SP "(%%rcx)" \
610 \
611 "\n mov " #SUSPENDABLE_FP "(%%rcx), %%rbp" \
612 "\n mov " #SUSPENDABLE_SP "(%%rcx), %%rsp" \
613 \
614 "\n movq %%rax, %0" \
615 : "=r"(res) \
616 : "r"(stacks), "r"(fn), "r"(data) \
617 : "rcx", "rax", "cc", "memory")
618 INLINED_ASM(24, 32, 40, 48);
619
620 # elif defined(__x86_64__)
621 # define INLINED_ASM(MAIN_FP, MAIN_SP, SUSPENDABLE_FP, SUSPENDABLE_SP) \
622 CHECK_OFFSETS(MAIN_FP, MAIN_SP, SUSPENDABLE_FP, SUSPENDABLE_SP); \
623 asm("\n mov %1, %%rdi" \
624 "\n mov %%rbp, " #SUSPENDABLE_FP "(%%rdi)" \
625 "\n mov %%rsp, " #SUSPENDABLE_SP "(%%rdi)" \
626 \
627 "\n mov " #MAIN_FP "(%%rdi), %%rbp" \
628 "\n mov " #MAIN_SP "(%%rdi), %%rsp" \
629 \
630 "\n push %%rdi" \
631 "\n push %%rdx" \
632 \
633 "\n mov %3, %%rdi" \
634 "\n call *%2" \
635 \
636 "\n pop %%rdx" \
637 "\n pop %%rdi" \
638 \
639 "\n mov %%rbp, " #MAIN_FP "(%%rdi)" \
640 "\n mov %%rsp, " #MAIN_SP "(%%rdi)" \
641 \
642 "\n mov " #SUSPENDABLE_FP "(%%rdi), %%rbp" \
643 "\n mov " #SUSPENDABLE_SP "(%%rdi), %%rsp" \
644 \
645 "\n movq %%rax, %0" \
646 : "=r"(res) \
647 : "r"(stacks), "r"(fn), "r"(data) \
648 : "rdi", "rax", "cc", "memory")
649 INLINED_ASM(24, 32, 40, 48);
650 # elif defined(__i386__) || defined(_M_IX86)
651 # define CALLER_SAVED_REGS "eax", "ecx", "edx"
652 # define INLINED_ASM(MAIN_FP, MAIN_SP, SUSPENDABLE_FP, SUSPENDABLE_SP) \
653 CHECK_OFFSETS(MAIN_FP, MAIN_SP, SUSPENDABLE_FP, SUSPENDABLE_SP); \
654 asm("\n mov %1, %%edx" \
655 "\n mov %%ebp, " #SUSPENDABLE_FP "(%%edx)" \
656 "\n mov %%esp, " #SUSPENDABLE_SP "(%%edx)" \
657 \
658 "\n mov " #MAIN_FP "(%%edx), %%ebp" \
659 "\n mov " #MAIN_SP "(%%edx), %%esp" \
660 \
661 "\n push %%edx" \
662 "\n sub $8, %%esp" \
663 "\n push %3" \
664 "\n call *%2" \
665 "\n add $12, %%esp" \
666 "\n pop %%edx" \
667 \
668 "\n mov %%ebp, " #MAIN_FP "(%%edx)" \
669 "\n mov %%esp, " #MAIN_SP "(%%edx)" \
670 \
671 "\n mov " #SUSPENDABLE_FP "(%%edx), %%ebp" \
672 "\n mov " #SUSPENDABLE_SP "(%%edx), %%esp" \
673 \
674 "\n mov %%eax, %0" \
675 : "=r"(res) \
676 : "r"(stacks), "r"(fn), "r"(data) \
677 : CALLER_SAVED_REGS, "cc", "memory")
678 INLINED_ASM(12, 16, 20, 24);
679
680 # elif defined(__arm__)
681 # define INLINED_ASM(MAIN_FP, MAIN_SP, SUSPENDABLE_FP, SUSPENDABLE_SP) \
682 CHECK_OFFSETS(MAIN_FP, MAIN_SP, SUSPENDABLE_FP, SUSPENDABLE_SP); \
683 asm("\n mov r0, %1" \
684 "\n mov r1, sp" \
685 "\n str r11, [r0, #" #SUSPENDABLE_FP "]" \
686 "\n str r1, [r0, #" #SUSPENDABLE_SP "]" \
687 \
688 "\n ldr r11, [r0, #" #MAIN_FP "]" \
689 "\n ldr r1, [r0, #" #MAIN_SP "]" \
690 "\n mov sp, r1" \
691 \
692 "\n str r0, [sp, #-8]! " \
693 \
694 "\n mov r0, %3" \
695 "\n blx %2" \
696 \
697 "\n ldr r2, [sp], #8 " \
698 \
699 "\n mov r1, sp" \
700 "\n str r11, [r2, #" #MAIN_FP "]" \
701 "\n str r1, [r2, #" #MAIN_SP "]" \
702 \
703 "\n ldr r11, [r2, #" #SUSPENDABLE_FP "]" \
704 "\n ldr r1, [r2, #" #SUSPENDABLE_SP "]" \
705 "\n mov sp, r1" \
706 "\n mov %0, r0" \
707 : "=r"(res) \
708 : "r"(stacks), "r"(fn), "r"(data) \
709 : "r0", "r1", "r2", "r3", "cc", "memory")
710 INLINED_ASM(12, 16, 20, 24);
711
712 #elif defined(__loongarch_lp64)
713 # define CALLER_SAVED_REGS \
714 "$ra", "$a0", "$a1", "$a2", "$a3", "$a4", "$a5", "$a6", "$a7", \
715 "$t0", "$t1", "$t2", "$t3", "$t4", "$t5", "$t6", "$t7", "$t8", \
716 "$f0", "$f1", "$f2", "$f3", "$f4", "$f5", "$f6", "$f7", "$f8", \
717 "$f9", "$f10", "$f11", "$f12", "$f13", "$f14", "$f15", "$f16", \
718 "$f17", "$f18", "$f19", "$f20", "$f21", "$f22", "$f23"
719 # define INLINED_ASM(MAIN_FP, MAIN_SP, SUSPENDABLE_FP, SUSPENDABLE_SP) \
720 CHECK_OFFSETS(MAIN_FP, MAIN_SP, SUSPENDABLE_FP, SUSPENDABLE_SP); \
721 asm volatile( \
722 "\n move $a0, %1" \
723 "\n st.d $fp, $a0, " #SUSPENDABLE_FP \
724 "\n st.d $sp, $a0, " #SUSPENDABLE_SP \
725 \
726 "\n ld.d $fp, $a0, " #MAIN_FP \
727 "\n ld.d $sp, $a0, " #MAIN_SP \
728 \
729 "\n addi.d $sp, $sp, -16" \
730 "\n st.d $a0, $sp, 8" \
731 \
732 "\n move $a0, %3" \
733 "\n jirl $ra, %2, 0" \
734 \
735 "\n ld.d $a3, $sp, 8" \
736 "\n addi.d $sp, $sp, 16" \
737 \
738 "\n st.d $fp, $a3, " #MAIN_FP \
739 "\n st.d $sp, $a3, " #MAIN_SP \
740 \
741 "\n ld.d $fp, $a3, " #SUSPENDABLE_FP \
742 "\n ld.d $sp, $a3, " #SUSPENDABLE_SP \
743 "\n move %0, $a0" \
744 : "=r"(res) \
745 : "r"(stacks), "r"(fn), "r"(data) \
746 : "$a0", "$a3", CALLER_SAVED_REGS, "cc", "memory")
747 INLINED_ASM(24, 32, 40, 48);
748
749 # else
750 MOZ_CRASH("Not supported for this platform");
751 # endif
752 // clang-format on
753 # endif // JS_SIMULATOR
754
755 bool ok = res;
756 suspender->setActive(cx);
757 cx->wasm().promiseIntegration.setActiveSuspender(suspender);
758
759 # undef INLINED_ASM
760 # undef CHECK_OFFSETS
761 # undef CALLER_SAVED_REGS
762
763 return ok;
764 }
765
766 static void CleanupActiveSuspender(JSContext* cx) {
767 SuspenderObject* suspender = cx->wasm().promiseIntegration.activeSuspender();
768 MOZ_ASSERT(suspender);
769 cx->wasm().promiseIntegration.setActiveSuspender(nullptr);
770 suspender->setMoribund(cx);
771 }
772
773 // Suspending
774
775 // Builds a wasm module with following structure:
776 // (module
777 // (type $params (struct (field ..)*)))
778 // (type $results (struct (field ..)*)))
779 // (import "" "" (func $suspending.wrappedfn ..))
780 // (func $suspending.exported .. )
781 // (func $suspending.trampoline ..)
782 // (func $suspending.continue-on-suspendable ..)
783 // (export "" (func $suspending.exported))
784 // )
785 //
786 // The module provides logic for the state transitions (see the SMDOC):
787 // - Invoke Suspending Import via $suspending.exported
788 // - Suspending Function Returns a Promise via $suspending.trampoline
789 // - Promise Resolved transitions via $suspending.continue-on-suspendable
790 //
791 class SuspendingFunctionModuleFactory {
792 public:
793 enum TypeIdx {
794 ParamsTypeIndex,
795 ResultsTypeIndex,
796 };
797
798 enum FnIdx {
799 WrappedFnIndex,
800 ExportedFnIndex,
801 TrampolineFnIndex,
802 ContinueOnSuspendableFnIndex
803 };
804
805 private:
806 // Builds function that will be imported to wasm module:
807 // (func $suspending.exported
808 // (param ..)* (result ..)*
809 // (local $suspender externref)
810 // (local $results (ref $results))
811 // call $builtin.current-suspender
812 // local.tee $suspender
813 // ref.func $suspending.trampoline
814 // local.get $i*
815 // stuct.new $param-type
816 // stack-switch SwitchToMain ;; <- (suspender,fn,data)
817 // local.get $suspender
818 // call $builtin.get-suspending-promise-result
819 // ref.cast $results-type
820 // local.set $results
821 // (struct.get $results (local.get $results))*
822 // )
823 bool encodeExportedFunction(CodeMetadata& codeMeta, uint32_t paramsSize,
824 uint32_t resultSize, uint32_t paramsOffset,
825 RefType resultType, Bytes& bytecode) {
826 Encoder encoder(bytecode, *codeMeta.types);
827 ValTypeVector locals;
828 if (!locals.emplaceBack(RefType::extern_())) {
829 return false;
830 }
831 if (!locals.emplaceBack(resultType)) {
832 return false;
833 }
834 if (!EncodeLocalEntries(encoder, locals)) {
835 return false;
836 }
837
838 const int suspenderIndex = paramsSize;
839 if (!encoder.writeOp(Op::I32Const) || !encoder.writeVarU32(0)) {
840 return false;
841 }
842 if (!encoder.writeOp(MozOp::CallBuiltinModuleFunc) ||
843 !encoder.writeVarU32((uint32_t)BuiltinModuleFuncId::CurrentSuspender)) {
844 return false;
845 }
846 if (!encoder.writeOp(Op::LocalTee) ||
847 !encoder.writeVarU32(suspenderIndex)) {
848 return false;
849 }
850
851 // Results local is located after all params and suspender.
852 const int resultsIndex = paramsSize + 1;
853
854 if (!encoder.writeOp(Op::RefFunc) ||
855 !encoder.writeVarU32(TrampolineFnIndex)) {
856 return false;
857 }
858 for (uint32_t i = 0; i < paramsSize; i++) {
859 if (!encoder.writeOp(Op::LocalGet) ||
860 !encoder.writeVarU32(i + paramsOffset)) {
861 return false;
862 }
863 }
864 if (!encoder.writeOp(GcOp::StructNew) ||
865 !encoder.writeVarU32(ParamsTypeIndex)) {
866 return false;
867 }
868
869 if (!encoder.writeOp(MozOp::StackSwitch) ||
870 !encoder.writeVarU32(uint32_t(StackSwitchKind::SwitchToMain))) {
871 return false;
872 }
873
874 if (!encoder.writeOp(Op::LocalGet) ||
875 !encoder.writeVarU32(suspenderIndex)) {
876 return false;
877 }
878 if (!encoder.writeOp(MozOp::CallBuiltinModuleFunc) ||
879 !encoder.writeVarU32(
880 (uint32_t)BuiltinModuleFuncId::GetSuspendingPromiseResult)) {
881 return false;
882 }
883 if (!encoder.writeOp(GcOp::RefCast) ||
884 !encoder.writeVarU32(ResultsTypeIndex) ||
885 !encoder.writeOp(Op::LocalSet) || !encoder.writeVarU32(resultsIndex)) {
886 return false;
887 }
888 for (uint32_t i = 0; i < resultSize; i++) {
889 if (!encoder.writeOp(Op::LocalGet) ||
890 !encoder.writeVarU32(resultsIndex) ||
891 !encoder.writeOp(GcOp::StructGet) ||
892 !encoder.writeVarU32(ResultsTypeIndex) || !encoder.writeVarU32(i)) {
893 return false;
894 }
895 }
896 return encoder.writeOp(Op::End);
897 }
898
899 // Builds function that is called on main stack:
900 // (func $suspending.trampoline
901 // (param $params (ref $suspender)) (param $param (ref $param-type))
902 // (result anyref)
903 // local.get $suspender ;; for $builtin.forward-exn-to-suspended below
904 // block (result exnref)
905 // try_table (catch_all_ref 0)
906 // local.get $suspender ;; for call $add-promise-reactions
907 // (struct.get $param-type $i (local.get $param))*
908 // call $suspending.wrappedfn
909 // ref.func $suspending.continue-on-suspendable
910 // call $builtin.add-promise-reactions
911 // return
912 // end
913 // unreachable
914 // end
915 // call $builtin.forward-exn-to-suspended
916 // )
917 // The function calls suspending import and returns into the
918 // $promising.exported function because that was the top function
919 // on the main stack.
920 bool encodeTrampolineFunction(CodeMetadata& codeMeta, uint32_t paramsSize,
921 Bytes& bytecode) {
922 Encoder encoder(bytecode, *codeMeta.types);
923 if (!EncodeLocalEntries(encoder, ValTypeVector())) {
924 return false;
925 }
926 const uint32_t SuspenderIndex = 0;
927 const uint32_t ParamsIndex = 1;
928
929 if (!encoder.writeOp(Op::LocalGet) ||
930 !encoder.writeVarU32(SuspenderIndex)) {
931 return false;
932 }
933
934 if (!encoder.writeOp(Op::Block) ||
935 !encoder.writeFixedU8(uint8_t(TypeCode::ExnRef))) {
936 return false;
937 }
938
939 if (!encoder.writeOp(Op::TryTable) ||
940 !encoder.writeFixedU8(uint8_t(TypeCode::BlockVoid)) ||
941 !encoder.writeVarU32(1) ||
942 !encoder.writeFixedU8(/* catch_all_ref = */ 0x03) ||
943 !encoder.writeVarU32(0)) {
944 return false;
945 }
946
947 // For AddPromiseReactions call below.
948 if (!encoder.writeOp(Op::LocalGet) ||
949 !encoder.writeVarU32(SuspenderIndex)) {
950 return false;
951 }
952
953 for (uint32_t i = 0; i < paramsSize; i++) {
954 if (!encoder.writeOp(Op::LocalGet) || !encoder.writeVarU32(ParamsIndex)) {
955 return false;
956 }
957 if (!encoder.writeOp(GcOp::StructGet) ||
958 !encoder.writeVarU32(ParamsTypeIndex) || !encoder.writeVarU32(i)) {
959 return false;
960 }
961 }
962 if (!encoder.writeOp(Op::Call) || !encoder.writeVarU32(WrappedFnIndex)) {
963 return false;
964 }
965 if (!encoder.writeOp(Op::RefFunc) ||
966 !encoder.writeVarU32(ContinueOnSuspendableFnIndex)) {
967 return false;
968 }
969
970 if (!encoder.writeOp(MozOp::CallBuiltinModuleFunc) ||
971 !encoder.writeVarU32(
972 (uint32_t)BuiltinModuleFuncId::AddPromiseReactions)) {
973 return false;
974 }
975
976 if (!encoder.writeOp(Op::Return) || !encoder.writeOp(Op::End) ||
977 !encoder.writeOp(Op::Unreachable) || !encoder.writeOp(Op::End)) {
978 return false;
979 }
980
981 if (!encoder.writeOp(MozOp::CallBuiltinModuleFunc) ||
982 !encoder.writeVarU32(
983 (uint32_t)BuiltinModuleFuncId::ForwardExceptionToSuspended)) {
984 return false;
985 }
986
987 return encoder.writeOp(Op::End);
988 }
989
990 // Builds function that is called on main stack:
991 // (func $suspending.continue-on-suspendable
992 // (param $params (ref $suspender)) (param $results externref)
993 // (result externref)
994 // local.get $suspender
995 // ref.null funcref
996 // local.get $results
997 // any.convert_extern
998 // stack-switch ContinueOnSuspendable
999 // )
1000 bool encodeContinueOnSuspendableFunction(CodeMetadata& codeMeta,
1001 uint32_t resultsSize,
1002 Bytes& bytecode) {
1003 Encoder encoder(bytecode, *codeMeta.types);
1004 if (!EncodeLocalEntries(encoder, ValTypeVector())) {
1005 return false;
1006 }
1007
1008 const uint32_t SuspenderIndex = 0;
1009 const uint32_t ResultsIndex = 1;
1010
1011 if (!encoder.writeOp(Op::LocalGet) ||
1012 !encoder.writeVarU32(SuspenderIndex)) {
1013 return false;
1014 }
1015 if (!encoder.writeOp(Op::RefNull) ||
1016 !encoder.writeValType(ValType(RefType::func()))) {
1017 return false;
1018 }
1019 if (!encoder.writeOp(Op::LocalGet) || !encoder.writeVarU32(ResultsIndex) ||
1020 !encoder.writeOp(GcOp::AnyConvertExtern)) {
1021 return false;
1022 }
1023
1024 if (!encoder.writeOp(MozOp::StackSwitch) ||
1025 !encoder.writeVarU32(
1026 uint32_t(StackSwitchKind::ContinueOnSuspendable))) {
1027 return false;
1028 }
1029
1030 return encoder.writeOp(Op::End);
1031 }
1032
1033 public:
1034 SharedModule build(JSContext* cx, HandleObject func, ValTypeVector&& params,
1035 ValTypeVector&& results) {
1036 FeatureOptions options;
1037 options.isBuiltinModule = true;
1038 options.requireExnref = true;
1039
1040 ScriptedCaller scriptedCaller;
1041 SharedCompileArgs compileArgs =
1042 CompileArgs::buildAndReport(cx, std::move(scriptedCaller), options);
1043 if (!compileArgs) {
1044 return nullptr;
1045 }
1046
1047 MutableModuleMetadata moduleMeta = js_new<ModuleMetadata>();
1048 if (!moduleMeta || !moduleMeta->init(*compileArgs)) {
1049 return nullptr;
1050 }
1051 MutableCodeMetadata codeMeta = moduleMeta->codeMeta;
1052
1053 MOZ_ASSERT(IonPlatformSupport());
1054 CompilerEnvironment compilerEnv(CompileMode::Once, Tier::Optimized,
1055 DebugEnabled::False);
1056 compilerEnv.computeParameters();
1057
1058 RefType suspenderType = RefType::extern_();
1059 RefType promiseType = RefType::extern_();
1060
1061 ValTypeVector paramsWithoutSuspender;
1062
1063 const size_t resultsSize = results.length();
1064 const size_t paramsSize = params.length();
1065 const size_t paramsOffset = 0;
1066 if (!paramsWithoutSuspender.append(params.begin(), params.end())) {
1067 ReportOutOfMemory(cx);
1068 return nullptr;
1069 }
1070
1071 ValTypeVector resultsRef;
1072 if (!resultsRef.emplaceBack(promiseType)) {
1073 ReportOutOfMemory(cx);
1074 return nullptr;
1075 }
1076
1077 StructType boxedParamsStruct;
1078 if (!StructType::createImmutable(paramsWithoutSuspender,
1079 &boxedParamsStruct)) {
1080 ReportOutOfMemory(cx);
1081 return nullptr;
1082 }
1083 MOZ_ASSERT(codeMeta->types->length() == ParamsTypeIndex);
1084 if (!codeMeta->types->addType(std::move(boxedParamsStruct))) {
1085 return nullptr;
1086 }
1087
1088 StructType boxedResultType;
1089 if (!StructType::createImmutable(results, &boxedResultType)) {
1090 ReportOutOfMemory(cx);
1091 return nullptr;
1092 }
1093 MOZ_ASSERT(codeMeta->types->length() == ResultsTypeIndex);
1094 if (!codeMeta->types->addType(std::move(boxedResultType))) {
1095 return nullptr;
1096 }
1097
1098 MOZ_ASSERT(codeMeta->funcs.length() == WrappedFnIndex);
1099 if (!moduleMeta->addDefinedFunc(std::move(paramsWithoutSuspender),
1100 std::move(resultsRef))) {
1101 return nullptr;
1102 }
1103
1104 // Imports names are not important, declare functions above as imports.
1105 codeMeta->numFuncImports = codeMeta->funcs.length();
1106
1107 // We will be looking up and using the exports function by index so
1108 // the name doesn't matter.
1109 MOZ_ASSERT(codeMeta->funcs.length() == ExportedFnIndex);
1110 if (!moduleMeta->addDefinedFunc(std::move(params), std::move(results),
1111 /*declareForRef = */ true,
1112 mozilla::Some(CacheableName()))) {
1113 return nullptr;
1114 }
1115
1116 ValTypeVector paramsTrampoline, resultsTrampoline;
1117 if (!paramsTrampoline.emplaceBack(suspenderType) ||
1118 !paramsTrampoline.emplaceBack(RefType::fromTypeDef(
1119 &(*codeMeta->types)[ParamsTypeIndex], false)) ||
1120 !resultsTrampoline.emplaceBack(RefType::any())) {
1121 ReportOutOfMemory(cx);
1122 return nullptr;
1123 }
1124 MOZ_ASSERT(codeMeta->funcs.length() == TrampolineFnIndex);
1125 if (!moduleMeta->addDefinedFunc(std::move(paramsTrampoline),
1126 std::move(resultsTrampoline),
1127 /*declareForRef = */ true)) {
1128 return nullptr;
1129 }
1130
1131 ValTypeVector paramsContinueOnSuspendable, resultsContinueOnSuspendable;
1132 if (!paramsContinueOnSuspendable.emplaceBack(suspenderType) ||
1133 !paramsContinueOnSuspendable.emplaceBack(RefType::extern_())) {
1134 ReportOutOfMemory(cx);
1135 return nullptr;
1136 }
1137 MOZ_ASSERT(codeMeta->funcs.length() == ContinueOnSuspendableFnIndex);
1138 if (!moduleMeta->addDefinedFunc(std::move(paramsContinueOnSuspendable),
1139 std::move(resultsContinueOnSuspendable),
1140 /*declareForRef = */ true)) {
1141 return nullptr;
1142 }
1143
1144 if (!moduleMeta->prepareForCompile(compilerEnv.mode())) {
1145 return nullptr;
1146 }
1147
1148 ModuleGenerator mg(*codeMeta, compilerEnv, compilerEnv.initialState(),
1149 nullptr, nullptr, nullptr);
1150 if (!mg.initializeCompleteTier()) {
1151 return nullptr;
1152 }
1153 // Build functions and keep bytecodes around until the end.
1154 uint32_t funcBytecodeOffset = CallSite::FIRST_VALID_BYTECODE_OFFSET;
1155 Bytes bytecode;
1156 if (!encodeExportedFunction(
1157 *codeMeta, paramsSize, resultsSize, paramsOffset,
1158 RefType::fromTypeDef(&(*codeMeta->types)[ResultsTypeIndex], false),
1159 bytecode)) {
1160 ReportOutOfMemory(cx);
1161 return nullptr;
1162 }
1163 if (!mg.compileFuncDef(ExportedFnIndex, funcBytecodeOffset,
1164 bytecode.begin(),
1165 bytecode.begin() + bytecode.length())) {
1166 return nullptr;
1167 }
1168 funcBytecodeOffset += bytecode.length();
1169
1170 Bytes bytecode2;
1171 if (!encodeTrampolineFunction(*codeMeta, paramsSize, bytecode2)) {
1172 ReportOutOfMemory(cx);
1173 return nullptr;
1174 }
1175 if (!mg.compileFuncDef(TrampolineFnIndex, funcBytecodeOffset,
1176 bytecode2.begin(),
1177 bytecode2.begin() + bytecode2.length())) {
1178 return nullptr;
1179 }
1180 funcBytecodeOffset += bytecode2.length();
1181
1182 Bytes bytecode3;
1183 if (!encodeContinueOnSuspendableFunction(*codeMeta, paramsSize,
1184 bytecode3)) {
1185 ReportOutOfMemory(cx);
1186 return nullptr;
1187 }
1188 if (!mg.compileFuncDef(ContinueOnSuspendableFnIndex, funcBytecodeOffset,
1189 bytecode3.begin(),
1190 bytecode3.begin() + bytecode3.length())) {
1191 return nullptr;
1192 }
1193 funcBytecodeOffset += bytecode3.length();
1194
1195 if (!mg.finishFuncDefs()) {
1196 return nullptr;
1197 }
1198
1199 return mg.finishModule(BytecodeBufferOrSource(), *moduleMeta,
1200 /*maybeCompleteTier2Listener=*/nullptr);
1201 }
1202 };
1203
1204 // Reaction on resolved/rejected suspending promise.
1205 static bool WasmPISuspendTaskContinue(JSContext* cx, unsigned argc, Value* vp) {
1206 CallArgs args = CallArgsFromVp(argc, vp);
1207 // The arg[0] has result of resolved promise, or rejection reason.
1208 Rooted<JSFunction*> callee(cx, &args.callee().as<JSFunction>());
1209 RootedValue suspender(cx, callee->getExtendedSlot(SUSPENDER_SLOT));
1210 RootedValue suspendingPromise(cx, callee->getExtendedSlot(PROMISE_SLOT));
1211
1212 // Convert result of the promise into the parameters/arguments for the
1213 // $suspending.continue-on-suspendable.
1214 RootedFunction continueOnSuspendable(
1215 cx, &callee->getExtendedSlot(CONTINUE_ON_SUSPENDABLE_SLOT)
1216 .toObject()
1217 .as<JSFunction>());
1218 JS::RootedValueArray<2> argv(cx);
1219 argv[0].set(suspender);
1220 argv[1].set(suspendingPromise);
1221
1222 JS::Rooted<JS::Value> rval(cx);
1223 if (Call(cx, UndefinedHandleValue, continueOnSuspendable, argv, &rval)) {
1224 return true;
1225 }
1226
1227 // The stack was unwound during exception -- time to release resources.
1228 CleanupActiveSuspender(cx);
1229
1230 if (cx->isThrowingOutOfMemory()) {
1231 return false;
1232 }
1233 Rooted<PromiseObject*> promise(
1234 cx, suspender.toObject().as<SuspenderObject>().promisingPromise());
1235 return RejectPromiseWithPendingError(cx, promise);
1236 }
1237
1238 // Wraps original import to catch all exceptions and convert result to a
1239 // promise.
1240 // Seen as $suspending.wrappedfn in wasm.
1241 static bool WasmPIWrapSuspendingImport(JSContext* cx, unsigned argc,
1242 Value* vp) {
1243 CallArgs args = CallArgsFromVp(argc, vp);
1244 Rooted<JSFunction*> callee(cx, &args.callee().as<JSFunction>());
1245 RootedValue originalImportFunc(cx, callee->getExtendedSlot(WRAPPED_FN_SLOT));
1246
1247 // Catching exceptions here.
1248 RootedValue rval(cx);
1249 if (Call(cx, UndefinedHandleValue, originalImportFunc, args, &rval)) {
1250 // Convert the result to a resolved promise later in AddPromiseReactions.
1251 args.rval().set(rval);
1252 return true;
1253 }
1254
1255 // Deferring pending exception to the handler in the
1256 // $suspending.trampoline.
1257 return false;
1258 }
1259
1260 JSFunction* WasmSuspendingFunctionCreate(JSContext* cx, HandleObject func,
1261 ValTypeVector&& params,
1262 ValTypeVector&& results) {
1263 MOZ_ASSERT(IsCallable(ObjectValue(*func)) &&
1264 !IsCrossCompartmentWrapper(func));
1265
1266 SuspendingFunctionModuleFactory moduleFactory;
1267 SharedModule module =
1268 moduleFactory.build(cx, func, std::move(params), std::move(results));
1269 if (!module) {
1270 return nullptr;
1271 }
1272
1273 // Instantiate the module.
1274 Rooted<ImportValues> imports(cx);
1275
1276 // Add $suspending.wrappedfn to imports.
1277 RootedFunction funcWrapper(
1278 cx, NewNativeFunction(cx, WasmPIWrapSuspendingImport, 0, nullptr,
1279 gc::AllocKind::FUNCTION_EXTENDED, GenericObject));
1280 if (!funcWrapper) {
1281 return nullptr;
1282 }
1283 funcWrapper->initExtendedSlot(WRAPPED_FN_SLOT, ObjectValue(*func));
1284 if (!imports.get().funcs.append(funcWrapper)) {
1285 ReportOutOfMemory(cx);
1286 return nullptr;
1287 }
1288
1289 Rooted<WasmInstanceObject*> instance(cx);
1290 if (!module->instantiate(cx, imports.get(), nullptr, &instance)) {
1291 // Can also trap on invalid input function.
1292 return nullptr;
1293 }
1294
1295 // Returns the $suspending.exported function.
1296 RootedFunction wasmFunc(cx);
1297 if (!WasmInstanceObject::getExportedFunction(
1298 cx, instance, SuspendingFunctionModuleFactory::ExportedFnIndex,
1299 &wasmFunc)) {
1300 return nullptr;
1301 }
1302 return wasmFunc;
1303 }
1304
1305 JSFunction* WasmSuspendingFunctionCreate(JSContext* cx, HandleObject func,
1306 const FuncType& type) {
1307 ValTypeVector params, results;
1308 if (!params.append(type.args().begin(), type.args().end()) ||
1309 !results.append(type.results().begin(), type.results().end())) {
1310 ReportOutOfMemory(cx);
1311 return nullptr;
1312 }
1313 return WasmSuspendingFunctionCreate(cx, func, std::move(params),
1314 std::move(results));
1315 }
1316
1317 // Promising
1318
1319 // Builds a wasm module with following structure:
1320 // (module
1321 // (type $params (struct (field ..)*))
1322 // (type $results (struct (field ..)*))
1323 // (type $create-suspender-result (struct (field externref externref)))
1324 // (import "" "" (func $promising.wrappedfn ..))
1325 // (func $promising.exported .. )
1326 // (func $promising.trampoline ..)
1327 // (export "" (func $promising.exported))
1328 // )
1329 //
1330 // The module provides logic for the Invoke Promising Import state transition
1331 // via $promising.exported and $promising.trampoline (see the SMDOC).
1332 //
1333 class PromisingFunctionModuleFactory {
1334 public:
1335 enum TypeIdx {
1336 ParamsTypeIndex,
1337 ResultsTypeIndex,
1338 };
1339
1340 enum FnIdx {
1341 WrappedFnIndex,
1342 ExportedFnIndex,
1343 TrampolineFnIndex,
1344 };
1345
1346 private:
1347 // Builds function that will be exported for JS:
1348 // (func $promising.exported
1349 // (param ..)* (result externref)
1350 // (local $suspender externref)
1351 // call $builtin.create-suspender
1352 // local.tee $suspender
1353 // call $builtin.create-promising-promise ;; -> (promise)
1354 // local.get $suspender
1355 // ref.func $promising.trampoline
1356 // local.get $i*
1357 // stuct.new $param-type
1358 // stack-switch SwitchToSuspendable ;; <- (suspender,fn,data)
1359 // )
1360 bool encodeExportedFunction(CodeMetadata& codeMeta, uint32_t paramsSize,
1361 Bytes& bytecode) {
1362 Encoder encoder(bytecode, *codeMeta.types);
1363 ValTypeVector locals;
1364 if (!locals.emplaceBack(RefType::extern_())) {
1365 return false;
1366 }
1367 if (!EncodeLocalEntries(encoder, locals)) {
1368 return false;
1369 }
1370
1371 const uint32_t SuspenderIndex = paramsSize;
1372 if (!encoder.writeOp(Op::I32Const) || !encoder.writeVarU32(0)) {
1373 return false;
1374 }
1375 if (!encoder.writeOp(MozOp::CallBuiltinModuleFunc) ||
1376 !encoder.writeVarU32((uint32_t)BuiltinModuleFuncId::CreateSuspender)) {
1377 return false;
1378 }
1379
1380 if (!encoder.writeOp(Op::LocalTee) ||
1381 !encoder.writeVarU32(SuspenderIndex)) {
1382 return false;
1383 }
1384 if (!encoder.writeOp(MozOp::CallBuiltinModuleFunc) ||
1385 !encoder.writeVarU32(
1386 (uint32_t)BuiltinModuleFuncId::CreatePromisingPromise)) {
1387 return false;
1388 }
1389
1390 if (!encoder.writeOp(Op::LocalGet) ||
1391 !encoder.writeVarU32(SuspenderIndex)) {
1392 return false;
1393 }
1394 if (!encoder.writeOp(Op::RefFunc) ||
1395 !encoder.writeVarU32(TrampolineFnIndex)) {
1396 return false;
1397 }
1398 for (uint32_t i = 0; i < paramsSize; i++) {
1399 if (!encoder.writeOp(Op::LocalGet) || !encoder.writeVarU32(i)) {
1400 return false;
1401 }
1402 }
1403 if (!encoder.writeOp(GcOp::StructNew) ||
1404 !encoder.writeVarU32(ParamsTypeIndex)) {
1405 return false;
1406 }
1407 if (!encoder.writeOp(MozOp::StackSwitch) ||
1408 !encoder.writeVarU32(uint32_t(StackSwitchKind::SwitchToSuspendable))) {
1409 return false;
1410 }
1411
1412 return encoder.writeOp(Op::End);
1413 }
1414
1415 // Builds function that is called on alternative stack:
1416 // (func $promising.trampoline
1417 // (param $suspender externref) (param $params (ref $param-type))
1418 // (result externref)
1419 // local.get $suspender ;; for call $set-results
1420 // (local.get $suspender)?
1421 // (struct.get $param-type $i (local.get $param))*
1422 // (local.get $suspender)?
1423 // call $promising.wrappedfn
1424 // struct.new $result-type
1425 // call $builtin.set-promising-promise-results
1426 // )
1427 bool encodeTrampolineFunction(CodeMetadata& codeMeta, uint32_t paramsSize,
1428 Bytes& bytecode) {
1429 Encoder encoder(bytecode, *codeMeta.types);
1430 if (!EncodeLocalEntries(encoder, ValTypeVector())) {
1431 return false;
1432 }
1433 const uint32_t SuspenderIndex = 0;
1434 const uint32_t ParamsIndex = 1;
1435
1436 // Reserved for SetResultsFnIndex call at the end
1437 if (!encoder.writeOp(Op::LocalGet) ||
1438 !encoder.writeVarU32(SuspenderIndex)) {
1439 return false;
1440 }
1441
1442 for (uint32_t i = 0; i < paramsSize; i++) {
1443 if (!encoder.writeOp(Op::LocalGet) || !encoder.writeVarU32(ParamsIndex)) {
1444 return false;
1445 }
1446 if (!encoder.writeOp(GcOp::StructGet) ||
1447 !encoder.writeVarU32(ParamsTypeIndex) || !encoder.writeVarU32(i)) {
1448 return false;
1449 }
1450 }
1451 if (!encoder.writeOp(Op::Call) || !encoder.writeVarU32(WrappedFnIndex)) {
1452 return false;
1453 }
1454
1455 if (!encoder.writeOp(GcOp::StructNew) ||
1456 !encoder.writeVarU32(ResultsTypeIndex)) {
1457 return false;
1458 }
1459 if (!encoder.writeOp(MozOp::CallBuiltinModuleFunc) ||
1460 !encoder.writeVarU32(
1461 (uint32_t)BuiltinModuleFuncId::SetPromisingPromiseResults)) {
1462 return false;
1463 }
1464
1465 return encoder.writeOp(Op::End);
1466 }
1467
1468 public:
1469 SharedModule build(JSContext* cx, HandleFunction fn, ValTypeVector&& params,
1470 ValTypeVector&& results) {
1471 const FuncType& fnType = fn->wasmTypeDef()->funcType();
1472 size_t paramsSize = params.length();
1473
1474 RefType suspenderType = RefType::extern_();
1475
1476 FeatureOptions options;
1477 options.isBuiltinModule = true;
1478
1479 ScriptedCaller scriptedCaller;
1480 SharedCompileArgs compileArgs =
1481 CompileArgs::buildAndReport(cx, std::move(scriptedCaller), options);
1482 if (!compileArgs) {
1483 return nullptr;
1484 }
1485
1486 MutableModuleMetadata moduleMeta = js_new<ModuleMetadata>();
1487 if (!moduleMeta || !moduleMeta->init(*compileArgs)) {
1488 return nullptr;
1489 }
1490 MutableCodeMetadata codeMeta = moduleMeta->codeMeta;
1491
1492 MOZ_ASSERT(IonPlatformSupport());
1493 CompilerEnvironment compilerEnv(CompileMode::Once, Tier::Optimized,
1494 DebugEnabled::False);
1495 compilerEnv.computeParameters();
1496
1497 StructType boxedParamsStruct;
1498 if (!StructType::createImmutable(params, &boxedParamsStruct)) {
1499 ReportOutOfMemory(cx);
1500 return nullptr;
1501 }
1502 MOZ_ASSERT(codeMeta->types->length() == ParamsTypeIndex);
1503 if (!codeMeta->types->addType(std::move(boxedParamsStruct))) {
1504 return nullptr;
1505 }
1506
1507 StructType boxedResultType;
1508 if (!StructType::createImmutable(fnType.results(), &boxedResultType)) {
1509 ReportOutOfMemory(cx);
1510 return nullptr;
1511 }
1512 MOZ_ASSERT(codeMeta->types->length() == ResultsTypeIndex);
1513 if (!codeMeta->types->addType(std::move(boxedResultType))) {
1514 return nullptr;
1515 }
1516
1517 ValTypeVector paramsForWrapper, resultsForWrapper;
1518 if (!paramsForWrapper.append(fnType.args().begin(), fnType.args().end()) ||
1519 !resultsForWrapper.append(fnType.results().begin(),
1520 fnType.results().end())) {
1521 ReportOutOfMemory(cx);
1522 return nullptr;
1523 }
1524 MOZ_ASSERT(codeMeta->funcs.length() == WrappedFnIndex);
1525 if (!moduleMeta->addDefinedFunc(std::move(paramsForWrapper),
1526 std::move(resultsForWrapper))) {
1527 return nullptr;
1528 }
1529
1530 // Imports names are not important, declare functions above as imports.
1531 codeMeta->numFuncImports = codeMeta->funcs.length();
1532
1533 // We will be looking up and using the exports function by index so
1534 // the name doesn't matter.
1535 MOZ_ASSERT(codeMeta->funcs.length() == ExportedFnIndex);
1536 if (!moduleMeta->addDefinedFunc(std::move(params), std::move(results),
1537 /* declareFoRef = */ true,
1538 mozilla::Some(CacheableName()))) {
1539 return nullptr;
1540 }
1541
1542 ValTypeVector paramsTrampoline, resultsTrampoline;
1543 if (!paramsTrampoline.emplaceBack(suspenderType) ||
1544 !paramsTrampoline.emplaceBack(RefType::fromTypeDef(
1545 &(*codeMeta->types)[ParamsTypeIndex], false))) {
1546 ReportOutOfMemory(cx);
1547 return nullptr;
1548 }
1549 MOZ_ASSERT(codeMeta->funcs.length() == TrampolineFnIndex);
1550 if (!moduleMeta->addDefinedFunc(std::move(paramsTrampoline),
1551 std::move(resultsTrampoline),
1552 /* declareFoRef = */ true)) {
1553 return nullptr;
1554 }
1555
1556 if (!moduleMeta->prepareForCompile(compilerEnv.mode())) {
1557 return nullptr;
1558 }
1559
1560 ModuleGenerator mg(*codeMeta, compilerEnv, compilerEnv.initialState(),
1561 nullptr, nullptr, nullptr);
1562 if (!mg.initializeCompleteTier()) {
1563 return nullptr;
1564 }
1565 // Build functions and keep bytecodes around until the end.
1566 Bytes bytecode;
1567 uint32_t funcBytecodeOffset = CallSite::FIRST_VALID_BYTECODE_OFFSET;
1568 if (!encodeExportedFunction(*codeMeta, paramsSize, bytecode)) {
1569 ReportOutOfMemory(cx);
1570 return nullptr;
1571 }
1572 if (!mg.compileFuncDef(ExportedFnIndex, funcBytecodeOffset,
1573 bytecode.begin(),
1574 bytecode.begin() + bytecode.length())) {
1575 return nullptr;
1576 }
1577 funcBytecodeOffset += bytecode.length();
1578
1579 Bytes bytecode2;
1580 if (!encodeTrampolineFunction(*codeMeta, paramsSize, bytecode2)) {
1581 ReportOutOfMemory(cx);
1582 return nullptr;
1583 }
1584 if (!mg.compileFuncDef(TrampolineFnIndex, funcBytecodeOffset,
1585 bytecode2.begin(),
1586 bytecode2.begin() + bytecode2.length())) {
1587 return nullptr;
1588 }
1589 funcBytecodeOffset += bytecode2.length();
1590
1591 if (!mg.finishFuncDefs()) {
1592 return nullptr;
1593 }
1594
1595 return mg.finishModule(BytecodeBufferOrSource(), *moduleMeta,
1596 /*maybeCompleteTier2Listener=*/nullptr);
1597 }
1598 };
1599
1600 // Wraps call to wasm $promising.exported function to catch an exception and
1601 // return a promise instead.
1602 static bool WasmPIPromisingFunction(JSContext* cx, unsigned argc, Value* vp) {
1603 CallArgs args = CallArgsFromVp(argc, vp);
1604 Rooted<JSFunction*> callee(cx, &args.callee().as<JSFunction>());
1605 RootedFunction fn(
1606 cx,
1607 &callee->getExtendedSlot(WRAPPED_FN_SLOT).toObject().as<JSFunction>());
1608
1609 // Catching exceptions here.
1610 if (Call(cx, UndefinedHandleValue, fn, args, args.rval())) {
1611 return true;
1612 }
1613
1614 // During an exception the stack was unwound -- time to release resources.
1615 CleanupActiveSuspender(cx);
1616
1617 if (cx->isThrowingOutOfMemory()) {
1618 return false;
1619 }
1620
1621 RootedObject promiseObject(cx, NewPromiseObject(cx, nullptr));
1622 if (!promiseObject) {
1623 return false;
1624 }
1625 args.rval().setObject(*promiseObject);
1626
1627 Rooted<PromiseObject*> promise(cx, &promiseObject->as<PromiseObject>());
1628 return RejectPromiseWithPendingError(cx, promise);
1629 }
1630
1631 JSFunction* WasmPromisingFunctionCreate(JSContext* cx, HandleObject func,
1632 ValTypeVector&& params,
1633 ValTypeVector&& results) {
1634 RootedFunction wrappedWasmFunc(cx, &func->as<JSFunction>());
1635 MOZ_ASSERT(wrappedWasmFunc->isWasm());
1636 const FuncType& wrappedWasmFuncType =
1637 wrappedWasmFunc->wasmTypeDef()->funcType();
1638
1639 MOZ_ASSERT(results.length() == 0 && params.length() == 0);
1640 if (!results.append(RefType::extern_())) {
1641 ReportOutOfMemory(cx);
1642 return nullptr;
1643 }
1644 if (!params.append(wrappedWasmFuncType.args().begin(),
1645 wrappedWasmFuncType.args().end())) {
1646 ReportOutOfMemory(cx);
1647 return nullptr;
1648 }
1649
1650 PromisingFunctionModuleFactory moduleFactory;
1651 SharedModule module = moduleFactory.build(
1652 cx, wrappedWasmFunc, std::move(params), std::move(results));
1653 // Instantiate the module.
1654 Rooted<ImportValues> imports(cx);
1655
1656 // Add wrapped function ($promising.wrappedfn) to imports.
1657 if (!imports.get().funcs.append(func)) {
1658 ReportOutOfMemory(cx);
1659 return nullptr;
1660 }
1661
1662 Rooted<WasmInstanceObject*> instance(cx);
1663 if (!module->instantiate(cx, imports.get(), nullptr, &instance)) {
1664 MOZ_ASSERT(cx->isThrowingOutOfMemory());
1665 return nullptr;
1666 }
1667
1668 // Wrap $promising.exported function for exceptions/traps handling.
1669 RootedFunction wasmFunc(cx);
1670 if (!WasmInstanceObject::getExportedFunction(
1671 cx, instance, PromisingFunctionModuleFactory::ExportedFnIndex,
1672 &wasmFunc)) {
1673 return nullptr;
1674 }
1675
1676 RootedFunction wasmFuncWrapper(
1677 cx, NewNativeFunction(cx, WasmPIPromisingFunction, 0, nullptr,
1678 gc::AllocKind::FUNCTION_EXTENDED, GenericObject));
1679 if (!wasmFuncWrapper) {
1680 return nullptr;
1681 }
1682 wasmFuncWrapper->initExtendedSlot(WRAPPED_FN_SLOT, ObjectValue(*wasmFunc));
1683 return wasmFuncWrapper;
1684 }
1685
1686 // Gets active suspender.
1687 // The reserved parameter is a workaround for limitation in the
1688 // WasmBuiltinModule.yaml generator to always have params.
1689 // Seen as $builtin.current-suspender to wasm.
1690 SuspenderObject* CurrentSuspender(Instance* instance, int32_t reserved) {
1691 MOZ_ASSERT(SASigCurrentSuspender.failureMode == FailureMode::FailOnNullPtr);
1692 JSContext* cx = instance->cx();
1693 SuspenderObject* suspender = cx->wasm().promiseIntegration.activeSuspender();
1694 if (!suspender) {
1695 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1696 JSMSG_JSPI_INVALID_STATE);
1697 return nullptr;
1698 }
1699 return suspender;
1700 }
1701
1702 // Creates a suspender and promise (that will be returned to JS code).
1703 // Seen as $builtin.create-suspender to wasm.
1704 SuspenderObject* CreateSuspender(Instance* instance, int32_t reserved) {
1705 MOZ_ASSERT(SASigCreateSuspender.failureMode == FailureMode::FailOnNullPtr);
1706 JSContext* cx = instance->cx();
1707 return SuspenderObject::create(cx);
1708 }
1709
1710 // Creates a promise that will be returned at promising call.
1711 // Seen as $builtin.create-promising-promise to wasm.
1712 PromiseObject* CreatePromisingPromise(Instance* instance,
1713 SuspenderObject* suspender) {
1714 MOZ_ASSERT(SASigCreatePromisingPromise.failureMode ==
1715 FailureMode::FailOnNullPtr);
1716 JSContext* cx = instance->cx();
1717
1718 Rooted<SuspenderObject*> suspenderObject(cx, suspender);
1719 RootedObject promiseObject(cx, NewPromiseObject(cx, nullptr));
1720 if (!promiseObject) {
1721 return nullptr;
1722 }
1723
1724 Rooted<PromiseObject*> promise(cx, &promiseObject->as<PromiseObject>());
1725 suspenderObject->setPromisingPromise(promise);
1726 return promise.get();
1727 }
1728
1729 // Converts promise results into actual function result, or exception/trap
1730 // if rejected.
1731 // Seen as $builtin.get-suspending-promise-result to wasm.
1732 JSObject* GetSuspendingPromiseResult(Instance* instance, void* result,
1733 SuspenderObject* suspender) {
1734 MOZ_ASSERT(SASigGetSuspendingPromiseResult.failureMode ==
1735 FailureMode::FailOnNullPtr);
1736 JSContext* cx = instance->cx();
1737 Rooted<SuspenderObject*> suspenderObject(cx, suspender);
1738 RootedAnyRef resultRef(cx, AnyRef::fromCompiledCode(result));
1739
1740 SuspenderObject::ReturnType returnType =
1741 suspenderObject->suspendingReturnType();
1742 MOZ_ASSERT(returnType != SuspenderObject::ReturnType::Unknown);
1743 Rooted<PromiseObject*> promise(
1744 cx, returnType == SuspenderObject::ReturnType::Promise
1745 ? &resultRef.toJSObject().as<PromiseObject>()
1746 : nullptr);
1747
1748 # ifdef DEBUG
1749 auto resetReturnType = mozilla::MakeScopeExit([&suspenderObject]() {
1750 suspenderObject->setSuspendingReturnType(
1751 SuspenderObject::ReturnType::Unknown);
1752 });
1753 # endif
1754
1755 if (promise ? promise->state() == JS::PromiseState::Rejected
1756 : returnType == SuspenderObject::ReturnType::Exception) {
1757 // Promise was rejected or an exception was thrown, set pending exception
1758 // and fail.
1759 RootedValue reason(
1760 cx, promise ? promise->reason() : resultRef.get().toJSValue());
1761 cx->setPendingException(reason, ShouldCaptureStack::Maybe);
1762 return nullptr;
1763 }
1764
1765 // The exception and rejection are handled above -- expect resolved promise.
1766 MOZ_ASSERT(promise->state() == JS::PromiseState::Fulfilled);
1767 RootedValue jsValue(cx, promise->value());
1768
1769 // Construct the results object.
1770 Rooted<WasmStructObject*> results(
1771 cx, instance->constantStructNewDefault(
1772 cx, SuspendingFunctionModuleFactory::ResultsTypeIndex));
1773 const FieldTypeVector& fields = results->typeDef().structType().fields_;
1774
1775 if (fields.length() > 0) {
1776 // The struct object is constructed based on returns of exported function.
1777 // It is the only way we can get ValType for Val::fromJSValue call.
1778 const wasm::FuncType& sig = instance->codeMeta().getFuncType(
1779 SuspendingFunctionModuleFactory::ExportedFnIndex);
1780
1781 if (fields.length() == 1) {
1782 RootedVal val(cx);
1783 MOZ_ASSERT(sig.result(0).storageType() == fields[0].type);
1784 if (!Val::fromJSValue(cx, sig.result(0), jsValue, &val)) {
1785 return nullptr;
1786 }
1787 results->storeVal(val, 0);
1788 } else {
1789 // The multi-value result is wrapped into ArrayObject/Iterable.
1790 Rooted<ArrayObject*> array(cx);
1791 if (!IterableToArray(cx, jsValue, &array)) {
1792 return nullptr;
1793 }
1794 if (fields.length() != array->length()) {
1795 UniqueChars expected(JS_smprintf("%zu", fields.length()));
1796 UniqueChars got(JS_smprintf("%u", array->length()));
1797 if (!expected || !got) {
1798 ReportOutOfMemory(cx);
1799 return nullptr;
1800 }
1801
1802 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
1803 JSMSG_WASM_WRONG_NUMBER_OF_VALUES,
1804 expected.get(), got.get());
1805 return nullptr;
1806 }
1807
1808 for (size_t i = 0; i < fields.length(); i++) {
1809 RootedVal val(cx);
1810 RootedValue v(cx, array->getDenseElement(i));
1811 MOZ_ASSERT(sig.result(i).storageType() == fields[i].type);
1812 if (!Val::fromJSValue(cx, sig.result(i), v, &val)) {
1813 return nullptr;
1814 }
1815 results->storeVal(val, i);
1816 }
1817 }
1818 }
1819 return results;
1820 }
1821
1822 // Collects returned suspending promising, and registers callbacks to
1823 // react on it using WasmPISuspendTaskContinue.
1824 // Seen as $builtin.add-promise-reactions to wasm.
1825 void* AddPromiseReactions(Instance* instance, SuspenderObject* suspender,
1826 void* result, JSFunction* continueOnSuspendable) {
1827 MOZ_ASSERT(SASigAddPromiseReactions.failureMode ==
1828 FailureMode::FailOnInvalidRef);
1829 JSContext* cx = instance->cx();
1830
1831 RootedAnyRef resultRef(cx, AnyRef::fromCompiledCode(result));
1832 RootedValue resultValue(cx, resultRef.get().toJSValue());
1833 Rooted<SuspenderObject*> suspenderObject(cx, suspender);
1834 RootedFunction fn(cx, continueOnSuspendable);
1835
1836 // Wrap a promise.
1837 RootedObject promiseConstructor(cx, GetPromiseConstructor(cx));
1838 RootedObject promiseObj(cx,
1839 PromiseResolve(cx, promiseConstructor, resultValue));
1840 if (!promiseObj) {
1841 return AnyRef::invalid().forCompiledCode();
1842 }
1843 Rooted<PromiseObject*> promiseObject(cx, &promiseObj->as<PromiseObject>());
1844
1845 suspenderObject->setSuspendingReturnType(
1846 SuspenderObject::ReturnType::Promise);
1847
1848 // Add promise reactions
1849 RootedFunction then_(
1850 cx, NewNativeFunction(cx, WasmPISuspendTaskContinue, 1, nullptr,
1851 gc::AllocKind::FUNCTION_EXTENDED, GenericObject));
1852 then_->initExtendedSlot(SUSPENDER_SLOT, ObjectValue(*suspenderObject));
1853 then_->initExtendedSlot(CONTINUE_ON_SUSPENDABLE_SLOT, ObjectValue(*fn));
1854 then_->initExtendedSlot(PROMISE_SLOT, ObjectValue(*promiseObject));
1855 if (!JS::AddPromiseReactions(cx, promiseObject, then_, then_)) {
1856 return AnyRef::invalid().forCompiledCode();
1857 }
1858 return AnyRef::fromJSObject(*promiseObject).forCompiledCode();
1859 }
1860
1861 // Changes exit stack frame pointers to suspendable stack and recast exception
1862 // to wasm reference. Seen as $builtin.forward-exn-to-suspended to wasm.
1863 void* ForwardExceptionToSuspended(Instance* instance,
1864 SuspenderObject* suspender, void* exception) {
1865 MOZ_ASSERT(SASigForwardExceptionToSuspended.failureMode ==
1866 FailureMode::Infallible);
1867
1868 suspender->forwardToSuspendable();
1869 suspender->setSuspendingReturnType(SuspenderObject::ReturnType::Exception);
1870 return exception;
1871 }
1872
1873 // Resolves the promise using results packed by wasm.
1874 // Seen as $builtin.set-promising-promise-results to wasm.
1875 int32_t SetPromisingPromiseResults(Instance* instance,
1876 SuspenderObject* suspender,
1877 WasmStructObject* results) {
1878 MOZ_ASSERT(SASigSetPromisingPromiseResults.failureMode ==
1879 FailureMode::FailOnNegI32);
1880 JSContext* cx = instance->cx();
1881 Rooted<WasmStructObject*> res(cx, results);
1882 Rooted<SuspenderObject*> suspenderObject(cx, suspender);
1883 RootedObject promise(cx, suspenderObject->promisingPromise());
1884
1885 const StructType& resultType = res->typeDef().structType();
1886 RootedValue val(cx);
1887 // Unbox the result value from the struct, if any.
1888 switch (resultType.fields_.length()) {
1889 case 0:
1890 break;
1891 case 1: {
1892 if (!res->getField(cx, /*index=*/0, &val)) {
1893 return false;
1894 }
1895 } break;
1896 default: {
1897 Rooted<ArrayObject*> array(cx, NewDenseEmptyArray(cx));
1898 if (!array) {
1899 return false;
1900 }
1901 for (size_t i = 0; i < resultType.fields_.length(); i++) {
1902 RootedValue item(cx);
1903 if (!res->getField(cx, i, &item)) {
1904 return false;
1905 }
1906 if (!NewbornArrayPush(cx, array, item)) {
1907 return false;
1908 }
1909 }
1910 val.setObject(*array);
1911 } break;
1912 }
1913 ResolvePromise(cx, promise, val);
1914 return 0;
1915 }
1916
1917 void UpdateSuspenderState(Instance* instance, SuspenderObject* suspender,
1918 UpdateSuspenderStateAction action) {
1919 MOZ_ASSERT(SASigUpdateSuspenderState.failureMode == FailureMode::Infallible);
1920
1921 JSContext* cx = instance->cx();
1922 switch (action) {
1923 case UpdateSuspenderStateAction::Enter:
1924 suspender->enter(cx);
1925 break;
1926 case UpdateSuspenderStateAction::Suspend:
1927 suspender->suspend(cx);
1928 break;
1929 case UpdateSuspenderStateAction::Resume:
1930 suspender->resume(cx);
1931 break;
1932 case UpdateSuspenderStateAction::Leave:
1933 suspender->leave(cx);
1934 break;
1935 default:
1936 MOZ_CRASH();
1937 }
1938 }
1939
1940 } // namespace js::wasm
1941 #endif // ENABLE_WASM_JSPI