Debian Codegraph @

js/src/wasm/WasmBuiltins.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 2017 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/WasmBuiltins.h"
20
21 #include "mozilla/Atomics.h"
22 #include "mozilla/ScopeExit.h"
23
24 #include "fdlibm.h"
25 #include "jslibmath.h"
26 #include "jsmath.h"
27
28 #include "gc/GC.h"
29 #include "jit/AtomicOperations.h"
30 #include "jit/InlinableNatives.h"
31 #include "jit/JitRuntime.h"
32 #include "jit/MacroAssembler.h"
33 #include "jit/ProcessExecutableMemory.h"
34 #include "jit/Simulator.h"
35 #include "js/experimental/JitInfo.h" // JSJitInfo
36 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
37 #include "js/friend/StackLimits.h" // js::AutoCheckRecursionLimit
38 #include "threading/Mutex.h"
39 #include "util/Memory.h"
40 #include "util/Poison.h"
41 #include "vm/BigIntType.h"
42 #include "vm/ErrorObject.h"
43 #include "wasm/WasmCodegenTypes.h"
44 #include "wasm/WasmDebug.h"
45 #include "wasm/WasmDebugFrame.h"
46 #include "wasm/WasmGcObject.h"
47 #include "wasm/WasmInstance.h"
48 #include "wasm/WasmPI.h"
49 #include "wasm/WasmStubs.h"
50
51 #include "debugger/DebugAPI-inl.h"
52 #include "vm/ErrorObject-inl.h"
53 #include "vm/JSContext-inl.h"
54 #include "vm/Stack-inl.h"
55 #include "wasm/WasmInstance-inl.h"
56
57 using namespace js;
58 using namespace jit;
59 using namespace wasm;
60
61 using mozilla::EnumeratedArray;
62 using mozilla::HashGeneric;
63 using mozilla::MakeEnumeratedRange;
64 using mozilla::Maybe;
65 using mozilla::Nothing;
66 using mozilla::Some;
67
68 static const unsigned BUILTIN_THUNK_LIFO_SIZE = 64 * 1024;
69
70 // ============================================================================
71 // WebAssembly builtin C++ functions called from wasm code to implement internal
72 // wasm operations: type descriptions.
73
74 // Some abbreviations, for the sake of conciseness.
75 #define _F64 MIRType::Double
76 #define _F32 MIRType::Float32
77 #define _I32 MIRType::Int32
78 #define _I64 MIRType::Int64
79 #define _PTR MIRType::Pointer
80 #define _RoN MIRType::WasmAnyRef
81 #define _WAD MIRType::WasmArrayData
82 #define _VOID MIRType::None
83 #define _END MIRType::None
84 #define _Infallible FailureMode::Infallible
85 #define _FailOnNegI32 FailureMode::FailOnNegI32
86 #define _FailOnMaxI32 FailureMode::FailOnMaxI32
87 #define _FailOnNullPtr FailureMode::FailOnNullPtr
88 #define _FailOnInvalidRef FailureMode::FailOnInvalidRef
89
90 namespace js {
91 namespace wasm {
92
93 constexpr SymbolicAddressSignature SASigSinNativeD = {
94 SymbolicAddress::SinNativeD, _F64, _Infallible, 1, {_F64, _END}};
95 constexpr SymbolicAddressSignature SASigSinFdlibmD = {
96 SymbolicAddress::SinFdlibmD, _F64, _Infallible, 1, {_F64, _END}};
97 constexpr SymbolicAddressSignature SASigCosNativeD = {
98 SymbolicAddress::CosNativeD, _F64, _Infallible, 1, {_F64, _END}};
99 constexpr SymbolicAddressSignature SASigCosFdlibmD = {
100 SymbolicAddress::CosFdlibmD, _F64, _Infallible, 1, {_F64, _END}};
101 constexpr SymbolicAddressSignature SASigTanNativeD = {
102 SymbolicAddress::TanNativeD, _F64, _Infallible, 1, {_F64, _END}};
103 constexpr SymbolicAddressSignature SASigTanFdlibmD = {
104 SymbolicAddress::TanFdlibmD, _F64, _Infallible, 1, {_F64, _END}};
105 constexpr SymbolicAddressSignature SASigASinD = {
106 SymbolicAddress::ASinD, _F64, _Infallible, 1, {_F64, _END}};
107 constexpr SymbolicAddressSignature SASigACosD = {
108 SymbolicAddress::ACosD, _F64, _Infallible, 1, {_F64, _END}};
109 constexpr SymbolicAddressSignature SASigATanD = {
110 SymbolicAddress::ATanD, _F64, _Infallible, 1, {_F64, _END}};
111 constexpr SymbolicAddressSignature SASigCeilD = {
112 SymbolicAddress::CeilD, _F64, _Infallible, 1, {_F64, _END}};
113 constexpr SymbolicAddressSignature SASigCeilF = {
114 SymbolicAddress::CeilF, _F32, _Infallible, 1, {_F32, _END}};
115 constexpr SymbolicAddressSignature SASigFloorD = {
116 SymbolicAddress::FloorD, _F64, _Infallible, 1, {_F64, _END}};
117 constexpr SymbolicAddressSignature SASigFloorF = {
118 SymbolicAddress::FloorF, _F32, _Infallible, 1, {_F32, _END}};
119 constexpr SymbolicAddressSignature SASigTruncD = {
120 SymbolicAddress::TruncD, _F64, _Infallible, 1, {_F64, _END}};
121 constexpr SymbolicAddressSignature SASigTruncF = {
122 SymbolicAddress::TruncF, _F32, _Infallible, 1, {_F32, _END}};
123 constexpr SymbolicAddressSignature SASigNearbyIntD = {
124 SymbolicAddress::NearbyIntD, _F64, _Infallible, 1, {_F64, _END}};
125 constexpr SymbolicAddressSignature SASigNearbyIntF = {
126 SymbolicAddress::NearbyIntF, _F32, _Infallible, 1, {_F32, _END}};
127 constexpr SymbolicAddressSignature SASigExpD = {
128 SymbolicAddress::ExpD, _F64, _Infallible, 1, {_F64, _END}};
129 constexpr SymbolicAddressSignature SASigLogD = {
130 SymbolicAddress::LogD, _F64, _Infallible, 1, {_F64, _END}};
131 constexpr SymbolicAddressSignature SASigPowD = {
132 SymbolicAddress::PowD, _F64, _Infallible, 2, {_F64, _F64, _END}};
133 constexpr SymbolicAddressSignature SASigATan2D = {
134 SymbolicAddress::ATan2D, _F64, _Infallible, 2, {_F64, _F64, _END}};
135 constexpr SymbolicAddressSignature SASigArrayMemMove = {
136 SymbolicAddress::ArrayMemMove,
137 _VOID,
138 _Infallible,
139 6,
140 {_WAD, _I32, _WAD, _I32, _I32, _I32, _END}};
141 constexpr SymbolicAddressSignature SASigArrayRefsMove = {
142 SymbolicAddress::ArrayRefsMove,
143 _VOID,
144 _Infallible,
145 5,
146 {_WAD, _I32, _WAD, _I32, _I32, _END}};
147 constexpr SymbolicAddressSignature SASigMemoryGrowM32 = {
148 SymbolicAddress::MemoryGrowM32,
149 _I32,
150 _Infallible,
151 3,
152 {_PTR, _I32, _I32, _END}};
153 constexpr SymbolicAddressSignature SASigMemoryGrowM64 = {
154 SymbolicAddress::MemoryGrowM64,
155 _I64,
156 _Infallible,
157 3,
158 {_PTR, _I64, _I32, _END}};
159 constexpr SymbolicAddressSignature SASigMemorySizeM32 = {
160 SymbolicAddress::MemorySizeM32, _I32, _Infallible, 2, {_PTR, _I32, _END}};
161 constexpr SymbolicAddressSignature SASigMemorySizeM64 = {
162 SymbolicAddress::MemorySizeM64, _I64, _Infallible, 2, {_PTR, _I32, _END}};
163 constexpr SymbolicAddressSignature SASigWaitI32M32 = {
164 SymbolicAddress::WaitI32M32,
165 _I32,
166 _FailOnNegI32,
167 5,
168 {_PTR, _I32, _I32, _I64, _I32, _END}};
169 constexpr SymbolicAddressSignature SASigWaitI32M64 = {
170 SymbolicAddress::WaitI32M64,
171 _I32,
172 _FailOnNegI32,
173 5,
174 {_PTR, _I64, _I32, _I64, _I32, _END}};
175 constexpr SymbolicAddressSignature SASigWaitI64M32 = {
176 SymbolicAddress::WaitI64M32,
177 _I32,
178 _FailOnNegI32,
179 5,
180 {_PTR, _I32, _I64, _I64, _I32, _END}};
181 constexpr SymbolicAddressSignature SASigWaitI64M64 = {
182 SymbolicAddress::WaitI64M64,
183 _I32,
184 _FailOnNegI32,
185 5,
186 {_PTR, _I64, _I64, _I64, _I32, _END}};
187 constexpr SymbolicAddressSignature SASigWakeM32 = {
188 SymbolicAddress::WakeM32,
189 _I32,
190 _FailOnNegI32,
191 4,
192 {_PTR, _I32, _I32, _I32, _END}};
193 constexpr SymbolicAddressSignature SASigWakeM64 = {
194 SymbolicAddress::WakeM64,
195 _I32,
196 _FailOnNegI32,
197 4,
198 {_PTR, _I64, _I32, _I32, _END}};
199 constexpr SymbolicAddressSignature SASigMemCopyM32 = {
200 SymbolicAddress::MemCopyM32,
201 _VOID,
202 _FailOnNegI32,
203 5,
204 {_PTR, _I32, _I32, _I32, _PTR, _END}};
205 constexpr SymbolicAddressSignature SASigMemCopySharedM32 = {
206 SymbolicAddress::MemCopySharedM32,
207 _VOID,
208 _FailOnNegI32,
209 5,
210 {_PTR, _I32, _I32, _I32, _PTR, _END}};
211 constexpr SymbolicAddressSignature SASigMemCopyM64 = {
212 SymbolicAddress::MemCopyM64,
213 _VOID,
214 _FailOnNegI32,
215 5,
216 {_PTR, _I64, _I64, _I64, _PTR, _END}};
217 constexpr SymbolicAddressSignature SASigMemCopySharedM64 = {
218 SymbolicAddress::MemCopySharedM64,
219 _VOID,
220 _FailOnNegI32,
221 5,
222 {_PTR, _I64, _I64, _I64, _PTR, _END}};
223 constexpr SymbolicAddressSignature SASigMemCopyAny = {
224 SymbolicAddress::MemCopyAny,
225 _VOID,
226 _FailOnNegI32,
227 6,
228 {_PTR, _I64, _I64, _I64, _I32, _I32, _END}};
229 constexpr SymbolicAddressSignature SASigDataDrop = {
230 SymbolicAddress::DataDrop, _VOID, _FailOnNegI32, 2, {_PTR, _I32, _END}};
231 constexpr SymbolicAddressSignature SASigMemFillM32 = {
232 SymbolicAddress::MemFillM32,
233 _VOID,
234 _FailOnNegI32,
235 5,
236 {_PTR, _I32, _I32, _I32, _PTR, _END}};
237 constexpr SymbolicAddressSignature SASigMemFillSharedM32 = {
238 SymbolicAddress::MemFillSharedM32,
239 _VOID,
240 _FailOnNegI32,
241 5,
242 {_PTR, _I32, _I32, _I32, _PTR, _END}};
243 constexpr SymbolicAddressSignature SASigMemFillM64 = {
244 SymbolicAddress::MemFillM64,
245 _VOID,
246 _FailOnNegI32,
247 5,
248 {_PTR, _I64, _I32, _I64, _PTR, _END}};
249 constexpr SymbolicAddressSignature SASigMemFillSharedM64 = {
250 SymbolicAddress::MemFillSharedM64,
251 _VOID,
252 _FailOnNegI32,
253 5,
254 {_PTR, _I64, _I32, _I64, _PTR, _END}};
255 constexpr SymbolicAddressSignature SASigMemDiscardM32 = {
256 SymbolicAddress::MemDiscardM32,
257 _VOID,
258 _FailOnNegI32,
259 4,
260 {_PTR, _I32, _I32, _PTR, _END}};
261 constexpr SymbolicAddressSignature SASigMemDiscardSharedM32 = {
262 SymbolicAddress::MemDiscardSharedM32,
263 _VOID,
264 _FailOnNegI32,
265 4,
266 {_PTR, _I32, _I32, _PTR, _END}};
267 constexpr SymbolicAddressSignature SASigMemDiscardM64 = {
268 SymbolicAddress::MemDiscardM64,
269 _VOID,
270 _FailOnNegI32,
271 4,
272 {_PTR, _I64, _I64, _PTR, _END}};
273 constexpr SymbolicAddressSignature SASigMemDiscardSharedM64 = {
274 SymbolicAddress::MemDiscardSharedM64,
275 _VOID,
276 _FailOnNegI32,
277 4,
278 {_PTR, _I64, _I64, _PTR, _END}};
279 constexpr SymbolicAddressSignature SASigMemInitM32 = {
280 SymbolicAddress::MemInitM32,
281 _VOID,
282 _FailOnNegI32,
283 6,
284 {_PTR, _I32, _I32, _I32, _I32, _I32, _END}};
285 constexpr SymbolicAddressSignature SASigMemInitM64 = {
286 SymbolicAddress::MemInitM64,
287 _VOID,
288 _FailOnNegI32,
289 6,
290 {_PTR, _I64, _I32, _I32, _I32, _I32, _END}};
291 constexpr SymbolicAddressSignature SASigTableCopy = {
292 SymbolicAddress::TableCopy,
293 _VOID,
294 _FailOnNegI32,
295 6,
296 {_PTR, _I32, _I32, _I32, _I32, _I32, _END}};
297 constexpr SymbolicAddressSignature SASigElemDrop = {
298 SymbolicAddress::ElemDrop, _VOID, _FailOnNegI32, 2, {_PTR, _I32, _END}};
299 constexpr SymbolicAddressSignature SASigTableFill = {
300 SymbolicAddress::TableFill,
301 _VOID,
302 _FailOnNegI32,
303 5,
304 {_PTR, _I32, _RoN, _I32, _I32, _END}};
305 constexpr SymbolicAddressSignature SASigTableGet = {SymbolicAddress::TableGet,
306 _RoN,
307 _FailOnInvalidRef,
308 3,
309 {_PTR, _I32, _I32, _END}};
310 constexpr SymbolicAddressSignature SASigTableGrow = {
311 SymbolicAddress::TableGrow,
312 _I32,
313 _Infallible,
314 4,
315 {_PTR, _RoN, _I32, _I32, _END}};
316 constexpr SymbolicAddressSignature SASigTableInit = {
317 SymbolicAddress::TableInit,
318 _VOID,
319 _FailOnNegI32,
320 6,
321 {_PTR, _I32, _I32, _I32, _I32, _I32, _END}};
322 constexpr SymbolicAddressSignature SASigTableSet = {
323 SymbolicAddress::TableSet,
324 _VOID,
325 _FailOnNegI32,
326 4,
327 {_PTR, _I32, _RoN, _I32, _END}};
328 constexpr SymbolicAddressSignature SASigTableSize = {
329 SymbolicAddress::TableSize, _I32, _Infallible, 2, {_PTR, _I32, _END}};
330 constexpr SymbolicAddressSignature SASigRefFunc = {
331 SymbolicAddress::RefFunc, _RoN, _FailOnInvalidRef, 2, {_PTR, _I32, _END}};
332 constexpr SymbolicAddressSignature SASigPostBarrierEdge = {
333 SymbolicAddress::PostBarrierEdge,
334 _VOID,
335 _Infallible,
336 2,
337 {_PTR, _PTR, _END}};
338 constexpr SymbolicAddressSignature SASigPostBarrierEdgePrecise = {
339 SymbolicAddress::PostBarrierEdgePrecise,
340 _VOID,
341 _Infallible,
342 3,
343 {_PTR, _PTR, _RoN, _END}};
344 constexpr SymbolicAddressSignature SASigPostBarrierWholeCell = {
345 SymbolicAddress::PostBarrierWholeCell,
346 _VOID,
347 _Infallible,
348 2,
349 {_PTR, _PTR, _END}};
350 constexpr SymbolicAddressSignature SASigExceptionNew = {
351 SymbolicAddress::ExceptionNew, _RoN, _FailOnNullPtr, 2, {_PTR, _RoN, _END}};
352 constexpr SymbolicAddressSignature SASigThrowException = {
353 SymbolicAddress::ThrowException,
354 _VOID,
355 _FailOnNegI32,
356 2,
357 {_PTR, _RoN, _END}};
358 constexpr SymbolicAddressSignature SASigStructNewIL_true = {
359 SymbolicAddress::StructNewIL_true,
360 _RoN,
361 _FailOnNullPtr,
362 3,
363 {_PTR, _I32, _PTR, _END}};
364 constexpr SymbolicAddressSignature SASigStructNewIL_false = {
365 SymbolicAddress::StructNewIL_false,
366 _RoN,
367 _FailOnNullPtr,
368 3,
369 {_PTR, _I32, _PTR, _END}};
370 constexpr SymbolicAddressSignature SASigStructNewOOL_true = {
371 SymbolicAddress::StructNewOOL_true,
372 _RoN,
373 _FailOnNullPtr,
374 3,
375 {_PTR, _I32, _PTR, _END}};
376 constexpr SymbolicAddressSignature SASigStructNewOOL_false = {
377 SymbolicAddress::StructNewOOL_false,
378 _RoN,
379 _FailOnNullPtr,
380 3,
381 {_PTR, _I32, _PTR, _END}};
382 constexpr SymbolicAddressSignature SASigArrayNew_true = {
383 SymbolicAddress::ArrayNew_true,
384 _RoN,
385 _FailOnNullPtr,
386 4,
387 {_PTR, _I32, _I32, _PTR, _END}};
388 constexpr SymbolicAddressSignature SASigArrayNew_false = {
389 SymbolicAddress::ArrayNew_false,
390 _RoN,
391 _FailOnNullPtr,
392 4,
393 {_PTR, _I32, _I32, _PTR, _END}};
394 constexpr SymbolicAddressSignature SASigArrayNewData = {
395 SymbolicAddress::ArrayNewData,
396 _RoN,
397 _FailOnNullPtr,
398 6,
399 {_PTR, _I32, _I32, _I32, _PTR, _I32, _END}};
400 constexpr SymbolicAddressSignature SASigArrayNewElem = {
401 SymbolicAddress::ArrayNewElem,
402 _RoN,
403 _FailOnNullPtr,
404 6,
405 {_PTR, _I32, _I32, _I32, _PTR, _I32, _END}};
406 constexpr SymbolicAddressSignature SASigArrayInitData = {
407 SymbolicAddress::ArrayInitData,
408 _VOID,
409 _FailOnNegI32,
410 6,
411 {_PTR, _RoN, _I32, _I32, _I32, _I32, _END}};
412 constexpr SymbolicAddressSignature SASigArrayInitElem = {
413 SymbolicAddress::ArrayInitElem,
414 _VOID,
415 _FailOnNegI32,
416 7,
417 {_PTR, _RoN, _I32, _I32, _I32, _I32, _I32, _END}};
418 constexpr SymbolicAddressSignature SASigArrayCopy = {
419 SymbolicAddress::ArrayCopy,
420 _VOID,
421 _FailOnNegI32,
422 7,
423 {_PTR, _RoN, _I32, _RoN, _I32, _I32, _I32, _END}};
424
425 #define VISIT_BUILTIN_FUNC(op, export, sa_name, ...) \
426 constexpr SymbolicAddressSignature SASig##sa_name = { \
427 SymbolicAddress::sa_name, \
428 DECLARE_BUILTIN_MODULE_FUNC_RESULT_MIRTYPE_##op, \
429 DECLARE_BUILTIN_MODULE_FUNC_FAILMODE_##op, \
430 DECLARE_BUILTIN_MODULE_FUNC_PARAM_MIRTYPES_##op};
431
432 FOR_EACH_BUILTIN_MODULE_FUNC(VISIT_BUILTIN_FUNC)
433 #undef VISIT_BUILTIN_FUNC
434
435 #ifdef ENABLE_WASM_JSPI
436 constexpr SymbolicAddressSignature SASigUpdateSuspenderState = {
437 SymbolicAddress::UpdateSuspenderState,
438 _VOID,
439 _Infallible,
440 3,
441 {_PTR, _PTR, _I32, _END}};
442 #endif
443
444 } // namespace wasm
445 } // namespace js
446
447 #undef _F64
448 #undef _F32
449 #undef _I32
450 #undef _I64
451 #undef _PTR
452 #undef _RoN
453 #undef _VOID
454 #undef _END
455 #undef _Infallible
456 #undef _FailOnNegI32
457 #undef _FailOnNullPtr
458
459 #ifdef DEBUG
460 ABIType ToABIType(FailureMode mode) {
461 switch (mode) {
462 case FailureMode::FailOnNegI32:
463 return ABIType::Int32;
464 case FailureMode::FailOnNullPtr:
465 case FailureMode::FailOnInvalidRef:
466 return ABIType::General;
467 default:
468 MOZ_CRASH("unexpected failure mode");
469 }
470 }
471
472 ABIType ToABIType(MIRType type) {
473 switch (type) {
474 case MIRType::None:
475 case MIRType::Int32:
476 return ABIType::Int32;
477 case MIRType::Int64:
478 return ABIType::Int64;
479 case MIRType::Pointer:
480 case MIRType::WasmAnyRef:
481 return ABIType::General;
482 case MIRType::Float32:
483 return ABIType::Float32;
484 case MIRType::Double:
485 return ABIType::Float64;
486 default:
487 MOZ_CRASH("unexpected type");
488 }
489 }
490
491 ABIFunctionType ToABIType(const SymbolicAddressSignature& sig) {
492 MOZ_ASSERT_IF(sig.failureMode != FailureMode::Infallible,
493 ToABIType(sig.failureMode) == ToABIType(sig.retType));
494 int abiType = 0;
495 for (int i = 0; i < sig.numArgs; i++) {
496 abiType <<= ABITypeArgShift;
497 abiType |= uint32_t(ToABIType(sig.argTypes[i]));
498 }
499 abiType <<= ABITypeArgShift;
500 abiType |= uint32_t(ToABIType(sig.retType));
501 return ABIFunctionType(abiType);
502 }
503 #endif
504
505 // ============================================================================
506 // WebAssembly builtin C++ functions called from wasm code to implement internal
507 // wasm operations: implementations.
508
509 #if defined(JS_CODEGEN_ARM)
510 extern "C" {
511
512 extern MOZ_EXPORT int64_t __aeabi_idivmod(int, int);
513
514 extern MOZ_EXPORT int64_t __aeabi_uidivmod(int, int);
515 }
516 #endif
517
518 // This utility function can only be called for builtins that are called
519 // directly from wasm code.
520 static JitActivation* CallingActivation(JSContext* cx) {
521 Activation* act = cx->activation();
522 MOZ_ASSERT(act->asJit()->hasWasmExitFP());
523 return act->asJit();
524 }
525
526 template <typename Fn, typename... Ts>
527 static bool ForwardToMainStack(Fn fn, JSContext* cx, Ts... args) {
528 #ifdef ENABLE_WASM_JSPI
529 if (IsSuspendableStackActive(cx)) {
530 struct InvokeContext {
531 bool (*fn)(JSContext*, Ts...);
532 JSContext* cx;
533 std::tuple<Ts...> args;
534 static bool Run(InvokeContext* data) {
535 return data->fn(data->cx, std::get<Ts>(data->args)...);
536 }
537 } data = {fn, cx, std::make_tuple(args...)};
538 return CallOnMainStack(
539 cx, reinterpret_cast<CallOnMainStackFn>(InvokeContext::Run), &data);
540 }
541 #endif
542 return fn(cx, args...);
543 }
544
545 static bool WasmHandleDebugTrap() {
546 JSContext* cx = TlsContext.get(); // Cold code
547 JitActivation* activation = CallingActivation(cx);
548 Frame* fp = activation->wasmExitFP();
549 Instance* instance = GetNearestEffectiveInstance(fp);
550 const Code& code = instance->code();
551 MOZ_ASSERT(code.debugEnabled());
552
553 // The debug trap stub is the innermost frame. It's return address is the
554 // actual trap site.
555 CallSite site;
556 MOZ_ALWAYS_TRUE(code.lookupCallSite(fp->returnAddress(), &site));
557
558 // Advance to the actual trapping frame.
559 fp = fp->wasmCaller();
560 DebugFrame* debugFrame = DebugFrame::from(fp);
561
562 if (site.kind() == CallSiteKind::EnterFrame) {
563 if (!instance->debug().enterFrameTrapsEnabled()) {
564 return true;
565 }
566 debugFrame->setIsDebuggee();
567 debugFrame->observe(cx);
568 if (!ForwardToMainStack(DebugAPI::onEnterFrame, cx,
569 js::AbstractFramePtr(debugFrame))) {
570 if (cx->isPropagatingForcedReturn()) {
571 cx->clearPropagatingForcedReturn();
572 // Ignoring forced return because changing code execution order is
573 // not yet implemented in the wasm baseline.
574 // TODO properly handle forced return and resume wasm execution.
575 JS_ReportErrorASCII(cx,
576 "Unexpected resumption value from onEnterFrame");
577 }
578 return false;
579 }
580 return true;
581 }
582 if (site.kind() == CallSiteKind::LeaveFrame ||
583 site.kind() == CallSiteKind::CollapseFrame) {
584 if (site.kind() == CallSiteKind::LeaveFrame &&
585 !debugFrame->updateReturnJSValue(cx)) {
586 return false;
587 }
588 if (site.kind() == CallSiteKind::CollapseFrame) {
589 debugFrame->discardReturnJSValue();
590 }
591 bool ok = ForwardToMainStack(DebugAPI::onLeaveFrame, cx,
592 js::AbstractFramePtr(debugFrame),
593 (const jsbytecode*)nullptr, true);
594 debugFrame->leave(cx);
595 return ok;
596 }
597
598 DebugState& debug = instance->debug();
599 MOZ_ASSERT(debug.hasBreakpointTrapAtOffset(site.lineOrBytecode()));
600 if (debug.stepModeEnabled(debugFrame->funcIndex())) {
601 if (!ForwardToMainStack(DebugAPI::onSingleStep, cx)) {
602 if (cx->isPropagatingForcedReturn()) {
603 cx->clearPropagatingForcedReturn();
604 // TODO properly handle forced return.
605 JS_ReportErrorASCII(cx,
606 "Unexpected resumption value from onSingleStep");
607 }
608 return false;
609 }
610 }
611 if (debug.hasBreakpointSite(site.lineOrBytecode())) {
612 if (!ForwardToMainStack(DebugAPI::onTrap, cx)) {
613 if (cx->isPropagatingForcedReturn()) {
614 cx->clearPropagatingForcedReturn();
615 // TODO properly handle forced return.
616 JS_ReportErrorASCII(
617 cx, "Unexpected resumption value from breakpoint handler");
618 }
619 return false;
620 }
621 }
622 return true;
623 }
624
625 // Check if the pending exception, if any, is catchable by wasm.
626 static WasmExceptionObject* GetOrWrapWasmException(JitActivation* activation,
627 JSContext* cx) {
628 if (!cx->isExceptionPending()) {
629 return nullptr;
630 }
631
632 // Traps are generally not catchable as wasm exceptions. The only case in
633 // which they are catchable is for Trap::ThrowReported, which the wasm
634 // compiler uses to throw exceptions and is the source of exceptions from C++.
635 bool isTrapThrowReported =
636 activation->isWasmTrapping() &&
637 activation->wasmTrapData().trap == Trap::ThrowReported;
638 if (activation->isWasmTrapping() && !isTrapThrowReported) {
639 return nullptr;
640 }
641
642 if (cx->isThrowingOverRecursed() || cx->isThrowingOutOfMemory()) {
643 return nullptr;
644 }
645
646 mozilla::Maybe<gc::AutoSuppressGC> suppress;
647 if (isTrapThrowReported) {
648 suppress.emplace(cx);
649 }
650
651 // Write the exception out here to exn to avoid having to get the pending
652 // exception and checking for OOM multiple times.
653 RootedValue exn(cx);
654 if (cx->getPendingException(&exn)) {
655 // Check if a JS exception originated from a wasm trap.
656 if (exn.isObject() && exn.toObject().is<ErrorObject>()) {
657 ErrorObject& err = exn.toObject().as<ErrorObject>();
658 if (err.fromWasmTrap()) {
659 return nullptr;
660 }
661 }
662
663 // Get or create a wasm exception to represent the pending exception
664 Rooted<WasmExceptionObject*> wasmExn(cx);
665 if (exn.isObject() && exn.toObject().is<WasmExceptionObject>()) {
666 // We're already throwing a wasm exception
667 wasmExn = &exn.toObject().as<WasmExceptionObject>();
668
669 // If wasm is rethrowing a wrapped JS value, then set the pending
670 // exception on cx to be the wrapped value. This will ensure that if we
671 // unwind out of wasm the wrapper exception will not escape.
672 //
673 // We also do this here, and not at the end of wasm::HandleThrow so that
674 // any DebugAPI calls see the wrapped JS value, not the wrapper
675 // exception.
676 if (wasmExn->isWrappedJSValue()) {
677 // Re-use exn to avoid needing a new root
678 exn = wasmExn->wrappedJSValue();
679 cx->setPendingException(exn, nullptr);
680 }
681 } else {
682 // Wrap all thrown JS values in a wasm exception. This is required so
683 // that all exceptions have tags, and the 'null' JS value becomes a
684 // non-null wasm exception.
685 wasmExn = WasmExceptionObject::wrapJSValue(cx, exn);
686 }
687
688 if (wasmExn) {
689 return wasmExn;
690 }
691 }
692
693 MOZ_ASSERT(cx->isThrowingOutOfMemory());
694 return nullptr;
695 }
696
697 static const wasm::TryNote* FindNonDelegateTryNote(
698 const wasm::Code& code, const uint8_t* pc, const CodeBlock** codeBlock) {
699 const wasm::TryNote* tryNote = code.lookupTryNote((void*)pc, codeBlock);
700 while (tryNote && tryNote->isDelegate()) {
701 pc = (*codeBlock)->base() + tryNote->delegateOffset();
702 const wasm::TryNote* delegateTryNote =
703 code.lookupTryNote((void*)pc, codeBlock);
704 MOZ_RELEASE_ASSERT(delegateTryNote == nullptr ||
705 delegateTryNote->tryBodyBegin() <
706 tryNote->tryBodyBegin());
707 tryNote = delegateTryNote;
708 }
709 return tryNote;
710 }
711
712 // Request tier-2 compilation for the calling wasm function.
713
714 static void WasmHandleRequestTierUp(Instance* instance) {
715 JSContext* cx = instance->cx();
716
717 // Don't turn this into a release assert - TlsContext.get() can be expensive.
718 MOZ_ASSERT(cx == TlsContext.get());
719
720 // Neither this routine nor the stub that calls it make any attempt to
721 // communicate roots to the GC. This is OK because we will only be
722 // compiling code here, which shouldn't GC. Nevertheless ..
723 JS::AutoAssertNoGC nogc(cx);
724
725 JitActivation* activation = CallingActivation(cx);
726 Frame* fp = activation->wasmExitFP();
727
728 // Similarly, don't turn this into a release assert.
729 MOZ_ASSERT(instance == GetNearestEffectiveInstance(fp));
730
731 // Figure out the requesting funcIndex. We could add a field to the
732 // Instance and, in the slow path of BaseCompiler::addHotnessCheck, write it
733 // in there. That would avoid having to call LookupCodeBlock here, but (1)
734 // LookupCodeBlock is pretty cheap and (2) this would make hotness checks
735 // larger. It doesn't seem like a worthwhile tradeoff.
736 void* resumePC = fp->returnAddress();
737 const CodeRange* codeRange;
738 const CodeBlock* codeBlock = LookupCodeBlock(resumePC, &codeRange);
739 MOZ_RELEASE_ASSERT(codeBlock && codeRange);
740
741 uint32_t funcIndex = codeRange->funcIndex();
742
743 // See BaseCompiler::addHotnessCheck for rationale. If this fails, and
744 // `counter` is a very large negative number (close to -2^31), it may be that
745 // a hotness check didn't have its step patched in.
746 int32_t counter = instance->readHotnessCounter(funcIndex);
747 MOZ_RELEASE_ASSERT(counter >= -127 && counter <= -1);
748
749 // Function `funcIndex` is requesting tier-up. This can go one of three ways:
750 // - the request is a duplicate -- ignore
751 // - tier-up compilation succeeds -- we hope
752 // - tier-up compilation fails (eg, OOMs).
753 // We have no feasible way to recover.
754 //
755 // Regardless of the outcome, we want to defer duplicate requests as long as
756 // possible. So set the counter to "infinity" right now.
757 instance->resetHotnessCounter(funcIndex);
758
759 // Submit the collected profiling information for call_ref to be available
760 // for compilation.
761 instance->submitCallRefHints(funcIndex);
762
763 if (JS::Prefs::wasm_lazy_tiering_synchronous()) {
764 UniqueChars error;
765 UniqueCharsVector warnings;
766 mozilla::Atomic<bool> cancelled(false);
767 bool ok = CompilePartialTier2(*codeBlock->code, funcIndex, &error,
768 &warnings, &cancelled);
769 ReportTier2ResultsOffThread(cancelled, ok, mozilla::Some(funcIndex),
770 codeBlock->code->codeMeta().scriptedCaller(),
771 error, warnings);
772 return;
773 }
774
775 // Try to Ion-compile it. Note that `ok == true` signifies either
776 // "duplicate request" or "not a duplicate, and compilation succeeded".
777 bool ok = codeBlock->code->requestTierUp(funcIndex);
778
779 // If compilation failed, there's no feasible way to recover. We use the
780 // 'off thread' logging mechanism to avoid possibly triggering a GC.
781 if (!ok) {
782 wasm::LogOffThread("Failed to tier-up function=%d in instance=%p.",
783 funcIndex, instance);
784 }
785 }
786
787 // Unwind the activation in response to a thrown exception. This function is
788 // responsible for notifying the debugger of each unwound frame.
789 //
790 // This function will look for try-catch handlers and, if not trapping or
791 // throwing an uncatchable exception, will write the handler info in |*rfe|.
792 //
793 // If no try-catch handler is found, return to the caller to continue unwinding
794 // JS JIT frames.
795 void wasm::HandleExceptionWasm(JSContext* cx, JitFrameIter& iter,
796 jit::ResumeFromException* rfe) {
797 MOZ_ASSERT(iter.isWasm());
798 MOZ_ASSERT(CallingActivation(cx) == iter.activation());
799 MOZ_ASSERT(cx->activation()->asJit()->hasWasmExitFP());
800 MOZ_ASSERT(rfe->kind == ExceptionResumeKind::EntryFrame);
801
802 // WasmFrameIter iterates down wasm frames in the activation starting at
803 // JitActivation::wasmExitFP(). Calling WasmFrameIter::startUnwinding pops
804 // JitActivation::wasmExitFP() once each time WasmFrameIter is incremented,
805 // ultimately leaving no wasm exit FP when the WasmFrameIter is done(). This
806 // is necessary to prevent a wasm::DebugFrame from being observed again after
807 // we just called onLeaveFrame (which would lead to the frame being re-added
808 // to the map of live frames, right as it becomes trash).
809
810 #ifdef DEBUG
811 auto onExit = mozilla::MakeScopeExit([cx] {
812 MOZ_ASSERT(!cx->activation()->asJit()->isWasmTrapping(),
813 "unwinding clears the trapping state");
814 MOZ_ASSERT(!cx->activation()->asJit()->hasWasmExitFP(),
815 "unwinding leaves no wasm exit fp");
816 });
817 #endif
818
819 MOZ_ASSERT(!iter.done());
820
821 // Make the iterator adjust the JitActivation so that each popped frame
822 // will not be visible to other FrameIters that are created while we're
823 // unwinding (such as by debugging code).
824 iter.asWasm().setIsLeavingFrames();
825
826 JitActivation* activation = CallingActivation(cx);
827 Rooted<WasmExceptionObject*> wasmExn(cx,
828 GetOrWrapWasmException(activation, cx));
829
830 for (; !iter.done() && iter.isWasm(); ++iter) {
831 // Wasm code can enter same-compartment realms, so reset cx->realm to
832 // this frame's realm.
833 WasmFrameIter& wasmFrame = iter.asWasm();
834 cx->setRealmForJitExceptionHandler(wasmFrame.instance()->realm());
835
836 // Only look for an exception handler if there's a catchable exception.
837 if (wasmExn) {
838 const wasm::Code& code = wasmFrame.instance()->code();
839 const uint8_t* pc = wasmFrame.resumePCinCurrentFrame();
840 const wasm::CodeBlock* codeBlock = nullptr;
841 const wasm::TryNote* tryNote =
842 FindNonDelegateTryNote(code, pc, &codeBlock);
843
844 if (tryNote) {
845 // Skip tryNote if pc is at return stub generated by
846 // wasmCollapseFrameSlow.
847 CallSite site;
848 if (code.lookupCallSite((void*)pc, &site) &&
849 site.kind() == CallSiteKind::ReturnStub) {
850 continue;
851 }
852
853 cx->clearPendingException();
854 wasmFrame.instance()->setPendingException(wasmExn);
855
856 rfe->kind = ExceptionResumeKind::WasmCatch;
857 rfe->framePointer = (uint8_t*)wasmFrame.frame();
858 rfe->instance = wasmFrame.instance();
859
860 rfe->stackPointer =
861 (uint8_t*)(rfe->framePointer - tryNote->landingPadFramePushed());
862 rfe->target = codeBlock->base() + tryNote->landingPadEntryPoint();
863
864 // Make sure to clear trapping state if we got here due to a trap.
865 if (activation->isWasmTrapping()) {
866 activation->finishWasmTrap();
867 }
868 activation->setWasmExitFP(nullptr);
869 return;
870 }
871 }
872
873 if (!wasmFrame.debugEnabled()) {
874 continue;
875 }
876
877 DebugFrame* frame = wasmFrame.debugFrame();
878 frame->clearReturnJSValue();
879
880 // Assume ResumeMode::Terminate if no exception is pending --
881 // no onExceptionUnwind handlers must be fired.
882 if (cx->isExceptionPending()) {
883 if (!ForwardToMainStack(DebugAPI::onExceptionUnwind, cx,
884 AbstractFramePtr(frame))) {
885 if (cx->isPropagatingForcedReturn()) {
886 cx->clearPropagatingForcedReturn();
887 // Unexpected trap return -- raising error since throw recovery
888 // is not yet implemented in the wasm baseline.
889 // TODO properly handle forced return and resume wasm execution.
890 JS_ReportErrorASCII(
891 cx, "Unexpected resumption value from onExceptionUnwind");
892 wasmExn = nullptr;
893 }
894 }
895 }
896
897 bool ok =
898 ForwardToMainStack(DebugAPI::onLeaveFrame, cx, AbstractFramePtr(frame),
899 (const jsbytecode*)nullptr, false);
900 if (ok) {
901 // Unexpected success from the handler onLeaveFrame -- raising error
902 // since throw recovery is not yet implemented in the wasm baseline.
903 // TODO properly handle success and resume wasm execution.
904 JS_ReportErrorASCII(cx, "Unexpected success from onLeaveFrame");
905 wasmExn = nullptr;
906 }
907 frame->leave(cx);
908 }
909
910 // Assert that any pending exception escaping to non-wasm code is not a
911 // wrapper exception object
912 #ifdef DEBUG
913 if (cx->isExceptionPending()) {
914 Rooted<Value> pendingException(cx, cx->getPendingExceptionUnwrapped());
915 MOZ_ASSERT_IF(pendingException.isObject() &&
916 pendingException.toObject().is<WasmExceptionObject>(),
917 !pendingException.toObject()
918 .as<WasmExceptionObject>()
919 .isWrappedJSValue());
920 }
921 #endif
922 }
923
924 static void* WasmHandleThrow(jit::ResumeFromException* rfe) {
925 jit::HandleException(rfe);
926 // Return a pointer to the exception handler trampoline code to jump to from
927 // the throw stub.
928 JSContext* cx = TlsContext.get();
929 return cx->runtime()->jitRuntime()->getExceptionTailReturnValueCheck().value;
930 }
931
932 // Has the same return-value convention as HandleTrap().
933 static void* CheckInterrupt(JSContext* cx, JitActivation* activation) {
934 ResetInterruptState(cx);
935
936 if (!CheckForInterrupt(cx)) {
937 return nullptr;
938 }
939
940 void* resumePC = activation->wasmTrapData().resumePC;
941 activation->finishWasmTrap();
942 return resumePC;
943 }
944
945 // The calling convention between this function and its caller in the stub
946 // generated by GenerateTrapExit() is:
947 // - return nullptr if the stub should jump to the throw stub to unwind
948 // the activation;
949 // - return the (non-null) resumePC that should be jumped if execution should
950 // resume after the trap.
951 static void* WasmHandleTrap() {
952 JSContext* cx = TlsContext.get(); // Cold code
953 JitActivation* activation = CallingActivation(cx);
954
955 switch (activation->wasmTrapData().trap) {
956 case Trap::Unreachable: {
957 ReportTrapError(cx, JSMSG_WASM_UNREACHABLE);
958 return nullptr;
959 }
960 case Trap::IntegerOverflow: {
961 ReportTrapError(cx, JSMSG_WASM_INTEGER_OVERFLOW);
962 return nullptr;
963 }
964 case Trap::InvalidConversionToInteger: {
965 ReportTrapError(cx, JSMSG_WASM_INVALID_CONVERSION);
966 return nullptr;
967 }
968 case Trap::IntegerDivideByZero: {
969 ReportTrapError(cx, JSMSG_WASM_INT_DIVIDE_BY_ZERO);
970 return nullptr;
971 }
972 case Trap::IndirectCallToNull: {
973 ReportTrapError(cx, JSMSG_WASM_IND_CALL_TO_NULL);
974 return nullptr;
975 }
976 case Trap::IndirectCallBadSig: {
977 ReportTrapError(cx, JSMSG_WASM_IND_CALL_BAD_SIG);
978 return nullptr;
979 }
980 case Trap::NullPointerDereference: {
981 ReportTrapError(cx, JSMSG_WASM_DEREF_NULL);
982 return nullptr;
983 }
984 case Trap::BadCast: {
985 ReportTrapError(cx, JSMSG_WASM_BAD_CAST);
986 return nullptr;
987 }
988 case Trap::OutOfBounds: {
989 ReportTrapError(cx, JSMSG_WASM_OUT_OF_BOUNDS);
990 return nullptr;
991 }
992 case Trap::UnalignedAccess: {
993 ReportTrapError(cx, JSMSG_WASM_UNALIGNED_ACCESS);
994 return nullptr;
995 }
996 case Trap::CheckInterrupt:
997 return CheckInterrupt(cx, activation);
998 case Trap::StackOverflow: {
999 // Instance::setInterrupt() causes a fake stack overflow. Since
1000 // Instance::setInterrupt() is called racily, it's possible for a real
1001 // stack overflow to trap, followed by a racy call to setInterrupt().
1002 // Thus, we must check for a real stack overflow first before we
1003 // CheckInterrupt() and possibly resume execution.
1004 AutoCheckRecursionLimit recursion(cx);
1005 if (!recursion.check(cx)) {
1006 return nullptr;
1007 }
1008 if (activation->wasmExitInstance()->isInterrupted()) {
1009 return CheckInterrupt(cx, activation);
1010 }
1011 ReportTrapError(cx, JSMSG_OVER_RECURSED);
1012 return nullptr;
1013 }
1014 case Trap::ThrowReported:
1015 // Error was already reported under another name.
1016 return nullptr;
1017 case Trap::Limit:
1018 break;
1019 }
1020
1021 MOZ_CRASH("unexpected trap");
1022 }
1023
1024 static void WasmReportV128JSCall() {
1025 JSContext* cx = TlsContext.get(); // Cold code
1026 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
1027 JSMSG_WASM_BAD_VAL_TYPE);
1028 }
1029
1030 static int32_t CoerceInPlace_ToInt32(Value* rawVal) {
1031 JSContext* cx = TlsContext.get(); // Cold code
1032
1033 int32_t i32;
1034 RootedValue val(cx, *rawVal);
1035 if (!ToInt32(cx, val, &i32)) {
1036 *rawVal = PoisonedObjectValue(0x42);
1037 return false;
1038 }
1039
1040 *rawVal = Int32Value(i32);
1041 return true;
1042 }
1043
1044 static int32_t CoerceInPlace_ToBigInt(Value* rawVal) {
1045 JSContext* cx = TlsContext.get(); // Cold code
1046
1047 RootedValue val(cx, *rawVal);
1048 BigInt* bi = ToBigInt(cx, val);
1049 if (!bi) {
1050 *rawVal = PoisonedObjectValue(0x43);
1051 return false;
1052 }
1053
1054 *rawVal = BigIntValue(bi);
1055 return true;
1056 }
1057
1058 static int32_t CoerceInPlace_ToNumber(Value* rawVal) {
1059 JSContext* cx = TlsContext.get(); // Cold code
1060
1061 double dbl;
1062 RootedValue val(cx, *rawVal);
1063 if (!ToNumber(cx, val, &dbl)) {
1064 *rawVal = PoisonedObjectValue(0x42);
1065 return false;
1066 }
1067
1068 *rawVal = DoubleValue(dbl);
1069 return true;
1070 }
1071
1072 static void* BoxValue_Anyref(Value* rawVal) {
1073 JSContext* cx = TlsContext.get(); // Cold code
1074 RootedValue val(cx, *rawVal);
1075 RootedAnyRef result(cx, AnyRef::null());
1076 if (!AnyRef::fromJSValue(cx, val, &result)) {
1077 return nullptr;
1078 }
1079 return result.get().forCompiledCode();
1080 }
1081
1082 static int32_t CoerceInPlace_JitEntry(int funcIndex, Instance* instance,
1083 Value* argv) {
1084 JSContext* cx = TlsContext.get(); // Cold code
1085
1086 const Code& code = instance->code();
1087 const FuncType& funcType = code.codeMeta().getFuncType(funcIndex);
1088
1089 for (size_t i = 0; i < funcType.args().length(); i++) {
1090 HandleValue arg = HandleValue::fromMarkedLocation(&argv[i]);
1091 switch (funcType.args()[i].kind()) {
1092 case ValType::I32: {
1093 int32_t i32;
1094 if (!ToInt32(cx, arg, &i32)) {
1095 return false;
1096 }
1097 argv[i] = Int32Value(i32);
1098 break;
1099 }
1100 case ValType::I64: {
1101 // In this case we store a BigInt value as there is no value type
1102 // corresponding directly to an I64. The conversion to I64 happens
1103 // in the JIT entry stub.
1104 BigInt* bigint = ToBigInt(cx, arg);
1105 if (!bigint) {
1106 return false;
1107 }
1108 argv[i] = BigIntValue(bigint);
1109 break;
1110 }
1111 case ValType::F32:
1112 case ValType::F64: {
1113 double dbl;
1114 if (!ToNumber(cx, arg, &dbl)) {
1115 return false;
1116 }
1117 // No need to convert double-to-float for f32, it's done inline
1118 // in the wasm stub later.
1119 argv[i] = DoubleValue(dbl);
1120 break;
1121 }
1122 case ValType::Ref: {
1123 // Guarded against by temporarilyUnsupportedReftypeForEntry()
1124 MOZ_RELEASE_ASSERT(funcType.args()[i].refType().isExtern());
1125 // Perform any fallible boxing that may need to happen so that the JIT
1126 // code does not need to.
1127 if (AnyRef::valueNeedsBoxing(arg)) {
1128 JSObject* boxedValue = AnyRef::boxValue(cx, arg);
1129 if (!boxedValue) {
1130 return false;
1131 }
1132 argv[i] = ObjectOrNullValue(boxedValue);
1133 }
1134 break;
1135 }
1136 case ValType::V128: {
1137 // Guarded against by hasV128ArgOrRet()
1138 MOZ_CRASH("unexpected input argument in CoerceInPlace_JitEntry");
1139 }
1140 default: {
1141 MOZ_CRASH("unexpected input argument in CoerceInPlace_JitEntry");
1142 }
1143 }
1144 }
1145
1146 return true;
1147 }
1148
1149 // Allocate a BigInt without GC, corresponds to the similar VMFunction.
1150 static BigInt* AllocateBigIntTenuredNoGC() {
1151 JSContext* cx = TlsContext.get(); // Cold code (the caller is elaborate)
1152
1153 return cx->newCell<BigInt, NoGC>(gc::Heap::Tenured);
1154 }
1155
1156 static int64_t DivI64(uint32_t x_hi, uint32_t x_lo, uint32_t y_hi,
1157 uint32_t y_lo) {
1158 int64_t x = ((uint64_t)x_hi << 32) + x_lo;
1159 int64_t y = ((uint64_t)y_hi << 32) + y_lo;
1160 MOZ_ASSERT(x != INT64_MIN || y != -1);
1161 MOZ_ASSERT(y != 0);
1162 return x / y;
1163 }
1164
1165 static int64_t UDivI64(uint32_t x_hi, uint32_t x_lo, uint32_t y_hi,
1166 uint32_t y_lo) {
1167 uint64_t x = ((uint64_t)x_hi << 32) + x_lo;
1168 uint64_t y = ((uint64_t)y_hi << 32) + y_lo;
1169 MOZ_ASSERT(y != 0);
1170 return int64_t(x / y);
1171 }
1172
1173 static int64_t ModI64(uint32_t x_hi, uint32_t x_lo, uint32_t y_hi,
1174 uint32_t y_lo) {
1175 int64_t x = ((uint64_t)x_hi << 32) + x_lo;
1176 int64_t y = ((uint64_t)y_hi << 32) + y_lo;
1177 MOZ_ASSERT(x != INT64_MIN || y != -1);
1178 MOZ_ASSERT(y != 0);
1179 return x % y;
1180 }
1181
1182 static int64_t UModI64(uint32_t x_hi, uint32_t x_lo, uint32_t y_hi,
1183 uint32_t y_lo) {
1184 uint64_t x = ((uint64_t)x_hi << 32) + x_lo;
1185 uint64_t y = ((uint64_t)y_hi << 32) + y_lo;
1186 MOZ_ASSERT(y != 0);
1187 return int64_t(x % y);
1188 }
1189
1190 static int64_t TruncateDoubleToInt64(double input) {
1191 // Note: INT64_MAX is not representable in double. It is actually
1192 // INT64_MAX + 1. Therefore also sending the failure value.
1193 if (input >= double(INT64_MAX) || input < double(INT64_MIN) ||
1194 std::isnan(input)) {
1195 return int64_t(0x8000000000000000);
1196 }
1197 return int64_t(input);
1198 }
1199
1200 static uint64_t TruncateDoubleToUint64(double input) {
1201 // Note: UINT64_MAX is not representable in double. It is actually
1202 // UINT64_MAX + 1. Therefore also sending the failure value.
1203 if (input >= double(UINT64_MAX) || input <= -1.0 || std::isnan(input)) {
1204 return int64_t(0x8000000000000000);
1205 }
1206 return uint64_t(input);
1207 }
1208
1209 static int64_t SaturatingTruncateDoubleToInt64(double input) {
1210 // Handle in-range values (except INT64_MIN).
1211 if (fabs(input) < -double(INT64_MIN)) {
1212 return int64_t(input);
1213 }
1214 // Handle NaN.
1215 if (std::isnan(input)) {
1216 return 0;
1217 }
1218 // Handle positive overflow.
1219 if (input > 0) {
1220 return INT64_MAX;
1221 }
1222 // Handle negative overflow.
1223 return INT64_MIN;
1224 }
1225
1226 static uint64_t SaturatingTruncateDoubleToUint64(double input) {
1227 // Handle positive overflow.
1228 if (input >= -double(INT64_MIN) * 2.0) {
1229 return UINT64_MAX;
1230 }
1231 // Handle in-range values.
1232 if (input > -1.0) {
1233 return uint64_t(input);
1234 }
1235 // Handle NaN and negative overflow.
1236 return 0;
1237 }
1238
1239 static double Int64ToDouble(int32_t x_hi, uint32_t x_lo) {
1240 int64_t x = int64_t((uint64_t(x_hi) << 32)) + int64_t(x_lo);
1241 return double(x);
1242 }
1243
1244 static float Int64ToFloat32(int32_t x_hi, uint32_t x_lo) {
1245 int64_t x = int64_t((uint64_t(x_hi) << 32)) + int64_t(x_lo);
1246 return float(x);
1247 }
1248
1249 static double Uint64ToDouble(int32_t x_hi, uint32_t x_lo) {
1250 uint64_t x = (uint64_t(x_hi) << 32) + uint64_t(x_lo);
1251 return double(x);
1252 }
1253
1254 static float Uint64ToFloat32(int32_t x_hi, uint32_t x_lo) {
1255 uint64_t x = (uint64_t(x_hi) << 32) + uint64_t(x_lo);
1256 return float(x);
1257 }
1258
1259 static void WasmArrayMemMove(uint8_t* destArrayData, uint32_t destIndex,
1260 const uint8_t* srcArrayData, uint32_t srcIndex,
1261 uint32_t elementSize, uint32_t count) {
1262 AutoUnsafeCallWithABI unsafe;
1263 memmove(&destArrayData[size_t(elementSize) * destIndex],
1264 &srcArrayData[size_t(elementSize) * srcIndex],
1265 size_t(elementSize) * count);
1266 }
1267
1268 static void WasmArrayRefsMove(GCPtr<AnyRef>* destArrayData, uint32_t destIndex,
1269 AnyRef* srcArrayData, uint32_t srcIndex,
1270 uint32_t count) {
1271 AutoUnsafeCallWithABI unsafe;
1272 GCPtr<AnyRef>* dstBegin = destArrayData + destIndex;
1273 AnyRef* srcBegin = srcArrayData + srcIndex;
1274 // The std::copy performs GCPtr::set() operation under the hood.
1275 if (uintptr_t(dstBegin) < uintptr_t(srcBegin)) {
1276 std::copy(srcBegin, srcBegin + count, dstBegin);
1277 } else {
1278 std::copy_backward(srcBegin, srcBegin + count, dstBegin + count);
1279 }
1280 }
1281
1282 template <class F>
1283 static inline void* FuncCast(F* funcPtr, ABIFunctionType abiType) {
1284 void* pf = JS_FUNC_TO_DATA_PTR(void*, funcPtr);
1285 #ifdef JS_SIMULATOR
1286 pf = Simulator::RedirectNativeFunction(pf, abiType);
1287 #endif
1288 return pf;
1289 }
1290
1291 #ifdef WASM_CODEGEN_DEBUG
1292 void wasm::PrintI32(int32_t val) { fprintf(stderr, "i32(%d) ", val); }
1293
1294 void wasm::PrintPtr(uint8_t* val) { fprintf(stderr, "ptr(%p) ", val); }
1295
1296 void wasm::PrintF32(float val) { fprintf(stderr, "f32(%f) ", val); }
1297
1298 void wasm::PrintF64(double val) { fprintf(stderr, "f64(%lf) ", val); }
1299
1300 void wasm::PrintText(const char* out) { fprintf(stderr, "%s", out); }
1301 #endif
1302
1303 void* wasm::AddressOf(SymbolicAddress imm, ABIFunctionType* abiType) {
1304 // See NeedsBuiltinThunk for a classification of the different names here.
1305 switch (imm) {
1306 case SymbolicAddress::HandleDebugTrap:
1307 *abiType = Args_General0;
1308 return FuncCast(WasmHandleDebugTrap, *abiType);
1309 case SymbolicAddress::HandleRequestTierUp:
1310 *abiType = Args_General1;
1311 return FuncCast(WasmHandleRequestTierUp, *abiType);
1312 case SymbolicAddress::HandleThrow:
1313 *abiType = Args_General1;
1314 return FuncCast(WasmHandleThrow, *abiType);
1315 case SymbolicAddress::HandleTrap:
1316 *abiType = Args_General0;
1317 return FuncCast(WasmHandleTrap, *abiType);
1318 case SymbolicAddress::ReportV128JSCall:
1319 *abiType = Args_General0;
1320 return FuncCast(WasmReportV128JSCall, *abiType);
1321 case SymbolicAddress::CallImport_General:
1322 *abiType = Args_Int32_GeneralInt32Int32General;
1323 return FuncCast(Instance::callImport_general, *abiType);
1324 case SymbolicAddress::CoerceInPlace_ToInt32:
1325 *abiType = Args_General1;
1326 return FuncCast(CoerceInPlace_ToInt32, *abiType);
1327 case SymbolicAddress::CoerceInPlace_ToBigInt:
1328 *abiType = Args_General1;
1329 return FuncCast(CoerceInPlace_ToBigInt, *abiType);
1330 case SymbolicAddress::CoerceInPlace_ToNumber:
1331 *abiType = Args_General1;
1332 return FuncCast(CoerceInPlace_ToNumber, *abiType);
1333 case SymbolicAddress::CoerceInPlace_JitEntry:
1334 *abiType = Args_General3;
1335 return FuncCast(CoerceInPlace_JitEntry, *abiType);
1336 case SymbolicAddress::ToInt32:
1337 *abiType = Args_Int_Double;
1338 return FuncCast<int32_t(double)>(JS::ToInt32, *abiType);
1339 case SymbolicAddress::BoxValue_Anyref:
1340 *abiType = Args_General1;
1341 return FuncCast(BoxValue_Anyref, *abiType);
1342 case SymbolicAddress::AllocateBigInt:
1343 *abiType = Args_General0;
1344 return FuncCast(AllocateBigIntTenuredNoGC, *abiType);
1345 case SymbolicAddress::DivI64:
1346 *abiType = Args_Int64_Int32Int32Int32Int32;
1347 return FuncCast(DivI64, *abiType);
1348 case SymbolicAddress::UDivI64:
1349 *abiType = Args_Int64_Int32Int32Int32Int32;
1350 return FuncCast(UDivI64, *abiType);
1351 case SymbolicAddress::ModI64:
1352 *abiType = Args_Int64_Int32Int32Int32Int32;
1353 return FuncCast(ModI64, *abiType);
1354 case SymbolicAddress::UModI64:
1355 *abiType = Args_Int64_Int32Int32Int32Int32;
1356 return FuncCast(UModI64, *abiType);
1357 case SymbolicAddress::TruncateDoubleToUint64:
1358 *abiType = Args_Int64_Double;
1359 return FuncCast(TruncateDoubleToUint64, *abiType);
1360 case SymbolicAddress::TruncateDoubleToInt64:
1361 *abiType = Args_Int64_Double;
1362 return FuncCast(TruncateDoubleToInt64, *abiType);
1363 case SymbolicAddress::SaturatingTruncateDoubleToUint64:
1364 *abiType = Args_Int64_Double;
1365 return FuncCast(SaturatingTruncateDoubleToUint64, *abiType);
1366 case SymbolicAddress::SaturatingTruncateDoubleToInt64:
1367 *abiType = Args_Int64_Double;
1368 return FuncCast(SaturatingTruncateDoubleToInt64, *abiType);
1369 case SymbolicAddress::Uint64ToDouble:
1370 *abiType = Args_Double_IntInt;
1371 return FuncCast(Uint64ToDouble, *abiType);
1372 case SymbolicAddress::Uint64ToFloat32:
1373 *abiType = Args_Float32_IntInt;
1374 return FuncCast(Uint64ToFloat32, *abiType);
1375 case SymbolicAddress::Int64ToDouble:
1376 *abiType = Args_Double_IntInt;
1377 return FuncCast(Int64ToDouble, *abiType);
1378 case SymbolicAddress::Int64ToFloat32:
1379 *abiType = Args_Float32_IntInt;
1380 return FuncCast(Int64ToFloat32, *abiType);
1381 #if defined(JS_CODEGEN_ARM)
1382 case SymbolicAddress::aeabi_idivmod:
1383 *abiType = Args_Int64_GeneralGeneral;
1384 return FuncCast(__aeabi_idivmod, *abiType);
1385 case SymbolicAddress::aeabi_uidivmod:
1386 *abiType = Args_Int64_GeneralGeneral;
1387 return FuncCast(__aeabi_uidivmod, *abiType);
1388 #endif
1389 case SymbolicAddress::ModD:
1390 *abiType = Args_Double_DoubleDouble;
1391 return FuncCast(NumberMod, *abiType);
1392 case SymbolicAddress::SinNativeD:
1393 *abiType = Args_Double_Double;
1394 return FuncCast<double(double)>(sin, *abiType);
1395 case SymbolicAddress::SinFdlibmD:
1396 *abiType = Args_Double_Double;
1397 return FuncCast<double(double)>(fdlibm_sin, *abiType);
1398 case SymbolicAddress::CosNativeD:
1399 *abiType = Args_Double_Double;
1400 return FuncCast<double(double)>(cos, *abiType);
1401 case SymbolicAddress::CosFdlibmD:
1402 *abiType = Args_Double_Double;
1403 return FuncCast<double(double)>(fdlibm_cos, *abiType);
1404 case SymbolicAddress::TanNativeD:
1405 *abiType = Args_Double_Double;
1406 return FuncCast<double(double)>(tan, *abiType);
1407 case SymbolicAddress::TanFdlibmD:
1408 *abiType = Args_Double_Double;
1409 return FuncCast<double(double)>(fdlibm_tan, *abiType);
1410 case SymbolicAddress::ASinD:
1411 *abiType = Args_Double_Double;
1412 return FuncCast<double(double)>(fdlibm_asin, *abiType);
1413 case SymbolicAddress::ACosD:
1414 *abiType = Args_Double_Double;
1415 return FuncCast<double(double)>(fdlibm_acos, *abiType);
1416 case SymbolicAddress::ATanD:
1417 *abiType = Args_Double_Double;
1418 return FuncCast<double(double)>(fdlibm_atan, *abiType);
1419 case SymbolicAddress::CeilD:
1420 *abiType = Args_Double_Double;
1421 return FuncCast<double(double)>(fdlibm_ceil, *abiType);
1422 case SymbolicAddress::CeilF:
1423 *abiType = Args_Float32_Float32;
1424 return FuncCast<float(float)>(fdlibm_ceilf, *abiType);
1425 case SymbolicAddress::FloorD:
1426 *abiType = Args_Double_Double;
1427 return FuncCast<double(double)>(fdlibm_floor, *abiType);
1428 case SymbolicAddress::FloorF:
1429 *abiType = Args_Float32_Float32;
1430 return FuncCast<float(float)>(fdlibm_floorf, *abiType);
1431 case SymbolicAddress::TruncD:
1432 *abiType = Args_Double_Double;
1433 return FuncCast<double(double)>(fdlibm_trunc, *abiType);
1434 case SymbolicAddress::TruncF:
1435 *abiType = Args_Float32_Float32;
1436 return FuncCast<float(float)>(fdlibm_truncf, *abiType);
1437 case SymbolicAddress::NearbyIntD:
1438 *abiType = Args_Double_Double;
1439 return FuncCast<double(double)>(fdlibm_nearbyint, *abiType);
1440 case SymbolicAddress::NearbyIntF:
1441 *abiType = Args_Float32_Float32;
1442 return FuncCast<float(float)>(fdlibm_nearbyintf, *abiType);
1443 case SymbolicAddress::ExpD:
1444 *abiType = Args_Double_Double;
1445 return FuncCast<double(double)>(fdlibm_exp, *abiType);
1446 case SymbolicAddress::LogD:
1447 *abiType = Args_Double_Double;
1448 return FuncCast<double(double)>(fdlibm_log, *abiType);
1449 case SymbolicAddress::PowD:
1450 *abiType = Args_Double_DoubleDouble;
1451 return FuncCast(ecmaPow, *abiType);
1452 case SymbolicAddress::ATan2D:
1453 *abiType = Args_Double_DoubleDouble;
1454 return FuncCast(ecmaAtan2, *abiType);
1455 case SymbolicAddress::ArrayMemMove:
1456 *abiType = Args_Void_GeneralInt32GeneralInt32Int32Int32;
1457 return FuncCast(WasmArrayMemMove, *abiType);
1458 case SymbolicAddress::ArrayRefsMove:
1459 *abiType = Args_Void_GeneralInt32GeneralInt32Int32;
1460 return FuncCast(WasmArrayRefsMove, *abiType);
1461
1462 case SymbolicAddress::MemoryGrowM32:
1463 *abiType = Args_Int32_GeneralInt32Int32;
1464 MOZ_ASSERT(*abiType == ToABIType(SASigMemoryGrowM32));
1465 return FuncCast(Instance::memoryGrow_m32, *abiType);
1466 case SymbolicAddress::MemoryGrowM64:
1467 *abiType = Args_Int64_GeneralInt64Int32;
1468 MOZ_ASSERT(*abiType == ToABIType(SASigMemoryGrowM64));
1469 return FuncCast(Instance::memoryGrow_m64, *abiType);
1470 case SymbolicAddress::MemorySizeM32:
1471 *abiType = Args_Int32_GeneralInt32;
1472 MOZ_ASSERT(*abiType == ToABIType(SASigMemorySizeM32));
1473 return FuncCast(Instance::memorySize_m32, *abiType);
1474 case SymbolicAddress::MemorySizeM64:
1475 *abiType = Args_Int64_GeneralInt32;
1476 MOZ_ASSERT(*abiType == ToABIType(SASigMemorySizeM64));
1477 return FuncCast(Instance::memorySize_m64, *abiType);
1478 case SymbolicAddress::WaitI32M32:
1479 *abiType = Args_Int32_GeneralInt32Int32Int64Int32;
1480 MOZ_ASSERT(*abiType == ToABIType(SASigWaitI32M32));
1481 return FuncCast(Instance::wait_i32_m32, *abiType);
1482 case SymbolicAddress::WaitI32M64:
1483 *abiType = Args_Int32_GeneralInt64Int32Int64Int32;
1484 MOZ_ASSERT(*abiType == ToABIType(SASigWaitI32M64));
1485 return FuncCast(Instance::wait_i32_m64, *abiType);
1486 case SymbolicAddress::WaitI64M32:
1487 *abiType = Args_Int32_GeneralInt32Int64Int64Int32;
1488 MOZ_ASSERT(*abiType == ToABIType(SASigWaitI64M32));
1489 return FuncCast(Instance::wait_i64_m32, *abiType);
1490 case SymbolicAddress::WaitI64M64:
1491 *abiType = Args_Int32_GeneralInt64Int64Int64Int32;
1492 MOZ_ASSERT(*abiType == ToABIType(SASigWaitI64M64));
1493 return FuncCast(Instance::wait_i64_m64, *abiType);
1494 case SymbolicAddress::WakeM32:
1495 *abiType = Args_Int32_GeneralInt32Int32Int32;
1496 MOZ_ASSERT(*abiType == ToABIType(SASigWakeM32));
1497 return FuncCast(Instance::wake_m32, *abiType);
1498 case SymbolicAddress::WakeM64:
1499 *abiType = Args_Int32_GeneralInt64Int32Int32;
1500 MOZ_ASSERT(*abiType == ToABIType(SASigWakeM64));
1501 return FuncCast(Instance::wake_m64, *abiType);
1502 case SymbolicAddress::MemCopyM32:
1503 *abiType = Args_Int32_GeneralInt32Int32Int32General;
1504 MOZ_ASSERT(*abiType == ToABIType(SASigMemCopyM32));
1505 return FuncCast(Instance::memCopy_m32, *abiType);
1506 case SymbolicAddress::MemCopySharedM32:
1507 *abiType = Args_Int32_GeneralInt32Int32Int32General;
1508 MOZ_ASSERT(*abiType == ToABIType(SASigMemCopySharedM32));
1509 return FuncCast(Instance::memCopyShared_m32, *abiType);
1510 case SymbolicAddress::MemCopyM64:
1511 *abiType = Args_Int32_GeneralInt64Int64Int64General;
1512 MOZ_ASSERT(*abiType == ToABIType(SASigMemCopyM64));
1513 return FuncCast(Instance::memCopy_m64, *abiType);
1514 case SymbolicAddress::MemCopySharedM64:
1515 *abiType = Args_Int32_GeneralInt64Int64Int64General;
1516 MOZ_ASSERT(*abiType == ToABIType(SASigMemCopySharedM64));
1517 return FuncCast(Instance::memCopyShared_m64, *abiType);
1518 case SymbolicAddress::MemCopyAny:
1519 *abiType = Args_Int32_GeneralInt64Int64Int64Int32Int32;
1520 MOZ_ASSERT(*abiType == ToABIType(SASigMemCopyAny));
1521 return FuncCast(Instance::memCopy_any, *abiType);
1522 case SymbolicAddress::DataDrop:
1523 *abiType = Args_Int32_GeneralInt32;
1524 MOZ_ASSERT(*abiType == ToABIType(SASigDataDrop));
1525 return FuncCast(Instance::dataDrop, *abiType);
1526 case SymbolicAddress::MemFillM32:
1527 *abiType = Args_Int32_GeneralInt32Int32Int32General;
1528 MOZ_ASSERT(*abiType == ToABIType(SASigMemFillM32));
1529 return FuncCast(Instance::memFill_m32, *abiType);
1530 case SymbolicAddress::MemFillSharedM32:
1531 *abiType = Args_Int32_GeneralInt32Int32Int32General;
1532 MOZ_ASSERT(*abiType == ToABIType(SASigMemFillSharedM32));
1533 return FuncCast(Instance::memFillShared_m32, *abiType);
1534 case SymbolicAddress::MemFillM64:
1535 *abiType = Args_Int32_GeneralInt64Int32Int64General;
1536 MOZ_ASSERT(*abiType == ToABIType(SASigMemFillM64));
1537 return FuncCast(Instance::memFill_m64, *abiType);
1538 case SymbolicAddress::MemFillSharedM64:
1539 *abiType = Args_Int32_GeneralInt64Int32Int64General;
1540 MOZ_ASSERT(*abiType == ToABIType(SASigMemFillSharedM64));
1541 return FuncCast(Instance::memFillShared_m64, *abiType);
1542 case SymbolicAddress::MemDiscardM32:
1543 *abiType = Args_Int32_GeneralInt32Int32General;
1544 MOZ_ASSERT(*abiType == ToABIType(SASigMemDiscardM32));
1545 return FuncCast(Instance::memDiscard_m32, *abiType);
1546 case SymbolicAddress::MemDiscardSharedM32:
1547 *abiType = Args_Int32_GeneralInt32Int32General;
1548 MOZ_ASSERT(*abiType == ToABIType(SASigMemDiscardSharedM32));
1549 return FuncCast(Instance::memDiscardShared_m32, *abiType);
1550 case SymbolicAddress::MemDiscardM64:
1551 *abiType = Args_Int32_GeneralInt64Int64General;
1552 MOZ_ASSERT(*abiType == ToABIType(SASigMemDiscardM64));
1553 return FuncCast(Instance::memDiscard_m64, *abiType);
1554 case SymbolicAddress::MemDiscardSharedM64:
1555 *abiType = Args_Int32_GeneralInt64Int64General;
1556 MOZ_ASSERT(*abiType == ToABIType(SASigMemDiscardSharedM64));
1557 return FuncCast(Instance::memDiscardShared_m64, *abiType);
1558 case SymbolicAddress::MemInitM32:
1559 *abiType = Args_Int32_GeneralInt32Int32Int32Int32Int32;
1560 MOZ_ASSERT(*abiType == ToABIType(SASigMemInitM32));
1561 return FuncCast(Instance::memInit_m32, *abiType);
1562 case SymbolicAddress::MemInitM64:
1563 *abiType = Args_Int32_GeneralInt64Int32Int32Int32Int32;
1564 MOZ_ASSERT(*abiType == ToABIType(SASigMemInitM64));
1565 return FuncCast(Instance::memInit_m64, *abiType);
1566 case SymbolicAddress::TableCopy:
1567 *abiType = Args_Int32_GeneralInt32Int32Int32Int32Int32;
1568 MOZ_ASSERT(*abiType == ToABIType(SASigTableCopy));
1569 return FuncCast(Instance::tableCopy, *abiType);
1570 case SymbolicAddress::ElemDrop:
1571 *abiType = Args_Int32_GeneralInt32;
1572 MOZ_ASSERT(*abiType == ToABIType(SASigElemDrop));
1573 return FuncCast(Instance::elemDrop, *abiType);
1574 case SymbolicAddress::TableFill:
1575 *abiType = Args_Int32_GeneralInt32GeneralInt32Int32;
1576 MOZ_ASSERT(*abiType == ToABIType(SASigTableFill));
1577 return FuncCast(Instance::tableFill, *abiType);
1578 case SymbolicAddress::TableInit:
1579 *abiType = Args_Int32_GeneralInt32Int32Int32Int32Int32;
1580 MOZ_ASSERT(*abiType == ToABIType(SASigTableInit));
1581 return FuncCast(Instance::tableInit, *abiType);
1582 case SymbolicAddress::TableGet:
1583 *abiType = Args_General_GeneralInt32Int32;
1584 MOZ_ASSERT(*abiType == ToABIType(SASigTableGet));
1585 return FuncCast(Instance::tableGet, *abiType);
1586 case SymbolicAddress::TableGrow:
1587 *abiType = Args_Int32_GeneralGeneralInt32Int32;
1588 MOZ_ASSERT(*abiType == ToABIType(SASigTableGrow));
1589 return FuncCast(Instance::tableGrow, *abiType);
1590 case SymbolicAddress::TableSet:
1591 *abiType = Args_Int32_GeneralInt32GeneralInt32;
1592 MOZ_ASSERT(*abiType == ToABIType(SASigTableSet));
1593 return FuncCast(Instance::tableSet, *abiType);
1594 case SymbolicAddress::TableSize:
1595 *abiType = Args_Int32_GeneralInt32;
1596 MOZ_ASSERT(*abiType == ToABIType(SASigTableSize));
1597 return FuncCast(Instance::tableSize, *abiType);
1598 case SymbolicAddress::RefFunc:
1599 *abiType = Args_General_GeneralInt32;
1600 MOZ_ASSERT(*abiType == ToABIType(SASigRefFunc));
1601 return FuncCast(Instance::refFunc, *abiType);
1602 case SymbolicAddress::PostBarrierEdge:
1603 *abiType = Args_Int32_GeneralGeneral;
1604 MOZ_ASSERT(*abiType == ToABIType(SASigPostBarrierEdge));
1605 return FuncCast(Instance::postBarrierEdge, *abiType);
1606 case SymbolicAddress::PostBarrierEdgePrecise:
1607 *abiType = Args_Int32_GeneralGeneralGeneral;
1608 MOZ_ASSERT(*abiType == ToABIType(SASigPostBarrierEdgePrecise));
1609 return FuncCast(Instance::postBarrierEdgePrecise, *abiType);
1610 case SymbolicAddress::PostBarrierWholeCell:
1611 *abiType = Args_Int32_GeneralGeneral;
1612 MOZ_ASSERT(*abiType == ToABIType(SASigPostBarrierWholeCell));
1613 return FuncCast(Instance::postBarrierWholeCell, *abiType);
1614 case SymbolicAddress::StructNewIL_true:
1615 *abiType = Args_General_GeneralInt32General;
1616 MOZ_ASSERT(*abiType == ToABIType(SASigStructNewIL_true));
1617 return FuncCast(Instance::structNewIL<true>, *abiType);
1618 case SymbolicAddress::StructNewIL_false:
1619 *abiType = Args_General_GeneralInt32General;
1620 MOZ_ASSERT(*abiType == ToABIType(SASigStructNewIL_false));
1621 return FuncCast(Instance::structNewIL<false>, *abiType);
1622 case SymbolicAddress::StructNewOOL_true:
1623 *abiType = Args_General_GeneralInt32General;
1624 MOZ_ASSERT(*abiType == ToABIType(SASigStructNewOOL_true));
1625 return FuncCast(Instance::structNewOOL<true>, *abiType);
1626 case SymbolicAddress::StructNewOOL_false:
1627 *abiType = Args_General_GeneralInt32General;
1628 MOZ_ASSERT(*abiType == ToABIType(SASigStructNewOOL_false));
1629 return FuncCast(Instance::structNewOOL<false>, *abiType);
1630 case SymbolicAddress::ArrayNew_true:
1631 *abiType = Args_General_GeneralInt32Int32General;
1632 MOZ_ASSERT(*abiType == ToABIType(SASigArrayNew_true));
1633 return FuncCast(Instance::arrayNew<true>, *abiType);
1634 case SymbolicAddress::ArrayNew_false:
1635 *abiType = Args_General_GeneralInt32Int32General;
1636 MOZ_ASSERT(*abiType == ToABIType(SASigArrayNew_false));
1637 return FuncCast(Instance::arrayNew<false>, *abiType);
1638 case SymbolicAddress::ArrayNewData:
1639 *abiType = Args_General_GeneralInt32Int32Int32GeneralInt32;
1640 MOZ_ASSERT(*abiType == ToABIType(SASigArrayNewData));
1641 return FuncCast(Instance::arrayNewData, *abiType);
1642 case SymbolicAddress::ArrayNewElem:
1643 *abiType = Args_General_GeneralInt32Int32Int32GeneralInt32;
1644 MOZ_ASSERT(*abiType == ToABIType(SASigArrayNewElem));
1645 return FuncCast(Instance::arrayNewElem, *abiType);
1646 case SymbolicAddress::ArrayInitData:
1647 *abiType = Args_Int32_GeneralGeneralInt32Int32Int32Int32;
1648 MOZ_ASSERT(*abiType == ToABIType(SASigArrayInitData));
1649 return FuncCast(Instance::arrayInitData, *abiType);
1650 case SymbolicAddress::ArrayInitElem:
1651 *abiType = Args_Int32_GeneralGeneralInt32Int32Int32Int32Int32;
1652 MOZ_ASSERT(*abiType == ToABIType(SASigArrayInitElem));
1653 return FuncCast(Instance::arrayInitElem, *abiType);
1654 case SymbolicAddress::ArrayCopy:
1655 *abiType = Args_Int32_GeneralGeneralInt32GeneralInt32Int32Int32;
1656 MOZ_ASSERT(*abiType == ToABIType(SASigArrayCopy));
1657 return FuncCast(Instance::arrayCopy, *abiType);
1658 case SymbolicAddress::SlotsToAllocKindBytesTable:
1659 return (void*)gc::slotsToAllocKindBytes;
1660 case SymbolicAddress::ExceptionNew:
1661 *abiType = Args_General2;
1662 MOZ_ASSERT(*abiType == ToABIType(SASigExceptionNew));
1663 return FuncCast(Instance::exceptionNew, *abiType);
1664 case SymbolicAddress::ThrowException:
1665 *abiType = Args_Int32_GeneralGeneral;
1666 MOZ_ASSERT(*abiType == ToABIType(SASigThrowException));
1667 return FuncCast(Instance::throwException, *abiType);
1668
1669 #ifdef ENABLE_WASM_JSPI
1670 case SymbolicAddress::UpdateSuspenderState:
1671 *abiType = Args_Int32_GeneralGeneralInt32;
1672 MOZ_ASSERT(*abiType == ToABIType(SASigUpdateSuspenderState));
1673 return FuncCast(UpdateSuspenderState, *abiType);
1674 #endif
1675
1676 #ifdef WASM_CODEGEN_DEBUG
1677 case SymbolicAddress::PrintI32:
1678 *abiType = Args_General1;
1679 return FuncCast(PrintI32, *abiType);
1680 case SymbolicAddress::PrintPtr:
1681 *abiType = Args_General1;
1682 return FuncCast(PrintPtr, *abiType);
1683 case SymbolicAddress::PrintF32:
1684 *abiType = Args_Int_Float32;
1685 return FuncCast(PrintF32, *abiType);
1686 case SymbolicAddress::PrintF64:
1687 *abiType = Args_Int_Double;
1688 return FuncCast(PrintF64, *abiType);
1689 case SymbolicAddress::PrintText:
1690 *abiType = Args_General1;
1691 return FuncCast(PrintText, *abiType);
1692 #endif
1693 #define VISIT_BUILTIN_FUNC(op, export, sa_name, abitype, entry, ...) \
1694 case SymbolicAddress::sa_name: \
1695 *abiType = abitype; \
1696 return FuncCast(entry, *abiType);
1697 FOR_EACH_BUILTIN_MODULE_FUNC(VISIT_BUILTIN_FUNC)
1698 #undef VISIT_BUILTIN_FUNC
1699 case SymbolicAddress::Limit:
1700 break;
1701 }
1702
1703 MOZ_CRASH("Bad SymbolicAddress");
1704 }
1705
1706 bool wasm::IsRoundingFunction(SymbolicAddress callee, jit::RoundingMode* mode) {
1707 switch (callee) {
1708 case SymbolicAddress::FloorD:
1709 case SymbolicAddress::FloorF:
1710 *mode = jit::RoundingMode::Down;
1711 return true;
1712 case SymbolicAddress::CeilD:
1713 case SymbolicAddress::CeilF:
1714 *mode = jit::RoundingMode::Up;
1715 return true;
1716 case SymbolicAddress::TruncD:
1717 case SymbolicAddress::TruncF:
1718 *mode = jit::RoundingMode::TowardsZero;
1719 return true;
1720 case SymbolicAddress::NearbyIntD:
1721 case SymbolicAddress::NearbyIntF:
1722 *mode = jit::RoundingMode::NearestTiesToEven;
1723 return true;
1724 default:
1725 return false;
1726 }
1727 }
1728
1729 bool wasm::NeedsBuiltinThunk(SymbolicAddress sym) {
1730 // Also see "The Wasm Builtin ABIs" in WasmFrame.h.
1731 switch (sym) {
1732 // No thunk, because they do their work within the activation
1733 case SymbolicAddress::HandleThrow: // GenerateThrowStub
1734 case SymbolicAddress::HandleTrap: // GenerateTrapExit
1735 return false;
1736
1737 // No thunk, because some work has to be done within the activation before
1738 // the activation exit: when called, arbitrary wasm registers are live and
1739 // must be saved, and the stack pointer may not be aligned for any ABI.
1740 case SymbolicAddress::HandleDebugTrap: // GenerateDebugStub
1741 case SymbolicAddress::HandleRequestTierUp: // GenerateRequestTierUpStub
1742
1743 // No thunk, because their caller manages the activation exit explicitly
1744 case SymbolicAddress::CallImport_General: // GenerateImportInterpExit
1745 case SymbolicAddress::CoerceInPlace_ToInt32: // GenerateImportJitExit
1746 case SymbolicAddress::CoerceInPlace_ToNumber: // GenerateImportJitExit
1747 case SymbolicAddress::CoerceInPlace_ToBigInt: // GenerateImportJitExit
1748 case SymbolicAddress::BoxValue_Anyref: // GenerateImportJitExit
1749 return false;
1750
1751 #ifdef WASM_CODEGEN_DEBUG
1752 // No thunk, because they call directly into C++ code that does not interact
1753 // with the rest of the VM at all.
1754 case SymbolicAddress::PrintI32: // Debug stub printers
1755 case SymbolicAddress::PrintPtr:
1756 case SymbolicAddress::PrintF32:
1757 case SymbolicAddress::PrintF64:
1758 case SymbolicAddress::PrintText:
1759 return false;
1760 #endif
1761
1762 // No thunk because they're just data
1763 case SymbolicAddress::SlotsToAllocKindBytesTable:
1764 return false;
1765
1766 // Everyone else gets a thunk to handle the exit from the activation
1767 case SymbolicAddress::ToInt32:
1768 case SymbolicAddress::DivI64:
1769 case SymbolicAddress::UDivI64:
1770 case SymbolicAddress::ModI64:
1771 case SymbolicAddress::UModI64:
1772 case SymbolicAddress::TruncateDoubleToUint64:
1773 case SymbolicAddress::TruncateDoubleToInt64:
1774 case SymbolicAddress::SaturatingTruncateDoubleToUint64:
1775 case SymbolicAddress::SaturatingTruncateDoubleToInt64:
1776 case SymbolicAddress::Uint64ToDouble:
1777 case SymbolicAddress::Uint64ToFloat32:
1778 case SymbolicAddress::Int64ToDouble:
1779 case SymbolicAddress::Int64ToFloat32:
1780 #if defined(JS_CODEGEN_ARM)
1781 case SymbolicAddress::aeabi_idivmod:
1782 case SymbolicAddress::aeabi_uidivmod:
1783 #endif
1784 case SymbolicAddress::AllocateBigInt:
1785 case SymbolicAddress::ModD:
1786 case SymbolicAddress::SinNativeD:
1787 case SymbolicAddress::SinFdlibmD:
1788 case SymbolicAddress::CosNativeD:
1789 case SymbolicAddress::CosFdlibmD:
1790 case SymbolicAddress::TanNativeD:
1791 case SymbolicAddress::TanFdlibmD:
1792 case SymbolicAddress::ASinD:
1793 case SymbolicAddress::ACosD:
1794 case SymbolicAddress::ATanD:
1795 case SymbolicAddress::CeilD:
1796 case SymbolicAddress::CeilF:
1797 case SymbolicAddress::FloorD:
1798 case SymbolicAddress::FloorF:
1799 case SymbolicAddress::TruncD:
1800 case SymbolicAddress::TruncF:
1801 case SymbolicAddress::NearbyIntD:
1802 case SymbolicAddress::NearbyIntF:
1803 case SymbolicAddress::ExpD:
1804 case SymbolicAddress::LogD:
1805 case SymbolicAddress::PowD:
1806 case SymbolicAddress::ATan2D:
1807 case SymbolicAddress::ArrayMemMove:
1808 case SymbolicAddress::ArrayRefsMove:
1809 case SymbolicAddress::MemoryGrowM32:
1810 case SymbolicAddress::MemoryGrowM64:
1811 case SymbolicAddress::MemorySizeM32:
1812 case SymbolicAddress::MemorySizeM64:
1813 case SymbolicAddress::WaitI32M32:
1814 case SymbolicAddress::WaitI32M64:
1815 case SymbolicAddress::WaitI64M32:
1816 case SymbolicAddress::WaitI64M64:
1817 case SymbolicAddress::WakeM32:
1818 case SymbolicAddress::WakeM64:
1819 case SymbolicAddress::CoerceInPlace_JitEntry:
1820 case SymbolicAddress::ReportV128JSCall:
1821 case SymbolicAddress::MemCopyM32:
1822 case SymbolicAddress::MemCopySharedM32:
1823 case SymbolicAddress::MemCopyM64:
1824 case SymbolicAddress::MemCopySharedM64:
1825 case SymbolicAddress::MemCopyAny:
1826 case SymbolicAddress::DataDrop:
1827 case SymbolicAddress::MemFillM32:
1828 case SymbolicAddress::MemFillSharedM32:
1829 case SymbolicAddress::MemFillM64:
1830 case SymbolicAddress::MemFillSharedM64:
1831 case SymbolicAddress::MemDiscardM32:
1832 case SymbolicAddress::MemDiscardSharedM32:
1833 case SymbolicAddress::MemDiscardM64:
1834 case SymbolicAddress::MemDiscardSharedM64:
1835 case SymbolicAddress::MemInitM32:
1836 case SymbolicAddress::MemInitM64:
1837 case SymbolicAddress::TableCopy:
1838 case SymbolicAddress::ElemDrop:
1839 case SymbolicAddress::TableFill:
1840 case SymbolicAddress::TableGet:
1841 case SymbolicAddress::TableGrow:
1842 case SymbolicAddress::TableInit:
1843 case SymbolicAddress::TableSet:
1844 case SymbolicAddress::TableSize:
1845 case SymbolicAddress::RefFunc:
1846 case SymbolicAddress::PostBarrierEdge:
1847 case SymbolicAddress::PostBarrierEdgePrecise:
1848 case SymbolicAddress::PostBarrierWholeCell:
1849 case SymbolicAddress::ExceptionNew:
1850 case SymbolicAddress::ThrowException:
1851 case SymbolicAddress::StructNewIL_true:
1852 case SymbolicAddress::StructNewIL_false:
1853 case SymbolicAddress::StructNewOOL_true:
1854 case SymbolicAddress::StructNewOOL_false:
1855 case SymbolicAddress::ArrayNew_true:
1856 case SymbolicAddress::ArrayNew_false:
1857 case SymbolicAddress::ArrayNewData:
1858 case SymbolicAddress::ArrayNewElem:
1859 case SymbolicAddress::ArrayInitData:
1860 case SymbolicAddress::ArrayInitElem:
1861 case SymbolicAddress::ArrayCopy:
1862 #define VISIT_BUILTIN_FUNC(op, export, sa_name, ...) \
1863 case SymbolicAddress::sa_name:
1864 FOR_EACH_BUILTIN_MODULE_FUNC(VISIT_BUILTIN_FUNC)
1865 #undef VISIT_BUILTIN_FUNC
1866 #ifdef ENABLE_WASM_JSPI
1867 case SymbolicAddress::UpdateSuspenderState:
1868 #endif
1869 return true;
1870
1871 case SymbolicAddress::Limit:
1872 break;
1873 }
1874
1875 MOZ_CRASH("unexpected symbolic address");
1876 }
1877
1878 // ============================================================================
1879 // [SMDOC] JS Fast Wasm Imports
1880 //
1881 // JS builtins that can be imported by wasm modules and called efficiently
1882 // through thunks. These thunks conform to the internal wasm ABI and thus can be
1883 // patched in for import calls. Calling a JS builtin through a thunk is much
1884 // faster than calling out through the generic import call trampoline which will
1885 // end up in the slowest C++ Instance::callImport path.
1886 //
1887 // Each JS builtin can have several overloads. These must all be enumerated in
1888 // PopulateTypedNatives() so they can be included in the process-wide thunk set.
1889 // Additionally to the traditional overloading based on types, every builtin
1890 // can also have a version implemented by fdlibm or the native math library.
1891 // This is useful for fingerprinting resistance.
1892
1893 #define FOR_EACH_SIN_COS_TAN_NATIVE(_) \
1894 _(math_sin, MathSin) \
1895 _(math_tan, MathTan) \
1896 _(math_cos, MathCos)
1897
1898 #define FOR_EACH_UNARY_NATIVE(_) \
1899 _(math_exp, MathExp) \
1900 _(math_log, MathLog) \
1901 _(math_asin, MathASin) \
1902 _(math_atan, MathATan) \
1903 _(math_acos, MathACos) \
1904 _(math_log10, MathLog10) \
1905 _(math_log2, MathLog2) \
1906 _(math_log1p, MathLog1P) \
1907 _(math_expm1, MathExpM1) \
1908 _(math_sinh, MathSinH) \
1909 _(math_tanh, MathTanH) \
1910 _(math_cosh, MathCosH) \
1911 _(math_asinh, MathASinH) \
1912 _(math_atanh, MathATanH) \
1913 _(math_acosh, MathACosH) \
1914 _(math_sign, MathSign) \
1915 _(math_trunc, MathTrunc) \
1916 _(math_cbrt, MathCbrt)
1917
1918 #define FOR_EACH_BINARY_NATIVE(_) \
1919 _(ecmaAtan2, MathATan2) \
1920 _(ecmaHypot, MathHypot) \
1921 _(ecmaPow, MathPow)
1922
1923 #define DEFINE_SIN_COS_TAN_FLOAT_WRAPPER(func, _) \
1924 static float func##_native_impl_f32(float x) { \
1925 return float(func##_native_impl(double(x))); \
1926 } \
1927 static float func##_fdlibm_impl_f32(float x) { \
1928 return float(func##_fdlibm_impl(double(x))); \
1929 }
1930
1931 #define DEFINE_UNARY_FLOAT_WRAPPER(func, _) \
1932 static float func##_impl_f32(float x) { \
1933 return float(func##_impl(double(x))); \
1934 }
1935
1936 #define DEFINE_BINARY_FLOAT_WRAPPER(func, _) \
1937 static float func##_f32(float x, float y) { \
1938 return float(func(double(x), double(y))); \
1939 }
1940
1941 FOR_EACH_SIN_COS_TAN_NATIVE(DEFINE_SIN_COS_TAN_FLOAT_WRAPPER)
1942 FOR_EACH_UNARY_NATIVE(DEFINE_UNARY_FLOAT_WRAPPER)
1943 FOR_EACH_BINARY_NATIVE(DEFINE_BINARY_FLOAT_WRAPPER)
1944
1945 #undef DEFINE_UNARY_FLOAT_WRAPPER
1946 #undef DEFINE_BINARY_FLOAT_WRAPPER
1947
1948 struct TypedNative {
1949 InlinableNative native;
1950 ABIFunctionType abiType;
1951 enum class FdlibmImpl : uint8_t { No, Yes } fdlibm;
1952
1953 TypedNative(InlinableNative native, ABIFunctionType abiType,
1954 FdlibmImpl fdlibm)
1955 : native(native), abiType(abiType), fdlibm(fdlibm) {}
1956
1957 using Lookup = TypedNative;
1958 static HashNumber hash(const Lookup& l) {
1959 return HashGeneric(uint32_t(l.native), uint32_t(l.abiType),
1960 uint32_t(l.fdlibm));
1961 }
1962 static bool match(const TypedNative& lhs, const Lookup& rhs) {
1963 return lhs.native == rhs.native && lhs.abiType == rhs.abiType &&
1964 lhs.fdlibm == rhs.fdlibm;
1965 }
1966 };
1967
1968 using TypedNativeToFuncPtrMap =
1969 HashMap<TypedNative, void*, TypedNative, SystemAllocPolicy>;
1970
1971 static bool PopulateTypedNatives(TypedNativeToFuncPtrMap* typedNatives) {
1972 #define ADD_OVERLOAD(funcName, native, abiType, fdlibm) \
1973 if (!typedNatives->putNew(TypedNative(InlinableNative::native, abiType, \
1974 TypedNative::FdlibmImpl::fdlibm), \
1975 FuncCast(funcName, abiType))) \
1976 return false;
1977
1978 #define ADD_SIN_COS_TAN_OVERLOADS(funcName, native) \
1979 ADD_OVERLOAD(funcName##_native_impl, native, Args_Double_Double, No) \
1980 ADD_OVERLOAD(funcName##_fdlibm_impl, native, Args_Double_Double, Yes) \
1981 ADD_OVERLOAD(funcName##_native_impl_f32, native, Args_Float32_Float32, No) \
1982 ADD_OVERLOAD(funcName##_fdlibm_impl_f32, native, Args_Float32_Float32, Yes)
1983
1984 #define ADD_UNARY_OVERLOADS(funcName, native) \
1985 ADD_OVERLOAD(funcName##_impl, native, Args_Double_Double, No) \
1986 ADD_OVERLOAD(funcName##_impl_f32, native, Args_Float32_Float32, No)
1987
1988 #define ADD_BINARY_OVERLOADS(funcName, native) \
1989 ADD_OVERLOAD(funcName, native, Args_Double_DoubleDouble, No) \
1990 ADD_OVERLOAD(funcName##_f32, native, Args_Float32_Float32Float32, No)
1991
1992 FOR_EACH_SIN_COS_TAN_NATIVE(ADD_SIN_COS_TAN_OVERLOADS)
1993 FOR_EACH_UNARY_NATIVE(ADD_UNARY_OVERLOADS)
1994 FOR_EACH_BINARY_NATIVE(ADD_BINARY_OVERLOADS)
1995
1996 #undef ADD_UNARY_OVERLOADS
1997 #undef ADD_BINARY_OVERLOADS
1998
1999 return true;
2000 }
2001
2002 #undef FOR_EACH_UNARY_NATIVE
2003 #undef FOR_EACH_BINARY_NATIVE
2004
2005 // ============================================================================
2006 // [SMDOC] Process-wide builtin thunk set
2007 //
2008 // Thunks are inserted between wasm calls and the C++ callee and achieve two
2009 // things:
2010 // - bridging the few differences between the internal wasm ABI and the
2011 // external native ABI (viz. float returns on x86 and soft-fp ARM)
2012 // - executing an exit prologue/epilogue which in turn allows any profiling
2013 // iterator to see the full stack up to the wasm operation that called out
2014 //
2015 // Thunks are created for two kinds of C++ callees, enumerated above:
2016 // - SymbolicAddress: for statically compiled calls in the wasm module
2017 // - Imported JS builtins: optimized calls to imports
2018 //
2019 // All thunks are created up front, lazily, when the first wasm module is
2020 // compiled in the process. Thunks are kept alive until the JS engine shuts down
2021 // in the process. No thunks are created at runtime after initialization. This
2022 // simple scheme allows several simplifications:
2023 // - no reference counting to keep thunks alive
2024 // - no problems toggling W^X permissions which, because of multiple executing
2025 // threads, would require each thunk allocation to be on its own page
2026 // The cost for creating all thunks at once is relatively low since all thunks
2027 // fit within the smallest executable-code allocation quantum (64k).
2028
2029 using TypedNativeToCodeRangeMap =
2030 HashMap<TypedNative, uint32_t, TypedNative, SystemAllocPolicy>;
2031
2032 using SymbolicAddressToCodeRangeArray =
2033 EnumeratedArray<SymbolicAddress, uint32_t, size_t(SymbolicAddress::Limit)>;
2034
2035 struct BuiltinThunks {
2036 uint8_t* codeBase;
2037 size_t codeSize;
2038 CodeRangeVector codeRanges;
2039 TypedNativeToCodeRangeMap typedNativeToCodeRange;
2040 SymbolicAddressToCodeRangeArray symbolicAddressToCodeRange;
2041 uint32_t provisionalLazyJitEntryOffset;
2042
2043 BuiltinThunks() : codeBase(nullptr), codeSize(0) {}
2044
2045 ~BuiltinThunks() {
2046 if (codeBase) {
2047 DeallocateExecutableMemory(codeBase, codeSize);
2048 }
2049 }
2050 };
2051
2052 MOZ_RUNINIT Mutex initBuiltinThunks(mutexid::WasmInitBuiltinThunks);
2053 mozilla::Atomic<const BuiltinThunks*> builtinThunks;
2054
2055 bool wasm::EnsureBuiltinThunksInitialized() {
2056 AutoMarkJitCodeWritableForThread writable;
2057 return EnsureBuiltinThunksInitialized(writable);
2058 }
2059
2060 bool wasm::EnsureBuiltinThunksInitialized(
2061 AutoMarkJitCodeWritableForThread& writable) {
2062 LockGuard<Mutex> guard(initBuiltinThunks);
2063 if (builtinThunks) {
2064 return true;
2065 }
2066
2067 auto thunks = MakeUnique<BuiltinThunks>();
2068 if (!thunks) {
2069 return false;
2070 }
2071
2072 LifoAlloc lifo(BUILTIN_THUNK_LIFO_SIZE, js::MallocArena);
2073 TempAllocator tempAlloc(&lifo);
2074 WasmMacroAssembler masm(tempAlloc);
2075 AutoCreatedBy acb(masm, "wasm::EnsureBuiltinThunksInitialized");
2076
2077 for (auto sym : MakeEnumeratedRange(SymbolicAddress::Limit)) {
2078 if (!NeedsBuiltinThunk(sym)) {
2079 thunks->symbolicAddressToCodeRange[sym] = UINT32_MAX;
2080 continue;
2081 }
2082
2083 uint32_t codeRangeIndex = thunks->codeRanges.length();
2084 thunks->symbolicAddressToCodeRange[sym] = codeRangeIndex;
2085
2086 ABIFunctionType abiType;
2087 void* funcPtr = AddressOf(sym, &abiType);
2088
2089 ExitReason exitReason(sym);
2090
2091 CallableOffsets offsets;
2092 if (!GenerateBuiltinThunk(masm, abiType, exitReason, funcPtr, &offsets)) {
2093 return false;
2094 }
2095 if (!thunks->codeRanges.emplaceBack(CodeRange::BuiltinThunk, offsets)) {
2096 return false;
2097 }
2098 }
2099
2100 TypedNativeToFuncPtrMap typedNatives;
2101 if (!PopulateTypedNatives(&typedNatives)) {
2102 return false;
2103 }
2104
2105 for (TypedNativeToFuncPtrMap::Range r = typedNatives.all(); !r.empty();
2106 r.popFront()) {
2107 TypedNative typedNative = r.front().key();
2108
2109 uint32_t codeRangeIndex = thunks->codeRanges.length();
2110 if (!thunks->typedNativeToCodeRange.putNew(typedNative, codeRangeIndex)) {
2111 return false;
2112 }
2113
2114 ABIFunctionType abiType = typedNative.abiType;
2115 void* funcPtr = r.front().value();
2116
2117 ExitReason exitReason = ExitReason::Fixed::BuiltinNative;
2118
2119 CallableOffsets offsets;
2120 if (!GenerateBuiltinThunk(masm, abiType, exitReason, funcPtr, &offsets)) {
2121 return false;
2122 }
2123 if (!thunks->codeRanges.emplaceBack(CodeRange::BuiltinThunk, offsets)) {
2124 return false;
2125 }
2126 }
2127
2128 // Provisional lazy JitEntry stub: This is a shared stub that can be installed
2129 // in the jit-entry jump table. It uses the JIT ABI and when invoked will
2130 // retrieve (via TlsContext()) and invoke the context-appropriate
2131 // invoke-from-interpreter jit stub, thus serving as the initial, unoptimized
2132 // jit-entry stub for any exported wasm function that has a jit-entry.
2133
2134 #ifdef DEBUG
2135 // We need to allow this machine code to bake in a C++ code pointer, so we
2136 // disable the wasm restrictions while generating this stub.
2137 JitContext jitContext;
2138 bool oldFlag = jitContext.setIsCompilingWasm(false);
2139 #endif
2140
2141 Offsets provisionalLazyJitEntryOffsets;
2142 if (!GenerateProvisionalLazyJitEntryStub(masm,
2143 &provisionalLazyJitEntryOffsets)) {
2144 return false;
2145 }
2146 thunks->provisionalLazyJitEntryOffset = provisionalLazyJitEntryOffsets.begin;
2147
2148 #ifdef DEBUG
2149 jitContext.setIsCompilingWasm(oldFlag);
2150 #endif
2151
2152 masm.finish();
2153 if (masm.oom()) {
2154 return false;
2155 }
2156
2157 size_t allocSize = AlignBytes(masm.bytesNeeded(), ExecutableCodePageSize);
2158
2159 thunks->codeSize = allocSize;
2160 thunks->codeBase = (uint8_t*)AllocateExecutableMemory(
2161 allocSize, ProtectionSetting::Writable, MemCheckKind::MakeUndefined);
2162 if (!thunks->codeBase) {
2163 return false;
2164 }
2165
2166 masm.executableCopy(thunks->codeBase);
2167 memset(thunks->codeBase + masm.bytesNeeded(), 0,
2168 allocSize - masm.bytesNeeded());
2169
2170 masm.processCodeLabels(thunks->codeBase);
2171 PatchDebugSymbolicAccesses(thunks->codeBase, masm);
2172
2173 MOZ_ASSERT(masm.callSites().empty());
2174 MOZ_ASSERT(masm.callSiteTargets().empty());
2175 MOZ_ASSERT(masm.trapSites().empty());
2176 MOZ_ASSERT(masm.tryNotes().empty());
2177 MOZ_ASSERT(masm.codeRangeUnwindInfos().empty());
2178
2179 if (!ExecutableAllocator::makeExecutableAndFlushICache(thunks->codeBase,
2180 thunks->codeSize)) {
2181 return false;
2182 }
2183
2184 builtinThunks = thunks.release();
2185 return true;
2186 }
2187
2188 void wasm::ReleaseBuiltinThunks() {
2189 if (builtinThunks) {
2190 const BuiltinThunks* ptr = builtinThunks;
2191 js_delete(const_cast<BuiltinThunks*>(ptr));
2192 builtinThunks = nullptr;
2193 }
2194 }
2195
2196 void* wasm::SymbolicAddressTarget(SymbolicAddress sym) {
2197 MOZ_ASSERT(builtinThunks);
2198
2199 ABIFunctionType abiType;
2200 void* funcPtr = AddressOf(sym, &abiType);
2201
2202 if (!NeedsBuiltinThunk(sym)) {
2203 return funcPtr;
2204 }
2205
2206 const BuiltinThunks& thunks = *builtinThunks;
2207 uint32_t codeRangeIndex = thunks.symbolicAddressToCodeRange[sym];
2208 return thunks.codeBase + thunks.codeRanges[codeRangeIndex].begin();
2209 }
2210
2211 void* wasm::ProvisionalLazyJitEntryStub() {
2212 MOZ_ASSERT(builtinThunks);
2213
2214 const BuiltinThunks& thunks = *builtinThunks;
2215 return thunks.codeBase + thunks.provisionalLazyJitEntryOffset;
2216 }
2217
2218 static Maybe<ABIFunctionType> ToBuiltinABIFunctionType(
2219 const FuncType& funcType) {
2220 const ValTypeVector& args = funcType.args();
2221 const ValTypeVector& results = funcType.results();
2222
2223 if (results.length() != 1) {
2224 return Nothing();
2225 }
2226
2227 if ((args.length() + 1) > (sizeof(uint32_t) * 8 / ABITypeArgShift)) {
2228 return Nothing();
2229 }
2230
2231 uint32_t abiType = 0;
2232 for (size_t i = 0; i < args.length(); i++) {
2233 switch (args[i].kind()) {
2234 case ValType::F32:
2235 abiType <<= ABITypeArgShift;
2236 abiType |= uint32_t(ABIType::Float32);
2237 break;
2238 case ValType::F64:
2239 abiType <<= ABITypeArgShift;
2240 abiType |= uint32_t(ABIType::Float64);
2241 break;
2242 default:
2243 return Nothing();
2244 }
2245 }
2246
2247 abiType <<= ABITypeArgShift;
2248 switch (results[0].kind()) {
2249 case ValType::F32:
2250 abiType |= uint32_t(ABIType::Float32);
2251 break;
2252 case ValType::F64:
2253 abiType |= uint32_t(ABIType::Float64);
2254 break;
2255 default:
2256 return Nothing();
2257 }
2258
2259 return Some(ABIFunctionType(abiType));
2260 }
2261
2262 void* wasm::MaybeGetBuiltinThunk(JSFunction* f, const FuncType& funcType) {
2263 MOZ_ASSERT(builtinThunks);
2264
2265 if (!f->isNativeFun() || !f->hasJitInfo() ||
2266 f->jitInfo()->type() != JSJitInfo::InlinableNative) {
2267 return nullptr;
2268 }
2269
2270 Maybe<ABIFunctionType> abiType = ToBuiltinABIFunctionType(funcType);
2271 if (!abiType) {
2272 return nullptr;
2273 }
2274
2275 const BuiltinThunks& thunks = *builtinThunks;
2276
2277 // If this function must use the fdlibm implementation first try to lookup
2278 // the fdlibm version. If that version doesn't exist we still fallback to
2279 // the normal native.
2280 if (math_use_fdlibm_for_sin_cos_tan() ||
2281 f->realm()->creationOptions().alwaysUseFdlibm()) {
2282 TypedNative typedNative(f->jitInfo()->inlinableNative, *abiType,
2283 TypedNative::FdlibmImpl::Yes);
2284 auto p =
2285 thunks.typedNativeToCodeRange.readonlyThreadsafeLookup(typedNative);
2286 if (p) {
2287 return thunks.codeBase + thunks.codeRanges[p->value()].begin();
2288 }
2289 }
2290
2291 TypedNative typedNative(f->jitInfo()->inlinableNative, *abiType,
2292 TypedNative::FdlibmImpl::No);
2293 auto p = thunks.typedNativeToCodeRange.readonlyThreadsafeLookup(typedNative);
2294 if (!p) {
2295 return nullptr;
2296 }
2297
2298 return thunks.codeBase + thunks.codeRanges[p->value()].begin();
2299 }
2300
2301 bool wasm::LookupBuiltinThunk(void* pc, const CodeRange** codeRange,
2302 const uint8_t** codeBase) {
2303 if (!builtinThunks) {
2304 return false;
2305 }
2306
2307 const BuiltinThunks& thunks = *builtinThunks;
2308 if (pc < thunks.codeBase || pc >= thunks.codeBase + thunks.codeSize) {
2309 return false;
2310 }
2311
2312 *codeBase = thunks.codeBase;
2313
2314 CodeRange::OffsetInCode target((uint8_t*)pc - thunks.codeBase);
2315 *codeRange = LookupInSorted(thunks.codeRanges, target);
2316
2317 return !!*codeRange;
2318 }