Source code

Revision control

Copy as Markdown

Other Tools

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
*
* Copyright 2016 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "wasm/WasmJS.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/EndianUtils.h"
#include "mozilla/Maybe.h"
#include "mozilla/RangedPtr.h"
#include <algorithm>
#include "jsapi.h"
#include "jsexn.h"
#include "ds/IdValuePair.h" // js::IdValuePair
#include "gc/GCContext.h"
#include "jit/AtomicOperations.h"
#include "jit/JitContext.h"
#include "jit/JitOptions.h"
#include "jit/Simulator.h"
#include "js/ForOfIterator.h"
#include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
#include "js/Printf.h"
#include "js/PropertyAndElement.h" // JS_DefineProperty, JS_GetProperty
#include "js/PropertySpec.h" // JS_{PS,FN}{,_END}
#include "js/Stack.h" // BuildStackString
#include "js/StreamConsumer.h"
#include "util/StringBuffer.h"
#include "util/Text.h"
#include "vm/ErrorObject.h"
#include "vm/FunctionFlags.h" // js::FunctionFlags
#include "vm/GlobalObject.h" // js::GlobalObject
#include "vm/HelperThreadState.h" // js::PromiseHelperTask
#include "vm/Interpreter.h"
#include "vm/JSFunction.h"
#include "vm/PlainObject.h" // js::PlainObject
#include "vm/PromiseObject.h" // js::PromiseObject
#include "vm/StringType.h"
#include "vm/Warnings.h" // js::WarnNumberASCII
#include "vm/WellKnownAtom.h" // js_*_str
#include "wasm/WasmBaselineCompile.h"
#include "wasm/WasmBuiltins.h"
#include "wasm/WasmCompile.h"
#include "wasm/WasmCraneliftCompile.h"
#include "wasm/WasmDebug.h"
#include "wasm/WasmInstance.h"
#include "wasm/WasmIntrinsic.h"
#include "wasm/WasmIonCompile.h"
#include "wasm/WasmModule.h"
#include "wasm/WasmProcess.h"
#include "wasm/WasmSignalHandlers.h"
#include "wasm/WasmStubs.h"
#include "wasm/WasmValidate.h"
#include "vm/ArrayBufferObject-inl.h"
#include "vm/JSObject-inl.h"
#include "vm/NativeObject-inl.h"
#include "wasm/WasmInstance-inl.h"
/*
* [SMDOC] WebAssembly code rules (evolving)
*
* TlsContext.get() is only to be invoked from functions that have been invoked
* _directly_ by generated code as cold(!) Builtin calls, from code that is
* only used by signal handlers, or from helper functions that have been
* called _directly_ from a simulator. All other code shall pass in a
* JSContext* to functions that need it, or an Instance* or Instance* since
* the context is available through them.
*
* Code that uses TlsContext.get() shall annotate each such call with the
* reason why the call is OK.
*/
using namespace js;
using namespace js::jit;
using namespace js::wasm;
using mozilla::CheckedInt;
using mozilla::Nothing;
using mozilla::RangedPtr;
using mozilla::Span;
// About the fuzzer intercession points: If fuzzing has been selected and only a
// single compiler has been selected then we will disable features that are not
// supported by that single compiler. This is strictly a concession to the
// fuzzer infrastructure.
static inline bool IsFuzzingIon(JSContext* cx) {
return IsFuzzing() && !cx->options().wasmBaseline() &&
cx->options().wasmIon() && !cx->options().wasmCranelift();
}
static inline bool IsFuzzingCranelift(JSContext* cx) {
return IsFuzzing() && !cx->options().wasmBaseline() &&
!cx->options().wasmIon() && cx->options().wasmCranelift();
}
// These functions read flags and apply fuzzing intercession policies. Never go
// directly to the flags in code below, always go via these accessors.
#ifdef ENABLE_WASM_SIMD_WORMHOLE
static inline bool WasmSimdWormholeFlag(JSContext* cx) {
return cx->options().wasmSimdWormhole();
}
#endif
static inline bool WasmThreadsFlag(JSContext* cx) {
return cx->realm() &&
cx->realm()->creationOptions().getSharedMemoryAndAtomicsEnabled();
}
#define WASM_FEATURE(NAME, LOWER_NAME, COMPILE_PRED, COMPILER_PRED, FLAG_PRED, \
...) \
static inline bool Wasm##NAME##Flag(JSContext* cx) { \
return (COMPILE_PRED) && (FLAG_PRED) && cx->options().wasm##NAME(); \
}
JS_FOR_WASM_FEATURES(WASM_FEATURE, WASM_FEATURE, WASM_FEATURE);
#undef WASM_FEATURE
static inline bool WasmDebuggerActive(JSContext* cx) {
if (IsFuzzingIon(cx) || IsFuzzingCranelift(cx)) {
return false;
}
return cx->realm() && cx->realm()->debuggerObservesWasm();
}
/*
* [SMDOC] Compiler and feature selection; compiler and feature availability.
*
* In order to make the computation of whether a wasm feature or wasm compiler
* is available predictable, we have established some rules, and implemented
* those rules.
*
* Code elsewhere should use the predicates below to test for features and
* compilers, it should never try to compute feature and compiler availability
* in other ways.
*
* At the outset, there is a set of selected compilers C containing at most one
* baseline compiler [*] and at most one optimizing compiler [**], and a set of
* selected features F. These selections come from defaults and from overrides
* by command line switches in the shell and javascript.option.wasm_X in the
* browser. Defaults for both features and compilers may be platform specific,
* for example, some compilers may not be available on some platforms because
* they do not support the architecture at all or they do not support features
* that must be enabled by default on the platform.
*
* [*] Currently we have only one, "baseline" aka "Rabaldr", but other
* implementations have additional baseline translators, eg from wasm
* bytecode to an internal code processed by an interpreter.
*
* [**] Currently we have two, "ion" aka "Baldr", and "Cranelift".
*
*
* Compiler availability:
*
* The set of features F induces a set of available compilers A: these are the
* compilers that all support all the features in F. (Some of these compilers
* may not be in the set C.)
*
* The sets C and A are intersected, yielding a set of enabled compilers E.
* Notably, the set E may be empty, in which case wasm is effectively disabled
* (though the WebAssembly object is still present in the global environment).
*
* An important consequence is that selecting a feature that is not supported by
* a particular compiler disables that compiler completely -- there is no notion
* of a compiler being available but suddenly failing when an unsupported
* feature is used by a program. If a compiler is available, it supports all
* the features that have been selected.
*
* Equally important, a feature cannot be enabled by default on a platform if
* the feature is not supported by all the compilers we wish to have enabled by
* default on the platform. We MUST by-default disable features on a platform
* that are not supported by all the compilers on the platform.
*
* As an example:
*
* On ARM64 the default compilers are Baseline and Cranelift. Say Cranelift
* does not support feature X. Thus X cannot be enabled by default on ARM64.
* However, X support can be compiled-in to SpiderMonkey, and the user can opt
* to enable X. Doing so will disable Cranelift.
*
* In contrast, X can be enabled by default on x64, where the default
* compilers are Baseline and Ion, both of which support X.
*
* A subtlety is worth noting: on x64, enabling Cranelift (thus disabling Ion)
* will not disable X. Instead, the presence of X in the selected feature set
* will disable Cranelift, leaving only Baseline. This follows from the logic
* described above.
*
* In a shell build, the testing functions wasmCompilersPresent,
* wasmCompileMode, wasmCraneliftDisabledByFeatures, and
* wasmIonDisabledByFeatures can be used to probe compiler availability and the
* reasons for a compiler being unavailable.
*
*
* Feature availability:
*
* A feature is available if it is selected and there is at least one available
* compiler that implements it.
*
* For example, --wasm-gc selects the GC feature, and if Baseline is available
* then the feature is available.
*
* In a shell build, there are per-feature testing functions (of the form
* wasmFeatureEnabled) to probe whether specific features are available.
*/
// Compiler availability predicates. These must be kept in sync with the
// feature predicates in the next section below.
//
// These can't call the feature predicates since the feature predicates call
// back to these predicates. So there will be a small amount of duplicated
// logic here, but as compilers reach feature parity that duplication will go
// away.
//
// There's a static precedence order between the optimizing compilers. This
// order currently ranks Cranelift over Ion on all platforms because Cranelift
// is disabled by default on all platforms: anyone who has enabled Cranelift
// will wish to use it instead of Ion.
//
// The precedence order is implemented by guards in IonAvailable() and
// CraneliftAvailable(). We expect that it will become more complex as the
// default settings change. But it should remain static.
bool wasm::BaselineAvailable(JSContext* cx) {
if (!cx->options().wasmBaseline() || !BaselinePlatformSupport()) {
return false;
}
bool isDisabled = false;
MOZ_ALWAYS_TRUE(BaselineDisabledByFeatures(cx, &isDisabled));
return !isDisabled;
}
bool wasm::IonAvailable(JSContext* cx) {
if (!cx->options().wasmIon() || !IonPlatformSupport()) {
return false;
}
bool isDisabled = false;
MOZ_ALWAYS_TRUE(IonDisabledByFeatures(cx, &isDisabled));
return !isDisabled && !CraneliftAvailable(cx);
}
bool wasm::WasmCompilerForAsmJSAvailable(JSContext* cx) {
// For now, restrict this to Ion - we have not tested Cranelift properly.
return IonAvailable(cx);
}
template <size_t ArrayLength>
static inline bool Append(JSStringBuilder* reason, const char (&s)[ArrayLength],
char* sep) {
if ((*sep && !reason->append(*sep)) || !reason->append(s)) {
return false;
}
*sep = ',';
return true;
}
bool wasm::BaselineDisabledByFeatures(JSContext* cx, bool* isDisabled,
JSStringBuilder* reason) {
// Baseline cannot be used if we are testing serialization.
bool testSerialization = WasmTestSerializationFlag(cx);
if (reason) {
char sep = 0;
if (testSerialization && !Append(reason, "testSerialization", &sep)) {
return false;
}
}
*isDisabled = testSerialization;
return true;
}
bool wasm::IonDisabledByFeatures(JSContext* cx, bool* isDisabled,
JSStringBuilder* reason) {
// Ion has no debugging support, no gc support.
bool debug = WasmDebuggerActive(cx);
bool functionReferences = WasmFunctionReferencesFlag(cx);
bool gc = WasmGcFlag(cx);
if (reason) {
char sep = 0;
if (debug && !Append(reason, "debug", &sep)) {
return false;
}
if (functionReferences && !Append(reason, "function-references", &sep)) {
return false;
}
if (gc && !Append(reason, "gc", &sep)) {
return false;
}
}
*isDisabled = debug || functionReferences || gc;
return true;
}
bool wasm::CraneliftAvailable(JSContext* cx) {
if (!cx->options().wasmCranelift() || !CraneliftPlatformSupport()) {
return false;
}
bool isDisabled = false;
MOZ_ALWAYS_TRUE(CraneliftDisabledByFeatures(cx, &isDisabled));
return !isDisabled;
}
bool wasm::CraneliftDisabledByFeatures(JSContext* cx, bool* isDisabled,
JSStringBuilder* reason) {
// Cranelift has no debugging support, no serialization support, no gc
// support, no simd, and no exceptions support.
bool debug = WasmDebuggerActive(cx);
bool testSerialization = WasmTestSerializationFlag(cx);
bool functionReferences = WasmFunctionReferencesFlag(cx);
bool gc = WasmGcFlag(cx);
#ifdef JS_CODEGEN_ARM64
// Cranelift aarch64 has full SIMD support.
bool simdOnNonAarch64 = false;
#else
bool simdOnNonAarch64 = WasmSimdFlag(cx);
#endif
bool exn = WasmExceptionsFlag(cx);
if (reason) {
char sep = 0;
if (debug && !Append(reason, "debug", &sep)) {
return false;
}
if (testSerialization && !Append(reason, "testSerialization", &sep)) {
return false;
}
if (functionReferences && !Append(reason, "function-references", &sep)) {
return false;
}
if (gc && !Append(reason, "gc", &sep)) {
return false;
}
if (simdOnNonAarch64 && !Append(reason, "simd", &sep)) {
return false;
}
if (exn && !Append(reason, "exceptions", &sep)) {
return false;
}
}
*isDisabled = debug || testSerialization || functionReferences || gc ||
simdOnNonAarch64 || exn;
return true;
}
bool wasm::AnyCompilerAvailable(JSContext* cx) {
return wasm::BaselineAvailable(cx) || wasm::IonAvailable(cx) ||
wasm::CraneliftAvailable(cx);
}
// Feature predicates. These must be kept in sync with the predicates in the
// section above.
//
// The meaning of these predicates is tricky: A predicate is true for a feature
// if the feature is enabled and/or compiled-in *and* we have *at least one*
// compiler that can support the feature. Subsequent compiler selection must
// ensure that only compilers that actually support the feature are used.
#define WASM_FEATURE(NAME, LOWER_NAME, COMPILE_PRED, COMPILER_PRED, FLAG_PRED, \
...) \
bool wasm::NAME##Available(JSContext* cx) { \
return Wasm##NAME##Flag(cx) && (COMPILER_PRED); \
}
JS_FOR_WASM_FEATURES(WASM_FEATURE, WASM_FEATURE, WASM_FEATURE)
#undef WASM_FEATURE
bool wasm::IsSimdPrivilegedContext(JSContext* cx) {
// This may be slightly more lenient than we want in an ideal world, but it
// remains safe.
return cx->realm() && cx->realm()->principals() &&
cx->realm()->principals()->isSystemOrAddonPrincipal();
}
bool wasm::SimdWormholeAvailable(JSContext* cx) {
#ifdef ENABLE_WASM_SIMD_WORMHOLE
// The #ifdef ensures that we only enable the wormhole on hardware that
// supports it and if SIMD support is compiled in.
//
// Next we must check that the CPU supports SIMD; it might not, even if SIMD
// is available. Do this directly, not via WasmSimdFlag().
//
// Do not go via WasmSimdFlag() because we do not want to gate on
// j.o.wasm_simd. If the wormhole is available, requesting it will
// force-enable SIMD.
return js::jit::JitSupportsWasmSimd() &&
(WasmSimdWormholeFlag(cx) || IsSimdPrivilegedContext(cx)) &&
(IonAvailable(cx) || BaselineAvailable(cx)) && !CraneliftAvailable(cx);
#else
return false;
#endif
}
bool wasm::ThreadsAvailable(JSContext* cx) {
return WasmThreadsFlag(cx) && AnyCompilerAvailable(cx);
}
bool wasm::HasPlatformSupport(JSContext* cx) {
#if !MOZ_LITTLE_ENDIAN()
return false;
#else
if (!HasJitBackend()) {
return false;
}
if (gc::SystemPageSize() > wasm::PageSize) {
return false;
}
if (!JitOptions.supportsUnalignedAccesses) {
return false;
}
if (!wasm::EnsureFullSignalHandlers(cx)) {
return false;
}
if (!jit::JitSupportsAtomics()) {
return false;
}
// Wasm threads require 8-byte lock-free atomics.
if (!jit::AtomicOperations::isLockfree8()) {
return false;
}
// Test only whether the compilers are supported on the hardware, not whether
// they are enabled.
return BaselinePlatformSupport() || IonPlatformSupport() ||
CraneliftPlatformSupport();
#endif
}
bool wasm::HasSupport(JSContext* cx) {
// If the general wasm pref is on, it's on for everything.
bool prefEnabled = cx->options().wasm();
// If the general pref is off, check trusted principals.
if (MOZ_UNLIKELY(!prefEnabled)) {
prefEnabled = cx->options().wasmForTrustedPrinciples() && cx->realm() &&
cx->realm()->principals() &&
cx->realm()->principals()->isSystemOrAddonPrincipal();
}
// Do not check for compiler availability, as that may be run-time variant.
// For HasSupport() we want a stable answer depending only on prefs.
return prefEnabled && HasPlatformSupport(cx);
}
bool wasm::StreamingCompilationAvailable(JSContext* cx) {
// This should match EnsureStreamSupport().
return HasSupport(cx) && AnyCompilerAvailable(cx) &&
cx->runtime()->offThreadPromiseState.ref().initialized() &&
CanUseExtraThreads() && cx->runtime()->consumeStreamCallback &&
cx->runtime()->reportStreamErrorCallback;
}
bool wasm::CodeCachingAvailable(JSContext* cx) {
// Fuzzilli breaks the out-of-process compilation mechanism,
// so we disable it permanently in those builds.
#ifdef FUZZING_JS_FUZZILLI
return false;
#else
// At the moment, we require Ion support for code caching. The main reason
// for this is that wasm::CompileAndSerialize() does not have access to
// information about which optimizing compiler it should use. See comments in
// CompileAndSerialize(), below.
return StreamingCompilationAvailable(cx) && IonAvailable(cx);
#endif
}
// ============================================================================
// Imports
static bool ThrowBadImportArg(JSContext* cx) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_IMPORT_ARG);
return false;
}
static bool ThrowBadImportType(JSContext* cx, const char* field,
const char* str) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_IMPORT_TYPE, field, str);
return false;
}
static bool GetProperty(JSContext* cx, HandleObject obj, const char* chars,
MutableHandleValue v) {
JSAtom* atom = AtomizeUTF8Chars(cx, chars, strlen(chars));
if (!atom) {
return false;
}
RootedId id(cx, AtomToId(atom));
return GetProperty(cx, obj, obj, id, v);
}
bool js::wasm::GetImports(JSContext* cx, const Module& module,
HandleObject importObj, ImportValues* imports) {
if (!module.imports().empty() && !importObj) {
return ThrowBadImportArg(cx);
}
const Metadata& metadata = module.metadata();
uint32_t tagIndex = 0;
const TagDescVector& tags = metadata.tags;
uint32_t globalIndex = 0;
const GlobalDescVector& globals = metadata.globals;
uint32_t tableIndex = 0;
const TableDescVector& tables = metadata.tables;
for (const Import& import : module.imports()) {
RootedValue v(cx);
if (!GetProperty(cx, importObj, import.module.get(), &v)) {
return false;
}
if (!v.isObject()) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_IMPORT_FIELD,
import.module.get());
return false;
}
RootedObject obj(cx, &v.toObject());
if (!GetProperty(cx, obj, import.field.get(), &v)) {
return false;
}
switch (import.kind) {
case DefinitionKind::Function: {
if (!IsFunctionObject(v)) {
return ThrowBadImportType(cx, import.field.get(), "Function");
}
if (!imports->funcs.append(&v.toObject().as<JSFunction>())) {
return false;
}
break;
}
case DefinitionKind::Table: {
const uint32_t index = tableIndex++;
if (!v.isObject() || !v.toObject().is<WasmTableObject>()) {
return ThrowBadImportType(cx, import.field.get(), "Table");
}
RootedWasmTableObject obj(cx, &v.toObject().as<WasmTableObject>());
if (obj->table().elemType() != tables[index].elemType) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_TBL_TYPE_LINK);
return false;
}
if (!imports->tables.append(obj)) {
return false;
}
break;
}
case DefinitionKind::Memory: {
if (!v.isObject() || !v.toObject().is<WasmMemoryObject>()) {
return ThrowBadImportType(cx, import.field.get(), "Memory");
}
MOZ_ASSERT(!imports->memory);
imports->memory = &v.toObject().as<WasmMemoryObject>();
break;
}
case DefinitionKind::Tag: {
const uint32_t index = tagIndex++;
if (!v.isObject() || !v.toObject().is<WasmTagObject>()) {
return ThrowBadImportType(cx, import.field.get(), "Tag");
}
RootedWasmTagObject obj(cx, &v.toObject().as<WasmTagObject>());
// Checks whether the signature of the imported exception object matches
// the signature declared in the exception import's TagDesc.
if (obj->resultType() != tags[index].type->resultType()) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_TAG_SIG, import.module.get(),
import.field.get());
return false;
}
if (!imports->tagObjs.append(obj)) {
ReportOutOfMemory(cx);
return false;
}
break;
}
case DefinitionKind::Global: {
const uint32_t index = globalIndex++;
const GlobalDesc& global = globals[index];
MOZ_ASSERT(global.importIndex() == index);
RootedVal val(cx);
if (v.isObject() && v.toObject().is<WasmGlobalObject>()) {
RootedWasmGlobalObject obj(cx, &v.toObject().as<WasmGlobalObject>());
if (obj->isMutable() != global.isMutable()) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_GLOB_MUT_LINK);
return false;
}
if (obj->type() != global.type()) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_GLOB_TYPE_LINK);
return false;
}
if (imports->globalObjs.length() <= index &&
!imports->globalObjs.resize(index + 1)) {
ReportOutOfMemory(cx);
return false;
}
imports->globalObjs[index] = obj;
val = obj->val();
} else {
if (!global.type().isRefType()) {
if (global.type() == ValType::I64 && !v.isBigInt()) {
return ThrowBadImportType(cx, import.field.get(), "BigInt");
}
if (global.type() != ValType::I64 && !v.isNumber()) {
return ThrowBadImportType(cx, import.field.get(), "Number");
}
} else {
if (!global.type().isExternRef() && !v.isObjectOrNull()) {
return ThrowBadImportType(cx, import.field.get(),
"Object-or-null value required for "
"non-externref reference type");
}
}
if (global.isMutable()) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_GLOB_MUT_LINK);
return false;
}
if (!Val::fromJSValue(cx, global.type(), v, &val)) {
return false;
}
}
if (!imports->globalValues.append(val)) {
return false;
}
break;
}
}
}
MOZ_ASSERT(globalIndex == globals.length() ||
!globals[globalIndex].isImport());
return true;
}
static bool DescribeScriptedCaller(JSContext* cx, ScriptedCaller* caller,
const char* introducer) {
// Note: JS::DescribeScriptedCaller returns whether a scripted caller was
// found, not whether an error was thrown. This wrapper function converts
// back to the more ordinary false-if-error form.
JS::AutoFilename af;
if (JS::DescribeScriptedCaller(cx, &af, &caller->line)) {
caller->filename =
FormatIntroducedFilename(cx, af.get(), caller->line, introducer);
if (!caller->filename) {
return false;
}
}
return true;
}
// Parse the options bag that is optionally passed to functions that compile
// wasm. This is for internal experimentation purposes. See comments about the
// SIMD wormhole in WasmConstants.h.
static bool ParseCompileOptions(JSContext* cx, HandleValue maybeOptions,
FeatureOptions* options) {
if (SimdWormholeAvailable(cx)) {
if (maybeOptions.isObject()) {
RootedValue wormholeVal(cx);
RootedObject obj(cx, &maybeOptions.toObject());
if (!JS_GetProperty(cx, obj, "simdWormhole", &wormholeVal)) {
return false;
}
if (wormholeVal.isBoolean()) {
options->simdWormhole = wormholeVal.toBoolean();
}
}
}
return true;
}
static SharedCompileArgs InitCompileArgs(JSContext* cx,
HandleValue maybeOptions,
const char* introducer) {
ScriptedCaller scriptedCaller;
if (!DescribeScriptedCaller(cx, &scriptedCaller, introducer)) {
return nullptr;
}
FeatureOptions options;
if (!ParseCompileOptions(cx, maybeOptions, &options)) {
return nullptr;
}
return CompileArgs::buildAndReport(cx, std::move(scriptedCaller), options);
}
// ============================================================================
// Testing / Fuzzing support
bool wasm::Eval(JSContext* cx, Handle<TypedArrayObject*> code,
HandleObject importObj, HandleValue maybeOptions,
MutableHandleWasmInstanceObject instanceObj) {
if (!GlobalObject::ensureConstructor(cx, cx->global(), JSProto_WebAssembly)) {
return false;
}
MutableBytes bytecode = cx->new_<ShareableBytes>();
if (!bytecode) {
return false;
}
if (!bytecode->append((uint8_t*)code->dataPointerEither().unwrap(),
code->byteLength())) {
ReportOutOfMemory(cx);
return false;
}
SharedCompileArgs compileArgs =
InitCompileArgs(cx, maybeOptions, "wasm_eval");
if (!compileArgs) {
return false;
}
UniqueChars error;
UniqueCharsVector warnings;
SharedModule module =
CompileBuffer(*compileArgs, *bytecode, &error, &warnings, nullptr);
if (!module) {
if (error) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_COMPILE_ERROR, error.get());
return false;
}
ReportOutOfMemory(cx);
return false;
}
Rooted<ImportValues> imports(cx);
if (!GetImports(cx, *module, importObj, imports.address())) {
return false;
}
return module->instantiate(cx, imports.get(), nullptr, instanceObj);
}
struct MOZ_STACK_CLASS SerializeListener : JS::OptimizedEncodingListener {
// MOZ_STACK_CLASS means these can be nops.
MozExternalRefCountType MOZ_XPCOM_ABI AddRef() override { return 0; }
MozExternalRefCountType MOZ_XPCOM_ABI Release() override { return 0; }
DebugOnly<bool> called = false;
Bytes* serialized;
explicit SerializeListener(Bytes* serialized) : serialized(serialized) {}
void storeOptimizedEncoding(const uint8_t* bytes, size_t length) override {
MOZ_ASSERT(!called);
called = true;
if (serialized->resizeUninitialized(length)) {
memcpy(serialized->begin(), bytes, length);
}
}
};
bool wasm::CompileAndSerialize(JSContext* cx, const ShareableBytes& bytecode,
Bytes* serialized) {
// The caller must check that code caching is available
MOZ_ASSERT(CodeCachingAvailable(cx));
// Create and manually fill in compile args for code caching
MutableCompileArgs compileArgs = js_new<CompileArgs>(ScriptedCaller());
if (!compileArgs) {
return false;
}
// The caller has ensured CodeCachingAvailable(). Moreover, we want to ensure
// we go straight to tier-2 so that we synchronously call
// JS::OptimizedEncodingListener::storeOptimizedEncoding().
compileArgs->baselineEnabled = false;
compileArgs->forceTiering = false;
// We always pick Ion here, and we depend on CodeCachingAvailable() having
// determined that Ion is available, see comments at CodeCachingAvailable().
// To do better, we need to pass information about which compiler that should
// be used into CompileAndSerialize().
compileArgs->ionEnabled = true;
// Select features that are enabled. This is guaranteed to be consistent with
// our compiler selection, as code caching is only available if ion is
// available, and ion is only available if it's not disabled by enabled
// features.
compileArgs->features = FeatureArgs::build(cx, FeatureOptions());
SerializeListener listener(serialized);
UniqueChars error;
UniqueCharsVector warnings;
SharedModule module =
CompileBuffer(*compileArgs, bytecode, &error, &warnings, &listener);
if (!module) {
fprintf(stderr, "Compilation error: %s\n", error ? error.get() : "oom");
return false;
}
MOZ_ASSERT(module->code().hasTier(Tier::Serialized));
MOZ_ASSERT(listener.called);
return !listener.serialized->empty();
}
bool wasm::DeserializeModule(JSContext* cx, const Bytes& serialized,
MutableHandleObject moduleObj) {
MutableModule module =
Module::deserialize(serialized.begin(), serialized.length());
if (!module) {
ReportOutOfMemory(cx);
return false;
}
moduleObj.set(module->createObject(cx));
return !!moduleObj;
}
// ============================================================================
// Common functions
// '[EnforceRange] unsigned long' types are coerced with
// ConvertToInt(v, 32, 'unsigned')
// defined in Web IDL Section 3.2.4.9.
//
// This just generalizes that to an arbitrary limit that is representable as an
// integer in double form.
static bool EnforceRange(JSContext* cx, HandleValue v, const char* kind,
const char* noun, uint64_t max, uint64_t* val) {
// Step 4.
double x;
if (!ToNumber(cx, v, &x)) {
return false;
}
// Step 5.
if (mozilla::IsNegativeZero(x)) {
x = 0.0;
}
// Step 6.1.
if (!mozilla::IsFinite(x)) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_UINT32, kind, noun);
return false;
}
// Step 6.2.
x = JS::ToInteger(x);
// Step 6.3.
if (x < 0 || x > double(max)) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_UINT32, kind, noun);
return false;
}
*val = uint64_t(x);
MOZ_ASSERT(double(*val) == x);
return true;
}
static bool EnforceRangeU32(JSContext* cx, HandleValue v, const char* kind,
const char* noun, uint32_t* u32) {
uint64_t u64 = 0;
if (!EnforceRange(cx, v, kind, noun, uint64_t(UINT32_MAX), &u64)) {
return false;
}
*u32 = uint32_t(u64);
return true;
}
static bool GetLimit(JSContext* cx, HandleObject obj, const char* name,
const char* noun, const char* msg, uint32_t range,
bool* found, uint64_t* value) {
JSAtom* atom = Atomize(cx, name, strlen(name));
if (!atom) {
return false;
}
RootedId id(cx, AtomToId(atom));
RootedValue val(cx);
if (!GetProperty(cx, obj, obj, id, &val)) {
return false;
}
if (val.isUndefined()) {
*found = false;
return true;
}
*found = true;
// The range can be greater than 53, but then the logic in EnforceRange has to
// change to avoid precision loss.
MOZ_ASSERT(range < 54);
return EnforceRange(cx, val, noun, msg, (uint64_t(1) << range) - 1, value);
}
static bool GetLimits(JSContext* cx, HandleObject obj, LimitsKind kind,
Limits* limits) {
limits->indexType = IndexType::I32;
// Memory limits may specify an alternate index type, and we need this to
// check the ranges for initial and maximum, so look for the index type first.
if (kind == LimitsKind::Memory) {
#ifdef ENABLE_WASM_MEMORY64
// Get the index type field
JSAtom* indexTypeAtom = Atomize(cx, "index", strlen("index"));
if (!indexTypeAtom) {
return false;
}
RootedId indexTypeId(cx, AtomToId(indexTypeAtom));
RootedValue indexTypeVal(cx);
if (!GetProperty(cx, obj, obj, indexTypeId, &indexTypeVal)) {
return false;
}
// The index type has a default value
if (!indexTypeVal.isUndefined()) {
if (!ToIndexType(cx, indexTypeVal, &limits->indexType)) {
return false;
}
if (limits->indexType == IndexType::I64 && !Memory64Available(cx)) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_WASM_NO_MEM64_LINK);
return false;
}
}
#endif
}
const char* noun = (kind == LimitsKind::Memory ? "Memory" : "Table");
// 2^48 is a valid value, so the range goes to 49 bits. Values above 2^48 are
// filtered later, just as values above 2^16 are filtered for mem32.
const uint32_t range = limits->indexType == IndexType::I32 ? 32 : 49;
uint64_t limit = 0;
bool haveInitial = false;
if (!GetLimit(cx, obj, "initial", noun, "initial size", range, &haveInitial,
&limit)) {
return false;
}
if (haveInitial) {
limits->initial = limit;
}
bool haveMinimum = false;
#ifdef ENABLE_WASM_TYPE_REFLECTIONS
if (!GetLimit(cx, obj, "minimum", noun, "initial size", range, &haveMinimum,
&limit)) {
return false;
}
if (haveMinimum) {
limits->initial = limit;
}
#endif
if (!(haveInitial || haveMinimum)) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_MISSING_REQUIRED, "initial");
return false;
}
if (haveInitial && haveMinimum) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_SUPPLY_ONLY_ONE, "minimum", "initial");
return false;
}
bool haveMaximum = false;
if (!GetLimit(cx, obj, "maximum", noun, "maximum size", range, &haveMaximum,
&limit)) {
return false;
}
if (haveMaximum) {
limits->maximum = Some(limit);
}
limits->shared = Shareable::False;
// Memory limits may be shared.
if (kind == LimitsKind::Memory) {
// Get the shared field
JSAtom* sharedAtom = Atomize(cx, "shared", strlen("shared"));
if (!sharedAtom) {
return false;
}
RootedId sharedId(cx, AtomToId(sharedAtom));
RootedValue sharedVal(cx);
if (!GetProperty(cx, obj, obj, sharedId, &sharedVal)) {
return false;
}
// shared's default value is false, which is already the value set above.
if (!sharedVal.isUndefined()) {
limits->shared =
ToBoolean(sharedVal) ? Shareable::True : Shareable::False;
if (limits->shared == Shareable::True) {
if (!haveMaximum) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_WASM_MISSING_MAXIMUM, noun);
return false;
}
if (!cx->realm()
->creationOptions()
.getSharedMemoryAndAtomicsEnabled()) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_WASM_NO_SHMEM_LINK);
return false;
}
}
}
}
return true;
}
static bool CheckLimits(JSContext* cx, uint64_t maximumField, LimitsKind kind,
Limits* limits) {
const char* noun = (kind == LimitsKind::Memory ? "Memory" : "Table");
if (limits->initial > maximumField) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, JSMSG_WASM_BAD_RANGE,
noun, "initial size");
return false;
}
if (limits->maximum.isSome() &&
(*limits->maximum > maximumField || limits->initial > *limits->maximum)) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, JSMSG_WASM_BAD_RANGE,
noun, "maximum size");
return false;
}
return true;
}
template <class Class, const char* name>
static JSObject* CreateWasmConstructor(JSContext* cx, JSProtoKey key) {
RootedAtom className(cx, Atomize(cx, name, strlen(name)));
if (!className) {
return nullptr;
}
return NewNativeConstructor(cx, Class::construct, 1, className);
}
static JSObject* GetWasmConstructorPrototype(JSContext* cx,
const CallArgs& callArgs,
JSProtoKey key) {
RootedObject proto(cx);
if (!GetPrototypeFromBuiltinConstructor(cx, callArgs, key, &proto)) {
return nullptr;
}
if (!proto) {
proto = GlobalObject::getOrCreatePrototype(cx, key);
}
return proto;
}
static JSString* UTF8CharsToString(JSContext* cx, const char* chars) {
return NewStringCopyUTF8Z(cx, JS::ConstUTF8CharsZ(chars, strlen(chars)));
}
[[nodiscard]] static bool ParseValTypes(JSContext* cx, HandleValue src,
ValTypeVector& dest) {
JS::ForOfIterator iterator(cx);
if (!iterator.init(src, JS::ForOfIterator::ThrowOnNonIterable)) {
return false;
}
RootedValue nextParam(cx);
while (true) {
bool done;
if (!iterator.next(&nextParam, &done)) {
return false;
}
if (done) {
break;
}
ValType valType;
if (!ToValType(cx, nextParam, &valType) || !dest.append(valType)) {
return false;
}
}
return true;
}
#ifdef ENABLE_WASM_TYPE_REFLECTIONS
[[nodiscard]] static JSObject* ValTypesToArray(JSContext* cx,
const ValTypeVector& valTypes) {
RootedArrayObject arrayObj(cx, NewDenseEmptyArray(cx));
for (ValType valType : valTypes) {
RootedString type(cx, UTF8CharsToString(cx, ToJSAPIString(valType).get()));
if (!type) {
return nullptr;
}
if (!NewbornArrayPush(cx, arrayObj, StringValue(type))) {
return nullptr;
}
}
return arrayObj;
}
static JSObject* FuncTypeToObject(JSContext* cx, const FuncType& type) {
Rooted<IdValueVector> props(cx, IdValueVector(cx));
RootedObject parametersObj(cx, ValTypesToArray(cx, type.args()));
if (!parametersObj ||
!props.append(IdValuePair(NameToId(cx->names().parameters),
ObjectValue(*parametersObj)))) {
ReportOutOfMemory(cx);
return nullptr;
}
RootedObject resultsObj(cx, ValTypesToArray(cx, type.results()));
if (!resultsObj || !props.append(IdValuePair(NameToId(cx->names().results),
ObjectValue(*resultsObj)))) {
ReportOutOfMemory(cx);
return nullptr;
}
return NewPlainObjectWithProperties(cx, props.begin(), props.length(),
GenericObject);
}
static JSObject* TableTypeToObject(JSContext* cx, RefType type,
uint32_t initial, Maybe<uint32_t> maximum) {
Rooted<IdValueVector> props(cx, IdValueVector(cx));
RootedString elementType(cx,
UTF8CharsToString(cx, ToJSAPIString(type).get()));
if (!elementType || !props.append(IdValuePair(NameToId(cx->names().element),
StringValue(elementType)))) {
ReportOutOfMemory(cx);
return nullptr;
}
if (maximum.isSome()) {
if (!props.append(IdValuePair(NameToId(cx->names().maximum),
Int32Value(maximum.value())))) {
ReportOutOfMemory(cx);
return nullptr;
}
}
if (!props.append(
IdValuePair(NameToId(cx->names().minimum), Int32Value(initial)))) {
ReportOutOfMemory(cx);
return nullptr;
}
return NewPlainObjectWithProperties(cx, props.begin(), props.length(),
GenericObject);
}
static JSObject* MemoryTypeToObject(JSContext* cx, bool shared,
wasm::IndexType indexType,
wasm::Pages minPages,
Maybe<wasm::Pages> maxPages) {
Rooted<IdValueVector> props(cx, IdValueVector(cx));
if (maxPages) {
double maxPagesNum;
if (indexType == IndexType::I32) {
maxPagesNum = double(mozilla::AssertedCast<uint32_t>(maxPages->value()));
} else {
// The maximum number of pages is 2^48.
maxPagesNum = double(maxPages->value());
}
if (!props.append(IdValuePair(NameToId(cx->names().maximum),
NumberValue(maxPagesNum)))) {
ReportOutOfMemory(cx);
return nullptr;
}
}
double minPagesNum;
if (indexType == IndexType::I32) {
minPagesNum = double(mozilla::AssertedCast<uint32_t>(minPages.value()));
} else {
minPagesNum = double(minPages.value());
}
if (!props.append(IdValuePair(NameToId(cx->names().minimum),
NumberValue(minPagesNum)))) {
ReportOutOfMemory(cx);
return nullptr;
}
# ifdef ENABLE_WASM_MEMORY64
RootedString it(
cx, JS_NewStringCopyZ(cx, indexType == IndexType::I32 ? "i32" : "i64"));
if (!props.append(
IdValuePair(NameToId(cx->names().index), StringValue(it)))) {
ReportOutOfMemory(cx);
return nullptr;
}
# endif
if (!props.append(
IdValuePair(NameToId(cx->names().shared), BooleanValue(shared)))) {
ReportOutOfMemory(cx);
return nullptr;
}
return NewPlainObjectWithProperties(cx, props.begin(), props.length(),
GenericObject);
}
static JSObject* GlobalTypeToObject(JSContext* cx, ValType type,
bool isMutable) {
Rooted<IdValueVector> props(cx, IdValueVector(cx));
if (!props.append(IdValuePair(NameToId(cx->names().mutable_),
BooleanValue(isMutable)))) {
ReportOutOfMemory(cx);
return nullptr;
}
RootedString valueType(cx, UTF8CharsToString(cx, ToJSAPIString(type).get()));
if (!valueType || !props.append(IdValuePair(NameToId(cx->names().value),
StringValue(valueType)))) {
ReportOutOfMemory(cx);
return nullptr;
}
return NewPlainObjectWithProperties(cx, props.begin(), props.length(),
GenericObject);
}
static JSObject* TagTypeToObject(JSContext* cx,
const wasm::ValTypeVector& params) {
Rooted<IdValueVector> props(cx, IdValueVector(cx));
RootedObject parametersObj(cx, ValTypesToArray(cx, params));
if (!parametersObj ||
!props.append(IdValuePair(NameToId(cx->names().parameters),
ObjectValue(*parametersObj)))) {
ReportOutOfMemory(cx);
return nullptr;
}
return NewPlainObjectWithProperties(cx, props.begin(), props.length(),
GenericObject);
}
#endif // ENABLE_WASM_TYPE_REFLECTIONS
// ============================================================================
// WebAssembly.Module class and methods
const JSClassOps WasmModuleObject::classOps_ = {
nullptr, // addProperty
nullptr, // delProperty
nullptr, // enumerate
nullptr, // newEnumerate
nullptr, // resolve
nullptr, // mayResolve
WasmModuleObject::finalize, // finalize
nullptr, // call
nullptr, // construct
nullptr, // trace
};
const JSClass WasmModuleObject::class_ = {
"WebAssembly.Module",
JSCLASS_DELAY_METADATA_BUILDER |
JSCLASS_HAS_RESERVED_SLOTS(WasmModuleObject::RESERVED_SLOTS) |
JSCLASS_FOREGROUND_FINALIZE,
&WasmModuleObject::classOps_,
&WasmModuleObject::classSpec_,
};
const JSClass& WasmModuleObject::protoClass_ = PlainObject::class_;
static constexpr char WasmModuleName[] = "Module";
const ClassSpec WasmModuleObject::classSpec_ = {
CreateWasmConstructor<WasmModuleObject, WasmModuleName>,
GenericCreatePrototype<WasmModuleObject>,
WasmModuleObject::static_methods,
nullptr,
WasmModuleObject::methods,
WasmModuleObject::properties,
nullptr,
ClassSpec::DontDefineConstructor};
const JSPropertySpec WasmModuleObject::properties[] = {
JS_STRING_SYM_PS(toStringTag, "WebAssembly.Module", JSPROP_READONLY),
JS_PS_END};
const JSFunctionSpec WasmModuleObject::methods[] = {JS_FS_END};
const JSFunctionSpec WasmModuleObject::static_methods[] = {
JS_FN("imports", WasmModuleObject::imports, 1, JSPROP_ENUMERATE),
JS_FN("exports", WasmModuleObject::exports, 1, JSPROP_ENUMERATE),
JS_FN("customSections", WasmModuleObject::customSections, 2,
JSPROP_ENUMERATE),
JS_FS_END};
/* static */
void WasmModuleObject::finalize(JS::GCContext* gcx, JSObject* obj) {
const Module& module = obj->as<WasmModuleObject>().module();
obj->zone()->decJitMemory(module.codeLength(module.code().stableTier()));
gcx->release(obj, &module, module.gcMallocBytesExcludingCode(),
MemoryUse::WasmModule);
}
static bool IsModuleObject(JSObject* obj, const Module** module) {
WasmModuleObject* mobj = obj->maybeUnwrapIf<WasmModuleObject>();
if (!mobj) {
return false;
}
*module = &mobj->module();
return true;
}
static bool GetModuleArg(JSContext* cx, CallArgs args, uint32_t numRequired,
const char* name, const Module** module) {
if (!args.requireAtLeast(cx, name, numRequired)) {
return false;
}
if (!args[0].isObject() || !IsModuleObject(&args[0].toObject(), module)) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_MOD_ARG);
return false;
}
return true;
}
struct KindNames {
RootedPropertyName kind;
RootedPropertyName table;
RootedPropertyName memory;
RootedPropertyName tag;
RootedPropertyName type;
explicit KindNames(JSContext* cx)
: kind(cx), table(cx), memory(cx), tag(cx), type(cx) {}
};
static bool InitKindNames(JSContext* cx, KindNames* names) {
JSAtom* kind = Atomize(cx, "kind", strlen("kind"));
if (!kind) {
return false;
}
names->kind = kind->asPropertyName();
JSAtom* table = Atomize(cx, "table", strlen("table"));
if (!table) {
return false;
}
names->table = table->asPropertyName();
JSAtom* memory = Atomize(cx, "memory", strlen("memory"));
if (!memory) {
return false;
}
names->memory = memory->asPropertyName();
JSAtom* tag = Atomize(cx, "tag", strlen("tag"));
if (!tag) {
return false;
}
names->tag = tag->asPropertyName();
JSAtom* type = Atomize(cx, "type", strlen("type"));
if (!type) {
return false;
}
names->type = type->asPropertyName();
return true;
}
static JSString* KindToString(JSContext* cx, const KindNames& names,
DefinitionKind kind) {
switch (kind) {
case DefinitionKind::Function:
return cx->names().function;
case DefinitionKind::Table:
return names.table;
case DefinitionKind::Memory:
return names.memory;
case DefinitionKind::Global:
return cx->names().global;
case DefinitionKind::Tag:
return names.tag;
}
MOZ_CRASH("invalid kind");
}
/* static */
bool WasmModuleObject::imports(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
const Module* module;
if (!GetModuleArg(cx, args, 1, "WebAssembly.Module.imports", &module)) {
return false;
}
KindNames names(cx);
if (!InitKindNames(cx, &names)) {
return false;
}
RootedValueVector elems(cx);
if (!elems.reserve(module->imports().length())) {
return false;
}
#ifdef ENABLE_WASM_TYPE_REFLECTIONS
const Metadata& metadata = module->metadata();
const MetadataTier& metadataTier =
module->metadata(module->code().stableTier());
size_t numFuncImport = 0;
size_t numMemoryImport = 0;
size_t numGlobalImport = 0;
size_t numTableImport = 0;
size_t numTagImport = 0;
#endif // ENABLE_WASM_TYPE_REFLECTIONS
for (const Import& import : module->imports()) {
Rooted<IdValueVector> props(cx, IdValueVector(cx));
if (!props.reserve(3)) {
return false;
}
JSString* moduleStr = UTF8CharsToString(cx, import.module.get());
if (!moduleStr) {
return false;
}
props.infallibleAppend(
IdValuePair(NameToId(cx->names().module), StringValue(moduleStr)));
JSString* nameStr = UTF8CharsToString(cx, import.field.get());
if (!nameStr) {
return false;
}
props.infallibleAppend(
IdValuePair(NameToId(cx->names().name), StringValue(nameStr)));
JSString* kindStr = KindToString(cx, names, import.kind);
if (!kindStr) {
return false;
}
props.infallibleAppend(
IdValuePair(NameToId(names.kind), StringValue(kindStr)));
#ifdef ENABLE_WASM_TYPE_REFLECTIONS
RootedObject typeObj(cx);
switch (import.kind) {
case DefinitionKind::Function: {
size_t funcIndex = numFuncImport++;
typeObj = FuncTypeToObject(
cx, metadataTier.funcImports[funcIndex].funcType());
break;
}
case DefinitionKind::Table: {
size_t tableIndex = numTableImport++;
const TableDesc& table = metadata.tables[tableIndex];
typeObj = TableTypeToObject(cx, table.elemType, table.initialLength,
table.maximumLength);
break;
}
case DefinitionKind::Memory: {
DebugOnly<size_t> memoryIndex = numMemoryImport++;
MOZ_ASSERT(memoryIndex == 0);
const MemoryDesc& memory = *metadata.memory;
typeObj =
MemoryTypeToObject(cx, memory.isShared(), memory.indexType(),
memory.initialPages(), memory.maximumPages());
break;
}
case DefinitionKind::Global: {
size_t globalIndex = numGlobalImport++;
const GlobalDesc& global = metadata.globals[globalIndex];
typeObj = GlobalTypeToObject(cx, global.type(), global.isMutable());
break;
}
case DefinitionKind::Tag: {
size_t tagIndex = numTagImport++;
const TagDesc& tag = metadata.tags[tagIndex];
typeObj = TagTypeToObject(cx, tag.type->argTypes_);