Debian Codegraph @

js/src/wasm/WasmInstance.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/WasmInstance-inl.h"
20
21 #include "mozilla/CheckedInt.h"
22 #include "mozilla/DebugOnly.h"
23
24 #include <algorithm>
25 #include <utility>
26
27 #include "jsmath.h"
28
29 #include "builtin/String.h"
30 #include "gc/Barrier.h"
31 #include "gc/Marking.h"
32 #include "jit/AtomicOperations.h"
33 #include "jit/Disassemble.h"
34 #include "jit/JitCommon.h"
35 #include "jit/JitRuntime.h"
36 #include "jit/Registers.h"
37 #include "js/ForOfIterator.h"
38 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
39 #include "js/Stack.h" // JS::NativeStackLimitMin
40 #include "util/StringBuilder.h"
41 #include "util/Text.h"
42 #include "util/Unicode.h"
43 #include "vm/ArrayBufferObject.h"
44 #include "vm/BigIntType.h"
45 #include "vm/Compartment.h"
46 #include "vm/ErrorObject.h"
47 #include "vm/Interpreter.h"
48 #include "vm/Iteration.h"
49 #include "vm/JitActivation.h"
50 #include "vm/JSFunction.h"
51 #include "vm/PlainObject.h" // js::PlainObject
52 #include "wasm/WasmBuiltins.h"
53 #include "wasm/WasmCode.h"
54 #include "wasm/WasmDebug.h"
55 #include "wasm/WasmDebugFrame.h"
56 #include "wasm/WasmFeatures.h"
57 #include "wasm/WasmHeuristics.h"
58 #include "wasm/WasmInitExpr.h"
59 #include "wasm/WasmJS.h"
60 #include "wasm/WasmMemory.h"
61 #include "wasm/WasmModule.h"
62 #include "wasm/WasmModuleTypes.h"
63 #include "wasm/WasmPI.h"
64 #include "wasm/WasmStubs.h"
65 #include "wasm/WasmTypeDef.h"
66 #include "wasm/WasmValType.h"
67 #include "wasm/WasmValue.h"
68
69 #include "gc/Marking-inl.h"
70 #include "gc/StoreBuffer-inl.h"
71 #include "vm/ArrayBufferObject-inl.h"
72 #include "vm/JSObject-inl.h"
73 #include "wasm/WasmGcObject-inl.h"
74
75 using namespace js;
76 using namespace js::jit;
77 using namespace js::wasm;
78
79 using mozilla::CheckedUint32;
80 using mozilla::DebugOnly;
81 using mozilla::Maybe;
82 using mozilla::Nothing;
83 using mozilla::Some;
84
85 // Instance must be aligned at least as much as any of the integer, float,
86 // or SIMD values that we'd like to store in it.
87 static_assert(alignof(Instance) >=
88 std::max(sizeof(Registers::RegisterContent),
89 sizeof(FloatRegisters::RegisterContent)));
90
91 // The globalArea must be aligned at least as much as an instance. This is
92 // guaranteed to be sufficient for all data types we care about, including
93 // SIMD values. See the above assertion.
94 static_assert(Instance::offsetOfData() % alignof(Instance) == 0);
95
96 // We want the memory base to be the first field, and accessible with no
97 // offset. This incidentally is also an assertion that there is no superclass
98 // with fields.
99 static_assert(Instance::offsetOfMemory0Base() == 0);
100
101 // We want instance fields that are commonly accessed by the JIT to have
102 // compact encodings. A limit of less than 128 bytes is chosen to fit within
103 // the signed 8-bit mod r/m x86 encoding.
104 static_assert(Instance::offsetOfLastCommonJitField() < 128);
105
106 //////////////////////////////////////////////////////////////////////////////
107 //
108 // Functions and invocation.
109
110 FuncDefInstanceData* Instance::funcDefInstanceData(uint32_t funcIndex) const {
111 MOZ_ASSERT(funcIndex >= codeMeta().numFuncImports);
112 uint32_t funcDefIndex = funcIndex - codeMeta().numFuncImports;
113 FuncDefInstanceData* instanceData =
114 (FuncDefInstanceData*)(data() + codeMeta().funcDefsOffsetStart);
115 return &instanceData[funcDefIndex];
116 }
117
118 TypeDefInstanceData* Instance::typeDefInstanceData(uint32_t typeIndex) const {
119 TypeDefInstanceData* instanceData =
120 (TypeDefInstanceData*)(data() + codeMeta().typeDefsOffsetStart);
121 return &instanceData[typeIndex];
122 }
123
124 const void* Instance::addressOfGlobalCell(const GlobalDesc& global) const {
125 const void* cell = data() + global.offset();
126 // Indirect globals store a pointer to their cell in the instance global
127 // data. Dereference it to find the real cell.
128 if (global.isIndirect()) {
129 cell = *(const void**)cell;
130 }
131 return cell;
132 }
133
134 FuncImportInstanceData& Instance::funcImportInstanceData(uint32_t funcIndex) {
135 MOZ_ASSERT(funcIndex < codeMeta().numFuncImports);
136 FuncImportInstanceData* instanceData =
137 (FuncImportInstanceData*)(data() + codeMeta().funcImportsOffsetStart);
138 return instanceData[funcIndex];
139 }
140
141 FuncExportInstanceData& Instance::funcExportInstanceData(
142 uint32_t funcExportIndex) {
143 FuncExportInstanceData* instanceData =
144 (FuncExportInstanceData*)(data() + codeMeta().funcExportsOffsetStart);
145 return instanceData[funcExportIndex];
146 }
147
148 MemoryInstanceData& Instance::memoryInstanceData(uint32_t memoryIndex) const {
149 MemoryInstanceData* instanceData =
150 (MemoryInstanceData*)(data() + codeMeta().memoriesOffsetStart);
151 return instanceData[memoryIndex];
152 }
153
154 TableInstanceData& Instance::tableInstanceData(uint32_t tableIndex) const {
155 TableInstanceData* instanceData =
156 (TableInstanceData*)(data() + codeMeta().tablesOffsetStart);
157 return instanceData[tableIndex];
158 }
159
160 TagInstanceData& Instance::tagInstanceData(uint32_t tagIndex) const {
161 TagInstanceData* instanceData =
162 (TagInstanceData*)(data() + codeMeta().tagsOffsetStart);
163 return instanceData[tagIndex];
164 }
165
166 static bool UnpackResults(JSContext* cx, const ValTypeVector& resultTypes,
167 const Maybe<char*> stackResultsArea, uint64_t* argv,
168 MutableHandleValue rval) {
169 if (!stackResultsArea) {
170 MOZ_ASSERT(resultTypes.length() <= 1);
171 // Result is either one scalar value to unpack to a wasm value, or
172 // an ignored value for a zero-valued function.
173 if (resultTypes.length() == 1) {
174 return ToWebAssemblyValue(cx, rval, resultTypes[0], argv, true);
175 }
176 return true;
177 }
178
179 MOZ_ASSERT(stackResultsArea.isSome());
180 Rooted<ArrayObject*> array(cx);
181 if (!IterableToArray(cx, rval, &array)) {
182 return false;
183 }
184
185 if (resultTypes.length() != array->length()) {
186 UniqueChars expected(JS_smprintf("%zu", resultTypes.length()));
187 UniqueChars got(JS_smprintf("%u", array->length()));
188 if (!expected || !got) {
189 ReportOutOfMemory(cx);
190 return false;
191 }
192
193 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
194 JSMSG_WASM_WRONG_NUMBER_OF_VALUES, expected.get(),
195 got.get());
196 return false;
197 }
198
199 DebugOnly<uint64_t> previousOffset = ~(uint64_t)0;
200
201 ABIResultIter iter(ResultType::Vector(resultTypes));
202 // The values are converted in the order they are pushed on the
203 // abstract WebAssembly stack; switch to iterate in push order.
204 while (!iter.done()) {
205 iter.next();
206 }
207 DebugOnly<bool> seenRegisterResult = false;
208 for (iter.switchToPrev(); !iter.done(); iter.prev()) {
209 const ABIResult& result = iter.cur();
210 MOZ_ASSERT(!seenRegisterResult);
211 // Use rval as a scratch area to hold the extracted result.
212 rval.set(array->getDenseElement(iter.index()));
213 if (result.inRegister()) {
214 // Currently, if a function type has results, there can be only
215 // one register result. If there is only one result, it is
216 // returned as a scalar and not an iterable, so we don't get here.
217 // If there are multiple results, we extract the register result
218 // and set `argv[0]` set to the extracted result, to be returned by
219 // register in the stub. The register result follows any stack
220 // results, so this preserves conversion order.
221 if (!ToWebAssemblyValue(cx, rval, result.type(), argv, true)) {
222 return false;
223 }
224 seenRegisterResult = true;
225 continue;
226 }
227 uint32_t result_size = result.size();
228 MOZ_ASSERT(result_size == 4 || result_size == 8);
229 #ifdef DEBUG
230 if (previousOffset == ~(uint64_t)0) {
231 previousOffset = (uint64_t)result.stackOffset();
232 } else {
233 MOZ_ASSERT(previousOffset - (uint64_t)result_size ==
234 (uint64_t)result.stackOffset());
235 previousOffset -= (uint64_t)result_size;
236 }
237 #endif
238 char* loc = stackResultsArea.value() + result.stackOffset();
239 if (!ToWebAssemblyValue(cx, rval, result.type(), loc, result_size == 8)) {
240 return false;
241 }
242 }
243
244 return true;
245 }
246
247 bool Instance::callImport(JSContext* cx, uint32_t funcImportIndex,
248 unsigned argc, uint64_t* argv) {
249 AssertRealmUnchanged aru(cx);
250
251 const FuncImport& fi = code().funcImport(funcImportIndex);
252 const FuncType& funcType = codeMeta().getFuncType(funcImportIndex);
253
254 ArgTypeVector argTypes(funcType);
255 InvokeArgs args(cx);
256 if (!args.init(cx, argTypes.lengthWithoutStackResults())) {
257 return false;
258 }
259
260 if (funcType.hasUnexposableArgOrRet()) {
261 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
262 JSMSG_WASM_BAD_VAL_TYPE);
263 return false;
264 }
265
266 MOZ_ASSERT(argTypes.lengthWithStackResults() == argc);
267 Maybe<char*> stackResultPointer;
268 size_t lastBoxIndexPlusOne = 0;
269 {
270 JS::AutoAssertNoGC nogc;
271 for (size_t i = 0; i < argc; i++) {
272 const void* rawArgLoc = &argv[i];
273 if (argTypes.isSyntheticStackResultPointerArg(i)) {
274 stackResultPointer = Some(*(char**)rawArgLoc);
275 continue;
276 }
277 size_t naturalIndex = argTypes.naturalIndex(i);
278 ValType type = funcType.args()[naturalIndex];
279 // Avoid boxes creation not to trigger GC.
280 if (ToJSValueMayGC(type)) {
281 lastBoxIndexPlusOne = i + 1;
282 continue;
283 }
284 MutableHandleValue argValue = args[naturalIndex];
285 if (!ToJSValue(cx, rawArgLoc, type, argValue)) {
286 return false;
287 }
288 }
289 }
290
291 // Visit arguments that need to perform allocation in a second loop
292 // after the rest of arguments are converted.
293 for (size_t i = 0; i < lastBoxIndexPlusOne; i++) {
294 if (argTypes.isSyntheticStackResultPointerArg(i)) {
295 continue;
296 }
297 const void* rawArgLoc = &argv[i];
298 size_t naturalIndex = argTypes.naturalIndex(i);
299 ValType type = funcType.args()[naturalIndex];
300 if (!ToJSValueMayGC(type)) {
301 continue;
302 }
303 MOZ_ASSERT(!type.isRefRepr());
304 // The conversions are safe here because source values are not references
305 // and will not be moved.
306 MutableHandleValue argValue = args[naturalIndex];
307 if (!ToJSValue(cx, rawArgLoc, type, argValue)) {
308 return false;
309 }
310 }
311
312 FuncImportInstanceData& import = funcImportInstanceData(funcImportIndex);
313 Rooted<JSObject*> importCallable(cx, import.callable);
314 MOZ_ASSERT(cx->realm() == importCallable->nonCCWRealm());
315
316 RootedValue fval(cx, ObjectValue(*importCallable));
317 RootedValue thisv(cx, UndefinedValue());
318 RootedValue rval(cx);
319 if (!Call(cx, fval, thisv, args, &rval)) {
320 return false;
321 }
322
323 if (!UnpackResults(cx, funcType.results(), stackResultPointer, argv, &rval)) {
324 return false;
325 }
326
327 if (!JitOptions.enableWasmJitExit) {
328 return true;
329 }
330
331 // The import may already have become optimized.
332 void* jitExitCode = code().sharedStubs().base() + fi.jitExitCodeOffset();
333 if (import.code == jitExitCode) {
334 return true;
335 }
336
337 if (!importCallable->is<JSFunction>()) {
338 return true;
339 }
340
341 // Test if the function is JIT compiled.
342 if (!importCallable->as<JSFunction>().hasBytecode()) {
343 return true;
344 }
345
346 JSScript* script = importCallable->as<JSFunction>().nonLazyScript();
347 if (!script->hasJitScript()) {
348 return true;
349 }
350
351 // Skip if the function does not have a signature that allows for a JIT exit.
352 if (!funcType.canHaveJitExit()) {
353 return true;
354 }
355
356 // Let's optimize it!
357
358 import.code = jitExitCode;
359 return true;
360 }
361
362 /* static */ int32_t /* 0 to signal trap; 1 to signal OK */
363 Instance::callImport_general(Instance* instance, int32_t funcImportIndex,
364 int32_t argc, uint64_t* argv) {
365 JSContext* cx = instance->cx();
366 #ifdef ENABLE_WASM_JSPI
367 if (IsSuspendableStackActive(cx)) {
368 struct ImportCallData {
369 Instance* instance;
370 int32_t funcImportIndex;
371 int32_t argc;
372 uint64_t* argv;
373 static bool Call(ImportCallData* data) {
374 Instance* instance = data->instance;
375 JSContext* cx = instance->cx();
376 return instance->callImport(cx, data->funcImportIndex, data->argc,
377 data->argv);
378 }
379 } data = {instance, funcImportIndex, argc, argv};
380 return CallOnMainStack(
381 cx, reinterpret_cast<CallOnMainStackFn>(ImportCallData::Call), &data);
382 }
383 #endif
384 return instance->callImport(cx, funcImportIndex, argc, argv);
385 }
386
387 //////////////////////////////////////////////////////////////////////////////
388 //
389 // Atomic operations and shared memory.
390
391 template <typename ValT, typename PtrT>
392 static int32_t PerformWait(Instance* instance, uint32_t memoryIndex,
393 PtrT byteOffset, ValT value, int64_t timeout_ns) {
394 JSContext* cx = instance->cx();
395
396 if (byteOffset & (sizeof(ValT) - 1)) {
397 ReportTrapError(cx, JSMSG_WASM_UNALIGNED_ACCESS);
398 return -1;
399 }
400
401 if (!instance->memory(memoryIndex)->isShared()) {
402 ReportTrapError(cx, JSMSG_WASM_NONSHARED_WAIT);
403 return -1;
404 }
405
406 size_t memSizeBytes = instance->memory(memoryIndex)->volatileMemoryLength();
407 if (memSizeBytes < sizeof(ValT) || byteOffset > memSizeBytes - sizeof(ValT)) {
408 ReportTrapError(cx, JSMSG_WASM_OUT_OF_BOUNDS);
409 return -1;
410 }
411
412 mozilla::Maybe<mozilla::TimeDuration> timeout;
413 if (timeout_ns >= 0) {
414 timeout = mozilla::Some(
415 mozilla::TimeDuration::FromMicroseconds(double(timeout_ns) / 1000));
416 }
417
418 MOZ_ASSERT(byteOffset <= SIZE_MAX, "Bounds check is broken");
419 switch (atomics_wait_impl(cx, instance->sharedMemoryBuffer(memoryIndex),
420 size_t(byteOffset), value, timeout)) {
421 case FutexThread::WaitResult::OK:
422 return 0;
423 case FutexThread::WaitResult::NotEqual:
424 return 1;
425 case FutexThread::WaitResult::TimedOut:
426 return 2;
427 case FutexThread::WaitResult::Error:
428 return -1;
429 default:
430 MOZ_CRASH();
431 }
432 }
433
434 /* static */ int32_t Instance::wait_i32_m32(Instance* instance,
435 uint32_t byteOffset, int32_t value,
436 int64_t timeout_ns,
437 uint32_t memoryIndex) {
438 MOZ_ASSERT(SASigWaitI32M32.failureMode == FailureMode::FailOnNegI32);
439 return PerformWait(instance, memoryIndex, byteOffset, value, timeout_ns);
440 }
441
442 /* static */ int32_t Instance::wait_i32_m64(Instance* instance,
443 uint64_t byteOffset, int32_t value,
444 int64_t timeout_ns,
445 uint32_t memoryIndex) {
446 MOZ_ASSERT(SASigWaitI32M64.failureMode == FailureMode::FailOnNegI32);
447 return PerformWait(instance, memoryIndex, byteOffset, value, timeout_ns);
448 }
449
450 /* static */ int32_t Instance::wait_i64_m32(Instance* instance,
451 uint32_t byteOffset, int64_t value,
452 int64_t timeout_ns,
453 uint32_t memoryIndex) {
454 MOZ_ASSERT(SASigWaitI64M32.failureMode == FailureMode::FailOnNegI32);
455 return PerformWait(instance, memoryIndex, byteOffset, value, timeout_ns);
456 }
457
458 /* static */ int32_t Instance::wait_i64_m64(Instance* instance,
459 uint64_t byteOffset, int64_t value,
460 int64_t timeout_ns,
461 uint32_t memoryIndex) {
462 MOZ_ASSERT(SASigWaitI64M64.failureMode == FailureMode::FailOnNegI32);
463 return PerformWait(instance, memoryIndex, byteOffset, value, timeout_ns);
464 }
465
466 template <typename PtrT>
467 static int32_t PerformWake(Instance* instance, PtrT byteOffset, int32_t count,
468 uint32_t memoryIndex) {
469 JSContext* cx = instance->cx();
470
471 if (byteOffset & 3) {
472 ReportTrapError(cx, JSMSG_WASM_UNALIGNED_ACCESS);
473 return -1;
474 }
475
476 size_t memSizeBytes = instance->memory(memoryIndex)->volatileMemoryLength();
477 if (memSizeBytes < sizeof(int32_t) ||
478 byteOffset > memSizeBytes - sizeof(int32_t)) {
479 ReportTrapError(cx, JSMSG_WASM_OUT_OF_BOUNDS);
480 return -1;
481 }
482
483 if (!instance->memory(memoryIndex)->isShared()) {
484 return 0;
485 }
486
487 MOZ_ASSERT(byteOffset <= SIZE_MAX, "Bounds check is broken");
488 int64_t woken;
489 if (!atomics_notify_impl(cx, instance->sharedMemoryBuffer(memoryIndex),
490 size_t(byteOffset), int64_t(count), &woken)) {
491 return -1;
492 }
493
494 if (woken > INT32_MAX) {
495 ReportTrapError(cx, JSMSG_WASM_WAKE_OVERFLOW);
496 return -1;
497 }
498
499 return int32_t(woken);
500 }
501
502 /* static */ int32_t Instance::wake_m32(Instance* instance, uint32_t byteOffset,
503 int32_t count, uint32_t memoryIndex) {
504 MOZ_ASSERT(SASigWakeM32.failureMode == FailureMode::FailOnNegI32);
505 return PerformWake(instance, byteOffset, count, memoryIndex);
506 }
507
508 /* static */ int32_t Instance::wake_m64(Instance* instance, uint64_t byteOffset,
509 int32_t count, uint32_t memoryIndex) {
510 MOZ_ASSERT(SASigWakeM32.failureMode == FailureMode::FailOnNegI32);
511 return PerformWake(instance, byteOffset, count, memoryIndex);
512 }
513
514 //////////////////////////////////////////////////////////////////////////////
515 //
516 // Bulk memory operations.
517
518 /* static */ uint32_t Instance::memoryGrow_m32(Instance* instance,
519 uint32_t delta,
520 uint32_t memoryIndex) {
521 MOZ_ASSERT(SASigMemoryGrowM32.failureMode == FailureMode::Infallible);
522 MOZ_ASSERT(!instance->isAsmJS());
523
524 JSContext* cx = instance->cx();
525 Rooted<WasmMemoryObject*> memory(cx, instance->memory(memoryIndex));
526
527 // It is safe to cast to uint32_t, as all limits have been checked inside
528 // grow() and will not have been exceeded for a 32-bit memory.
529 uint32_t ret = uint32_t(WasmMemoryObject::grow(memory, uint64_t(delta), cx));
530
531 // If there has been a moving grow, this Instance should have been notified.
532 MOZ_RELEASE_ASSERT(
533 instance->memoryBase(memoryIndex) ==
534 instance->memory(memoryIndex)->buffer().dataPointerEither());
535
536 return ret;
537 }
538
539 /* static */ uint64_t Instance::memoryGrow_m64(Instance* instance,
540 uint64_t delta,
541 uint32_t memoryIndex) {
542 MOZ_ASSERT(SASigMemoryGrowM64.failureMode == FailureMode::Infallible);
543 MOZ_ASSERT(!instance->isAsmJS());
544
545 JSContext* cx = instance->cx();
546 Rooted<WasmMemoryObject*> memory(cx, instance->memory(memoryIndex));
547
548 uint64_t ret = WasmMemoryObject::grow(memory, delta, cx);
549
550 // If there has been a moving grow, this Instance should have been notified.
551 MOZ_RELEASE_ASSERT(
552 instance->memoryBase(memoryIndex) ==
553 instance->memory(memoryIndex)->buffer().dataPointerEither());
554
555 return ret;
556 }
557
558 /* static */ uint32_t Instance::memorySize_m32(Instance* instance,
559 uint32_t memoryIndex) {
560 MOZ_ASSERT(SASigMemorySizeM32.failureMode == FailureMode::Infallible);
561
562 // This invariant must hold when running Wasm code. Assert it here so we can
563 // write tests for cross-realm calls.
564 DebugOnly<JSContext*> cx = instance->cx();
565 MOZ_ASSERT(cx->realm() == instance->realm());
566
567 Pages pages = instance->memory(memoryIndex)->volatilePages();
568 #ifdef JS_64BIT
569 // Ensure that the memory size is no more than 4GiB.
570 MOZ_ASSERT(pages <= Pages(MaxMemory32PagesValidation));
571 #endif
572 return uint32_t(pages.value());
573 }
574
575 /* static */ uint64_t Instance::memorySize_m64(Instance* instance,
576 uint32_t memoryIndex) {
577 MOZ_ASSERT(SASigMemorySizeM64.failureMode == FailureMode::Infallible);
578
579 // This invariant must hold when running Wasm code. Assert it here so we can
580 // write tests for cross-realm calls.
581 DebugOnly<JSContext*> cx = instance->cx();
582 MOZ_ASSERT(cx->realm() == instance->realm());
583
584 Pages pages = instance->memory(memoryIndex)->volatilePages();
585 #ifdef JS_64BIT
586 MOZ_ASSERT(pages <= Pages(MaxMemory64PagesValidation));
587 #endif
588 return pages.value();
589 }
590
591 template <typename PointerT, typename CopyFuncT, typename IndexT>
592 inline int32_t WasmMemoryCopy(JSContext* cx, PointerT dstMemBase,
593 PointerT srcMemBase, size_t dstMemLen,
594 size_t srcMemLen, IndexT dstByteOffset,
595 IndexT srcByteOffset, IndexT len,
596 CopyFuncT memMove) {
597 if (!MemoryBoundsCheck(dstByteOffset, len, dstMemLen) ||
598 !MemoryBoundsCheck(srcByteOffset, len, srcMemLen)) {
599 ReportTrapError(cx, JSMSG_WASM_OUT_OF_BOUNDS);
600 return -1;
601 }
602
603 memMove(dstMemBase + uintptr_t(dstByteOffset),
604 srcMemBase + uintptr_t(srcByteOffset), size_t(len));
605 return 0;
606 }
607
608 template <typename I>
609 inline int32_t MemoryCopy(JSContext* cx, I dstByteOffset, I srcByteOffset,
610 I len, uint8_t* memBase) {
611 const WasmArrayRawBuffer* rawBuf = WasmArrayRawBuffer::fromDataPtr(memBase);
612 size_t memLen = rawBuf->byteLength();
613 return WasmMemoryCopy(cx, memBase, memBase, memLen, memLen, dstByteOffset,
614 srcByteOffset, len, memmove);
615 }
616
617 template <typename I>
618 inline int32_t MemoryCopyShared(JSContext* cx, I dstByteOffset, I srcByteOffset,
619 I len, uint8_t* memBase) {
620 using RacyMemMove =
621 void (*)(SharedMem<uint8_t*>, SharedMem<uint8_t*>, size_t);
622
623 const WasmSharedArrayRawBuffer* rawBuf =
624 WasmSharedArrayRawBuffer::fromDataPtr(memBase);
625 size_t memLen = rawBuf->volatileByteLength();
626
627 SharedMem<uint8_t*> sharedMemBase = SharedMem<uint8_t*>::shared(memBase);
628 return WasmMemoryCopy<SharedMem<uint8_t*>, RacyMemMove>(
629 cx, sharedMemBase, sharedMemBase, memLen, memLen, dstByteOffset,
630 srcByteOffset, len, AtomicOperations::memmoveSafeWhenRacy);
631 }
632
633 /* static */ int32_t Instance::memCopy_m32(Instance* instance,
634 uint32_t dstByteOffset,
635 uint32_t srcByteOffset, uint32_t len,
636 uint8_t* memBase) {
637 MOZ_ASSERT(SASigMemCopyM32.failureMode == FailureMode::FailOnNegI32);
638 JSContext* cx = instance->cx();
639 return MemoryCopy(cx, dstByteOffset, srcByteOffset, len, memBase);
640 }
641
642 /* static */ int32_t Instance::memCopyShared_m32(Instance* instance,
643 uint32_t dstByteOffset,
644 uint32_t srcByteOffset,
645 uint32_t len,
646 uint8_t* memBase) {
647 MOZ_ASSERT(SASigMemCopySharedM32.failureMode == FailureMode::FailOnNegI32);
648 JSContext* cx = instance->cx();
649 return MemoryCopyShared(cx, dstByteOffset, srcByteOffset, len, memBase);
650 }
651
652 /* static */ int32_t Instance::memCopy_m64(Instance* instance,
653 uint64_t dstByteOffset,
654 uint64_t srcByteOffset, uint64_t len,
655 uint8_t* memBase) {
656 MOZ_ASSERT(SASigMemCopyM64.failureMode == FailureMode::FailOnNegI32);
657 JSContext* cx = instance->cx();
658 return MemoryCopy(cx, dstByteOffset, srcByteOffset, len, memBase);
659 }
660
661 /* static */ int32_t Instance::memCopyShared_m64(Instance* instance,
662 uint64_t dstByteOffset,
663 uint64_t srcByteOffset,
664 uint64_t len,
665 uint8_t* memBase) {
666 MOZ_ASSERT(SASigMemCopySharedM64.failureMode == FailureMode::FailOnNegI32);
667 JSContext* cx = instance->cx();
668 return MemoryCopyShared(cx, dstByteOffset, srcByteOffset, len, memBase);
669 }
670
671 // Dynamic dispatch to get the length of a memory given just the base and
672 // whether it is shared or not. This is only used for memCopy_any, where being
673 // slower is okay.
674 static inline size_t GetVolatileByteLength(uint8_t* memBase, bool isShared) {
675 if (isShared) {
676 return WasmSharedArrayRawBuffer::fromDataPtr(memBase)->volatileByteLength();
677 }
678 return WasmArrayRawBuffer::fromDataPtr(memBase)->byteLength();
679 }
680
681 /* static */ int32_t Instance::memCopy_any(Instance* instance,
682 uint64_t dstByteOffset,
683 uint64_t srcByteOffset, uint64_t len,
684 uint32_t dstMemIndex,
685 uint32_t srcMemIndex) {
686 MOZ_ASSERT(SASigMemCopyAny.failureMode == FailureMode::FailOnNegI32);
687 JSContext* cx = instance->cx();
688
689 using RacyMemMove =
690 void (*)(SharedMem<uint8_t*>, SharedMem<uint8_t*>, size_t);
691
692 const MemoryInstanceData& dstMemory =
693 instance->memoryInstanceData(dstMemIndex);
694 const MemoryInstanceData& srcMemory =
695 instance->memoryInstanceData(srcMemIndex);
696
697 uint8_t* dstMemBase = dstMemory.base;
698 uint8_t* srcMemBase = srcMemory.base;
699
700 size_t dstMemLen = GetVolatileByteLength(dstMemBase, dstMemory.isShared);
701 size_t srcMemLen = GetVolatileByteLength(srcMemBase, srcMemory.isShared);
702
703 return WasmMemoryCopy<SharedMem<uint8_t*>, RacyMemMove>(
704 cx, SharedMem<uint8_t*>::shared(dstMemBase),
705 SharedMem<uint8_t*>::shared(srcMemBase), dstMemLen, srcMemLen,
706 dstByteOffset, srcByteOffset, len, AtomicOperations::memmoveSafeWhenRacy);
707 }
708
709 template <typename T, typename F, typename I>
710 inline int32_t WasmMemoryFill(JSContext* cx, T memBase, size_t memLen,
711 I byteOffset, uint32_t value, I len, F memSet) {
712 if (!MemoryBoundsCheck(byteOffset, len, memLen)) {
713 ReportTrapError(cx, JSMSG_WASM_OUT_OF_BOUNDS);
714 return -1;
715 }
716
717 // The required write direction is upward, but that is not currently
718 // observable as there are no fences nor any read/write protect operation.
719 memSet(memBase + uintptr_t(byteOffset), int(value), size_t(len));
720 return 0;
721 }
722
723 template <typename I>
724 inline int32_t MemoryFill(JSContext* cx, I byteOffset, uint32_t value, I len,
725 uint8_t* memBase) {
726 const WasmArrayRawBuffer* rawBuf = WasmArrayRawBuffer::fromDataPtr(memBase);
727 size_t memLen = rawBuf->byteLength();
728 return WasmMemoryFill(cx, memBase, memLen, byteOffset, value, len, memset);
729 }
730
731 template <typename I>
732 inline int32_t MemoryFillShared(JSContext* cx, I byteOffset, uint32_t value,
733 I len, uint8_t* memBase) {
734 const WasmSharedArrayRawBuffer* rawBuf =
735 WasmSharedArrayRawBuffer::fromDataPtr(memBase);
736 size_t memLen = rawBuf->volatileByteLength();
737 return WasmMemoryFill(cx, SharedMem<uint8_t*>::shared(memBase), memLen,
738 byteOffset, value, len,
739 AtomicOperations::memsetSafeWhenRacy);
740 }
741
742 /* static */ int32_t Instance::memFill_m32(Instance* instance,
743 uint32_t byteOffset, uint32_t value,
744 uint32_t len, uint8_t* memBase) {
745 MOZ_ASSERT(SASigMemFillM32.failureMode == FailureMode::FailOnNegI32);
746 JSContext* cx = instance->cx();
747 return MemoryFill(cx, byteOffset, value, len, memBase);
748 }
749
750 /* static */ int32_t Instance::memFillShared_m32(Instance* instance,
751 uint32_t byteOffset,
752 uint32_t value, uint32_t len,
753 uint8_t* memBase) {
754 MOZ_ASSERT(SASigMemFillSharedM32.failureMode == FailureMode::FailOnNegI32);
755 JSContext* cx = instance->cx();
756 return MemoryFillShared(cx, byteOffset, value, len, memBase);
757 }
758
759 /* static */ int32_t Instance::memFill_m64(Instance* instance,
760 uint64_t byteOffset, uint32_t value,
761 uint64_t len, uint8_t* memBase) {
762 MOZ_ASSERT(SASigMemFillM64.failureMode == FailureMode::FailOnNegI32);
763 JSContext* cx = instance->cx();
764 return MemoryFill(cx, byteOffset, value, len, memBase);
765 }
766
767 /* static */ int32_t Instance::memFillShared_m64(Instance* instance,
768 uint64_t byteOffset,
769 uint32_t value, uint64_t len,
770 uint8_t* memBase) {
771 MOZ_ASSERT(SASigMemFillSharedM64.failureMode == FailureMode::FailOnNegI32);
772 JSContext* cx = instance->cx();
773 return MemoryFillShared(cx, byteOffset, value, len, memBase);
774 }
775
776 static bool BoundsCheckInit(uint32_t dstOffset, uint32_t srcOffset,
777 uint32_t len, size_t memLen, uint32_t segLen) {
778 uint64_t dstOffsetLimit = uint64_t(dstOffset) + uint64_t(len);
779 uint64_t srcOffsetLimit = uint64_t(srcOffset) + uint64_t(len);
780
781 return dstOffsetLimit > memLen || srcOffsetLimit > segLen;
782 }
783
784 static bool BoundsCheckInit(uint64_t dstOffset, uint32_t srcOffset,
785 uint32_t len, size_t memLen, uint32_t segLen) {
786 uint64_t dstOffsetLimit = dstOffset + uint64_t(len);
787 uint64_t srcOffsetLimit = uint64_t(srcOffset) + uint64_t(len);
788
789 return dstOffsetLimit < dstOffset || dstOffsetLimit > memLen ||
790 srcOffsetLimit > segLen;
791 }
792
793 template <typename I>
794 static int32_t MemoryInit(JSContext* cx, Instance* instance,
795 uint32_t memoryIndex, I dstOffset, uint32_t srcOffset,
796 uint32_t len, const DataSegment* maybeSeg) {
797 if (!maybeSeg) {
798 if (len == 0 && srcOffset == 0) {
799 return 0;
800 }
801
802 ReportTrapError(cx, JSMSG_WASM_OUT_OF_BOUNDS);
803 return -1;
804 }
805
806 const DataSegment& seg = *maybeSeg;
807 MOZ_RELEASE_ASSERT(!seg.active());
808
809 const uint32_t segLen = seg.bytes.length();
810 WasmMemoryObject* mem = instance->memory(memoryIndex);
811 const size_t memLen = mem->volatileMemoryLength();
812
813 // We are proposing to copy
814 //
815 // seg.bytes.begin()[ srcOffset .. srcOffset + len - 1 ]
816 // to
817 // memoryBase[ dstOffset .. dstOffset + len - 1 ]
818
819 if (BoundsCheckInit(dstOffset, srcOffset, len, memLen, segLen)) {
820 ReportTrapError(cx, JSMSG_WASM_OUT_OF_BOUNDS);
821 return -1;
822 }
823
824 // The required read/write direction is upward, but that is not currently
825 // observable as there are no fences nor any read/write protect operation.
826 SharedMem<uint8_t*> dataPtr = mem->buffer().dataPointerEither();
827 if (mem->isShared()) {
828 AtomicOperations::memcpySafeWhenRacy(
829 dataPtr + uintptr_t(dstOffset), (uint8_t*)seg.bytes.begin() + srcOffset,
830 len);
831 } else {
832 uint8_t* rawBuf = dataPtr.unwrap(/*Unshared*/);
833 memcpy(rawBuf + uintptr_t(dstOffset),
834 (const char*)seg.bytes.begin() + srcOffset, len);
835 }
836 return 0;
837 }
838
839 /* static */ int32_t Instance::memInit_m32(Instance* instance,
840 uint32_t dstOffset,
841 uint32_t srcOffset, uint32_t len,
842 uint32_t segIndex,
843 uint32_t memIndex) {
844 MOZ_ASSERT(SASigMemInitM32.failureMode == FailureMode::FailOnNegI32);
845 MOZ_RELEASE_ASSERT(size_t(segIndex) < instance->passiveDataSegments_.length(),
846 "ensured by validation");
847
848 JSContext* cx = instance->cx();
849 return MemoryInit(cx, instance, memIndex, dstOffset, srcOffset, len,
850 instance->passiveDataSegments_[segIndex]);
851 }
852
853 /* static */ int32_t Instance::memInit_m64(Instance* instance,
854 uint64_t dstOffset,
855 uint32_t srcOffset, uint32_t len,
856 uint32_t segIndex,
857 uint32_t memIndex) {
858 MOZ_ASSERT(SASigMemInitM64.failureMode == FailureMode::FailOnNegI32);
859 MOZ_RELEASE_ASSERT(size_t(segIndex) < instance->passiveDataSegments_.length(),
860 "ensured by validation");
861
862 JSContext* cx = instance->cx();
863 return MemoryInit(cx, instance, memIndex, dstOffset, srcOffset, len,
864 instance->passiveDataSegments_[segIndex]);
865 }
866
867 //////////////////////////////////////////////////////////////////////////////
868 //
869 // Bulk table operations.
870
871 /* static */ int32_t Instance::tableCopy(Instance* instance, uint32_t dstOffset,
872 uint32_t srcOffset, uint32_t len,
873 uint32_t dstTableIndex,
874 uint32_t srcTableIndex) {
875 MOZ_ASSERT(SASigTableCopy.failureMode == FailureMode::FailOnNegI32);
876
877 JSContext* cx = instance->cx();
878 const SharedTable& srcTable = instance->tables()[srcTableIndex];
879 uint32_t srcTableLen = srcTable->length();
880
881 const SharedTable& dstTable = instance->tables()[dstTableIndex];
882 uint32_t dstTableLen = dstTable->length();
883
884 // Bounds check and deal with arithmetic overflow.
885 uint64_t dstOffsetLimit = uint64_t(dstOffset) + len;
886 uint64_t srcOffsetLimit = uint64_t(srcOffset) + len;
887
888 if (dstOffsetLimit > dstTableLen || srcOffsetLimit > srcTableLen) {
889 ReportTrapError(cx, JSMSG_WASM_OUT_OF_BOUNDS);
890 return -1;
891 }
892
893 bool isOOM = false;
894
895 if (&srcTable == &dstTable && dstOffset > srcOffset) {
896 for (uint32_t i = len; i > 0; i--) {
897 if (!dstTable->copy(cx, *srcTable, dstOffset + (i - 1),
898 srcOffset + (i - 1))) {
899 isOOM = true;
900 break;
901 }
902 }
903 } else if (&srcTable == &dstTable && dstOffset == srcOffset) {
904 // No-op
905 } else {
906 for (uint32_t i = 0; i < len; i++) {
907 if (!dstTable->copy(cx, *srcTable, dstOffset + i, srcOffset + i)) {
908 isOOM = true;
909 break;
910 }
911 }
912 }
913
914 if (isOOM) {
915 return -1;
916 }
917 return 0;
918 }
919
920 #ifdef DEBUG
921 static bool AllSegmentsArePassive(const DataSegmentVector& vec) {
922 for (const DataSegment* seg : vec) {
923 if (seg->active()) {
924 return false;
925 }
926 }
927 return true;
928 }
929 #endif
930
931 bool Instance::initSegments(JSContext* cx,
932 const DataSegmentVector& dataSegments,
933 const ModuleElemSegmentVector& elemSegments) {
934 MOZ_ASSERT_IF(codeMeta().memories.length() == 0,
935 AllSegmentsArePassive(dataSegments));
936
937 Rooted<WasmInstanceObject*> instanceObj(cx, object());
938
939 // Write data/elem segments into memories/tables.
940
941 for (const ModuleElemSegment& seg : elemSegments) {
942 if (seg.active()) {
943 RootedVal offsetVal(cx);
944 if (!seg.offset().evaluate(cx, instanceObj, &offsetVal)) {
945 return false; // OOM
946 }
947
948 const wasm::Table* table = tables()[seg.tableIndex];
949 uint64_t offset = table->addressType() == AddressType::I32
950 ? offsetVal.get().i32()
951 : offsetVal.get().i64();
952
953 uint64_t tableLength = table->length();
954 if (offset > tableLength || tableLength - offset < seg.numElements()) {
955 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
956 JSMSG_WASM_OUT_OF_BOUNDS);
957 return false;
958 }
959
960 if (!initElems(cx, seg.tableIndex, seg, offset)) {
961 return false; // OOM
962 }
963 }
964 }
965
966 for (const DataSegment* seg : dataSegments) {
967 if (!seg->active()) {
968 continue;
969 }
970
971 Rooted<const WasmMemoryObject*> memoryObj(cx, memory(seg->memoryIndex));
972 size_t memoryLength = memoryObj->volatileMemoryLength();
973 uint8_t* memoryBase =
974 memoryObj->buffer().dataPointerEither().unwrap(/* memcpy */);
975
976 RootedVal offsetVal(cx);
977 if (!seg->offset().evaluate(cx, instanceObj, &offsetVal)) {
978 return false; // OOM
979 }
980 uint64_t offset = memoryObj->addressType() == AddressType::I32
981 ? offsetVal.get().i32()
982 : offsetVal.get().i64();
983 uint32_t count = seg->bytes.length();
984
985 if (offset > memoryLength || memoryLength - offset < count) {
986 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
987 JSMSG_WASM_OUT_OF_BOUNDS);
988 return false;
989 }
990 memcpy(memoryBase + uintptr_t(offset), seg->bytes.begin(), count);
991 }
992
993 return true;
994 }
995
996 bool Instance::initElems(JSContext* cx, uint32_t tableIndex,
997 const ModuleElemSegment& seg, uint32_t dstOffset) {
998 Table& table = *tables_[tableIndex];
999 MOZ_ASSERT(dstOffset <= table.length());
1000 MOZ_ASSERT(seg.numElements() <= table.length() - dstOffset);
1001
1002 if (seg.numElements() == 0) {
1003 return true;
1004 }
1005
1006 if (table.isFunction() &&
1007 seg.encoding == ModuleElemSegment::Encoding::Indices) {
1008 // Initialize this table of functions without creating any intermediate
1009 // JSFunctions.
1010 bool ok = iterElemsFunctions(
1011 seg, [&](uint32_t i, void* code, Instance* instance) -> bool {
1012 table.setFuncRef(dstOffset + i, code, instance);
1013 return true;
1014 });
1015 if (!ok) {
1016 return false;
1017 }
1018 } else {
1019 bool ok = iterElemsAnyrefs(cx, seg, [&](uint32_t i, AnyRef ref) -> bool {
1020 table.setRef(dstOffset + i, ref);
1021 return true;
1022 });
1023 if (!ok) {
1024 return false;
1025 }
1026 }
1027
1028 return true;
1029 }
1030
1031 template <typename F>
1032 bool Instance::iterElemsFunctions(const ModuleElemSegment& seg,
1033 const F& onFunc) {
1034 // In the future, we could theoretically get function data (instance + code
1035 // pointer) from segments with the expression encoding without creating
1036 // JSFunctions. But that is not how it works today. We can only bypass the
1037 // creation of JSFunctions for the index encoding.
1038 MOZ_ASSERT(seg.encoding == ModuleElemSegment::Encoding::Indices);
1039
1040 if (seg.numElements() == 0) {
1041 return true;
1042 }
1043
1044 const FuncImportVector& funcImports = code().funcImports();
1045
1046 for (uint32_t i = 0; i < seg.numElements(); i++) {
1047 uint32_t elemFuncIndex = seg.elemIndices[i];
1048
1049 if (elemFuncIndex < funcImports.length()) {
1050 FuncImportInstanceData& import = funcImportInstanceData(elemFuncIndex);
1051 MOZ_ASSERT(import.callable->isCallable());
1052
1053 if (import.callable->is<JSFunction>()) {
1054 JSFunction* fun = &import.callable->as<JSFunction>();
1055 if (!codeMeta().funcImportsAreJS && fun->isWasm()) {
1056 // This element is a wasm function imported from another
1057 // instance. To preserve the === function identity required by
1058 // the JS embedding spec, we must get the imported function's
1059 // underlying CodeRange.funcCheckedCallEntry and Instance so that
1060 // future Table.get()s produce the same function object as was
1061 // imported.
1062 if (!onFunc(i, fun->wasmCheckedCallEntry(), &fun->wasmInstance())) {
1063 return false;
1064 }
1065 continue;
1066 }
1067 }
1068 }
1069
1070 const CodeRange* codeRange;
1071 uint8_t* codeBase;
1072 code().funcCodeRange(elemFuncIndex, &codeRange, &codeBase);
1073 if (!onFunc(i, codeBase + codeRange->funcCheckedCallEntry(), this)) {
1074 return false;
1075 }
1076 }
1077
1078 return true;
1079 }
1080
1081 template <typename F>
1082 bool Instance::iterElemsAnyrefs(JSContext* cx, const ModuleElemSegment& seg,
1083 const F& onAnyRef) {
1084 if (seg.numElements() == 0) {
1085 return true;
1086 }
1087
1088 switch (seg.encoding) {
1089 case ModuleElemSegment::Encoding::Indices: {
1090 // The only types of indices that exist right now are function indices, so
1091 // this code is specialized to functions.
1092
1093 RootedFunction fun(cx);
1094 for (uint32_t i = 0; i < seg.numElements(); i++) {
1095 uint32_t funcIndex = seg.elemIndices[i];
1096 if (!getExportedFunction(cx, funcIndex, &fun) ||
1097 !onAnyRef(i, AnyRef::fromJSObject(*fun.get()))) {
1098 return false;
1099 }
1100 }
1101 break;
1102 }
1103 case ModuleElemSegment::Encoding::Expressions: {
1104 Rooted<WasmInstanceObject*> instanceObj(cx, object());
1105 const ModuleElemSegment::Expressions& exprs = seg.elemExpressions;
1106
1107 UniqueChars error;
1108 // The offset is a dummy because the expression has already been
1109 // validated.
1110 Decoder d(exprs.exprBytes.begin(), exprs.exprBytes.end(), 0, &error);
1111 for (uint32_t i = 0; i < seg.numElements(); i++) {
1112 RootedVal result(cx);
1113 if (!InitExpr::decodeAndEvaluate(cx, instanceObj, d, seg.elemType,
1114 &result)) {
1115 MOZ_ASSERT(!error); // The only possible failure should be OOM.
1116 return false;
1117 }
1118 // We would need to root this AnyRef if we were doing anything other
1119 // than storing it.
1120 AnyRef ref = result.get().ref();
1121 if (!onAnyRef(i, ref)) {
1122 return false;
1123 }
1124 }
1125 break;
1126 }
1127 default:
1128 MOZ_CRASH("unknown encoding type for element segment");
1129 }
1130 return true;
1131 }
1132
1133 /* static */ int32_t Instance::tableInit(Instance* instance, uint32_t dstOffset,
1134 uint32_t srcOffset, uint32_t len,
1135 uint32_t segIndex,
1136 uint32_t tableIndex) {
1137 MOZ_ASSERT(SASigTableInit.failureMode == FailureMode::FailOnNegI32);
1138
1139 MOZ_RELEASE_ASSERT(size_t(segIndex) < instance->passiveElemSegments_.length(),
1140 "ensured by validation");
1141
1142 JSContext* cx = instance->cx();
1143
1144 const InstanceElemSegment& seg = instance->passiveElemSegments_[segIndex];
1145 const uint32_t segLen = seg.length();
1146
1147 Table& table = *instance->tables()[tableIndex];
1148 const uint32_t tableLen = table.length();
1149
1150 // We are proposing to copy
1151 //
1152 // seg[ srcOffset .. srcOffset + len - 1 ]
1153 // to
1154 // tableBase[ dstOffset .. dstOffset + len - 1 ]
1155
1156 // Bounds check and deal with arithmetic overflow.
1157 uint64_t dstOffsetLimit = uint64_t(dstOffset) + uint64_t(len);
1158 uint64_t srcOffsetLimit = uint64_t(srcOffset) + uint64_t(len);
1159
1160 if (dstOffsetLimit > tableLen || srcOffsetLimit > segLen) {
1161 ReportTrapError(cx, JSMSG_WASM_OUT_OF_BOUNDS);
1162 return -1;
1163 }
1164
1165 for (size_t i = 0; i < len; i++) {
1166 table.setRef(dstOffset + i, seg[srcOffset + i]);
1167 }
1168
1169 return 0;
1170 }
1171
1172 /* static */ int32_t Instance::tableFill(Instance* instance, uint32_t start,
1173 void* value, uint32_t len,
1174 uint32_t tableIndex) {
1175 MOZ_ASSERT(SASigTableFill.failureMode == FailureMode::FailOnNegI32);
1176
1177 JSContext* cx = instance->cx();
1178 Table& table = *instance->tables()[tableIndex];
1179
1180 // Bounds check and deal with arithmetic overflow.
1181 uint64_t offsetLimit = uint64_t(start) + uint64_t(len);
1182
1183 if (offsetLimit > table.length()) {
1184 ReportTrapError(cx, JSMSG_WASM_OUT_OF_BOUNDS);
1185 return -1;
1186 }
1187
1188 switch (table.repr()) {
1189 case TableRepr::Ref:
1190 table.fillAnyRef(start, len, AnyRef::fromCompiledCode(value));
1191 break;
1192 case TableRepr::Func:
1193 MOZ_RELEASE_ASSERT(!table.isAsmJS());
1194 table.fillFuncRef(start, len, FuncRef::fromCompiledCode(value), cx);
1195 break;
1196 }
1197
1198 return 0;
1199 }
1200
1201 template <typename I>
1202 static bool WasmDiscardCheck(Instance* instance, I byteOffset, I byteLen,
1203 size_t memLen, bool shared) {
1204 JSContext* cx = instance->cx();
1205
1206 if (byteOffset % wasm::PageSize != 0 || byteLen % wasm::PageSize != 0) {
1207 ReportTrapError(cx, JSMSG_WASM_UNALIGNED_ACCESS);
1208 return false;
1209 }
1210
1211 if (!MemoryBoundsCheck(byteOffset, byteLen, memLen)) {
1212 ReportTrapError(cx, JSMSG_WASM_OUT_OF_BOUNDS);
1213 return false;
1214 }
1215
1216 return true;
1217 }
1218
1219 template <typename I>
1220 static int32_t MemDiscardNotShared(Instance* instance, I byteOffset, I byteLen,
1221 uint8_t* memBase) {
1222 WasmArrayRawBuffer* rawBuf = WasmArrayRawBuffer::fromDataPtr(memBase);
1223 size_t memLen = rawBuf->byteLength();
1224
1225 if (!WasmDiscardCheck(instance, byteOffset, byteLen, memLen, false)) {
1226 return -1;
1227 }
1228 rawBuf->discard(byteOffset, byteLen);
1229
1230 return 0;
1231 }
1232
1233 template <typename I>
1234 static int32_t MemDiscardShared(Instance* instance, I byteOffset, I byteLen,
1235 uint8_t* memBase) {
1236 WasmSharedArrayRawBuffer* rawBuf =
1237 WasmSharedArrayRawBuffer::fromDataPtr(memBase);
1238 size_t memLen = rawBuf->volatileByteLength();
1239
1240 if (!WasmDiscardCheck(instance, byteOffset, byteLen, memLen, true)) {
1241 return -1;
1242 }
1243 rawBuf->discard(byteOffset, byteLen);
1244
1245 return 0;
1246 }
1247
1248 /* static */ int32_t Instance::memDiscard_m32(Instance* instance,
1249 uint32_t byteOffset,
1250 uint32_t byteLen,
1251 uint8_t* memBase) {
1252 return MemDiscardNotShared(instance, byteOffset, byteLen, memBase);
1253 }
1254
1255 /* static */ int32_t Instance::memDiscard_m64(Instance* instance,
1256 uint64_t byteOffset,
1257 uint64_t byteLen,
1258 uint8_t* memBase) {
1259 return MemDiscardNotShared(instance, byteOffset, byteLen, memBase);
1260 }
1261
1262 /* static */ int32_t Instance::memDiscardShared_m32(Instance* instance,
1263 uint32_t byteOffset,
1264 uint32_t byteLen,
1265 uint8_t* memBase) {
1266 return MemDiscardShared(instance, byteOffset, byteLen, memBase);
1267 }
1268
1269 /* static */ int32_t Instance::memDiscardShared_m64(Instance* instance,
1270 uint64_t byteOffset,
1271 uint64_t byteLen,
1272 uint8_t* memBase) {
1273 return MemDiscardShared(instance, byteOffset, byteLen, memBase);
1274 }
1275
1276 /* static */ void* Instance::tableGet(Instance* instance, uint32_t address,
1277 uint32_t tableIndex) {
1278 MOZ_ASSERT(SASigTableGet.failureMode == FailureMode::FailOnInvalidRef);
1279
1280 JSContext* cx = instance->cx();
1281 const Table& table = *instance->tables()[tableIndex];
1282 if (address >= table.length()) {
1283 ReportTrapError(cx, JSMSG_WASM_TABLE_OUT_OF_BOUNDS);
1284 return AnyRef::invalid().forCompiledCode();
1285 }
1286
1287 switch (table.repr()) {
1288 case TableRepr::Ref:
1289 return table.getAnyRef(address).forCompiledCode();
1290 case TableRepr::Func: {
1291 MOZ_RELEASE_ASSERT(!table.isAsmJS());
1292 RootedFunction fun(cx);
1293 if (!table.getFuncRef(cx, address, &fun)) {
1294 return AnyRef::invalid().forCompiledCode();
1295 }
1296 return FuncRef::fromJSFunction(fun).forCompiledCode();
1297 }
1298 }
1299 MOZ_CRASH("Should not happen");
1300 }
1301
1302 /* static */ uint32_t Instance::tableGrow(Instance* instance, void* initValue,
1303 uint32_t delta, uint32_t tableIndex) {
1304 MOZ_ASSERT(SASigTableGrow.failureMode == FailureMode::Infallible);
1305
1306 JSContext* cx = instance->cx();
1307 RootedAnyRef ref(cx, AnyRef::fromCompiledCode(initValue));
1308 Table& table = *instance->tables()[tableIndex];
1309
1310 uint32_t oldSize = table.grow(delta);
1311
1312 if (oldSize != uint32_t(-1) && initValue != nullptr) {
1313 table.fillUninitialized(oldSize, delta, ref, cx);
1314 }
1315
1316 #ifdef DEBUG
1317 if (!table.elemType().isNullable()) {
1318 table.assertRangeNotNull(oldSize, delta);
1319 }
1320 #endif // DEBUG
1321 return oldSize;
1322 }
1323
1324 /* static */ int32_t Instance::tableSet(Instance* instance, uint32_t address,
1325 void* value, uint32_t tableIndex) {
1326 MOZ_ASSERT(SASigTableSet.failureMode == FailureMode::FailOnNegI32);
1327
1328 JSContext* cx = instance->cx();
1329 Table& table = *instance->tables()[tableIndex];
1330
1331 if (address >= table.length()) {
1332 ReportTrapError(cx, JSMSG_WASM_TABLE_OUT_OF_BOUNDS);
1333 return -1;
1334 }
1335
1336 switch (table.repr()) {
1337 case TableRepr::Ref:
1338 table.setAnyRef(address, AnyRef::fromCompiledCode(value));
1339 break;
1340 case TableRepr::Func:
1341 MOZ_RELEASE_ASSERT(!table.isAsmJS());
1342 table.fillFuncRef(address, 1, FuncRef::fromCompiledCode(value), cx);
1343 break;
1344 }
1345
1346 return 0;
1347 }
1348
1349 /* static */ uint32_t Instance::tableSize(Instance* instance,
1350 uint32_t tableIndex) {
1351 MOZ_ASSERT(SASigTableSize.failureMode == FailureMode::Infallible);
1352 Table& table = *instance->tables()[tableIndex];
1353 return table.length();
1354 }
1355
1356 /* static */ void* Instance::refFunc(Instance* instance, uint32_t funcIndex) {
1357 MOZ_ASSERT(SASigRefFunc.failureMode == FailureMode::FailOnInvalidRef);
1358 JSContext* cx = instance->cx();
1359
1360 RootedFunction exportedFunc(cx);
1361 if (!instance->getExportedFunction(cx, funcIndex, &exportedFunc)) {
1362 MOZ_ASSERT(cx->isThrowingOutOfMemory());
1363 return AnyRef::invalid().forCompiledCode();
1364 }
1365 return FuncRef::fromJSFunction(exportedFunc.get()).forCompiledCode();
1366 }
1367
1368 //////////////////////////////////////////////////////////////////////////////
1369 //
1370 // Segment management.
1371
1372 /* static */ int32_t Instance::elemDrop(Instance* instance, uint32_t segIndex) {
1373 MOZ_ASSERT(SASigElemDrop.failureMode == FailureMode::FailOnNegI32);
1374
1375 MOZ_RELEASE_ASSERT(size_t(segIndex) < instance->passiveElemSegments_.length(),
1376 "ensured by validation");
1377
1378 instance->passiveElemSegments_[segIndex].clearAndFree();
1379 return 0;
1380 }
1381
1382 /* static */ int32_t Instance::dataDrop(Instance* instance, uint32_t segIndex) {
1383 MOZ_ASSERT(SASigDataDrop.failureMode == FailureMode::FailOnNegI32);
1384
1385 MOZ_RELEASE_ASSERT(size_t(segIndex) < instance->passiveDataSegments_.length(),
1386 "ensured by validation");
1387
1388 if (!instance->passiveDataSegments_[segIndex]) {
1389 return 0;
1390 }
1391
1392 SharedDataSegment& segRefPtr = instance->passiveDataSegments_[segIndex];
1393 MOZ_RELEASE_ASSERT(!segRefPtr->active());
1394
1395 // Drop this instance's reference to the DataSegment so it can be released.
1396 segRefPtr = nullptr;
1397 return 0;
1398 }
1399
1400 //////////////////////////////////////////////////////////////////////////////
1401 //
1402 // AnyRef support.
1403
1404 /* static */ void Instance::postBarrierEdge(Instance* instance,
1405 AnyRef* location) {
1406 MOZ_ASSERT(SASigPostBarrierEdge.failureMode == FailureMode::Infallible);
1407 MOZ_ASSERT(location);
1408 instance->storeBuffer_->putWasmAnyRef(location);
1409 }
1410
1411 /* static */ void Instance::postBarrierEdgePrecise(Instance* instance,
1412 AnyRef* location,
1413 void* prev) {
1414 MOZ_ASSERT(SASigPostBarrierEdgePrecise.failureMode ==
1415 FailureMode::Infallible);
1416 MOZ_ASSERT(location);
1417 AnyRef next = *location;
1418 InternalBarrierMethods<AnyRef>::postBarrier(
1419 location, wasm::AnyRef::fromCompiledCode(prev), next);
1420 }
1421
1422 /* static */ void Instance::postBarrierWholeCell(Instance* instance,
1423 gc::Cell* object) {
1424 MOZ_ASSERT(SASigPostBarrierWholeCell.failureMode == FailureMode::Infallible);
1425 MOZ_ASSERT(object);
1426 instance->storeBuffer_->putWholeCell(object);
1427 }
1428
1429 //////////////////////////////////////////////////////////////////////////////
1430 //
1431 // GC and exception handling support.
1432
1433 /* static */
1434 template <bool ZeroFields>
1435 void* Instance::structNewIL(Instance* instance, uint32_t typeDefIndex,
1436 gc::AllocSite* allocSite) {
1437 MOZ_ASSERT((ZeroFields ? SASigStructNewIL_true : SASigStructNewIL_false)
1438 .failureMode == FailureMode::FailOnNullPtr);
1439 JSContext* cx = instance->cx();
1440 TypeDefInstanceData* typeDefData =
1441 instance->typeDefInstanceData(typeDefIndex);
1442 // The new struct will be allocated in an initial heap as determined by
1443 // pretenuring logic as set up in `Instance::init`.
1444 return WasmStructObject::createStructIL<ZeroFields>(
1445 cx, typeDefData, allocSite, allocSite->initialHeap());
1446 }
1447
1448 template void* Instance::structNewIL<true>(Instance* instance,
1449 uint32_t typeDefIndex,
1450 gc::AllocSite* allocSite);
1451 template void* Instance::structNewIL<false>(Instance* instance,
1452 uint32_t typeDefIndex,
1453 gc::AllocSite* allocSite);
1454
1455 /* static */
1456 template <bool ZeroFields>
1457 void* Instance::structNewOOL(Instance* instance, uint32_t typeDefIndex,
1458 gc::AllocSite* allocSite) {
1459 MOZ_ASSERT((ZeroFields ? SASigStructNewOOL_true : SASigStructNewOOL_false)
1460 .failureMode == FailureMode::FailOnNullPtr);
1461 JSContext* cx = instance->cx();
1462 TypeDefInstanceData* typeDefData =
1463 instance->typeDefInstanceData(typeDefIndex);
1464 // The new struct will be allocated in an initial heap as determined by
1465 // pretenuring logic as set up in `Instance::init`.
1466 return WasmStructObject::createStructOOL<ZeroFields>(
1467 cx, typeDefData, allocSite, allocSite->initialHeap());
1468 }
1469
1470 template void* Instance::structNewOOL<true>(Instance* instance,
1471 uint32_t typeDefIndex,
1472 gc::AllocSite* allocSite);
1473 template void* Instance::structNewOOL<false>(Instance* instance,
1474 uint32_t typeDefIndex,
1475 gc::AllocSite* allocSite);
1476
1477 /* static */
1478 template <bool ZeroFields>
1479 void* Instance::arrayNew(Instance* instance, uint32_t numElements,
1480 uint32_t typeDefIndex, gc::AllocSite* allocSite) {
1481 MOZ_ASSERT(
1482 (ZeroFields ? SASigArrayNew_true : SASigArrayNew_false).failureMode ==
1483 FailureMode::FailOnNullPtr);
1484 JSContext* cx = instance->cx();
1485 TypeDefInstanceData* typeDefData =
1486 instance->typeDefInstanceData(typeDefIndex);
1487 // The new array will be allocated in an initial heap as determined by
1488 // pretenuring logic as set up in `Instance::init`.
1489 return WasmArrayObject::createArray<ZeroFields>(
1490 cx, typeDefData, allocSite, allocSite->initialHeap(), numElements);
1491 }
1492
1493 template void* Instance::arrayNew<true>(Instance* instance,
1494 uint32_t numElements,
1495 uint32_t typeDefIndex,
1496 gc::AllocSite* allocSite);
1497 template void* Instance::arrayNew<false>(Instance* instance,
1498 uint32_t numElements,
1499 uint32_t typeDefIndex,
1500 gc::AllocSite* allocSite);
1501
1502 // Copies from a data segment into a wasm GC array. Performs the necessary
1503 // bounds checks, accounting for the array's element size. If this function
1504 // returns false, it has already reported a trap error. Null arrays should
1505 // be handled in the caller.
1506 static bool ArrayCopyFromData(JSContext* cx, Handle<WasmArrayObject*> arrayObj,
1507 uint32_t arrayIndex, const DataSegment* seg,
1508 uint32_t segByteOffset, uint32_t numElements) {
1509 uint32_t elemSize = arrayObj->typeDef().arrayType().elementType().size();
1510
1511 // Compute the number of bytes to copy, ensuring it's below 2^32.
1512 CheckedUint32 numBytesToCopy =
1513 CheckedUint32(numElements) * CheckedUint32(elemSize);
1514 if (!numBytesToCopy.isValid()) {
1515 // Because the request implies that 2^32 or more bytes are to be copied.
1516 ReportTrapError(cx, JSMSG_WASM_OUT_OF_BOUNDS);
1517 return false;
1518 }
1519
1520 // Range-check the copy. The obvious thing to do is to compute the offset
1521 // of the last byte to copy, but that would cause underflow in the
1522 // zero-length-and-zero-offset case. Instead, compute that value plus one;
1523 // in other words the offset of the first byte *not* to copy.
1524 CheckedUint32 lastByteOffsetPlus1 =
1525 CheckedUint32(segByteOffset) + numBytesToCopy;
1526
1527 CheckedUint32 numBytesAvailable(seg->bytes.length());
1528 if (!lastByteOffsetPlus1.isValid() || !numBytesAvailable.isValid() ||
1529 lastByteOffsetPlus1.value() > numBytesAvailable.value()) {
1530 // Because the last byte to copy doesn't exist inside `seg->bytes`.
1531 ReportTrapError(cx, JSMSG_WASM_OUT_OF_BOUNDS);
1532 return false;
1533 }
1534
1535 // Range check the destination array.
1536 uint64_t dstNumElements = uint64_t(arrayObj->numElements_);
1537 if (uint64_t(arrayIndex) + uint64_t(numElements) > dstNumElements) {
1538 ReportTrapError(cx, JSMSG_WASM_OUT_OF_BOUNDS);
1539 return false;
1540 }
1541
1542 // This value is safe due to the previous range check on number of elements.
1543 // (We know the full result fits in the array, and we can't overflow uint64_t
1544 // since elemSize caps out at 16.)
1545 uint64_t dstByteOffset = uint64_t(arrayIndex) * uint64_t(elemSize);
1546
1547 // Because `numBytesToCopy` is an in-range `CheckedUint32`, the cast to
1548 // `size_t` is safe even on a 32-bit target.
1549 if (numElements != 0) {
1550 memcpy(&arrayObj->data_[dstByteOffset], &seg->bytes[segByteOffset],
1551 size_t(numBytesToCopy.value()));
1552 }
1553
1554 return true;
1555 }
1556
1557 // Copies from an element segment into a wasm GC array. Performs the necessary
1558 // bounds checks, accounting for the array's element size. If this function
1559 // returns false, it has already reported a trap error.
1560 static bool ArrayCopyFromElem(JSContext* cx, Handle<WasmArrayObject*> arrayObj,
1561 uint32_t arrayIndex,
1562 const InstanceElemSegment& seg,
1563 uint32_t segOffset, uint32_t numElements) {
1564 // Range-check the copy. As in ArrayCopyFromData, compute the index of the
1565 // last element to copy, plus one.
1566 CheckedUint32 lastIndexPlus1 =
1567 CheckedUint32(segOffset) + CheckedUint32(numElements);
1568 CheckedUint32 numElemsAvailable(seg.length());
1569 if (!lastIndexPlus1.isValid() || !numElemsAvailable.isValid() ||
1570 lastIndexPlus1.value() > numElemsAvailable.value()) {
1571 // Because the last element to copy doesn't exist inside the segment.
1572 ReportTrapError(cx, JSMSG_WASM_OUT_OF_BOUNDS);
1573 return false;
1574 }
1575
1576 // Range check the destination array.
1577 uint64_t dstNumElements = uint64_t(arrayObj->numElements_);
1578 if (uint64_t(arrayIndex) + uint64_t(numElements) > dstNumElements) {
1579 ReportTrapError(cx, JSMSG_WASM_OUT_OF_BOUNDS);
1580 return false;
1581 }
1582
1583 GCPtr<AnyRef>* dst = reinterpret_cast<GCPtr<AnyRef>*>(arrayObj->data_);
1584 for (uint32_t i = 0; i < numElements; i++) {
1585 dst[arrayIndex + i] = seg[segOffset + i];
1586 }
1587
1588 return true;
1589 }
1590
1591 // Creates an array (WasmArrayObject) containing `numElements` of type
1592 // described by `typeDef`. Initialises it with data copied from the data
1593 // segment whose index is `segIndex`, starting at byte offset `segByteOffset`
1594 // in the segment. Traps if the segment doesn't hold enough bytes to fill the
1595 // array.
1596 /* static */ void* Instance::arrayNewData(
1597 Instance* instance, uint32_t segByteOffset, uint32_t numElements,
1598 uint32_t typeDefIndex, gc::AllocSite* allocSite, uint32_t segIndex) {
1599 MOZ_ASSERT(SASigArrayNewData.failureMode == FailureMode::FailOnNullPtr);
1600 JSContext* cx = instance->cx();
1601 TypeDefInstanceData* typeDefData =
1602 instance->typeDefInstanceData(typeDefIndex);
1603
1604 // Check that the data segment is valid for use.
1605 MOZ_RELEASE_ASSERT(size_t(segIndex) < instance->passiveDataSegments_.length(),
1606 "ensured by validation");
1607 const DataSegment* seg = instance->passiveDataSegments_[segIndex];
1608
1609 // `seg` will be nullptr if the segment has already been 'data.drop'ed
1610 // (either implicitly in the case of 'active' segments during instantiation,
1611 // or explicitly by the data.drop instruction.) In that case we can
1612 // continue only if there's no need to copy any data out of it.
1613 if (!seg && (numElements != 0 || segByteOffset != 0)) {
1614 ReportTrapError(cx, JSMSG_WASM_OUT_OF_BOUNDS);
1615 return nullptr;
1616 }
1617 // At this point, if `seg` is null then `numElements` and `segByteOffset`
1618 // are both zero.
1619
1620 Rooted<WasmArrayObject*> arrayObj(
1621 cx,
1622 WasmArrayObject::createArray<true>(
1623 cx, typeDefData, allocSite, allocSite->initialHeap(), numElements));
1624 if (!arrayObj) {
1625 // WasmArrayObject::createArray will have reported OOM.
1626 return nullptr;
1627 }
1628 MOZ_RELEASE_ASSERT(arrayObj->is<WasmArrayObject>());
1629
1630 if (!seg) {
1631 // A zero-length array was requested and has been created, so we're done.
1632 return arrayObj;
1633 }
1634
1635 if (!ArrayCopyFromData(cx, arrayObj, 0, seg, segByteOffset, numElements)) {
1636 // Trap errors will be reported by ArrayCopyFromData.
1637 return nullptr;
1638 }
1639
1640 return arrayObj;
1641 }
1642
1643 // This is almost identical to ::arrayNewData, apart from the final part that
1644 // actually copies the data. It creates an array (WasmArrayObject)
1645 // containing `numElements` of type described by `typeDef`. Initialises it
1646 // with data copied from the element segment whose index is `segIndex`,
1647 // starting at element number `srcOffset` in the segment. Traps if the
1648 // segment doesn't hold enough elements to fill the array.
1649 /* static */ void* Instance::arrayNewElem(
1650 Instance* instance, uint32_t srcOffset, uint32_t numElements,
1651 uint32_t typeDefIndex, gc::AllocSite* allocSite, uint32_t segIndex) {
1652 MOZ_ASSERT(SASigArrayNewElem.failureMode == FailureMode::FailOnNullPtr);
1653 JSContext* cx = instance->cx();
1654 TypeDefInstanceData* typeDefData =
1655 instance->typeDefInstanceData(typeDefIndex);
1656
1657 // Check that the element segment is valid for use.
1658 MOZ_RELEASE_ASSERT(size_t(segIndex) < instance->passiveElemSegments_.length(),
1659 "ensured by validation");
1660 const InstanceElemSegment& seg = instance->passiveElemSegments_[segIndex];
1661
1662 const TypeDef* typeDef = typeDefData->typeDef;
1663
1664 // Any data coming from an element segment will be an AnyRef. Writes into
1665 // array memory are done with raw pointers, so we must ensure here that the
1666 // destination size is correct.
1667 MOZ_RELEASE_ASSERT(typeDef->arrayType().elementType().size() ==
1668 sizeof(AnyRef));
1669
1670 Rooted<WasmArrayObject*> arrayObj(
1671 cx,
1672 WasmArrayObject::createArray<true>(
1673 cx, typeDefData, allocSite, allocSite->initialHeap(), numElements));
1674 if (!arrayObj) {
1675 // WasmArrayObject::createArray will have reported OOM.
1676 return nullptr;
1677 }
1678 MOZ_RELEASE_ASSERT(arrayObj->is<WasmArrayObject>());
1679
1680 if (!ArrayCopyFromElem(cx, arrayObj, 0, seg, srcOffset, numElements)) {
1681 // Trap errors will be reported by ArrayCopyFromElems.
1682 return nullptr;
1683 }
1684
1685 return arrayObj;
1686 }
1687
1688 // Copies a range of the data segment `segIndex` into an array
1689 // (WasmArrayObject), starting at offset `segByteOffset` in the data segment and
1690 // index `index` in the array. `numElements` is the length of the copy in array
1691 // elements, NOT bytes - the number of bytes will be computed based on the type
1692 // of the array.
1693 //
1694 // Traps if accesses are out of bounds for either the data segment or the array,
1695 // or if the array object is null.
1696 /* static */ int32_t Instance::arrayInitData(Instance* instance, void* array,
1697 uint32_t index,
1698 uint32_t segByteOffset,
1699 uint32_t numElements,
1700 uint32_t segIndex) {
1701 MOZ_ASSERT(SASigArrayInitData.failureMode == FailureMode::FailOnNegI32);
1702 JSContext* cx = instance->cx();
1703
1704 // Check that the data segment is valid for use.
1705 MOZ_RELEASE_ASSERT(size_t(segIndex) < instance->passiveDataSegments_.length(),
1706 "ensured by validation");
1707 const DataSegment* seg = instance->passiveDataSegments_[segIndex];
1708
1709 // `seg` will be nullptr if the segment has already been 'data.drop'ed
1710 // (either implicitly in the case of 'active' segments during instantiation,
1711 // or explicitly by the data.drop instruction.) In that case we can
1712 // continue only if there's no need to copy any data out of it.
1713 if (!seg && (numElements != 0 || segByteOffset != 0)) {
1714 ReportTrapError(cx, JSMSG_WASM_OUT_OF_BOUNDS);
1715 return -1;
1716 }
1717 // At this point, if `seg` is null then `numElements` and `segByteOffset`
1718 // are both zero.
1719
1720 // Trap if the array is null.
1721 if (!array) {
1722 ReportTrapError(cx, JSMSG_WASM_DEREF_NULL);
1723 return -1;
1724 }
1725
1726 if (!seg) {
1727 // The segment was dropped, therefore a zero-length init was requested, so
1728 // we're done.
1729 return 0;
1730 }
1731
1732 // Get hold of the array.
1733 Rooted<WasmArrayObject*> arrayObj(cx, static_cast<WasmArrayObject*>(array));
1734 MOZ_RELEASE_ASSERT(arrayObj->is<WasmArrayObject>());
1735
1736 if (!ArrayCopyFromData(cx, arrayObj, index, seg, segByteOffset,
1737 numElements)) {
1738 // Trap errors will be reported by ArrayCopyFromData.
1739 return -1;
1740 }
1741
1742 return 0;
1743 }
1744
1745 // Copies a range of the element segment `segIndex` into an array
1746 // (WasmArrayObject), starting at offset `segOffset` in the elem segment and
1747 // index `index` in the array. `numElements` is the length of the copy.
1748 //
1749 // Traps if accesses are out of bounds for either the elem segment or the array,
1750 // or if the array object is null.
1751 /* static */ int32_t Instance::arrayInitElem(Instance* instance, void* array,
1752 uint32_t index, uint32_t segOffset,
1753 uint32_t numElements,
1754 uint32_t typeDefIndex,
1755 uint32_t segIndex) {
1756 MOZ_ASSERT(SASigArrayInitElem.failureMode == FailureMode::FailOnNegI32);
1757 JSContext* cx = instance->cx();
1758
1759 // Check that the element segment is valid for use.
1760 MOZ_RELEASE_ASSERT(size_t(segIndex) < instance->passiveElemSegments_.length(),
1761 "ensured by validation");
1762 const InstanceElemSegment& seg = instance->passiveElemSegments_[segIndex];
1763
1764 // Trap if the array is null.
1765 if (!array) {
1766 ReportTrapError(cx, JSMSG_WASM_DEREF_NULL);
1767 return -1;
1768 }
1769
1770 // Any data coming from an element segment will be an AnyRef. Writes into
1771 // array memory are done with raw pointers, so we must ensure here that the
1772 // destination size is correct.
1773 DebugOnly<const TypeDef*> typeDef =
1774 &instance->codeMeta().types->type(typeDefIndex);
1775 MOZ_ASSERT(typeDef->arrayType().elementType().size() == sizeof(AnyRef));
1776
1777 // Get hold of the array.
1778 Rooted<WasmArrayObject*> arrayObj(cx, static_cast<WasmArrayObject*>(array));
1779 MOZ_RELEASE_ASSERT(arrayObj->is<WasmArrayObject>());
1780
1781 if (!ArrayCopyFromElem(cx, arrayObj, index, seg, segOffset, numElements)) {
1782 // Trap errors will be reported by ArrayCopyFromElems.
1783 return -1;
1784 }
1785
1786 return 0;
1787 }
1788
1789 // Copies range of elements between two arrays.
1790 //
1791 // Traps if accesses are out of bounds for the arrays, or either array
1792 // object is null.
1793 //
1794 // This function is only used by baseline, Ion emits inline code using
1795 // WasmArrayMemMove and WasmArrayRefsMove builtins instead.
1796 /* static */ int32_t Instance::arrayCopy(Instance* instance, void* dstArray,
1797 uint32_t dstIndex, void* srcArray,
1798 uint32_t srcIndex,
1799 uint32_t numElements,
1800 uint32_t elementSize) {
1801 MOZ_ASSERT(SASigArrayCopy.failureMode == FailureMode::FailOnNegI32);
1802
1803 // At the entry point, `elementSize` may be negative to indicate
1804 // reftyped-ness of array elements. That is done in order to avoid having
1805 // to pass yet another (boolean) parameter here.
1806
1807 // "traps if either array is null"
1808 if (!srcArray || !dstArray) {
1809 ReportTrapError(instance->cx(), JSMSG_WASM_DEREF_NULL);
1810 return -1;
1811 }
1812
1813 bool elemsAreRefTyped = false;
1814 if (int32_t(elementSize) < 0) {
1815 elemsAreRefTyped = true;
1816 elementSize = uint32_t(-int32_t(elementSize));
1817 }
1818 MOZ_ASSERT(elementSize >= 1 && elementSize <= 16);
1819
1820 // Get hold of the two arrays.
1821 WasmArrayObject* dstArrayObj = static_cast<WasmArrayObject*>(dstArray);
1822 WasmArrayObject* srcArrayObj = static_cast<WasmArrayObject*>(srcArray);
1823 MOZ_ASSERT(dstArrayObj->is<WasmArrayObject>() &&
1824 srcArrayObj->is<WasmArrayObject>());
1825
1826 // If WasmArrayObject::numElements() is changed to return 64 bits, the
1827 // following checking logic will be incorrect.
1828 STATIC_ASSERT_WASMARRAYELEMENTS_NUMELEMENTS_IS_U32;
1829
1830 // "traps if destination + length > len(array1)"
1831 uint64_t dstNumElements = uint64_t(dstArrayObj->numElements_);
1832 if (uint64_t(dstIndex) + uint64_t(numElements) > dstNumElements) {
1833 // Potential GC hazard: srcArrayObj and dstArrayObj are invalidated by
1834 // reporting an error, do no use them after this point.
1835 ReportTrapError(instance->cx(), JSMSG_WASM_OUT_OF_BOUNDS);
1836 return -1;
1837 }
1838
1839 // "traps if source + length > len(array2)"
1840 uint64_t srcNumElements = uint64_t(srcArrayObj->numElements_);
1841 if (uint64_t(srcIndex) + uint64_t(numElements) > srcNumElements) {
1842 // Potential GC hazard: srcArrayObj and dstArrayObj are invalidated by
1843 // reporting an error, do no use them after this point.
1844 ReportTrapError(instance->cx(), JSMSG_WASM_OUT_OF_BOUNDS);
1845 return -1;
1846 }
1847
1848 if (numElements == 0) {
1849 // Early exit if there's no work to do.
1850 return 0;
1851 }
1852
1853 // Actually do the copy, taking care to handle cases where the src and dst
1854 // areas overlap.
1855 uint8_t* srcBase = srcArrayObj->data_;
1856 uint8_t* dstBase = dstArrayObj->data_;
1857 srcBase += size_t(srcIndex) * size_t(elementSize);
1858 dstBase += size_t(dstIndex) * size_t(elementSize);
1859 if (srcBase == dstBase) {
1860 // Early exit if there's no work to do.
1861 return 0;
1862 }
1863
1864 if (!elemsAreRefTyped) {
1865 // Hand off to memmove, which is presumably highly optimized.
1866 memmove(dstBase, srcBase, size_t(numElements) * size_t(elementSize));
1867 return 0;
1868 }
1869
1870 GCPtr<AnyRef>* dst = (GCPtr<AnyRef>*)dstBase;
1871 AnyRef* src = (AnyRef*)srcBase;
1872 // The std::copy performs GCPtr::set() operation under the hood.
1873 if (uintptr_t(dstBase) < uintptr_t(srcBase)) {
1874 std::copy(src, src + numElements, dst);
1875 } else {
1876 std::copy_backward(src, src + numElements, dst + numElements);
1877 }
1878 return 0;
1879 }
1880
1881 /* static */ void* Instance::exceptionNew(Instance* instance, void* tagArg) {
1882 MOZ_ASSERT(SASigExceptionNew.failureMode == FailureMode::FailOnNullPtr);
1883 JSContext* cx = instance->cx();
1884 AnyRef tag = AnyRef::fromCompiledCode(tagArg);
1885 Rooted<WasmTagObject*> tagObj(cx, &tag.toJSObject().as<WasmTagObject>());
1886 RootedObject proto(cx, &cx->global()->getPrototype(JSProto_WasmException));
1887 RootedObject stack(cx, nullptr);
1888 // An OOM will result in null which will be caught on the wasm side.
1889 return AnyRef::fromJSObjectOrNull(
1890 WasmExceptionObject::create(cx, tagObj, stack, proto))
1891 .forCompiledCode();
1892 }
1893
1894 /* static */ int32_t Instance::throwException(Instance* instance,
1895 void* exceptionArg) {
1896 MOZ_ASSERT(SASigThrowException.failureMode == FailureMode::FailOnNegI32);
1897
1898 JSContext* cx = instance->cx();
1899 AnyRef exception = AnyRef::fromCompiledCode(exceptionArg);
1900 RootedValue exnVal(cx, exception.toJSValue());
1901 cx->setPendingException(exnVal, nullptr);
1902
1903 // By always returning -1, we trigger a wasmTrap(Trap::ThrowReported),
1904 // and use that to trigger the stack walking for this exception.
1905 return -1;
1906 }
1907
1908 /* static */ int32_t Instance::intrI8VecMul(Instance* instance, uint32_t dest,
1909 uint32_t src1, uint32_t src2,
1910 uint32_t len, uint8_t* memBase) {
1911 MOZ_ASSERT(SASigIntrI8VecMul.failureMode == FailureMode::FailOnNegI32);
1912
1913 JSContext* cx = instance->cx();
1914 const WasmArrayRawBuffer* rawBuf = WasmArrayRawBuffer::fromDataPtr(memBase);
1915 size_t memLen = rawBuf->byteLength();
1916
1917 // Bounds check and deal with arithmetic overflow.
1918 uint64_t destLimit = uint64_t(dest) + uint64_t(len);
1919 uint64_t src1Limit = uint64_t(src1) + uint64_t(len);
1920 uint64_t src2Limit = uint64_t(src2) + uint64_t(len);
1921 if (destLimit > memLen || src1Limit > memLen || src2Limit > memLen) {
1922 ReportTrapError(cx, JSMSG_WASM_OUT_OF_BOUNDS);
1923 return -1;
1924 }
1925
1926 // Basic dot product
1927 uint8_t* destPtr = &memBase[dest];
1928 uint8_t* src1Ptr = &memBase[src1];
1929 uint8_t* src2Ptr = &memBase[src2];
1930 while (len > 0) {
1931 *destPtr = (*src1Ptr) * (*src2Ptr);
1932
1933 destPtr++;
1934 src1Ptr++;
1935 src2Ptr++;
1936 len--;
1937 }
1938
1939 return 0;
1940 }
1941
1942 #ifdef ENABLE_WASM_JS_STRING_BUILTINS
1943 template <bool isMutable>
1944 static WasmArrayObject* UncheckedCastToArrayI16(HandleAnyRef ref) {
1945 JSObject& object = ref.toJSObject();
1946 WasmArrayObject& array = object.as<WasmArrayObject>();
1947 DebugOnly<const ArrayType*> type(&array.typeDef().arrayType());
1948 MOZ_ASSERT(type->elementType() == StorageType::I16);
1949 MOZ_ASSERT(type->isMutable() == isMutable);
1950 return &array;
1951 }
1952
1953 /* static */
1954 int32_t Instance::stringTest(Instance* instance, void* stringArg) {
1955 MOZ_ASSERT(SASigStringTest.failureMode == FailureMode::Infallible);
1956 AnyRef string = AnyRef::fromCompiledCode(stringArg);
1957 if (string.isNull() || !string.isJSString()) {
1958 return 0;
1959 }
1960 return 1;
1961 }
1962
1963 /* static */
1964 void* Instance::stringCast(Instance* instance, void* stringArg) {
1965 MOZ_ASSERT(SASigStringCast.failureMode == FailureMode::FailOnNullPtr);
1966 AnyRef string = AnyRef::fromCompiledCode(stringArg);
1967 if (string.isNull() || !string.isJSString()) {
1968 ReportTrapError(instance->cx(), JSMSG_WASM_BAD_CAST);
1969 return nullptr;
1970 }
1971 return string.forCompiledCode();
1972 }
1973
1974 /* static */
1975 void* Instance::stringFromCharCodeArray(Instance* instance, void* arrayArg,
1976 uint32_t arrayStart,
1977 uint32_t arrayEnd) {
1978 MOZ_ASSERT(SASigStringFromCharCodeArray.failureMode ==
1979 FailureMode::FailOnNullPtr);
1980 JSContext* cx = instance->cx();
1981 RootedAnyRef arrayRef(cx, AnyRef::fromCompiledCode(arrayArg));
1982 if (arrayRef.isNull()) {
1983 ReportTrapError(instance->cx(), JSMSG_WASM_BAD_CAST);
1984 return nullptr;
1985 }
1986 Rooted<WasmArrayObject*> array(cx, UncheckedCastToArrayI16<true>(arrayRef));
1987
1988 if (arrayStart > arrayEnd || arrayEnd > array->numElements_) {
1989 ReportTrapError(cx, JSMSG_WASM_OUT_OF_BOUNDS);
1990 return nullptr;
1991 }
1992 uint32_t arrayCount = arrayEnd - arrayStart;
1993
1994 // GC is disabled on this call since it can cause the array to move,
1995 // invalidating the data pointer we pass as a parameter
1996 JSLinearString* string = NewStringCopyN<NoGC, char16_t>(
1997 cx, (char16_t*)array->data_ + arrayStart, arrayCount);
1998 if (!string) {
1999 // If the first attempt failed, we need to try again with a potential GC.
2000 // Acquire a stable version of the array that we can use. This may copy
2001 // inline data to the stack, so we avoid doing it unless we must.
2002 StableWasmArrayObjectElements<uint16_t> stableElements(cx, array);
2003 string = NewStringCopyN<CanGC, char16_t>(
2004 cx, (char16_t*)stableElements.elements() + arrayStart, arrayCount);
2005 if (!string) {
2006 MOZ_ASSERT(cx->isThrowingOutOfMemory());
2007 return nullptr;
2008 }
2009 }
2010 return AnyRef::fromJSString(string).forCompiledCode();
2011 }
2012
2013 /* static */
2014 int32_t Instance::stringIntoCharCodeArray(Instance* instance, void* stringArg,
2015 void* arrayArg, uint32_t arrayStart) {
2016 MOZ_ASSERT(SASigStringIntoCharCodeArray.failureMode ==
2017 FailureMode::FailOnNegI32);
2018 JSContext* cx = instance->cx();
2019 AnyRef stringRef = AnyRef::fromCompiledCode(stringArg);
2020 if (!stringRef.isJSString()) {
2021 ReportTrapError(cx, JSMSG_WASM_BAD_CAST);
2022 return -1;
2023 }
2024 Rooted<JSString*> string(cx, stringRef.toJSString());
2025 size_t stringLength = string->length();
2026
2027 RootedAnyRef arrayRef(cx, AnyRef::fromCompiledCode(arrayArg));
2028 if (arrayRef.isNull()) {
2029 ReportTrapError(instance->cx(), JSMSG_WASM_BAD_CAST);
2030 return -1;
2031 }
2032 Rooted<WasmArrayObject*> array(cx, UncheckedCastToArrayI16<true>(arrayRef));
2033
2034 CheckedUint32 lastIndexPlus1 = CheckedUint32(arrayStart) + stringLength;
2035 if (!lastIndexPlus1.isValid() ||
2036 lastIndexPlus1.value() > array->numElements_) {
2037 ReportTrapError(cx, JSMSG_WASM_OUT_OF_BOUNDS);
2038 return -1;
2039 }
2040
2041 JSLinearString* linearStr = string->ensureLinear(cx);
2042 if (!linearStr) {
2043 return -1;
2044 }
2045 char16_t* arrayData = reinterpret_cast<char16_t*>(array->data_);
2046 CopyChars(arrayData + arrayStart, *linearStr);
2047 return stringLength;
2048 }
2049
2050 void* Instance::stringFromCharCode(Instance* instance, uint32_t charCode) {
2051 MOZ_ASSERT(SASigStringFromCharCode.failureMode == FailureMode::FailOnNullPtr);
2052 JSContext* cx = instance->cx();
2053
2054 JSString* str = StringFromCharCode(cx, int32_t(charCode));
2055 if (!str) {
2056 MOZ_ASSERT(cx->isThrowingOutOfMemory());
2057 return nullptr;
2058 }
2059
2060 return AnyRef::fromJSString(str).forCompiledCode();
2061 }
2062
2063 void* Instance::stringFromCodePoint(Instance* instance, uint32_t codePoint) {
2064 MOZ_ASSERT(SASigStringFromCodePoint.failureMode ==
2065 FailureMode::FailOnNullPtr);
2066 JSContext* cx = instance->cx();
2067
2068 // Check for any error conditions before calling fromCodePoint so we report
2069 // the correct error
2070 if (codePoint > unicode::NonBMPMax) {
2071 ReportTrapError(cx, JSMSG_WASM_BAD_CODEPOINT);
2072 return nullptr;
2073 }
2074
2075 JSString* str = StringFromCodePoint(cx, char32_t(codePoint));
2076 if (!str) {
2077 MOZ_ASSERT(cx->isThrowingOutOfMemory());
2078 return nullptr;
2079 }
2080
2081 return AnyRef::fromJSString(str).forCompiledCode();
2082 }
2083
2084 int32_t Instance::stringCharCodeAt(Instance* instance, void* stringArg,
2085 uint32_t index) {
2086 MOZ_ASSERT(SASigStringCharCodeAt.failureMode == FailureMode::FailOnNegI32);
2087 JSContext* cx = instance->cx();
2088 AnyRef stringRef = AnyRef::fromCompiledCode(stringArg);
2089 if (!stringRef.isJSString()) {
2090 ReportTrapError(cx, JSMSG_WASM_BAD_CAST);
2091 return -1;
2092 }
2093
2094 Rooted<JSString*> string(cx, stringRef.toJSString());
2095 if (index >= string->length()) {
2096 ReportTrapError(cx, JSMSG_WASM_OUT_OF_BOUNDS);
2097 return -1;
2098 }
2099
2100 char16_t c;
2101 if (!string->getChar(cx, index, &c)) {
2102 MOZ_ASSERT(cx->isThrowingOutOfMemory());
2103 return false;
2104 }
2105 return c;
2106 }
2107
2108 int32_t Instance::stringCodePointAt(Instance* instance, void* stringArg,
2109 uint32_t index) {
2110 MOZ_ASSERT(SASigStringCodePointAt.failureMode == FailureMode::FailOnNegI32);
2111 JSContext* cx = instance->cx();
2112 AnyRef stringRef = AnyRef::fromCompiledCode(stringArg);
2113 if (!stringRef.isJSString()) {
2114 ReportTrapError(cx, JSMSG_WASM_BAD_CAST);
2115 return -1;
2116 }
2117
2118 Rooted<JSString*> string(cx, stringRef.toJSString());
2119 if (index >= string->length()) {
2120 ReportTrapError(cx, JSMSG_WASM_OUT_OF_BOUNDS);
2121 return -1;
2122 }
2123
2124 char32_t c;
2125 if (!string->getCodePoint(cx, index, &c)) {
2126 MOZ_ASSERT(cx->isThrowingOutOfMemory());
2127 return false;
2128 }
2129 return c;
2130 }
2131
2132 int32_t Instance::stringLength(Instance* instance, void* stringArg) {
2133 MOZ_ASSERT(SASigStringLength.failureMode == FailureMode::FailOnNegI32);
2134 JSContext* cx = instance->cx();
2135 AnyRef stringRef = AnyRef::fromCompiledCode(stringArg);
2136 if (!stringRef.isJSString()) {
2137 ReportTrapError(cx, JSMSG_WASM_BAD_CAST);
2138 return -1;
2139 }
2140
2141 static_assert(JS::MaxStringLength <= INT32_MAX);
2142 return (int32_t)stringRef.toJSString()->length();
2143 }
2144
2145 void* Instance::stringConcat(Instance* instance, void* firstStringArg,
2146 void* secondStringArg) {
2147 MOZ_ASSERT(SASigStringConcat.failureMode == FailureMode::FailOnNullPtr);
2148 JSContext* cx = instance->cx();
2149
2150 AnyRef firstStringRef = AnyRef::fromCompiledCode(firstStringArg);
2151 AnyRef secondStringRef = AnyRef::fromCompiledCode(secondStringArg);
2152 if (!firstStringRef.isJSString() || !secondStringRef.isJSString()) {
2153 ReportTrapError(cx, JSMSG_WASM_BAD_CAST);
2154 return nullptr;
2155 }
2156
2157 Rooted<JSString*> firstString(cx, firstStringRef.toJSString());
2158 Rooted<JSString*> secondString(cx, secondStringRef.toJSString());
2159 JSString* result = ConcatStrings<CanGC>(cx, firstString, secondString);
2160 if (!result) {
2161 MOZ_ASSERT(cx->isExceptionPending());
2162 return nullptr;
2163 }
2164 return AnyRef::fromJSString(result).forCompiledCode();
2165 }
2166
2167 void* Instance::stringSubstring(Instance* instance, void* stringArg,
2168 uint32_t startIndex, uint32_t endIndex) {
2169 MOZ_ASSERT(SASigStringSubstring.failureMode == FailureMode::FailOnNullPtr);
2170 JSContext* cx = instance->cx();
2171
2172 AnyRef stringRef = AnyRef::fromCompiledCode(stringArg);
2173 if (!stringRef.isJSString()) {
2174 ReportTrapError(cx, JSMSG_WASM_BAD_CAST);
2175 return nullptr;
2176 }
2177
2178 static_assert(JS::MaxStringLength <= INT32_MAX);
2179 RootedString string(cx, stringRef.toJSString());
2180 uint32_t stringLength = string->length();
2181 if (startIndex > stringLength || startIndex > endIndex) {
2182 return AnyRef::fromJSString(cx->names().empty_).forCompiledCode();
2183 }
2184
2185 if (endIndex > stringLength) {
2186 endIndex = stringLength;
2187 }
2188
2189 JSString* result =
2190 SubstringKernel(cx, string, startIndex, endIndex - startIndex);
2191 if (!result) {
2192 MOZ_ASSERT(cx->isThrowingOutOfMemory());
2193 return nullptr;
2194 }
2195 return AnyRef::fromJSString(result).forCompiledCode();
2196 }
2197
2198 int32_t Instance::stringEquals(Instance* instance, void* firstStringArg,
2199 void* secondStringArg) {
2200 MOZ_ASSERT(SASigStringEquals.failureMode == FailureMode::FailOnNegI32);
2201 JSContext* cx = instance->cx();
2202
2203 AnyRef firstStringRef = AnyRef::fromCompiledCode(firstStringArg);
2204 AnyRef secondStringRef = AnyRef::fromCompiledCode(secondStringArg);
2205
2206 // Null strings are considered equals
2207 if (firstStringRef.isNull() || secondStringRef.isNull()) {
2208 return firstStringRef.isNull() == secondStringRef.isNull();
2209 }
2210
2211 // Otherwise, rule out any other kind of reference value
2212 if (!firstStringRef.isJSString() || !secondStringRef.isJSString()) {
2213 ReportTrapError(cx, JSMSG_WASM_BAD_CAST);
2214 return -1;
2215 }
2216
2217 bool equals;
2218 if (!EqualStrings(cx, firstStringRef.toJSString(),
2219 secondStringRef.toJSString(), &equals)) {
2220 MOZ_ASSERT(cx->isThrowingOutOfMemory());
2221 return -1;
2222 }
2223 return equals ? 1 : 0;
2224 }
2225
2226 int32_t Instance::stringCompare(Instance* instance, void* firstStringArg,
2227 void* secondStringArg) {
2228 MOZ_ASSERT(SASigStringCompare.failureMode == FailureMode::FailOnMaxI32);
2229 JSContext* cx = instance->cx();
2230
2231 AnyRef firstStringRef = AnyRef::fromCompiledCode(firstStringArg);
2232 AnyRef secondStringRef = AnyRef::fromCompiledCode(secondStringArg);
2233 if (!firstStringRef.isJSString() || !secondStringRef.isJSString()) {
2234 ReportTrapError(cx, JSMSG_WASM_BAD_CAST);
2235 return INT32_MAX;
2236 }
2237
2238 int32_t result;
2239 if (!CompareStrings(cx, firstStringRef.toJSString(),
2240 secondStringRef.toJSString(), &result)) {
2241 MOZ_ASSERT(cx->isThrowingOutOfMemory());
2242 return INT32_MAX;
2243 }
2244
2245 if (result < 0) {
2246 return -1;
2247 }
2248 if (result > 0) {
2249 return 1;
2250 }
2251 return result;
2252 }
2253 #endif // ENABLE_WASM_JS_STRING_BUILTINS
2254
2255 //////////////////////////////////////////////////////////////////////////////
2256 //
2257 // Instance creation and related.
2258
2259 Instance::Instance(JSContext* cx, Handle<WasmInstanceObject*> object,
2260 const SharedCode& code, SharedTableVector&& tables,
2261 UniqueDebugState maybeDebug)
2262 : realm_(cx->realm()),
2263 onSuspendableStack_(false),
2264 allocSites_(nullptr),
2265 jsJitArgsRectifier_(
2266 cx->runtime()->jitRuntime()->getArgumentsRectifier().value),
2267 jsJitExceptionHandler_(
2268 cx->runtime()->jitRuntime()->getExceptionTail().value),
2269 preBarrierCode_(
2270 cx->runtime()->jitRuntime()->preBarrier(MIRType::WasmAnyRef).value),
2271 storeBuffer_(&cx->runtime()->gc.storeBuffer()),
2272 object_(object),
2273 code_(std::move(code)),
2274 tables_(std::move(tables)),
2275 maybeDebug_(std::move(maybeDebug)),
2276 debugFilter_(nullptr),
2277 callRefMetrics_(nullptr),
2278 maxInitializedGlobalsIndexPlus1_(0),
2279 addressOfLastBufferedWholeCell_(
2280 cx->runtime()->gc.addressOfLastBufferedWholeCell()) {
2281 for (size_t i = 0; i < N_BASELINE_SCRATCH_WORDS; i++) {
2282 baselineScratchWords_[i] = 0;
2283 }
2284 }
2285
2286 Instance* Instance::create(JSContext* cx, Handle<WasmInstanceObject*> object,
2287 const SharedCode& code, uint32_t instanceDataLength,
2288 SharedTableVector&& tables,
2289 UniqueDebugState maybeDebug) {
2290 void* base = js_calloc(alignof(Instance) + offsetof(Instance, data_) +
2291 instanceDataLength);
2292 if (!base) {
2293 ReportOutOfMemory(cx);
2294 return nullptr;
2295 }
2296 void* aligned = (void*)AlignBytes(uintptr_t(base), alignof(Instance));
2297
2298 auto* instance = new (aligned)
2299 Instance(cx, object, code, std::move(tables), std::move(maybeDebug));
2300 instance->allocatedBase_ = base;
2301 return instance;
2302 }
2303
2304 void Instance::destroy(Instance* instance) {
2305 instance->~Instance();
2306 js_free(instance->allocatedBase_);
2307 }
2308
2309 bool Instance::init(JSContext* cx, const JSObjectVector& funcImports,
2310 const ValVector& globalImportValues,
2311 Handle<WasmMemoryObjectVector> memories,
2312 const WasmGlobalObjectVector& globalObjs,
2313 const WasmTagObjectVector& tagObjs,
2314 const DataSegmentVector& dataSegments,
2315 const ModuleElemSegmentVector& elemSegments) {
2316 MOZ_ASSERT(!!maybeDebug_ == code().debugEnabled());
2317
2318 MOZ_ASSERT(funcImports.length() == code().funcImports().length());
2319 MOZ_ASSERT(tables_.length() == codeMeta().tables.length());
2320
2321 cx_ = cx;
2322 valueBoxClass_ = AnyRef::valueBoxClass();
2323 resetInterrupt(cx);
2324 jumpTable_ = code_->tieringJumpTable();
2325 debugFilter_ = nullptr;
2326 callRefMetrics_ = nullptr;
2327 addressOfNeedsIncrementalBarrier_ =
2328 cx->compartment()->zone()->addressOfNeedsIncrementalBarrier();
2329 addressOfNurseryPosition_ = cx->nursery().addressOfPosition();
2330 #ifdef JS_GC_ZEAL
2331 addressOfGCZealModeBits_ = cx->runtime()->gc.addressOfZealModeBits();
2332 #endif
2333
2334 // Initialize the request-tier-up stub pointer, if relevant
2335 if (code().mode() == CompileMode::LazyTiering) {
2336 setRequestTierUpStub(code().sharedStubs().base() +
2337 code().requestTierUpStubOffset());
2338 setUpdateCallRefMetricsStub(code().sharedStubs().base() +
2339 code().updateCallRefMetricsStubOffset());
2340 } else {
2341 setRequestTierUpStub(nullptr);
2342 setUpdateCallRefMetricsStub(nullptr);
2343 }
2344
2345 // Initialize the hotness counters, if relevant.
2346 if (code().mode() == CompileMode::LazyTiering) {
2347 // Computing the initial hotness counters requires the code section size.
2348 const size_t codeSectionSize = codeMeta().codeSectionSize();
2349 for (uint32_t funcIndex = codeMeta().numFuncImports;
2350 funcIndex < codeMeta().numFuncs(); funcIndex++) {
2351 funcDefInstanceData(funcIndex)->hotnessCounter =
2352 computeInitialHotnessCounter(funcIndex, codeSectionSize);
2353 }
2354 }
2355
2356 // Initialize type definitions in the instance data.
2357 const SharedTypeContext& types = codeMeta().types;
2358 Zone* zone = realm()->zone();
2359 for (uint32_t typeIndex = 0; typeIndex < types->length(); typeIndex++) {
2360 const TypeDef& typeDef = types->type(typeIndex);
2361 TypeDefInstanceData* typeDefData = typeDefInstanceData(typeIndex);
2362
2363 // Set default field values.
2364 new (typeDefData) TypeDefInstanceData();
2365
2366 // Store the runtime type for this type index
2367 typeDefData->typeDef = &typeDef;
2368 typeDefData->superTypeVector = typeDef.superTypeVector();
2369
2370 if (typeDef.kind() == TypeDefKind::Struct ||
2371 typeDef.kind() == TypeDefKind::Array) {
2372 // Compute the parameters that allocation will use. First, the class
2373 // and alloc kind for the type definition.
2374 const JSClass* clasp;
2375 gc::AllocKind allocKind;
2376
2377 if (typeDef.kind() == TypeDefKind::Struct) {
2378 clasp = WasmStructObject::classForTypeDef(&typeDef);
2379 allocKind = WasmStructObject::allocKindForTypeDef(&typeDef);
2380 allocKind = gc::GetFinalizedAllocKindForClass(allocKind, clasp);
2381 } else {
2382 clasp = &WasmArrayObject::class_;
2383 allocKind = gc::AllocKind::INVALID;
2384 }
2385
2386 // Find the shape using the class and recursion group
2387 const ObjectFlags objectFlags = {ObjectFlag::NotExtensible};
2388 typeDefData->shape =
2389 WasmGCShape::getShape(cx, clasp, cx->realm(), TaggedProto(),
2390 &typeDef.recGroup(), objectFlags);
2391 if (!typeDefData->shape) {
2392 return false;
2393 }
2394
2395 typeDefData->clasp = clasp;
2396 typeDefData->allocKind = allocKind;
2397
2398 // If `typeDef` is a struct, cache its size here, so that allocators
2399 // don't have to chase back through `typeDef` to determine that.
2400 // Similarly, if `typeDef` is an array, cache its array element size
2401 // here.
2402 MOZ_ASSERT(typeDefData->unused == 0);
2403 if (typeDef.kind() == TypeDefKind::Struct) {
2404 typeDefData->structTypeSize = typeDef.structType().size_;
2405 // StructLayout::close ensures this is an integral number of words.
2406 MOZ_ASSERT((typeDefData->structTypeSize % sizeof(uintptr_t)) == 0);
2407 } else {
2408 uint32_t arrayElemSize = typeDef.arrayType().elementType().size();
2409 typeDefData->arrayElemSize = arrayElemSize;
2410 MOZ_ASSERT(arrayElemSize == 16 || arrayElemSize == 8 ||
2411 arrayElemSize == 4 || arrayElemSize == 2 ||
2412 arrayElemSize == 1);
2413 }
2414 } else if (typeDef.kind() == TypeDefKind::Func) {
2415 // Nothing to do; the default values are OK.
2416 } else {
2417 MOZ_ASSERT(typeDef.kind() == TypeDefKind::None);
2418 MOZ_CRASH();
2419 }
2420 }
2421
2422 // Create and initialize alloc sites, they are all the same for Wasm.
2423 uint32_t allocSitesCount = codeTailMeta().numAllocSites;
2424 if (allocSitesCount > 0) {
2425 mozilla::CheckedInt<size_t> numBytesRequired =
2426 mozilla::CheckedInt<size_t>(allocSitesCount) *
2427 mozilla::CheckedInt<size_t>(sizeof(gc::AllocSite));
2428 if (!numBytesRequired.isValid()) {
2429 ReportOutOfMemory(cx);
2430 return false;
2431 }
2432 allocSites_ = (gc::AllocSite*)js_malloc(numBytesRequired.value());
2433 if (!allocSites_) {
2434 ReportOutOfMemory(cx);
2435 return false;
2436 }
2437 for (uint32_t i = 0; i < allocSitesCount; ++i) {
2438 new (&allocSites_[i]) gc::AllocSite();
2439 allocSites_[i].initWasm(zone);
2440 }
2441 }
2442
2443 // Initialize function imports in the instance data
2444 for (size_t i = 0; i < code().funcImports().length(); i++) {
2445 JSObject* f = funcImports[i];
2446
2447 #ifdef ENABLE_WASM_JSPI
2448 if (JSObject* suspendingObject = MaybeUnwrapSuspendingObject(f)) {
2449 // Compile suspending function Wasm wrapper.
2450 const FuncType& funcType = codeMeta().getFuncType(i);
2451 RootedObject wrapped(cx, suspendingObject);
2452 RootedFunction wrapper(
2453 cx, WasmSuspendingFunctionCreate(cx, wrapped, funcType));
2454 if (!wrapper) {
2455 return false;
2456 }
2457 MOZ_ASSERT(wrapper->isWasm());
2458 f = wrapper;
2459 }
2460 #endif
2461
2462 MOZ_ASSERT(f->isCallable());
2463 const FuncImport& fi = code().funcImport(i);
2464 const FuncType& funcType = codeMeta().getFuncType(i);
2465 FuncImportInstanceData& import = funcImportInstanceData(i);
2466 import.callable = f;
2467 if (f->is<JSFunction>()) {
2468 JSFunction* fun = &f->as<JSFunction>();
2469 if (!isAsmJS() && !codeMeta().funcImportsAreJS && fun->isWasm()) {
2470 import.instance = &fun->wasmInstance();
2471 import.realm = fun->realm();
2472 import.code = fun->wasmUncheckedCallEntry();
2473 } else if (void* thunk = MaybeGetBuiltinThunk(fun, funcType)) {
2474 import.instance = this;
2475 import.realm = fun->realm();
2476 import.code = thunk;
2477 } else {
2478 import.instance = this;
2479 import.realm = fun->realm();
2480 import.code = code().sharedStubs().base() + fi.interpExitCodeOffset();
2481 }
2482 } else {
2483 import.instance = this;
2484 import.realm = f->nonCCWRealm();
2485 import.code = code().sharedStubs().base() + fi.interpExitCodeOffset();
2486 }
2487 }
2488
2489 #ifdef DEBUG
2490 for (size_t i = 0; i < codeMeta().numExportedFuncs(); i++) {
2491 MOZ_ASSERT(!funcExportInstanceData(i).func);
2492 }
2493 #endif
2494
2495 // Initialize globals in the instance data.
2496 //
2497 // This must be performed after we have initialized runtime types as a global
2498 // initializer may reference them.
2499 //
2500 // We increment `maxInitializedGlobalsIndexPlus1_` every iteration of the
2501 // loop, as we call out to `InitExpr::evaluate` which may call
2502 // `constantGlobalGet` which uses this value to assert we're never accessing
2503 // uninitialized globals.
2504 maxInitializedGlobalsIndexPlus1_ = 0;
2505 for (size_t i = 0; i < codeMeta().globals.length();
2506 i++, maxInitializedGlobalsIndexPlus1_ = i) {
2507 const GlobalDesc& global = codeMeta().globals[i];
2508
2509 // Constants are baked into the code, never stored in the global area.
2510 if (global.isConstant()) {
2511 continue;
2512 }
2513
2514 uint8_t* globalAddr = data() + global.offset();
2515 switch (global.kind()) {
2516 case GlobalKind::Import: {
2517 size_t imported = global.importIndex();
2518 if (global.isIndirect()) {
2519 *(void**)globalAddr =
2520 (void*)&globalObjs[imported]->val().get().cell();
2521 } else {
2522 globalImportValues[imported].writeToHeapLocation(globalAddr);
2523 }
2524 break;
2525 }
2526 case GlobalKind::Variable: {
2527 RootedVal val(cx);
2528 const InitExpr& init = global.initExpr();
2529 Rooted<WasmInstanceObject*> instanceObj(cx, object());
2530 if (!init.evaluate(cx, instanceObj, &val)) {
2531 return false;
2532 }
2533
2534 if (global.isIndirect()) {
2535 // Initialize the cell
2536 globalObjs[i]->setVal(val);
2537
2538 // Link to the cell
2539 *(void**)globalAddr = globalObjs[i]->addressOfCell();
2540 } else {
2541 val.get().writeToHeapLocation(globalAddr);
2542 }
2543 break;
2544 }
2545 case GlobalKind::Constant: {
2546 MOZ_CRASH("skipped at the top");
2547 }
2548 }
2549 }
2550
2551 // All globals were initialized
2552 MOZ_ASSERT(maxInitializedGlobalsIndexPlus1_ == codeMeta().globals.length());
2553
2554 // Initialize memories in the instance data
2555 for (size_t i = 0; i < memories.length(); i++) {
2556 const MemoryDesc& md = codeMeta().memories[i];
2557 MemoryInstanceData& data = memoryInstanceData(i);
2558 WasmMemoryObject* memory = memories.get()[i];
2559
2560 data.memory = memory;
2561 data.base = memory->buffer().dataPointerEither().unwrap();
2562 size_t limit = memory->boundsCheckLimit();
2563 #if !defined(JS_64BIT)
2564 // We assume that the limit is a 32-bit quantity
2565 MOZ_ASSERT(limit <= UINT32_MAX);
2566 #endif
2567 data.boundsCheckLimit = limit;
2568 data.isShared = md.isShared();
2569
2570 // Add observer if our memory base may grow
2571 if (memory && memory->movingGrowable() &&
2572 !memory->addMovingGrowObserver(cx, object_)) {
2573 return false;
2574 }
2575 }
2576
2577 // Cache the default memory's values
2578 if (memories.length() > 0) {
2579 MemoryInstanceData& data = memoryInstanceData(0);
2580 memory0Base_ = data.base;
2581 memory0BoundsCheckLimit_ = data.boundsCheckLimit;
2582 } else {
2583 memory0Base_ = nullptr;
2584 memory0BoundsCheckLimit_ = 0;
2585 }
2586
2587 // Initialize tables in the instance data
2588 for (size_t i = 0; i < tables_.length(); i++) {
2589 const TableDesc& td = codeMeta().tables[i];
2590 TableInstanceData& table = tableInstanceData(i);
2591 table.length = tables_[i]->length();
2592 table.elements = tables_[i]->instanceElements();
2593 // Non-imported tables, with init_expr, has to be initialized with
2594 // the evaluated value.
2595 if (!td.isImported && td.initExpr) {
2596 Rooted<WasmInstanceObject*> instanceObj(cx, object());
2597 RootedVal val(cx);
2598 if (!td.initExpr->evaluate(cx, instanceObj, &val)) {
2599 return false;
2600 }
2601 RootedAnyRef ref(cx, val.get().ref());
2602 tables_[i]->fillUninitialized(0, tables_[i]->length(), ref, cx);
2603 }
2604 }
2605
2606 #ifdef DEBUG
2607 // All (linked) tables with non-nullable types must be initialized.
2608 for (size_t i = 0; i < tables_.length(); i++) {
2609 const TableDesc& td = codeMeta().tables[i];
2610 if (!td.elemType.isNullable()) {
2611 tables_[i]->assertRangeNotNull(0, tables_[i]->length());
2612 }
2613 }
2614 #endif // DEBUG
2615
2616 // Initialize tags in the instance data
2617 for (size_t i = 0; i < codeMeta().tags.length(); i++) {
2618 MOZ_ASSERT(tagObjs[i] != nullptr);
2619 tagInstanceData(i).object = tagObjs[i];
2620 }
2621 pendingException_ = nullptr;
2622 pendingExceptionTag_ = nullptr;
2623
2624 // Add debug filtering table.
2625 if (code().debugEnabled()) {
2626 size_t numFuncs = codeMeta().numFuncs();
2627 size_t numWords = std::max<size_t>((numFuncs + 31) / 32, 1);
2628 debugFilter_ = (uint32_t*)js_calloc(numWords, sizeof(uint32_t));
2629 if (!debugFilter_) {
2630 ReportOutOfMemory(cx);
2631 return false;
2632 }
2633 }
2634
2635 if (code().mode() == CompileMode::LazyTiering) {
2636 callRefMetrics_ = (CallRefMetrics*)js_calloc(
2637 codeTailMeta().numCallRefMetrics, sizeof(CallRefMetrics));
2638 if (!callRefMetrics_) {
2639 ReportOutOfMemory(cx);
2640 return false;
2641 }
2642 // A zeroed-out CallRefMetrics should satisfy
2643 // CallRefMetrics::checkInvariants.
2644 MOZ_ASSERT_IF(codeTailMeta().numCallRefMetrics > 0,
2645 callRefMetrics_[0].checkInvariants());
2646 } else {
2647 MOZ_ASSERT(codeTailMeta().numCallRefMetrics == 0);
2648 }
2649
2650 // Add observers if our tables may grow
2651 for (const SharedTable& table : tables_) {
2652 if (table->movingGrowable() && !table->addMovingGrowObserver(cx, object_)) {
2653 return false;
2654 }
2655 }
2656
2657 // Take references to the passive data segments
2658 if (!passiveDataSegments_.resize(dataSegments.length())) {
2659 ReportOutOfMemory(cx);
2660 return false;
2661 }
2662 for (size_t i = 0; i < dataSegments.length(); i++) {
2663 if (!dataSegments[i]->active()) {
2664 passiveDataSegments_[i] = dataSegments[i];
2665 }
2666 }
2667
2668 // Create InstanceElemSegments for any passive element segments, since these
2669 // are the ones available at runtime.
2670 if (!passiveElemSegments_.resize(elemSegments.length())) {
2671 ReportOutOfMemory(cx);
2672 return false;
2673 }
2674 for (size_t i = 0; i < elemSegments.length(); i++) {
2675 const ModuleElemSegment& seg = elemSegments[i];
2676 if (seg.kind == ModuleElemSegment::Kind::Passive) {
2677 passiveElemSegments_[i] = InstanceElemSegment();
2678 InstanceElemSegment& instanceSeg = passiveElemSegments_[i];
2679 if (!instanceSeg.reserve(seg.numElements())) {
2680 ReportOutOfMemory(cx);
2681 return false;
2682 }
2683
2684 bool ok = iterElemsAnyrefs(cx, seg, [&](uint32_t _, AnyRef ref) -> bool {
2685 instanceSeg.infallibleAppend(ref);
2686 return true;
2687 });
2688 if (!ok) {
2689 return false;
2690 }
2691 }
2692 }
2693
2694 return true;
2695 }
2696
2697 Instance::~Instance() {
2698 realm_->wasm.unregisterInstance(*this);
2699
2700 if (debugFilter_) {
2701 js_free(debugFilter_);
2702 }
2703 if (callRefMetrics_) {
2704 js_free(callRefMetrics_);
2705 }
2706 if (allocSites_) {
2707 js_free(allocSites_);
2708 }
2709
2710 // Any pending exceptions should have been consumed.
2711 MOZ_ASSERT(pendingException_.isNull());
2712 }
2713
2714 void Instance::setInterrupt() {
2715 interrupt_ = true;
2716 stackLimit_ = JS::NativeStackLimitMin;
2717 }
2718
2719 bool Instance::isInterrupted() const {
2720 return interrupt_ || stackLimit_ == JS::NativeStackLimitMin;
2721 }
2722
2723 void Instance::resetInterrupt(JSContext* cx) {
2724 interrupt_ = false;
2725 #ifdef ENABLE_WASM_JSPI
2726 if (cx->wasm().suspendableStackLimit != JS::NativeStackLimitMin) {
2727 stackLimit_ = cx->wasm().suspendableStackLimit;
2728 return;
2729 }
2730 #endif
2731 stackLimit_ = cx->stackLimitForJitCode(JS::StackForUntrustedScript);
2732 }
2733
2734 void Instance::setTemporaryStackLimit(JS::NativeStackLimit limit) {
2735 if (!isInterrupted()) {
2736 stackLimit_ = limit;
2737 }
2738 onSuspendableStack_ = true;
2739 }
2740
2741 void Instance::resetTemporaryStackLimit(JSContext* cx) {
2742 if (!isInterrupted()) {
2743 stackLimit_ = cx->stackLimitForJitCode(JS::StackForUntrustedScript);
2744 }
2745 onSuspendableStack_ = false;
2746 }
2747
2748 int32_t Instance::computeInitialHotnessCounter(uint32_t funcIndex,
2749 size_t codeSectionSize) {
2750 MOZ_ASSERT(code().mode() == CompileMode::LazyTiering);
2751 MOZ_ASSERT(codeSectionSize > 0);
2752 uint32_t bodyLength = codeTailMeta().funcDefRange(funcIndex).size();
2753 return LazyTieringHeuristics::estimateIonCompilationCost(bodyLength,
2754 codeSectionSize);
2755 }
2756
2757 void Instance::resetHotnessCounter(uint32_t funcIndex) {
2758 funcDefInstanceData(funcIndex)->hotnessCounter = INT32_MAX;
2759 }
2760
2761 int32_t Instance::readHotnessCounter(uint32_t funcIndex) const {
2762 return funcDefInstanceData(funcIndex)->hotnessCounter;
2763 }
2764
2765 void Instance::submitCallRefHints(uint32_t funcIndex) {
2766 #ifdef JS_JITSPEW
2767 bool headerShown = false;
2768 #endif
2769
2770 float requiredHotnessFraction =
2771 float(InliningHeuristics::rawCallRefPercent()) / 100.0;
2772
2773 // Limits as set by InliningHeuristics::InliningHeuristics().
2774 const DebugOnly<float> epsilon = 0.000001;
2775 MOZ_ASSERT(requiredHotnessFraction >= 0.1 - epsilon);
2776 MOZ_ASSERT(requiredHotnessFraction <= 1.0 + epsilon);
2777
2778 CallRefMetricsRange range = codeTailMeta().getFuncDefCallRefs(funcIndex);
2779 for (uint32_t callRefIndex = range.begin;
2780 callRefIndex < range.begin + range.length; callRefIndex++) {
2781 MOZ_RELEASE_ASSERT(callRefIndex < codeTailMeta().numCallRefMetrics);
2782
2783 // In this loop, for each CallRefMetrics, we create a corresponding
2784 // CallRefHint. The CallRefHint is a recommendation of which function(s)
2785 // to inline into the associated call site. It is based on call target
2786 // counts at the call site and incorporates other heuristics as implemented
2787 // by the code below.
2788 //
2789 // Later, when compiling the call site with Ion, the CallRefHint created
2790 // here is consulted. That may or may not result in inlining actually
2791 // taking place, since it depends also on context known only at
2792 // Ion-compilation time -- inlining depth, inlining budgets, etc. In
2793 // particular, if the call site is itself within a function that got
2794 // inlined multiple times, the call site may be compiled multiple times,
2795 // with inlining happening in some cases and not in others.
2796 //
2797 // The logic below tries to find reasons not to inline into this call site,
2798 // and if none are found, creates and stores a CallRefHint specifying the
2799 // recommended targets.
2800 //
2801 // The core criterion is that the set of targets that eventually get chosen
2802 // must together make up at least `requiredHotnessFraction` of all calls
2803 // made by this call site.
2804
2805 CallRefMetrics& metrics = callRefMetrics_[callRefIndex];
2806 MOZ_RELEASE_ASSERT(metrics.checkInvariants());
2807
2808 // For convenience, work with a copy of the candidates, not directly with
2809 // `metrics`.
2810 struct Candidate {
2811 uint32_t funcIndex = 0;
2812 uint32_t count = 0;
2813 Candidate() = default;
2814 Candidate(const Candidate&) = default;
2815 Candidate(uint32_t funcIndex, uint32_t count)
2816 : funcIndex(funcIndex), count(count) {}
2817 };
2818 Candidate candidates[CallRefMetrics::NUM_SLOTS];
2819 size_t numCandidates = 0;
2820
2821 // If we're going to recommend no inlining here, specify a reason.
2822 const char* skipReason = nullptr;
2823
2824 // The total count for targets that are individually tracked.
2825 uint64_t totalTrackedCount = 0;
2826 bool allCandidatesAreImports = true;
2827
2828 // Make a first pass over the candidates, skipping imports.
2829 for (size_t i = 0; i < CallRefMetrics::NUM_SLOTS; i++) {
2830 if (!metrics.targets[i]) {
2831 break;
2832 }
2833 uint32_t targetCount = metrics.counts[i];
2834 if (targetCount == 0) {
2835 continue;
2836 }
2837 totalTrackedCount += uint64_t(targetCount);
2838
2839 // We can't inline a call to a function which is in this module but has a
2840 // different Instance, since the potential callees of any function depend
2841 // on the instance it is associated with. Cross-instance calls should
2842 // have already been excluded from consideration by the code generated by
2843 // BaseCompiler::updateCallRefMetrics, but given that this is critical,
2844 // assert it here.
2845 const DebugOnly<Instance*> targetFuncInstance =
2846 static_cast<wasm::Instance*>(
2847 metrics.targets[i]
2848 ->getExtendedSlot(FunctionExtended::WASM_INSTANCE_SLOT)
2849 .toPrivate());
2850 MOZ_ASSERT(targetFuncInstance == this);
2851
2852 uint32_t targetFuncIndex = metrics.targets[i]->wasmFuncIndex();
2853 if (codeMeta().funcIsImport(targetFuncIndex)) {
2854 continue;
2855 }
2856 allCandidatesAreImports = false;
2857 candidates[numCandidates] = Candidate(targetFuncIndex, targetCount);
2858 numCandidates++;
2859 }
2860 MOZ_RELEASE_ASSERT(numCandidates <= CallRefMetrics::NUM_SLOTS);
2861
2862 // The total count of all calls made by this call site.
2863 uint64_t totalCount = totalTrackedCount + uint64_t(metrics.countOther);
2864
2865 // Throw out some obvious cases.
2866 if (totalCount == 0) {
2867 // See comments on definition of CallRefMetrics regarding overflow.
2868 skipReason = "(callsite unused)";
2869 } else if (metrics.targets[0] == nullptr) {
2870 // None of the calls made by this call site could be attributed to
2871 // specific callees; they all got lumped into CallRefMetrics::countOther.
2872 // See GenerateUpdateCallRefMetricsStub for possible reasons why.
2873 skipReason = "(no individually tracked targets)";
2874 } else if (numCandidates > 0 && allCandidatesAreImports) {
2875 // Imported functions can't be inlined.
2876 skipReason = "(all targets are imports)";
2877 }
2878
2879 // We want to avoid inlining large functions into cold(ish) call sites.
2880 if (!skipReason) {
2881 uint32_t totalTargetBodySize = 0;
2882 for (size_t i = 0; i < numCandidates; i++) {
2883 totalTargetBodySize +=
2884 codeTailMeta().funcDefRange(candidates[i].funcIndex).size();
2885 }
2886 if (totalCount < 2 * totalTargetBodySize) {
2887 skipReason = "(callsite too cold)";
2888 }
2889 }
2890
2891 // The final check is the most important. We need to choose some subset of
2892 // the candidates which together make up at least `requiredHotnessFraction`
2893 // of the calls made by this call site. However, to avoid generated code
2894 // wasting time on checking guards for relatively unlikely targets, we
2895 // ignore any candidate that does not achieve at least 10% of
2896 // `requiredHotnessFraction`. Also make up a CallRefHints in anticipation
2897 // of finding a usable set of candidates.
2898 CallRefHint hints;
2899 if (!skipReason) {
2900 MOZ_RELEASE_ASSERT(totalCount > 0); // Be sure to avoid NaN/Inf problems
2901 float usableFraction = 0.0;
2902 uint32_t numUsableCandidates = 0;
2903 for (size_t i = 0; i < numCandidates; i++) {
2904 float candidateFraction =
2905 float(candidates[i].count) / float(totalCount);
2906 if (candidateFraction >= 0.1 * requiredHotnessFraction) {
2907 usableFraction += candidateFraction;
2908 numUsableCandidates++;
2909 if (!hints.full()) {
2910 // Add this candidate to `hints`. This assumes that we
2911 // (more-or-less) encounter candidates in declining order of
2912 // hotness. See block comment on `struct CallRefMetrics`.
2913 hints.append(candidates[i].funcIndex);
2914 }
2915 }
2916 }
2917 if (numUsableCandidates == 0) {
2918 skipReason = "(no target is hot enough)";
2919 } else if (usableFraction < requiredHotnessFraction) {
2920 skipReason = "(collectively not hot enough)";
2921 }
2922 }
2923
2924 if (!skipReason) {
2925 // Success!
2926 MOZ_ASSERT(hints.length() > 0);
2927 codeTailMeta().setCallRefHint(callRefIndex, hints);
2928 } else {
2929 CallRefHint empty;
2930 codeTailMeta().setCallRefHint(callRefIndex, empty);
2931 }
2932
2933 #ifdef JS_JITSPEW
2934 if (!headerShown) {
2935 JS_LOG(wasmPerf, Info, "CM=..%06lx CallRefMetrics for I=..%06lx fI=%-4u",
2936 (unsigned long)(uintptr_t(&codeMeta()) & 0xFFFFFFL),
2937 (unsigned long)(uintptr_t(this) & 0xFFFFFFL), funcIndex);
2938 headerShown = true;
2939 }
2940
2941 JS::UniqueChars countsStr;
2942 for (size_t i = 0; i < CallRefMetrics::NUM_SLOTS; i++) {
2943 countsStr =
2944 JS_sprintf_append(std::move(countsStr), "%u ", metrics.counts[i]);
2945 }
2946 JS::UniqueChars targetStr;
2947 if (skipReason) {
2948 targetStr = JS_smprintf("%s", skipReason);
2949 } else {
2950 targetStr = JS_smprintf("%s", "fI ");
2951 for (size_t i = 0; i < hints.length(); i++) {
2952 targetStr =
2953 JS_sprintf_append(std::move(targetStr), "%u%s", hints.get(i),
2954 i + 1 < hints.length() ? ", " : "");
2955 }
2956 }
2957 JS_LOG(wasmPerf, Info, "CM=..%06lx %sother:%u --> %s",
2958 (unsigned long)(uintptr_t(&codeMeta()) & 0xFFFFFFL), countsStr.get(),
2959 metrics.countOther, targetStr.get());
2960 #endif
2961 }
2962 }
2963
2964 bool Instance::debugFilter(uint32_t funcIndex) const {
2965 return (debugFilter_[funcIndex / 32] >> funcIndex % 32) & 1;
2966 }
2967
2968 void Instance::setDebugFilter(uint32_t funcIndex, bool value) {
2969 if (value) {
2970 debugFilter_[funcIndex / 32] |= (1 << funcIndex % 32);
2971 } else {
2972 debugFilter_[funcIndex / 32] &= ~(1 << funcIndex % 32);
2973 }
2974 }
2975
2976 bool Instance::memoryAccessInGuardRegion(const uint8_t* addr,
2977 unsigned numBytes) const {
2978 MOZ_ASSERT(numBytes > 0);
2979
2980 for (uint32_t memoryIndex = 0; memoryIndex < codeMeta().memories.length();
2981 memoryIndex++) {
2982 uint8_t* base = memoryBase(memoryIndex).unwrap(/* comparison */);
2983 if (addr < base) {
2984 continue;
2985 }
2986
2987 WasmMemoryObject* mem = memory(memoryIndex);
2988 size_t lastByteOffset = addr - base + (numBytes - 1);
2989 if (lastByteOffset >= mem->volatileMemoryLength() &&
2990 lastByteOffset < mem->buffer().wasmMappedSize()) {
2991 return true;
2992 }
2993 }
2994 return false;
2995 }
2996
2997 void Instance::tracePrivate(JSTracer* trc) {
2998 // This method is only called from WasmInstanceObject so the only reason why
2999 // TraceEdge is called is so that the pointer can be updated during a moving
3000 // GC.
3001 MOZ_ASSERT_IF(trc->isMarkingTracer(), gc::IsMarked(trc->runtime(), object_));
3002 TraceEdge(trc, &object_, "wasm instance object");
3003
3004 // OK to just do one tier here; though the tiers have different funcImports
3005 // tables, they share the instance object.
3006 for (uint32_t funcIndex = 0; funcIndex < codeMeta().numFuncImports;
3007 funcIndex++) {
3008 TraceNullableEdge(trc, &funcImportInstanceData(funcIndex).callable,
3009 "wasm import");
3010 }
3011
3012 for (uint32_t funcExportIndex = 0;
3013 funcExportIndex < codeMeta().numExportedFuncs(); funcExportIndex++) {
3014 TraceNullableEdge(trc, &funcExportInstanceData(funcExportIndex).func,
3015 "wasm func export");
3016 }
3017
3018 for (uint32_t memoryIndex = 0;
3019 memoryIndex < code().codeMeta().memories.length(); memoryIndex++) {
3020 MemoryInstanceData& memoryData = memoryInstanceData(memoryIndex);
3021 TraceNullableEdge(trc, &memoryData.memory, "wasm memory object");
3022 }
3023
3024 for (const SharedTable& table : tables_) {
3025 table->trace(trc);
3026 }
3027
3028 for (const GlobalDesc& global : code().codeMeta().globals) {
3029 // Indirect reference globals get traced by the owning WebAssembly.Global.
3030 if (!global.type().isRefRepr() || global.isConstant() ||
3031 global.isIndirect()) {
3032 continue;
3033 }
3034 GCPtr<AnyRef>* obj = (GCPtr<AnyRef>*)(data() + global.offset());
3035 TraceNullableEdge(trc, obj, "wasm reference-typed global");
3036 }
3037
3038 for (uint32_t tagIndex = 0; tagIndex < code().codeMeta().tags.length();
3039 tagIndex++) {
3040 TraceNullableEdge(trc, &tagInstanceData(tagIndex).object, "wasm tag");
3041 }
3042
3043 const SharedTypeContext& types = codeMeta().types;
3044 for (uint32_t typeIndex = 0; typeIndex < types->length(); typeIndex++) {
3045 TypeDefInstanceData* typeDefData = typeDefInstanceData(typeIndex);
3046 TraceNullableEdge(trc, &typeDefData->shape, "wasm shape");
3047 }
3048
3049 if (callRefMetrics_) {
3050 for (uint32_t i = 0; i < codeTailMeta().numCallRefMetrics; i++) {
3051 CallRefMetrics* metrics = &callRefMetrics_[i];
3052 MOZ_ASSERT(metrics->checkInvariants());
3053 for (size_t j = 0; j < CallRefMetrics::NUM_SLOTS; j++) {
3054 TraceNullableEdge(trc, &metrics->targets[j], "indirect call target");
3055 }
3056 }
3057 }
3058
3059 TraceNullableEdge(trc, &pendingException_, "wasm pending exception value");
3060 TraceNullableEdge(trc, &pendingExceptionTag_, "wasm pending exception tag");
3061
3062 passiveElemSegments_.trace(trc);
3063
3064 if (maybeDebug_) {
3065 maybeDebug_->trace(trc);
3066 }
3067 }
3068
3069 void js::wasm::TraceInstanceEdge(JSTracer* trc, Instance* instance,
3070 const char* name) {
3071 if (IsTracerKind(trc, JS::TracerKind::Moving)) {
3072 // Compacting GC: The Instance does not move so there is nothing to do here.
3073 // Reading the object from the instance below would be a data race during
3074 // multi-threaded updates. Compacting GC does not rely on graph traversal
3075 // to find all edges that need to be updated.
3076 return;
3077 }
3078
3079 // Instance fields are traced by the owning WasmInstanceObject's trace
3080 // hook. Tracing this ensures they are traced once.
3081 JSObject* object = instance->objectUnbarriered();
3082 TraceManuallyBarrieredEdge(trc, &object, name);
3083 }
3084
3085 static uintptr_t* GetFrameScanStartForStackMap(
3086 const Frame* frame, const StackMap* map,
3087 uintptr_t* highestByteVisitedInPrevFrame) {
3088 // |frame| points somewhere in the middle of the area described by |map|.
3089 // We have to calculate |scanStart|, the lowest address that is described by
3090 // |map|, by consulting |map->frameOffsetFromTop|.
3091
3092 const size_t numMappedBytes = map->header.numMappedWords * sizeof(void*);
3093 const uintptr_t scanStart = uintptr_t(frame) +
3094 (map->header.frameOffsetFromTop * sizeof(void*)) -
3095 numMappedBytes;
3096 MOZ_ASSERT(0 == scanStart % sizeof(void*));
3097
3098 // Do what we can to assert that, for consecutive wasm frames, their stack
3099 // maps also abut exactly. This is a useful sanity check on the sizing of
3100 // stackmaps.
3101 //
3102 // In debug builds, the stackmap construction machinery goes to considerable
3103 // efforts to ensure that the stackmaps for consecutive frames abut exactly.
3104 // This is so as to ensure there are no areas of stack inadvertently ignored
3105 // by a stackmap, nor covered by two stackmaps. Hence any failure of this
3106 // assertion is serious and should be investigated.
3107 #ifndef JS_CODEGEN_ARM64
3108 MOZ_ASSERT_IF(
3109 highestByteVisitedInPrevFrame && *highestByteVisitedInPrevFrame != 0,
3110 *highestByteVisitedInPrevFrame + 1 == scanStart);
3111 #endif
3112
3113 if (highestByteVisitedInPrevFrame) {
3114 *highestByteVisitedInPrevFrame = scanStart + numMappedBytes - 1;
3115 }
3116
3117 // If we have some exit stub words, this means the map also covers an area
3118 // created by a exit stub, and so the highest word of that should be a
3119 // constant created by (code created by) GenerateTrapExit.
3120 MOZ_ASSERT_IF(map->header.numExitStubWords > 0,
3121 ((uintptr_t*)scanStart)[map->header.numExitStubWords - 1 -
3122 TrapExitDummyValueOffsetFromTop] ==
3123 TrapExitDummyValue);
3124
3125 return (uintptr_t*)scanStart;
3126 }
3127
3128 uintptr_t Instance::traceFrame(JSTracer* trc, const wasm::WasmFrameIter& wfi,
3129 uint8_t* nextPC,
3130 uintptr_t highestByteVisitedInPrevFrame) {
3131 const StackMap* map = code().lookupStackMap(nextPC);
3132 if (!map) {
3133 return 0;
3134 }
3135 Frame* frame = wfi.frame();
3136 uintptr_t* stackWords =
3137 GetFrameScanStartForStackMap(frame, map, &highestByteVisitedInPrevFrame);
3138
3139 // Hand refs off to the GC.
3140 for (uint32_t i = 0; i < map->header.numMappedWords; i++) {
3141 if (map->get(i) != StackMap::Kind::AnyRef) {
3142 continue;
3143 }
3144
3145 TraceManuallyBarrieredNullableEdge(trc, (AnyRef*)&stackWords[i],
3146 "Instance::traceWasmFrame: normal word");
3147 }
3148
3149 // Deal with any GC-managed fields in the DebugFrame, if it is
3150 // present and those fields may be live.
3151 if (map->header.hasDebugFrameWithLiveRefs) {
3152 DebugFrame* debugFrame = DebugFrame::from(frame);
3153 char* debugFrameP = (char*)debugFrame;
3154
3155 for (size_t i = 0; i < MaxRegisterResults; i++) {
3156 if (debugFrame->hasSpilledRegisterRefResult(i)) {
3157 char* resultRefP = debugFrameP + DebugFrame::offsetOfRegisterResult(i);
3158 TraceManuallyBarrieredNullableEdge(
3159 trc, (AnyRef*)resultRefP,
3160 "Instance::traceWasmFrame: DebugFrame::resultResults_");
3161 }
3162 }
3163
3164 if (debugFrame->hasCachedReturnJSValue()) {
3165 char* cachedReturnJSValueP =
3166 debugFrameP + DebugFrame::offsetOfCachedReturnJSValue();
3167 TraceManuallyBarrieredEdge(
3168 trc, (js::Value*)cachedReturnJSValueP,
3169 "Instance::traceWasmFrame: DebugFrame::cachedReturnJSValue_");
3170 }
3171 }
3172
3173 return highestByteVisitedInPrevFrame;
3174 }
3175
3176 void Instance::updateFrameForMovingGC(const wasm::WasmFrameIter& wfi,
3177 uint8_t* nextPC) {
3178 const StackMap* map = code().lookupStackMap(nextPC);
3179 if (!map) {
3180 return;
3181 }
3182 Frame* frame = wfi.frame();
3183 uintptr_t* stackWords = GetFrameScanStartForStackMap(frame, map, nullptr);
3184
3185 // Update interior array data pointers for any inline-storage arrays that
3186 // moved.
3187 for (uint32_t i = 0; i < map->header.numMappedWords; i++) {
3188 if (map->get(i) != StackMap::Kind::ArrayDataPointer) {
3189 continue;
3190 }
3191
3192 uint8_t** addressOfArrayDataPointer = (uint8_t**)&stackWords[i];
3193 if (WasmArrayObject::isDataInline(*addressOfArrayDataPointer)) {
3194 WasmArrayObject* oldArray =
3195 WasmArrayObject::fromInlineDataPointer(*addressOfArrayDataPointer);
3196 WasmArrayObject* newArray =
3197 (WasmArrayObject*)gc::MaybeForwarded(oldArray);
3198 *addressOfArrayDataPointer =
3199 WasmArrayObject::addressOfInlineData(newArray);
3200 }
3201 }
3202 }
3203
3204 WasmMemoryObject* Instance::memory(uint32_t memoryIndex) const {
3205 return memoryInstanceData(memoryIndex).memory;
3206 }
3207
3208 SharedMem<uint8_t*> Instance::memoryBase(uint32_t memoryIndex) const {
3209 MOZ_ASSERT_IF(
3210 memoryIndex == 0,
3211 memory0Base_ == memory(memoryIndex)->buffer().dataPointerEither());
3212 return memory(memoryIndex)->buffer().dataPointerEither();
3213 }
3214
3215 SharedArrayRawBuffer* Instance::sharedMemoryBuffer(uint32_t memoryIndex) const {
3216 MOZ_ASSERT(memory(memoryIndex)->isShared());
3217 return memory(memoryIndex)->sharedArrayRawBuffer();
3218 }
3219
3220 WasmInstanceObject* Instance::objectUnbarriered() const {
3221 return object_.unbarrieredGet();
3222 }
3223
3224 WasmInstanceObject* Instance::object() const { return object_; }
3225
3226 static bool GetInterpEntryAndEnsureStubs(JSContext* cx, Instance& instance,
3227 uint32_t funcIndex,
3228 const CallArgs& args,
3229 void** interpEntry,
3230 const FuncType** funcType) {
3231 const FuncExport* funcExport;
3232 if (!instance.code().getOrCreateInterpEntry(funcIndex, &funcExport,
3233 interpEntry)) {
3234 ReportOutOfMemory(cx);
3235 return false;
3236 }
3237
3238 *funcType = &instance.codeMeta().getFuncType(funcIndex);
3239
3240 #ifdef DEBUG
3241 // EnsureEntryStubs() has ensured proper jit-entry stubs have been created and
3242 // installed in funcIndex's JumpTable entry, so check against the presence of
3243 // the provisional lazy stub. See also
3244 // WasmInstanceObject::getExportedFunction().
3245 if (!funcExport->hasEagerStubs() && (*funcType)->canHaveJitEntry()) {
3246 if (!EnsureBuiltinThunksInitialized()) {
3247 ReportOutOfMemory(cx);
3248 return false;
3249 }
3250 JSFunction& callee = args.callee().as<JSFunction>();
3251 void* provisionalLazyJitEntryStub = ProvisionalLazyJitEntryStub();
3252 MOZ_ASSERT(provisionalLazyJitEntryStub);
3253 MOZ_ASSERT(callee.isWasmWithJitEntry());
3254 MOZ_ASSERT(*callee.wasmJitEntry() != provisionalLazyJitEntryStub);
3255 }
3256 #endif
3257 return true;
3258 }
3259
3260 bool wasm::ResultsToJSValue(JSContext* cx, ResultType type,
3261 void* registerResultLoc,
3262 Maybe<char*> stackResultsLoc,
3263 MutableHandleValue rval, CoercionLevel level) {
3264 if (type.empty()) {
3265 // No results: set to undefined, and we're done.
3266 rval.setUndefined();
3267 return true;
3268 }
3269
3270 // If we added support for multiple register results, we'd need to establish a
3271 // convention for how to store them to memory in registerResultLoc. For now
3272 // we can punt.
3273 static_assert(MaxRegisterResults == 1);
3274
3275 // Stack results written to stackResultsLoc; register result written
3276 // to registerResultLoc.
3277
3278 // First, convert the register return value, and prepare to iterate in
3279 // push order. Note that if the register result is a reference type,
3280 // it may be unrooted, so ToJSValue_anyref must not GC in that case.
3281 ABIResultIter iter(type);
3282 DebugOnly<bool> usedRegisterResult = false;
3283 for (; !iter.done(); iter.next()) {
3284 if (iter.cur().inRegister()) {
3285 MOZ_ASSERT(!usedRegisterResult);
3286 if (!ToJSValue<DebugCodegenVal>(cx, registerResultLoc, iter.cur().type(),
3287 rval, level)) {
3288 return false;
3289 }
3290 usedRegisterResult = true;
3291 }
3292 }
3293 MOZ_ASSERT(usedRegisterResult);
3294
3295 MOZ_ASSERT((stackResultsLoc.isSome()) == (iter.count() > 1));
3296 if (!stackResultsLoc) {
3297 // A single result: we're done.
3298 return true;
3299 }
3300
3301 // Otherwise, collect results in an array, in push order.
3302 Rooted<ArrayObject*> array(cx, NewDenseEmptyArray(cx));
3303 if (!array) {
3304 return false;
3305 }
3306 RootedValue tmp(cx);
3307 for (iter.switchToPrev(); !iter.done(); iter.prev()) {
3308 const ABIResult& result = iter.cur();
3309 if (result.onStack()) {
3310 char* loc = stackResultsLoc.value() + result.stackOffset();
3311 if (!ToJSValue<DebugCodegenVal>(cx, loc, result.type(), &tmp, level)) {
3312 return false;
3313 }
3314 if (!NewbornArrayPush(cx, array, tmp)) {
3315 return false;
3316 }
3317 } else {
3318 if (!NewbornArrayPush(cx, array, rval)) {
3319 return false;
3320 }
3321 }
3322 }
3323 rval.set(ObjectValue(*array));
3324 return true;
3325 }
3326
3327 class MOZ_RAII ReturnToJSResultCollector {
3328 class MOZ_RAII StackResultsRooter : public JS::CustomAutoRooter {
3329 ReturnToJSResultCollector& collector_;
3330
3331 public:
3332 StackResultsRooter(JSContext* cx, ReturnToJSResultCollector& collector)
3333 : JS::CustomAutoRooter(cx), collector_(collector) {}
3334
3335 void trace(JSTracer* trc) final {
3336 for (ABIResultIter iter(collector_.type_); !iter.done(); iter.next()) {
3337 const ABIResult& result = iter.cur();
3338 if (result.onStack() && result.type().isRefRepr()) {
3339 char* loc = collector_.stackResultsArea_.get() + result.stackOffset();
3340 AnyRef* refLoc = reinterpret_cast<AnyRef*>(loc);
3341 TraceNullableRoot(trc, refLoc, "StackResultsRooter::trace");
3342 }
3343 }
3344 }
3345 };
3346 friend class StackResultsRooter;
3347
3348 ResultType type_;
3349 UniquePtr<char[], JS::FreePolicy> stackResultsArea_;
3350 Maybe<StackResultsRooter> rooter_;
3351
3352 public:
3353 explicit ReturnToJSResultCollector(const ResultType& type) : type_(type) {};
3354 bool init(JSContext* cx) {
3355 bool needRooter = false;
3356 ABIResultIter iter(type_);
3357 for (; !iter.done(); iter.next()) {
3358 const ABIResult& result = iter.cur();
3359 if (result.onStack() && result.type().isRefRepr()) {
3360 needRooter = true;
3361 }
3362 }
3363 uint32_t areaBytes = iter.stackBytesConsumedSoFar();
3364 MOZ_ASSERT_IF(needRooter, areaBytes > 0);
3365 if (areaBytes > 0) {
3366 // It is necessary to zero storage for ref results, and it doesn't
3367 // hurt to do so for other POD results.
3368 stackResultsArea_ = cx->make_zeroed_pod_array<char>(areaBytes);
3369 if (!stackResultsArea_) {
3370 return false;
3371 }
3372 if (needRooter) {
3373 rooter_.emplace(cx, *this);
3374 }
3375 }
3376 return true;
3377 }
3378
3379 void* stackResultsArea() {
3380 MOZ_ASSERT(stackResultsArea_);
3381 return stackResultsArea_.get();
3382 }
3383
3384 bool collect(JSContext* cx, void* registerResultLoc, MutableHandleValue rval,
3385 CoercionLevel level) {
3386 Maybe<char*> stackResultsLoc =
3387 stackResultsArea_ ? Some(stackResultsArea_.get()) : Nothing();
3388 return ResultsToJSValue(cx, type_, registerResultLoc, stackResultsLoc, rval,
3389 level);
3390 }
3391 };
3392
3393 /*
3394 * [SMDOC] Exported wasm functions and the jit-entry stubs
3395 *
3396 * ## The kinds of exported functions
3397 *
3398 * There are several kinds of exported wasm functions. /Explicitly/ exported
3399 * functions are:
3400 *
3401 * - any wasm function exported via the export section
3402 * - any asm.js export
3403 * - the module start function
3404 *
3405 * There are also /implicitly/ exported functions, these are the functions whose
3406 * indices in the module are referenced outside the code segment, eg, in element
3407 * segments and in global initializers.
3408 *
3409 * ## Wasm functions as JSFunctions
3410 *
3411 * Any exported function can be manipulated by JS and wasm code, and to both the
3412 * exported function is represented as a JSFunction. To JS, that means that the
3413 * function can be called in the same way as any other JSFunction. To Wasm, it
3414 * means that the function is a reference with the same representation as
3415 * externref.
3416 *
3417 * However, the JSFunction object is created only when the function value is
3418 * actually exposed to JS the first time. The creation is performed by
3419 * getExportedFunction(), below, as follows:
3420 *
3421 * - A function exported via the export section (or from asm.js) is created
3422 * when the export object is created, which happens at instantiation time.
3423 *
3424 * - A function implicitly exported via a table is created when the table
3425 * element is read (by JS or wasm) and a function value is needed to
3426 * represent that value. Functions stored in tables by initializers have a
3427 * special representation that does not require the function object to be
3428 * created, as long as the initializing element segment uses the more
3429 * efficient index encoding instead of the more general expression encoding.
3430 *
3431 * - A function implicitly exported via a global initializer is created when
3432 * the global is initialized.
3433 *
3434 * - A function referenced from a ref.func instruction in code is created when
3435 * that instruction is executed the first time.
3436 *
3437 * The JSFunction representing a wasm function never changes: every reference to
3438 * the wasm function that exposes the JSFunction gets the same JSFunction. In
3439 * particular, imported functions already have a JSFunction representation (from
3440 * JS or from their home module), and will be exposed using that representation.
3441 *
3442 * The mapping from a wasm function to its JSFunction is instance-specific, and
3443 * held in a hashmap in the instance. If a module is shared across multiple
3444 * instances, possibly in multiple threads, each instance will have its own
3445 * JSFunction representing the wasm function.
3446 *
3447 * ## Stubs -- interpreter, eager, lazy, provisional, and absent
3448 *
3449 * While a Wasm exported function is just a JSFunction, the internal wasm ABI is
3450 * neither the C++ ABI nor the JS JIT ABI, so there needs to be an extra step
3451 * when C++ or JS JIT code calls wasm code. For this, execution passes through
3452 * a stub that is adapted to both the JS caller and the wasm callee.
3453 *
3454 * ### Interpreter stubs and jit-entry stubs
3455 *
3456 * When JS interpreted code calls a wasm function, we end up in
3457 * Instance::callExport() to execute the call. This function must enter wasm,
3458 * and to do this it uses a stub that is specific to the wasm function (see
3459 * GenerateInterpEntry) that is callable with the C++ interpreter ABI and which
3460 * will convert arguments as necessary and enter compiled wasm code.
3461 *
3462 * The interpreter stub is created eagerly, when the module is compiled.
3463 *
3464 * However, the interpreter call path is slow, and when JS jitted code calls
3465 * wasm we want to do better. In this case, there is a different, optimized
3466 * stub that is to be invoked, and it uses the JIT ABI. This is the jit-entry
3467 * stub for the function. Jitted code will call a wasm function's jit-entry
3468 * stub to invoke the function with the JIT ABI. The stub will adapt the call
3469 * to the wasm ABI.
3470 *
3471 * Some jit-entry stubs are created eagerly and some are created lazily.
3472 *
3473 * ### Eager jit-entry stubs
3474 *
3475 * The explicitly exported functions have stubs created for them eagerly. Eager
3476 * stubs are created with their tier when the module is compiled, see
3477 * ModuleGenerator::finishCodeBlock(), which calls wasm::GenerateStubs(), which
3478 * generates stubs for functions with eager stubs.
3479 *
3480 * An eager stub for tier-1 is upgraded to tier-2 if the module tiers up, see
3481 * below.
3482 *
3483 * ### Lazy jit-entry stubs
3484 *
3485 * Stubs are created lazily for all implicitly exported functions. These
3486 * functions may flow out to JS, but will only need a stub if they are ever
3487 * called from jitted code. (That's true for explicitly exported functions too,
3488 * but for them the presumption is that they will be called.)
3489 *
3490 * Lazy stubs are created only when they are needed, and they are /doubly/ lazy,
3491 * see getExportedFunction(), below: A function implicitly exported via a table
3492 * or global may be manipulated eagerly by host code without actually being
3493 * called (maybe ever), so we do not generate a lazy stub when the function
3494 * object escapes to JS, but instead delay stub generation until the function is
3495 * actually called.
3496 *
3497 * ### The provisional lazy jit-entry stub
3498 *
3499 * However, JS baseline compilation needs to have a stub to start with in order
3500 * to allow it to attach CacheIR data to the call (or it deoptimizes the call as
3501 * a C++ call). Thus when the JSFunction for the wasm export is retrieved by JS
3502 * code, a /provisional/ lazy jit-entry stub is associated with the function.
3503 * The stub will invoke the wasm function on the slow interpreter path via
3504 * callExport - if the function is ever called - and will cause a fast jit-entry
3505 * stub to be created at the time of the call. The provisional lazy stub is
3506 * shared globally, it contains no function-specific or context-specific data.
3507 *
3508 * Thus, the final lazy jit-entry stubs are eventually created by
3509 * Instance::callExport, when a call is routed through it on the slow path for
3510 * any of the reasons given above.
3511 *
3512 * ### Absent jit-entry stubs
3513 *
3514 * Some functions never get jit-entry stubs. The predicate canHaveJitEntry()
3515 * determines if a wasm function gets a stub, and it will deny this if the
3516 * function's signature exposes non-JS-compatible types (such as v128) or if
3517 * stub optimization has been disabled by a jit option. Calls to these
3518 * functions will continue to go via callExport and use the slow interpreter
3519 * stub.
3520 *
3521 * ## The jit-entry jump table
3522 *
3523 * The mapping from the exported function to its jit-entry stub is implemented
3524 * by the jit-entry jump table in the JumpTables object (see WasmCode.h). The
3525 * jit-entry jump table entry for a function holds a stub that the jit can call
3526 * to perform fast calls.
3527 *
3528 * While there is a single contiguous jump table, it has two logical sections:
3529 * one for eager stubs, and one for lazy stubs. These sections are initialized
3530 * and updated separately, using logic that is specific to each section.
3531 *
3532 * The value of the table element for an eager stub is a pointer to the stub
3533 * code in the current tier. The pointer is installed just after the creation
3534 * of the stub, before any code in the module is executed. If the module later
3535 * tiers up, the eager jit-entry stub for tier-1 code is replaced by one for
3536 * tier-2 code, see the next section.
3537 *
3538 * Initially the value of the jump table element for a lazy stub is null.
3539 *
3540 * If the function is retrieved by JS (by getExportedFunction()) and is not
3541 * barred from having a jit-entry, then the stub is upgraded to the shared
3542 * provisional lazy jit-entry stub. This upgrade happens to be racy if the
3543 * module is shared, and so the update is atomic and only happens if the entry
3544 * is already null. Since the provisional lazy stub is shared, this is fine; if
3545 * several threads try to upgrade at the same time, it is to the same shared
3546 * value.
3547 *
3548 * If the retrieved function is later invoked (via callExport()), the stub is
3549 * upgraded to an actual jit-entry stub for the current code tier, again if the
3550 * function is allowed to have a jit-entry. This is not racy -- though multiple
3551 * threads can be trying to create a jit-entry stub at the same time, they do so
3552 * under a lock and only the first to take the lock will be allowed to create a
3553 * stub, the others will reuse the first-installed stub.
3554 *
3555 * If the module later tiers up, the lazy jit-entry stub for tier-1 code (if it
3556 * exists) is replaced by one for tier-2 code, see the next section.
3557 *
3558 * (Note, the InterpEntry stub is never stored in the jit-entry table, as it
3559 * uses the C++ ABI, not the JIT ABI. It is accessible through the
3560 * FunctionEntry.)
3561 *
3562 * ### Interaction of the jit-entry jump table and tiering
3563 *
3564 * (For general info about tiering, see the comment in WasmCompile.cpp.)
3565 *
3566 * The jit-entry stub, whether eager or lazy, is specific to a code tier - a
3567 * stub will invoke the code for its function for the tier. When we tier up,
3568 * new jit-entry stubs must be created that reference tier-2 code, and must then
3569 * be patched into the jit-entry table. The complication here is that, since
3570 * the jump table is shared with its code between instances on multiple threads,
3571 * tier-1 code is running on other threads and new tier-1 specific jit-entry
3572 * stubs may be created concurrently with trying to create the tier-2 stubs on
3573 * the thread that performs the tiering-up. Indeed, there may also be
3574 * concurrent attempts to upgrade null jit-entries to the provisional lazy stub.
3575 *
3576 * Eager stubs:
3577 *
3578 * - Eager stubs for tier-2 code are patched in racily by Module::finishTier2()
3579 * along with code pointers for tiering; nothing conflicts with these writes.
3580 *
3581 * Lazy stubs:
3582 *
3583 * - An upgrade from a null entry to a lazy provisional stub is atomic and can
3584 * only happen if the entry is null, and it only happens in
3585 * getExportedFunction(). No lazy provisional stub will be installed if
3586 * there's another stub present.
3587 *
3588 * - The lazy tier-appropriate stub is installed by callExport() (really by
3589 * EnsureEntryStubs()) during the first invocation of the exported function
3590 * that reaches callExport(). That invocation must be from within JS, and so
3591 * the jit-entry element can't be null, because a prior getExportedFunction()
3592 * will have ensured that it is not: the lazy provisional stub will have been
3593 * installed. Hence the installing of the lazy tier-appropriate stub does
3594 * not race with the installing of the lazy provisional stub.
3595 *
3596 * - A lazy tier-1 stub is upgraded to a lazy tier-2 stub by
3597 * Module::finishTier2(). The upgrade needs to ensure that all tier-1 stubs
3598 * are upgraded, and that once the upgrade is finished, callExport() will
3599 * only create tier-2 lazy stubs. (This upgrading does not upgrade lazy
3600 * provisional stubs or absent stubs.)
3601 *
3602 * The locking protocol ensuring that all stubs are upgraded properly and
3603 * that the system switches to creating tier-2 stubs is implemented in
3604 * Module::finishTier2() and EnsureEntryStubs().
3605 *
3606 * ## Stub lifetimes and serialization
3607 *
3608 * Eager jit-entry stub code, along with stub code for import functions, is
3609 * serialized along with the tier-2 code for the module.
3610 *
3611 * Lazy stub code and thunks for builtin functions (including the provisional
3612 * lazy jit-entry stub) are never serialized.
3613 */
3614
3615 static bool WasmCall(JSContext* cx, unsigned argc, Value* vp) {
3616 CallArgs args = CallArgsFromVp(argc, vp);
3617 RootedFunction callee(cx, &args.callee().as<JSFunction>());
3618
3619 Instance& instance = callee->wasmInstance();
3620 uint32_t funcIndex = callee->wasmFuncIndex();
3621 return instance.callExport(cx, funcIndex, args);
3622 }
3623
3624 bool Instance::getExportedFunction(JSContext* cx, uint32_t funcIndex,
3625 MutableHandleFunction result) {
3626 MOZ_RELEASE_ASSERT(realm() == cx->realm());
3627
3628 uint32_t funcExportIndex = codeMeta().findFuncExportIndex(funcIndex);
3629 FuncExportInstanceData& instanceData =
3630 funcExportInstanceData(funcExportIndex);
3631
3632 // Early exit if we've already found or created this exported function
3633 if (instanceData.func) {
3634 result.set(instanceData.func);
3635 return true;
3636 }
3637
3638 // If this is an import, we need to recover the original function to maintain
3639 // reference equality between a re-exported function and 'ref.func'. The
3640 // identity of the imported function object is stable across tiers, which is
3641 // what we want.
3642 //
3643 // Use the imported function only if it is an exported function, otherwise
3644 // fall through to get a (possibly new) exported function.
3645 if (funcIndex < codeMeta().numFuncImports) {
3646 FuncImportInstanceData& import = funcImportInstanceData(funcIndex);
3647 if (import.callable->is<JSFunction>()) {
3648 JSFunction* fun = &import.callable->as<JSFunction>();
3649 if (!codeMeta().funcImportsAreJS && fun->isWasm()) {
3650 instanceData.func = fun;
3651 result.set(fun);
3652 return true;
3653 }
3654 }
3655 }
3656
3657 // Otherwise this is a locally defined function which we've never created a
3658 // function object for yet.
3659 const CodeBlock& codeBlock = code().funcCodeBlock(funcIndex);
3660 const CodeRange& codeRange = codeBlock.codeRange(funcIndex);
3661 const TypeDef& funcTypeDef = codeMeta().getFuncTypeDef(funcIndex);
3662 unsigned numArgs = funcTypeDef.funcType().args().length();
3663 Instance* instance = const_cast<Instance*>(this);
3664 const SuperTypeVector* superTypeVector = funcTypeDef.superTypeVector();
3665 void* uncheckedCallEntry =
3666 codeBlock.base() + codeRange.funcUncheckedCallEntry();
3667
3668 if (isAsmJS()) {
3669 // asm.js needs to act like a normal JS function which means having the
3670 // name from the original source and being callable as a constructor.
3671 Rooted<JSAtom*> name(cx, getFuncDisplayAtom(cx, funcIndex));
3672 if (!name) {
3673 return false;
3674 }
3675 result.set(NewNativeConstructor(cx, WasmCall, numArgs, name,
3676 gc::AllocKind::FUNCTION_EXTENDED,
3677 TenuredObject, FunctionFlags::ASMJS_CTOR));
3678 if (!result) {
3679 return false;
3680 }
3681 MOZ_ASSERT(result->isTenured());
3682 STATIC_ASSERT_WASM_FUNCTIONS_TENURED;
3683
3684 // asm.js does not support jit entries.
3685 result->initWasm(funcIndex, instance, superTypeVector, uncheckedCallEntry);
3686 } else {
3687 Rooted<JSAtom*> name(cx, NumberToAtom(cx, funcIndex));
3688 if (!name) {
3689 return false;
3690 }
3691 RootedObject proto(cx);
3692 #ifdef ENABLE_WASM_TYPE_REFLECTIONS
3693 proto = GlobalObject::getOrCreatePrototype(cx, JSProto_WasmFunction);
3694 if (!proto) {
3695 return false;
3696 }
3697 #endif
3698 result.set(NewFunctionWithProto(
3699 cx, WasmCall, numArgs, FunctionFlags::WASM, nullptr, name, proto,
3700 gc::AllocKind::FUNCTION_EXTENDED, TenuredObject));
3701 if (!result) {
3702 return false;
3703 }
3704 MOZ_ASSERT(result->isTenured());
3705 STATIC_ASSERT_WASM_FUNCTIONS_TENURED;
3706
3707 // Some applications eagerly access all table elements which currently
3708 // triggers worst-case behavior for lazy stubs, since each will allocate a
3709 // separate 4kb code page. Most eagerly-accessed functions are not called,
3710 // so use a shared, provisional (and slow) lazy stub as JitEntry and wait
3711 // until Instance::callExport() to create the fast entry stubs.
3712 if (funcTypeDef.funcType().canHaveJitEntry()) {
3713 const FuncExport& funcExport = codeBlock.lookupFuncExport(funcIndex);
3714 if (!funcExport.hasEagerStubs()) {
3715 if (!EnsureBuiltinThunksInitialized()) {
3716 return false;
3717 }
3718 void* provisionalLazyJitEntryStub = ProvisionalLazyJitEntryStub();
3719 MOZ_ASSERT(provisionalLazyJitEntryStub);
3720 code().setJitEntryIfNull(funcIndex, provisionalLazyJitEntryStub);
3721 }
3722 result->initWasmWithJitEntry(code().getAddressOfJitEntry(funcIndex),
3723 instance, superTypeVector,
3724 uncheckedCallEntry);
3725 } else {
3726 result->initWasm(funcIndex, instance, superTypeVector,
3727 uncheckedCallEntry);
3728 }
3729 }
3730
3731 instanceData.func = result;
3732 return true;
3733 }
3734
3735 bool Instance::callExport(JSContext* cx, uint32_t funcIndex,
3736 const CallArgs& args, CoercionLevel level) {
3737 if (memory0Base_) {
3738 // If there has been a moving grow, this Instance should have been notified.
3739 MOZ_RELEASE_ASSERT(memoryBase(0).unwrap() == memory0Base_);
3740 }
3741
3742 void* interpEntry;
3743 const FuncType* funcType;
3744 if (!GetInterpEntryAndEnsureStubs(cx, *this, funcIndex, args, &interpEntry,
3745 &funcType)) {
3746 return false;
3747 }
3748
3749 // Lossless coercions can handle unexposable arguments or returns. This is
3750 // only available in testing code.
3751 if (level != CoercionLevel::Lossless && funcType->hasUnexposableArgOrRet()) {
3752 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
3753 JSMSG_WASM_BAD_VAL_TYPE);
3754 return false;
3755 }
3756
3757 ArgTypeVector argTypes(*funcType);
3758 ResultType resultType(ResultType::Vector(funcType->results()));
3759 ReturnToJSResultCollector results(resultType);
3760 if (!results.init(cx)) {
3761 return false;
3762 }
3763
3764 // The calling convention for an external call into wasm is to pass an
3765 // array of 16-byte values where each value contains either a coerced int32
3766 // (in the low word), or a double value (in the low dword) value, with the
3767 // coercions specified by the wasm signature. The external entry point
3768 // unpacks this array into the system-ABI-specified registers and stack
3769 // memory and then calls into the internal entry point. The return value is
3770 // stored in the first element of the array (which, therefore, must have
3771 // length >= 1).
3772 Vector<ExportArg, 8> exportArgs(cx);
3773 if (!exportArgs.resize(
3774 std::max<size_t>(1, argTypes.lengthWithStackResults()))) {
3775 return false;
3776 }
3777
3778 Rooted<GCVector<AnyRef, 8, SystemAllocPolicy>> refs(cx);
3779
3780 DebugCodegen(DebugChannel::Function, "wasm-function[%d] arguments [",
3781 funcIndex);
3782 RootedValue v(cx);
3783 for (size_t i = 0; i < argTypes.lengthWithStackResults(); ++i) {
3784 void* rawArgLoc = &exportArgs[i];
3785 if (argTypes.isSyntheticStackResultPointerArg(i)) {
3786 *reinterpret_cast<void**>(rawArgLoc) = results.stackResultsArea();
3787 continue;
3788 }
3789 size_t naturalIdx = argTypes.naturalIndex(i);
3790 v = naturalIdx < args.length() ? args[naturalIdx] : UndefinedValue();
3791 ValType type = funcType->arg(naturalIdx);
3792 if (!ToWebAssemblyValue<DebugCodegenVal>(cx, v, type, rawArgLoc, true,
3793 level)) {
3794 return false;
3795 }
3796 if (type.isRefRepr()) {
3797 void* ptr = *reinterpret_cast<void**>(rawArgLoc);
3798 // Store in rooted array until no more GC is possible.
3799 RootedAnyRef ref(cx, AnyRef::fromCompiledCode(ptr));
3800 if (!refs.emplaceBack(ref.get())) {
3801 return false;
3802 }
3803 DebugCodegen(DebugChannel::Function, "/(#%d)", int(refs.length() - 1));
3804 }
3805 }
3806
3807 // Copy over reference values from the rooted array, if any.
3808 if (refs.length() > 0) {
3809 DebugCodegen(DebugChannel::Function, "; ");
3810 size_t nextRef = 0;
3811 for (size_t i = 0; i < argTypes.lengthWithStackResults(); ++i) {
3812 if (argTypes.isSyntheticStackResultPointerArg(i)) {
3813 continue;
3814 }
3815 size_t naturalIdx = argTypes.naturalIndex(i);
3816 ValType type = funcType->arg(naturalIdx);
3817 if (type.isRefRepr()) {
3818 AnyRef* rawArgLoc = (AnyRef*)&exportArgs[i];
3819 *rawArgLoc = refs[nextRef++];
3820 DebugCodegen(DebugChannel::Function, " ref(#%d) := %p ",
3821 int(nextRef - 1), *(void**)rawArgLoc);
3822 }
3823 }
3824 refs.clear();
3825 }
3826
3827 DebugCodegen(DebugChannel::Function, "]\n");
3828
3829 // Ensure pending exception is cleared before and after (below) call.
3830 MOZ_ASSERT(pendingException_.isNull());
3831
3832 {
3833 JitActivation activation(cx);
3834
3835 // Call the per-exported-function trampoline created by GenerateEntry.
3836 auto funcPtr = JS_DATA_TO_FUNC_PTR(ExportFuncPtr, interpEntry);
3837 if (!CALL_GENERATED_2(funcPtr, exportArgs.begin(), this)) {
3838 return false;
3839 }
3840 }
3841
3842 MOZ_ASSERT(pendingException_.isNull());
3843
3844 if (isAsmJS() && args.isConstructing()) {
3845 // By spec, when a JS function is called as a constructor and this
3846 // function returns a primary type, which is the case for all asm.js
3847 // exported functions, the returned value is discarded and an empty
3848 // object is returned instead.
3849 PlainObject* obj = NewPlainObject(cx);
3850 if (!obj) {
3851 return false;
3852 }
3853 args.rval().set(ObjectValue(*obj));
3854 return true;
3855 }
3856
3857 // Note that we're not rooting the register result, if any; we depend
3858 // on ResultsCollector::collect to root the value on our behalf,
3859 // before causing any GC.
3860 void* registerResultLoc = &exportArgs[0];
3861 DebugCodegen(DebugChannel::Function, "wasm-function[%d]; results [",
3862 funcIndex);
3863 if (!results.collect(cx, registerResultLoc, args.rval(), level)) {
3864 return false;
3865 }
3866 DebugCodegen(DebugChannel::Function, "]\n");
3867
3868 return true;
3869 }
3870
3871 void Instance::setPendingException(Handle<WasmExceptionObject*> exn) {
3872 pendingException_ = AnyRef::fromJSObject(*exn.get());
3873 pendingExceptionTag_ =
3874 AnyRef::fromJSObject(exn->as<WasmExceptionObject>().tag());
3875 }
3876
3877 void Instance::constantGlobalGet(uint32_t globalIndex,
3878 MutableHandleVal result) {
3879 MOZ_RELEASE_ASSERT(globalIndex < maxInitializedGlobalsIndexPlus1_);
3880 const GlobalDesc& global = codeMeta().globals[globalIndex];
3881
3882 // Constant globals are baked into the code and never stored in global data.
3883 if (global.isConstant()) {
3884 // We can just re-evaluate the global initializer to get the value.
3885 result.set(Val(global.constantValue()));
3886 return;
3887 }
3888
3889 // Otherwise, we need to load the initialized value from its cell.
3890 const void* cell = addressOfGlobalCell(global);
3891 result.address()->initFromHeapLocation(global.type(), cell);
3892 }
3893
3894 WasmStructObject* Instance::constantStructNewDefault(JSContext* cx,
3895 uint32_t typeIndex) {
3896 // We assume that constant structs will have a long lifetime and hence
3897 // allocate them directly in the tenured heap. Also, we have to dynamically
3898 // decide whether an OOL storage area is required. This is slow(er); do not
3899 // call here from generated code.
3900 TypeDefInstanceData* typeDefData = typeDefInstanceData(typeIndex);
3901 const wasm::TypeDef* typeDef = typeDefData->typeDef;
3902 MOZ_ASSERT(typeDef->kind() == wasm::TypeDefKind::Struct);
3903 uint32_t totalBytes = typeDef->structType().size_;
3904
3905 bool needsOOL = WasmStructObject::requiresOutlineBytes(totalBytes);
3906 return needsOOL ? WasmStructObject::createStructOOL<true>(
3907 cx, typeDefData, nullptr, gc::Heap::Tenured)
3908 : WasmStructObject::createStructIL<true>(
3909 cx, typeDefData, nullptr, gc::Heap::Tenured);
3910 }
3911
3912 WasmArrayObject* Instance::constantArrayNewDefault(JSContext* cx,
3913 uint32_t typeIndex,
3914 uint32_t numElements) {
3915 TypeDefInstanceData* typeDefData = typeDefInstanceData(typeIndex);
3916 // We assume that constant arrays will have a long lifetime and hence
3917 // allocate them directly in the tenured heap.
3918 return WasmArrayObject::createArray<true>(cx, typeDefData, nullptr,
3919 gc::Heap::Tenured, numElements);
3920 }
3921
3922 JSAtom* Instance::getFuncDisplayAtom(JSContext* cx, uint32_t funcIndex) const {
3923 // The "display name" of a function is primarily shown in Error.stack which
3924 // also includes location, so use getFuncNameBeforeLocation.
3925 UTF8Bytes name;
3926 bool ok;
3927 if (codeMetaForAsmJS()) {
3928 ok = codeMetaForAsmJS()->getFuncNameForAsmJS(funcIndex, &name);
3929 } else {
3930 ok = codeMeta().getFuncNameForWasm(NameContext::BeforeLocation, funcIndex,
3931 codeTailMeta().nameSectionPayload.get(),
3932 &name);
3933 }
3934 if (!ok) {
3935 return nullptr;
3936 }
3937
3938 return AtomizeUTF8Chars(cx, name.begin(), name.length());
3939 }
3940
3941 void Instance::ensureProfilingLabels(bool profilingEnabled) const {
3942 return code_->ensureProfilingLabels(profilingEnabled);
3943 }
3944
3945 void Instance::onMovingGrowMemory(const WasmMemoryObject* memory) {
3946 MOZ_ASSERT(!isAsmJS());
3947 MOZ_ASSERT(!memory->isShared());
3948
3949 for (uint32_t i = 0; i < codeMeta().memories.length(); i++) {
3950 MemoryInstanceData& md = memoryInstanceData(i);
3951 if (memory != md.memory) {
3952 continue;
3953 }
3954 ArrayBufferObject& buffer = md.memory->buffer().as<ArrayBufferObject>();
3955
3956 md.base = buffer.dataPointer();
3957 size_t limit = md.memory->boundsCheckLimit();
3958 #if !defined(JS_64BIT)
3959 // We assume that the limit is a 32-bit quantity
3960 MOZ_ASSERT(limit <= UINT32_MAX);
3961 #endif
3962 md.boundsCheckLimit = limit;
3963
3964 if (i == 0) {
3965 memory0Base_ = md.base;
3966 memory0BoundsCheckLimit_ = md.boundsCheckLimit;
3967 }
3968 }
3969 }
3970
3971 void Instance::onMovingGrowTable(const Table* table) {
3972 MOZ_ASSERT(!isAsmJS());
3973
3974 // `table` has grown and we must update cached data for it. Importantly,
3975 // we can have cached those data in more than one location: we'll have
3976 // cached them once for each time the table was imported into this instance.
3977 //
3978 // When an instance is registered as an observer of a table it is only
3979 // registered once, regardless of how many times the table was imported.
3980 // Thus when a table is grown, onMovingGrowTable() is only invoked once for
3981 // the table.
3982 //
3983 // Ergo we must go through the entire list of tables in the instance here
3984 // and check for the table in all the cached-data slots; we can't exit after
3985 // the first hit.
3986
3987 for (uint32_t i = 0; i < tables_.length(); i++) {
3988 if (tables_[i] != table) {
3989 continue;
3990 }
3991 TableInstanceData& table = tableInstanceData(i);
3992 table.length = tables_[i]->length();
3993 table.elements = tables_[i]->instanceElements();
3994 }
3995 }
3996
3997 JSString* Instance::createDisplayURL(JSContext* cx) {
3998 // In the best case, we simply have a URL, from a streaming compilation of a
3999 // fetched Response.
4000
4001 if (codeMeta().scriptedCaller().filenameIsURL) {
4002 const char* filename = codeMeta().scriptedCaller().filename.get();
4003 return NewStringCopyUTF8N(cx, JS::UTF8Chars(filename, strlen(filename)));
4004 }
4005
4006 // Otherwise, build wasm module URL from following parts:
4007 // - "wasm:" as protocol;
4008 // - URI encoded filename from metadata (if can be encoded), plus ":";
4009 // - 64-bit hash of the module bytes (as hex dump).
4010
4011 JSStringBuilder result(cx);
4012 if (!result.append("wasm:")) {
4013 return nullptr;
4014 }
4015
4016 if (const char* filename = codeMeta().scriptedCaller().filename.get()) {
4017 // EncodeURI returns false due to invalid chars or OOM -- fail only
4018 // during OOM.
4019 JSString* filenamePrefix = EncodeURI(cx, filename, strlen(filename));
4020 if (!filenamePrefix) {
4021 if (cx->isThrowingOutOfMemory()) {
4022 return nullptr;
4023 }
4024
4025 MOZ_ASSERT(!cx->isThrowingOverRecursed());
4026 cx->clearPendingException();
4027 return nullptr;
4028 }
4029
4030 if (!result.append(filenamePrefix)) {
4031 return nullptr;
4032 }
4033 }
4034
4035 if (code().debugEnabled()) {
4036 if (!result.append(":")) {
4037 return nullptr;
4038 }
4039
4040 const ModuleHash& hash = codeTailMeta().debugHash;
4041 for (unsigned char byte : hash) {
4042 unsigned char digit1 = byte / 16, digit2 = byte % 16;
4043 if (!result.append(
4044 (char)(digit1 < 10 ? digit1 + '0' : digit1 + 'a' - 10))) {
4045 return nullptr;
4046 }
4047 if (!result.append(
4048 (char)(digit2 < 10 ? digit2 + '0' : digit2 + 'a' - 10))) {
4049 return nullptr;
4050 }
4051 }
4052 }
4053
4054 return result.finishString();
4055 }
4056
4057 WasmBreakpointSite* Instance::getOrCreateBreakpointSite(JSContext* cx,
4058 uint32_t offset) {
4059 MOZ_ASSERT(debugEnabled());
4060 return debug().getOrCreateBreakpointSite(cx, this, offset);
4061 }
4062
4063 void Instance::destroyBreakpointSite(JS::GCContext* gcx, uint32_t offset) {
4064 MOZ_ASSERT(debugEnabled());
4065 return debug().destroyBreakpointSite(gcx, this, offset);
4066 }
4067
4068 void Instance::disassembleExport(JSContext* cx, uint32_t funcIndex, Tier tier,
4069 PrintCallback printString) const {
4070 const CodeBlock& codeBlock = code().funcCodeBlock(funcIndex);
4071 const FuncExport& funcExport = codeBlock.lookupFuncExport(funcIndex);
4072 const CodeRange& range = codeBlock.codeRange(funcExport);
4073
4074 MOZ_ASSERT(range.begin() < codeBlock.length());
4075 MOZ_ASSERT(range.end() < codeBlock.length());
4076
4077 uint8_t* functionCode = codeBlock.base() + range.begin();
4078 jit::Disassemble(functionCode, range.end() - range.begin(), printString);
4079 }
4080
4081 void Instance::addSizeOfMisc(
4082 mozilla::MallocSizeOf mallocSizeOf, CodeMetadata::SeenSet* seenCodeMeta,
4083 CodeMetadataForAsmJS::SeenSet* seenCodeMetaForAsmJS,
4084 Code::SeenSet* seenCode, Table::SeenSet* seenTables, size_t* code,
4085 size_t* data) const {
4086 *data += mallocSizeOf(this);
4087 for (const SharedTable& table : tables_) {
4088 *data += table->sizeOfIncludingThisIfNotSeen(mallocSizeOf, seenTables);
4089 }
4090
4091 if (maybeDebug_) {
4092 maybeDebug_->addSizeOfMisc(mallocSizeOf, seenCodeMeta, seenCodeMetaForAsmJS,
4093 seenCode, code, data);
4094 }
4095
4096 code_->addSizeOfMiscIfNotSeen(mallocSizeOf, seenCodeMeta,
4097 seenCodeMetaForAsmJS, seenCode, code, data);
4098 }
4099
4100 //////////////////////////////////////////////////////////////////////////////
4101 //
4102 // Reporting of errors that are traps.
4103
4104 void wasm::MarkPendingExceptionAsTrap(JSContext* cx) {
4105 RootedValue exn(cx);
4106 if (!cx->getPendingException(&exn)) {
4107 return;
4108 }
4109
4110 if (cx->isThrowingOutOfMemory()) {
4111 return;
4112 }
4113
4114 MOZ_RELEASE_ASSERT(exn.isObject() && exn.toObject().is<ErrorObject>());
4115 exn.toObject().as<ErrorObject>().setFromWasmTrap();
4116 }
4117
4118 void wasm::ReportTrapError(JSContext* cx, unsigned errorNumber) {
4119 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, errorNumber);
4120
4121 if (cx->isThrowingOutOfMemory()) {
4122 return;
4123 }
4124
4125 // Mark the exception as thrown from a trap to prevent if from being handled
4126 // by wasm exception handlers.
4127 MarkPendingExceptionAsTrap(cx);
4128 }