| 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/WasmJS.h" |
| 20 |
|
| 21 |
#include "mozilla/EndianUtils.h" |
| 22 |
#include "mozilla/Maybe.h" |
| 23 |
|
| 24 |
#include <algorithm> |
| 25 |
#include <cstdint> |
| 26 |
|
| 27 |
#include "jsapi.h" |
| 28 |
#include "jsexn.h" |
| 29 |
|
| 30 |
#include "ds/IdValuePair.h" // js::IdValuePair |
| 31 |
#include "frontend/FrontendContext.h" // AutoReportFrontendContext |
| 32 |
#include "gc/GCContext.h" |
| 33 |
#include "jit/AtomicOperations.h" |
| 34 |
#include "jit/FlushICache.h" |
| 35 |
#include "jit/JitContext.h" |
| 36 |
#include "jit/JitOptions.h" |
| 37 |
#include "jit/Simulator.h" |
| 38 |
#include "js/ColumnNumber.h" // JS::ColumnNumberOneOrigin |
| 39 |
#include "js/ForOfIterator.h" |
| 40 |
#include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_* |
| 41 |
#include "js/Printf.h" |
| 42 |
#include "js/PropertyAndElement.h" // JS_DefineProperty, JS_GetProperty |
| 43 |
#include "js/PropertySpec.h" // JS_{PS,FN}{,_END} |
| 44 |
#include "js/Stack.h" // BuildStackString |
| 45 |
#include "js/StreamConsumer.h" |
| 46 |
#include "util/StringBuilder.h" |
| 47 |
#include "util/Text.h" |
| 48 |
#include "vm/ErrorObject.h" |
| 49 |
#include "vm/FunctionFlags.h" // js::FunctionFlags |
| 50 |
#include "vm/GlobalObject.h" // js::GlobalObject |
| 51 |
#include "vm/HelperThreadState.h" // js::PromiseHelperTask |
| 52 |
#include "vm/Interpreter.h" |
| 53 |
#include "vm/JSFunction.h" |
| 54 |
#include "vm/PlainObject.h" // js::PlainObject |
| 55 |
#include "vm/PromiseObject.h" // js::PromiseObject |
| 56 |
#include "vm/SharedArrayObject.h" |
| 57 |
#include "vm/StringType.h" |
| 58 |
#include "vm/Warnings.h" // js::WarnNumberASCII |
| 59 |
#include "wasm/WasmBaselineCompile.h" |
| 60 |
#include "wasm/WasmBuiltinModule.h" |
| 61 |
#include "wasm/WasmBuiltins.h" |
| 62 |
#include "wasm/WasmCompile.h" |
| 63 |
#include "wasm/WasmDebug.h" |
| 64 |
#include "wasm/WasmFeatures.h" |
| 65 |
#include "wasm/WasmInstance.h" |
| 66 |
#include "wasm/WasmIonCompile.h" |
| 67 |
#include "wasm/WasmMemory.h" |
| 68 |
#include "wasm/WasmModule.h" |
| 69 |
#include "wasm/WasmPI.h" |
| 70 |
#include "wasm/WasmProcess.h" |
| 71 |
#include "wasm/WasmSignalHandlers.h" |
| 72 |
#include "wasm/WasmStubs.h" |
| 73 |
#include "wasm/WasmValidate.h" |
| 74 |
|
| 75 |
#include "gc/GCContext-inl.h" |
| 76 |
#include "gc/StableCellHasher-inl.h" |
| 77 |
#include "vm/ArrayBufferObject-inl.h" |
| 78 |
#include "vm/JSObject-inl.h" |
| 79 |
#include "vm/NativeObject-inl.h" |
| 80 |
#include "wasm/WasmInstance-inl.h" |
| 81 |
|
| 82 |
/* |
| 83 |
* [SMDOC] WebAssembly code rules (evolving) |
| 84 |
* |
| 85 |
* TlsContext.get() is only to be invoked from functions that have been invoked |
| 86 |
* _directly_ by generated code as cold(!) Builtin calls, from code that is |
| 87 |
* only used by signal handlers, or from helper functions that have been |
| 88 |
* called _directly_ from a simulator. All other code shall pass in a |
| 89 |
* JSContext* to functions that need it, or an Instance* or Instance* since |
| 90 |
* the context is available through them. |
| 91 |
* |
| 92 |
* Code that uses TlsContext.get() shall annotate each such call with the |
| 93 |
* reason why the call is OK. |
| 94 |
*/ |
| 95 |
|
| 96 |
using namespace js; |
| 97 |
using namespace js::jit; |
| 98 |
using namespace js::wasm; |
| 99 |
|
| 100 |
using mozilla::Maybe; |
| 101 |
using mozilla::Nothing; |
| 102 |
using mozilla::Some; |
| 103 |
using mozilla::Span; |
| 104 |
|
| 105 |
static bool ThrowCompileOutOfMemory(JSContext* cx) { |
| 106 |
// Most OOMs during compilation are due to large contiguous allocations, |
| 107 |
// and future allocations are likely to succeed. Throwing a proper error |
| 108 |
// object is nicer for users in these circumstances. |
| 109 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_OUT_OF_MEMORY); |
| 110 |
return false; |
| 111 |
} |
| 112 |
|
| 113 |
// ============================================================================ |
| 114 |
// Imports |
| 115 |
|
| 116 |
static bool ThrowBadImportArg(JSContext* cx) { |
| 117 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 118 |
JSMSG_WASM_BAD_IMPORT_ARG); |
| 119 |
return false; |
| 120 |
} |
| 121 |
|
| 122 |
static bool ThrowBadImportType(JSContext* cx, const CacheableName& field, |
| 123 |
const char* str) { |
| 124 |
UniqueChars fieldQuoted = field.toQuotedString(cx); |
| 125 |
if (!fieldQuoted) { |
| 126 |
ReportOutOfMemory(cx); |
| 127 |
return false; |
| 128 |
} |
| 129 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 130 |
JSMSG_WASM_BAD_IMPORT_TYPE, fieldQuoted.get(), str); |
| 131 |
return false; |
| 132 |
} |
| 133 |
|
| 134 |
// For now reject cross-compartment wrappers. These have more complicated realm |
| 135 |
// semantics (we use nonCCWRealm in a few places) and may require unwrapping to |
| 136 |
// test for specific function types. |
| 137 |
static bool IsCallableNonCCW(const Value& v) { |
| 138 |
return IsCallable(v) && !IsCrossCompartmentWrapper(&v.toObject()); |
| 139 |
} |
| 140 |
|
| 141 |
static bool IsWasmSuspendingWrapper(const Value& v) { |
| 142 |
return v.isObject() && js::IsWasmSuspendingObject(&v.toObject()); |
| 143 |
} |
| 144 |
|
| 145 |
bool js::wasm::GetImports(JSContext* cx, const Module& module, |
| 146 |
HandleObject importObj, ImportValues* imports) { |
| 147 |
const ModuleMetadata& moduleMeta = module.moduleMeta(); |
| 148 |
const CodeMetadata& codeMeta = module.codeMeta(); |
| 149 |
const BuiltinModuleIds& builtinModules = codeMeta.features().builtinModules; |
| 150 |
|
| 151 |
if (!moduleMeta.imports.empty() && !importObj) { |
| 152 |
return ThrowBadImportArg(cx); |
| 153 |
} |
| 154 |
|
| 155 |
BuiltinModuleInstances builtinInstances(cx); |
| 156 |
RootedValue importModuleValue(cx); |
| 157 |
RootedObject importModuleObject(cx); |
| 158 |
bool isImportedStringModule = false; |
| 159 |
RootedValue importFieldValue(cx); |
| 160 |
|
| 161 |
uint32_t tagIndex = 0; |
| 162 |
const TagDescVector& tags = codeMeta.tags; |
| 163 |
uint32_t globalIndex = 0; |
| 164 |
const GlobalDescVector& globals = codeMeta.globals; |
| 165 |
uint32_t tableIndex = 0; |
| 166 |
const TableDescVector& tables = codeMeta.tables; |
| 167 |
for (const Import& import : moduleMeta.imports) { |
| 168 |
Maybe<BuiltinModuleId> builtinModule = |
| 169 |
ImportMatchesBuiltinModule(import.module.utf8Bytes(), builtinModules); |
| 170 |
if (builtinModule) { |
| 171 |
if (*builtinModule == BuiltinModuleId::JSStringConstants) { |
| 172 |
isImportedStringModule = true; |
| 173 |
importModuleObject = nullptr; |
| 174 |
} else { |
| 175 |
MutableHandle<JSObject*> builtinInstance = |
| 176 |
builtinInstances[*builtinModule]; |
| 177 |
if (!builtinInstance && !wasm::InstantiateBuiltinModule( |
| 178 |
cx, *builtinModule, builtinInstance)) { |
| 179 |
return false; |
| 180 |
} |
| 181 |
isImportedStringModule = false; |
| 182 |
importModuleObject = builtinInstance; |
| 183 |
} |
| 184 |
} else { |
| 185 |
RootedId moduleName(cx); |
| 186 |
if (!import.module.toPropertyKey(cx, &moduleName)) { |
| 187 |
return false; |
| 188 |
} |
| 189 |
|
| 190 |
if (!GetProperty(cx, importObj, importObj, moduleName, |
| 191 |
&importModuleValue)) { |
| 192 |
return false; |
| 193 |
} |
| 194 |
|
| 195 |
if (!importModuleValue.isObject()) { |
| 196 |
UniqueChars moduleQuoted = import.module.toQuotedString(cx); |
| 197 |
if (!moduleQuoted) { |
| 198 |
ReportOutOfMemory(cx); |
| 199 |
return false; |
| 200 |
} |
| 201 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 202 |
JSMSG_WASM_BAD_IMPORT_FIELD, |
| 203 |
moduleQuoted.get()); |
| 204 |
return false; |
| 205 |
} |
| 206 |
|
| 207 |
isImportedStringModule = false; |
| 208 |
importModuleObject = &importModuleValue.toObject(); |
| 209 |
} |
| 210 |
MOZ_RELEASE_ASSERT(!isImportedStringModule || |
| 211 |
import.kind == DefinitionKind::Global); |
| 212 |
|
| 213 |
if (isImportedStringModule) { |
| 214 |
RootedString stringConstant(cx, import.field.toJSString(cx)); |
| 215 |
if (!stringConstant) { |
| 216 |
ReportOutOfMemory(cx); |
| 217 |
return false; |
| 218 |
} |
| 219 |
importFieldValue = StringValue(stringConstant); |
| 220 |
} else { |
| 221 |
RootedId fieldName(cx); |
| 222 |
if (!import.field.toPropertyKey(cx, &fieldName)) { |
| 223 |
return false; |
| 224 |
} |
| 225 |
if (!GetProperty(cx, importModuleObject, importModuleObject, fieldName, |
| 226 |
&importFieldValue)) { |
| 227 |
return false; |
| 228 |
} |
| 229 |
} |
| 230 |
|
| 231 |
switch (import.kind) { |
| 232 |
case DefinitionKind::Function: { |
| 233 |
if (!IsCallableNonCCW(importFieldValue) && |
| 234 |
!IsWasmSuspendingWrapper(importFieldValue)) { |
| 235 |
return ThrowBadImportType(cx, import.field, "Function"); |
| 236 |
} |
| 237 |
|
| 238 |
if (!imports->funcs.append(&importFieldValue.toObject())) { |
| 239 |
ReportOutOfMemory(cx); |
| 240 |
return false; |
| 241 |
} |
| 242 |
|
| 243 |
break; |
| 244 |
} |
| 245 |
case DefinitionKind::Table: { |
| 246 |
const uint32_t index = tableIndex++; |
| 247 |
if (!importFieldValue.isObject() || |
| 248 |
!importFieldValue.toObject().is<WasmTableObject>()) { |
| 249 |
return ThrowBadImportType(cx, import.field, "Table"); |
| 250 |
} |
| 251 |
|
| 252 |
Rooted<WasmTableObject*> obj( |
| 253 |
cx, &importFieldValue.toObject().as<WasmTableObject>()); |
| 254 |
if (obj->table().elemType() != tables[index].elemType) { |
| 255 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 256 |
JSMSG_WASM_BAD_TBL_TYPE_LINK); |
| 257 |
return false; |
| 258 |
} |
| 259 |
|
| 260 |
if (!imports->tables.append(obj)) { |
| 261 |
ReportOutOfMemory(cx); |
| 262 |
return false; |
| 263 |
} |
| 264 |
break; |
| 265 |
} |
| 266 |
case DefinitionKind::Memory: { |
| 267 |
if (!importFieldValue.isObject() || |
| 268 |
!importFieldValue.toObject().is<WasmMemoryObject>()) { |
| 269 |
return ThrowBadImportType(cx, import.field, "Memory"); |
| 270 |
} |
| 271 |
|
| 272 |
if (!imports->memories.append( |
| 273 |
&importFieldValue.toObject().as<WasmMemoryObject>())) { |
| 274 |
ReportOutOfMemory(cx); |
| 275 |
return false; |
| 276 |
} |
| 277 |
break; |
| 278 |
} |
| 279 |
case DefinitionKind::Tag: { |
| 280 |
const uint32_t index = tagIndex++; |
| 281 |
if (!importFieldValue.isObject() || |
| 282 |
!importFieldValue.toObject().is<WasmTagObject>()) { |
| 283 |
return ThrowBadImportType(cx, import.field, "Tag"); |
| 284 |
} |
| 285 |
|
| 286 |
Rooted<WasmTagObject*> obj( |
| 287 |
cx, &importFieldValue.toObject().as<WasmTagObject>()); |
| 288 |
|
| 289 |
// Checks whether the signature of the imported exception object matches |
| 290 |
// the signature declared in the exception import's TagDesc. |
| 291 |
if (!TagType::matches(*obj->tagType(), *tags[index].type)) { |
| 292 |
UniqueChars fieldQuoted = import.field.toQuotedString(cx); |
| 293 |
UniqueChars moduleQuoted = import.module.toQuotedString(cx); |
| 294 |
if (!fieldQuoted || !moduleQuoted) { |
| 295 |
ReportOutOfMemory(cx); |
| 296 |
return false; |
| 297 |
} |
| 298 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 299 |
JSMSG_WASM_BAD_TAG_SIG, moduleQuoted.get(), |
| 300 |
fieldQuoted.get()); |
| 301 |
return false; |
| 302 |
} |
| 303 |
|
| 304 |
if (!imports->tagObjs.append(obj)) { |
| 305 |
ReportOutOfMemory(cx); |
| 306 |
return false; |
| 307 |
} |
| 308 |
break; |
| 309 |
} |
| 310 |
case DefinitionKind::Global: { |
| 311 |
const uint32_t index = globalIndex++; |
| 312 |
const GlobalDesc& global = globals[index]; |
| 313 |
MOZ_ASSERT(global.importIndex() == index); |
| 314 |
|
| 315 |
RootedVal val(cx); |
| 316 |
if (importFieldValue.isObject() && |
| 317 |
importFieldValue.toObject().is<WasmGlobalObject>()) { |
| 318 |
Rooted<WasmGlobalObject*> obj( |
| 319 |
cx, &importFieldValue.toObject().as<WasmGlobalObject>()); |
| 320 |
|
| 321 |
if (obj->isMutable() != global.isMutable()) { |
| 322 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 323 |
JSMSG_WASM_BAD_GLOB_MUT_LINK); |
| 324 |
return false; |
| 325 |
} |
| 326 |
|
| 327 |
bool matches = global.isMutable() |
| 328 |
? obj->type() == global.type() |
| 329 |
: ValType::isSubTypeOf(obj->type(), global.type()); |
| 330 |
if (!matches) { |
| 331 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 332 |
JSMSG_WASM_BAD_GLOB_TYPE_LINK); |
| 333 |
return false; |
| 334 |
} |
| 335 |
|
| 336 |
if (imports->globalObjs.length() <= index && |
| 337 |
!imports->globalObjs.resize(index + 1)) { |
| 338 |
ReportOutOfMemory(cx); |
| 339 |
return false; |
| 340 |
} |
| 341 |
imports->globalObjs[index] = obj; |
| 342 |
val = obj->val(); |
| 343 |
} else { |
| 344 |
if (!global.type().isRefType()) { |
| 345 |
if (global.type() == ValType::I64 && !importFieldValue.isBigInt()) { |
| 346 |
return ThrowBadImportType(cx, import.field, "BigInt"); |
| 347 |
} |
| 348 |
if (global.type() != ValType::I64 && !importFieldValue.isNumber()) { |
| 349 |
return ThrowBadImportType(cx, import.field, "Number"); |
| 350 |
} |
| 351 |
} |
| 352 |
|
| 353 |
if (global.isMutable()) { |
| 354 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 355 |
JSMSG_WASM_BAD_GLOB_MUT_LINK); |
| 356 |
return false; |
| 357 |
} |
| 358 |
|
| 359 |
if (!Val::fromJSValue(cx, global.type(), importFieldValue, &val)) { |
| 360 |
return false; |
| 361 |
} |
| 362 |
} |
| 363 |
|
| 364 |
if (!imports->globalValues.append(val)) { |
| 365 |
ReportOutOfMemory(cx); |
| 366 |
return false; |
| 367 |
} |
| 368 |
|
| 369 |
break; |
| 370 |
} |
| 371 |
} |
| 372 |
} |
| 373 |
|
| 374 |
MOZ_ASSERT(globalIndex == globals.length() || |
| 375 |
!globals[globalIndex].isImport()); |
| 376 |
|
| 377 |
return true; |
| 378 |
} |
| 379 |
|
| 380 |
static bool DescribeScriptedCaller(JSContext* cx, ScriptedCaller* caller, |
| 381 |
const char* introducer) { |
| 382 |
// Note: JS::DescribeScriptedCaller returns whether a scripted caller was |
| 383 |
// found, not whether an error was thrown. This wrapper function converts |
| 384 |
// back to the more ordinary false-if-error form. |
| 385 |
|
| 386 |
JS::AutoFilename af; |
| 387 |
if (JS::DescribeScriptedCaller(&af, cx, &caller->line)) { |
| 388 |
caller->filename = |
| 389 |
FormatIntroducedFilename(af.get(), caller->line, introducer); |
| 390 |
if (!caller->filename) { |
| 391 |
ReportOutOfMemory(cx); |
| 392 |
return false; |
| 393 |
} |
| 394 |
} |
| 395 |
|
| 396 |
return true; |
| 397 |
} |
| 398 |
|
| 399 |
static SharedCompileArgs InitCompileArgs(JSContext* cx, FeatureOptions options, |
| 400 |
const char* introducer) { |
| 401 |
ScriptedCaller scriptedCaller; |
| 402 |
if (!DescribeScriptedCaller(cx, &scriptedCaller, introducer)) { |
| 403 |
return nullptr; |
| 404 |
} |
| 405 |
|
| 406 |
return CompileArgs::buildAndReport(cx, std::move(scriptedCaller), options); |
| 407 |
} |
| 408 |
|
| 409 |
// ============================================================================ |
| 410 |
// Testing / Fuzzing support |
| 411 |
|
| 412 |
bool wasm::Eval(JSContext* cx, Handle<TypedArrayObject*> code, |
| 413 |
HandleObject importObj, |
| 414 |
MutableHandle<WasmInstanceObject*> instanceObj) { |
| 415 |
if (!GlobalObject::ensureConstructor(cx, cx->global(), JSProto_WebAssembly)) { |
| 416 |
return false; |
| 417 |
} |
| 418 |
|
| 419 |
FeatureOptions options; |
| 420 |
SharedCompileArgs compileArgs = InitCompileArgs(cx, options, "wasm_eval"); |
| 421 |
if (!compileArgs) { |
| 422 |
return false; |
| 423 |
} |
| 424 |
|
| 425 |
BytecodeSource source((uint8_t*)code->dataPointerEither().unwrap(), |
| 426 |
code->byteLength().valueOr(0)); |
| 427 |
UniqueChars error; |
| 428 |
UniqueCharsVector warnings; |
| 429 |
SharedModule module = CompileBuffer( |
| 430 |
*compileArgs, BytecodeBufferOrSource(source), &error, &warnings, nullptr); |
| 431 |
if (!module) { |
| 432 |
if (error) { |
| 433 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 434 |
JSMSG_WASM_COMPILE_ERROR, error.get()); |
| 435 |
return false; |
| 436 |
} |
| 437 |
return ThrowCompileOutOfMemory(cx); |
| 438 |
} |
| 439 |
|
| 440 |
Rooted<ImportValues> imports(cx); |
| 441 |
if (!GetImports(cx, *module, importObj, imports.address())) { |
| 442 |
return false; |
| 443 |
} |
| 444 |
|
| 445 |
return module->instantiate(cx, imports.get(), nullptr, instanceObj); |
| 446 |
} |
| 447 |
|
| 448 |
struct MOZ_STACK_CLASS SerializeListener : JS::OptimizedEncodingListener { |
| 449 |
// MOZ_STACK_CLASS means these can be nops. |
| 450 |
MozExternalRefCountType MOZ_XPCOM_ABI AddRef() override { return 0; } |
| 451 |
MozExternalRefCountType MOZ_XPCOM_ABI Release() override { return 0; } |
| 452 |
|
| 453 |
mozilla::DebugOnly<bool> called = false; |
| 454 |
Bytes* serialized; |
| 455 |
explicit SerializeListener(Bytes* serialized) : serialized(serialized) {} |
| 456 |
|
| 457 |
void storeOptimizedEncoding(const uint8_t* bytes, size_t length) override { |
| 458 |
MOZ_ASSERT(!called); |
| 459 |
called = true; |
| 460 |
if (serialized->resizeUninitialized(length)) { |
| 461 |
memcpy(serialized->begin(), bytes, length); |
| 462 |
} |
| 463 |
} |
| 464 |
}; |
| 465 |
|
| 466 |
bool wasm::CompileAndSerialize(JSContext* cx, |
| 467 |
const BytecodeSource& bytecodeSource, |
| 468 |
Bytes* serialized) { |
| 469 |
// The caller must check that code caching is available |
| 470 |
MOZ_ASSERT(CodeCachingAvailable(cx)); |
| 471 |
|
| 472 |
// Create and manually fill in compile args for code caching |
| 473 |
MutableCompileArgs compileArgs = js_new<CompileArgs>(); |
| 474 |
if (!compileArgs) { |
| 475 |
return false; |
| 476 |
} |
| 477 |
|
| 478 |
// The caller has ensured CodeCachingAvailable(). Moreover, we want to ensure |
| 479 |
// we go straight to tier-2 so that we synchronously call |
| 480 |
// JS::OptimizedEncodingListener::storeOptimizedEncoding(). |
| 481 |
compileArgs->baselineEnabled = false; |
| 482 |
compileArgs->forceTiering = false; |
| 483 |
|
| 484 |
// We always pick Ion here, and we depend on CodeCachingAvailable() having |
| 485 |
// determined that Ion is available, see comments at CodeCachingAvailable(). |
| 486 |
// To do better, we need to pass information about which compiler that should |
| 487 |
// be used into CompileAndSerialize(). |
| 488 |
compileArgs->ionEnabled = true; |
| 489 |
|
| 490 |
// Select features that are enabled. This is guaranteed to be consistent with |
| 491 |
// our compiler selection, as code caching is only available if ion is |
| 492 |
// available, and ion is only available if it's not disabled by enabled |
| 493 |
// features. |
| 494 |
compileArgs->features = FeatureArgs::build(cx, FeatureOptions()); |
| 495 |
|
| 496 |
SerializeListener listener(serialized); |
| 497 |
|
| 498 |
UniqueChars error; |
| 499 |
UniqueCharsVector warnings; |
| 500 |
SharedModule module = |
| 501 |
CompileBuffer(*compileArgs, BytecodeBufferOrSource(bytecodeSource), |
| 502 |
&error, &warnings, &listener); |
| 503 |
if (!module) { |
| 504 |
fprintf(stderr, "Compilation error: %s\n", error ? error.get() : "oom"); |
| 505 |
return false; |
| 506 |
} |
| 507 |
|
| 508 |
MOZ_ASSERT(module->code().hasCompleteTier(Tier::Serialized)); |
| 509 |
MOZ_ASSERT(listener.called); |
| 510 |
return !listener.serialized->empty(); |
| 511 |
} |
| 512 |
|
| 513 |
bool wasm::DeserializeModule(JSContext* cx, const Bytes& serialized, |
| 514 |
MutableHandleObject moduleObj) { |
| 515 |
MutableModule module = |
| 516 |
Module::deserialize(serialized.begin(), serialized.length()); |
| 517 |
if (!module) { |
| 518 |
ReportOutOfMemory(cx); |
| 519 |
return false; |
| 520 |
} |
| 521 |
|
| 522 |
moduleObj.set(module->createObject(cx)); |
| 523 |
return !!moduleObj; |
| 524 |
} |
| 525 |
|
| 526 |
// ============================================================================ |
| 527 |
// Common functions |
| 528 |
|
| 529 |
// '[EnforceRange] unsigned long' types are coerced with |
| 530 |
// ConvertToInt(v, 32, 'unsigned') |
| 531 |
// defined in Web IDL Section 3.2.4.9. |
| 532 |
// |
| 533 |
// This just generalizes that to an arbitrary limit that is representable as an |
| 534 |
// integer in double form. |
| 535 |
|
| 536 |
static bool EnforceRange(JSContext* cx, HandleValue v, const char* kind, |
| 537 |
const char* noun, uint64_t max, uint64_t* val) { |
| 538 |
// Step 4. |
| 539 |
double x; |
| 540 |
if (!ToNumber(cx, v, &x)) { |
| 541 |
return false; |
| 542 |
} |
| 543 |
|
| 544 |
// Step 5. |
| 545 |
if (mozilla::IsNegativeZero(x)) { |
| 546 |
x = 0.0; |
| 547 |
} |
| 548 |
|
| 549 |
// Step 6.1. |
| 550 |
if (!std::isfinite(x)) { |
| 551 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 552 |
JSMSG_WASM_BAD_ENFORCE_RANGE, kind, noun); |
| 553 |
return false; |
| 554 |
} |
| 555 |
|
| 556 |
// Step 6.2. |
| 557 |
x = JS::ToInteger(x); |
| 558 |
|
| 559 |
// Step 6.3. |
| 560 |
if (x < 0 || x > double(max)) { |
| 561 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 562 |
JSMSG_WASM_BAD_ENFORCE_RANGE, kind, noun); |
| 563 |
return false; |
| 564 |
} |
| 565 |
|
| 566 |
*val = uint64_t(x); |
| 567 |
MOZ_ASSERT(double(*val) == x); |
| 568 |
return true; |
| 569 |
} |
| 570 |
|
| 571 |
static bool EnforceRangeU32(JSContext* cx, HandleValue v, const char* kind, |
| 572 |
const char* noun, uint32_t* u32) { |
| 573 |
uint64_t u64 = 0; |
| 574 |
if (!EnforceRange(cx, v, kind, noun, uint64_t(UINT32_MAX), &u64)) { |
| 575 |
return false; |
| 576 |
} |
| 577 |
*u32 = uint32_t(u64); |
| 578 |
return true; |
| 579 |
} |
| 580 |
|
| 581 |
static bool EnforceRangeU64(JSContext* cx, HandleValue v, const char* kind, |
| 582 |
const char* noun, uint64_t* u64) { |
| 583 |
// The max is Number.MAX_SAFE_INTEGER |
| 584 |
return EnforceRange(cx, v, kind, noun, (1LL << 53) - 1, u64); |
| 585 |
} |
| 586 |
|
| 587 |
static bool EnforceRangeBigInt64(JSContext* cx, HandleValue v, const char* kind, |
| 588 |
const char* noun, uint64_t* u64) { |
| 589 |
RootedBigInt bi(cx, ToBigInt(cx, v)); |
| 590 |
if (!bi) { |
| 591 |
return false; |
| 592 |
} |
| 593 |
if (!BigInt::isUint64(bi, u64)) { |
| 594 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 595 |
JSMSG_WASM_BAD_ENFORCE_RANGE, kind, noun); |
| 596 |
return false; |
| 597 |
} |
| 598 |
return true; |
| 599 |
} |
| 600 |
|
| 601 |
static bool EnforceAddressValue(JSContext* cx, HandleValue v, |
| 602 |
AddressType addressType, const char* kind, |
| 603 |
const char* noun, uint64_t* result) { |
| 604 |
switch (addressType) { |
| 605 |
case AddressType::I32: { |
| 606 |
uint32_t result32; |
| 607 |
if (!EnforceRangeU32(cx, v, kind, noun, &result32)) { |
| 608 |
return false; |
| 609 |
} |
| 610 |
*result = uint64_t(result32); |
| 611 |
return true; |
| 612 |
} |
| 613 |
case AddressType::I64: |
| 614 |
return EnforceRangeBigInt64(cx, v, kind, noun, result); |
| 615 |
default: |
| 616 |
MOZ_CRASH("unknown address type"); |
| 617 |
} |
| 618 |
} |
| 619 |
|
| 620 |
// The AddressValue typedef, a union of number and bigint, is used in the JS API |
| 621 |
// spec for memory and table arguments, where number is used for memory32 and |
| 622 |
// bigint is used for memory64. |
| 623 |
[[nodiscard]] static bool CreateAddressValue(JSContext* cx, uint64_t value, |
| 624 |
AddressType addressType, |
| 625 |
MutableHandleValue addressValue) { |
| 626 |
switch (addressType) { |
| 627 |
case AddressType::I32: |
| 628 |
MOZ_ASSERT(value <= UINT32_MAX); |
| 629 |
addressValue.set(NumberValue(value)); |
| 630 |
return true; |
| 631 |
case AddressType::I64: { |
| 632 |
BigInt* bi = BigInt::createFromUint64(cx, value); |
| 633 |
if (!bi) { |
| 634 |
return false; |
| 635 |
} |
| 636 |
addressValue.set(BigIntValue(bi)); |
| 637 |
return true; |
| 638 |
} |
| 639 |
default: |
| 640 |
MOZ_CRASH("unknown address type"); |
| 641 |
} |
| 642 |
} |
| 643 |
|
| 644 |
// Gets an AddressValue property ("initial" or "maximum") from a |
| 645 |
// MemoryDescriptor or TableDescriptor. The values returned by this should be |
| 646 |
// run through CheckLimits to enforce the validation limits prescribed by the |
| 647 |
// spec. |
| 648 |
static bool GetDescriptorAddressValue(JSContext* cx, HandleObject obj, |
| 649 |
const char* name, const char* noun, |
| 650 |
const char* msg, AddressType addressType, |
| 651 |
bool* found, uint64_t* value) { |
| 652 |
JSAtom* atom = Atomize(cx, name, strlen(name)); |
| 653 |
if (!atom) { |
| 654 |
return false; |
| 655 |
} |
| 656 |
RootedId id(cx, AtomToId(atom)); |
| 657 |
|
| 658 |
RootedValue val(cx); |
| 659 |
if (!GetProperty(cx, obj, obj, id, &val)) { |
| 660 |
return false; |
| 661 |
} |
| 662 |
|
| 663 |
if (val.isUndefined()) { |
| 664 |
*found = false; |
| 665 |
return true; |
| 666 |
} |
| 667 |
*found = true; |
| 668 |
|
| 669 |
return EnforceAddressValue(cx, val, addressType, noun, msg, value); |
| 670 |
} |
| 671 |
|
| 672 |
static bool GetLimits(JSContext* cx, HandleObject obj, LimitsKind kind, |
| 673 |
Limits* limits) { |
| 674 |
limits->addressType = AddressType::I32; |
| 675 |
|
| 676 |
// Limits may specify an alternate address type, and we need this to check the |
| 677 |
// ranges for initial and maximum, so look for the address type first. |
| 678 |
#ifdef ENABLE_WASM_MEMORY64 |
| 679 |
// Get the address type field |
| 680 |
JSAtom* addressTypeAtom = Atomize(cx, "address", strlen("address")); |
| 681 |
if (!addressTypeAtom) { |
| 682 |
return false; |
| 683 |
} |
| 684 |
RootedId addressTypeId(cx, AtomToId(addressTypeAtom)); |
| 685 |
RootedValue addressTypeVal(cx); |
| 686 |
if (!GetProperty(cx, obj, obj, addressTypeId, &addressTypeVal)) { |
| 687 |
return false; |
| 688 |
} |
| 689 |
|
| 690 |
// The address type has a default value |
| 691 |
if (!addressTypeVal.isUndefined()) { |
| 692 |
if (!ToAddressType(cx, addressTypeVal, &limits->addressType)) { |
| 693 |
return false; |
| 694 |
} |
| 695 |
|
| 696 |
if (limits->addressType == AddressType::I64 && !Memory64Available(cx)) { |
| 697 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 698 |
JSMSG_WASM_NO_MEM64_LINK); |
| 699 |
return false; |
| 700 |
} |
| 701 |
} |
| 702 |
#endif |
| 703 |
|
| 704 |
const char* noun = ToString(kind); |
| 705 |
uint64_t limit = 0; |
| 706 |
|
| 707 |
bool haveInitial = false; |
| 708 |
if (!GetDescriptorAddressValue(cx, obj, "initial", noun, "initial size", |
| 709 |
limits->addressType, &haveInitial, &limit)) { |
| 710 |
return false; |
| 711 |
} |
| 712 |
if (haveInitial) { |
| 713 |
limits->initial = limit; |
| 714 |
} |
| 715 |
|
| 716 |
bool haveMinimum = false; |
| 717 |
#ifdef ENABLE_WASM_TYPE_REFLECTIONS |
| 718 |
if (!GetDescriptorAddressValue(cx, obj, "minimum", noun, "initial size", |
| 719 |
limits->addressType, &haveMinimum, &limit)) { |
| 720 |
return false; |
| 721 |
} |
| 722 |
if (haveMinimum) { |
| 723 |
limits->initial = limit; |
| 724 |
} |
| 725 |
#endif |
| 726 |
|
| 727 |
if (!(haveInitial || haveMinimum)) { |
| 728 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 729 |
JSMSG_WASM_MISSING_REQUIRED, "initial"); |
| 730 |
return false; |
| 731 |
} |
| 732 |
if (haveInitial && haveMinimum) { |
| 733 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 734 |
JSMSG_WASM_SUPPLY_ONLY_ONE, "minimum", "initial"); |
| 735 |
return false; |
| 736 |
} |
| 737 |
|
| 738 |
bool haveMaximum = false; |
| 739 |
if (!GetDescriptorAddressValue(cx, obj, "maximum", noun, "maximum size", |
| 740 |
limits->addressType, &haveMaximum, &limit)) { |
| 741 |
return false; |
| 742 |
} |
| 743 |
if (haveMaximum) { |
| 744 |
limits->maximum = Some(limit); |
| 745 |
} |
| 746 |
|
| 747 |
limits->shared = Shareable::False; |
| 748 |
|
| 749 |
// Memory limits may be shared. |
| 750 |
if (kind == LimitsKind::Memory) { |
| 751 |
// Get the shared field |
| 752 |
JSAtom* sharedAtom = Atomize(cx, "shared", strlen("shared")); |
| 753 |
if (!sharedAtom) { |
| 754 |
return false; |
| 755 |
} |
| 756 |
RootedId sharedId(cx, AtomToId(sharedAtom)); |
| 757 |
|
| 758 |
RootedValue sharedVal(cx); |
| 759 |
if (!GetProperty(cx, obj, obj, sharedId, &sharedVal)) { |
| 760 |
return false; |
| 761 |
} |
| 762 |
|
| 763 |
// shared's default value is false, which is already the value set above. |
| 764 |
if (!sharedVal.isUndefined()) { |
| 765 |
limits->shared = |
| 766 |
ToBoolean(sharedVal) ? Shareable::True : Shareable::False; |
| 767 |
|
| 768 |
if (limits->shared == Shareable::True) { |
| 769 |
if (!haveMaximum) { |
| 770 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 771 |
JSMSG_WASM_MISSING_MAXIMUM, noun); |
| 772 |
return false; |
| 773 |
} |
| 774 |
|
| 775 |
if (!cx->realm() |
| 776 |
->creationOptions() |
| 777 |
.getSharedMemoryAndAtomicsEnabled()) { |
| 778 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 779 |
JSMSG_WASM_NO_SHMEM_LINK); |
| 780 |
return false; |
| 781 |
} |
| 782 |
} |
| 783 |
} |
| 784 |
} |
| 785 |
|
| 786 |
return true; |
| 787 |
} |
| 788 |
|
| 789 |
static bool CheckLimits(JSContext* cx, uint64_t validationMax, LimitsKind kind, |
| 790 |
Limits* limits) { |
| 791 |
const char* noun = ToString(kind); |
| 792 |
|
| 793 |
// There are several layers of validation and error-throwing here, including |
| 794 |
// one which is currently not defined by the JS API spec: |
| 795 |
// |
| 796 |
// - [EnforceRange] on parameters (must be TypeError) |
| 797 |
// - A check that initial <= maximum (must be RangeError) |
| 798 |
// - Either a mem_alloc or table_alloc operation, which has two components: |
| 799 |
// - A pre-condition that the given memory or table type is valid |
| 800 |
// (not specified, RangeError in practice) |
| 801 |
// - The actual allocation (should report OOM if it fails) |
| 802 |
// |
| 803 |
// There are two questions currently left open by the spec: when is the memory |
| 804 |
// or table type validated, and if it is invalid, what type of exception does |
| 805 |
// it throw? In practice, all browsers throw RangeError, and by the time you |
| 806 |
// read this the spec will hopefully have been updated to reflect this. See |
| 807 |
// the following issue: https://github.com/WebAssembly/spec/issues/1792 |
| 808 |
|
| 809 |
// Check that initial <= maximum |
| 810 |
if (limits->maximum.isSome() && *limits->maximum < limits->initial) { |
| 811 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 812 |
JSMSG_WASM_MAX_LT_INITIAL, noun); |
| 813 |
return false; |
| 814 |
} |
| 815 |
|
| 816 |
// Check wasm validation limits |
| 817 |
if (limits->initial > validationMax) { |
| 818 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, JSMSG_WASM_BAD_RANGE, |
| 819 |
noun, "initial size"); |
| 820 |
return false; |
| 821 |
} |
| 822 |
if (limits->maximum.isSome() && *limits->maximum > validationMax) { |
| 823 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, JSMSG_WASM_BAD_RANGE, |
| 824 |
noun, "maximum size"); |
| 825 |
return false; |
| 826 |
} |
| 827 |
|
| 828 |
return true; |
| 829 |
} |
| 830 |
|
| 831 |
template <class Class, const char* name> |
| 832 |
static JSObject* CreateWasmConstructor(JSContext* cx, JSProtoKey key) { |
| 833 |
Rooted<JSAtom*> className(cx, Atomize(cx, name, strlen(name))); |
| 834 |
if (!className) { |
| 835 |
return nullptr; |
| 836 |
} |
| 837 |
|
| 838 |
return NewNativeConstructor(cx, Class::construct, 1, className); |
| 839 |
} |
| 840 |
|
| 841 |
static JSObject* GetWasmConstructorPrototype(JSContext* cx, |
| 842 |
const CallArgs& callArgs, |
| 843 |
JSProtoKey key) { |
| 844 |
RootedObject proto(cx); |
| 845 |
if (!GetPrototypeFromBuiltinConstructor(cx, callArgs, key, &proto)) { |
| 846 |
return nullptr; |
| 847 |
} |
| 848 |
if (!proto) { |
| 849 |
proto = GlobalObject::getOrCreatePrototype(cx, key); |
| 850 |
} |
| 851 |
return proto; |
| 852 |
} |
| 853 |
|
| 854 |
[[nodiscard]] static bool ParseValTypes(JSContext* cx, HandleValue src, |
| 855 |
ValTypeVector& dest) { |
| 856 |
JS::ForOfIterator iterator(cx); |
| 857 |
|
| 858 |
if (!iterator.init(src, JS::ForOfIterator::ThrowOnNonIterable)) { |
| 859 |
return false; |
| 860 |
} |
| 861 |
|
| 862 |
RootedValue nextParam(cx); |
| 863 |
while (true) { |
| 864 |
bool done; |
| 865 |
if (!iterator.next(&nextParam, &done)) { |
| 866 |
return false; |
| 867 |
} |
| 868 |
if (done) { |
| 869 |
break; |
| 870 |
} |
| 871 |
|
| 872 |
ValType valType; |
| 873 |
if (!ToValType(cx, nextParam, &valType) || !dest.append(valType)) { |
| 874 |
return false; |
| 875 |
} |
| 876 |
} |
| 877 |
return true; |
| 878 |
} |
| 879 |
|
| 880 |
#ifdef ENABLE_WASM_TYPE_REFLECTIONS |
| 881 |
template <typename T> |
| 882 |
static JSString* TypeToString(JSContext* cx, T type) { |
| 883 |
UniqueChars chars = ToString(type, nullptr); |
| 884 |
if (!chars) { |
| 885 |
return nullptr; |
| 886 |
} |
| 887 |
return NewStringCopyUTF8Z( |
| 888 |
cx, JS::ConstUTF8CharsZ(chars.get(), strlen(chars.get()))); |
| 889 |
} |
| 890 |
|
| 891 |
# ifdef ENABLE_WASM_MEMORY64 |
| 892 |
static JSString* AddressTypeToString(JSContext* cx, AddressType type) { |
| 893 |
return JS_NewStringCopyZ(cx, ToString(type)); |
| 894 |
} |
| 895 |
# endif |
| 896 |
|
| 897 |
[[nodiscard]] static JSObject* ValTypesToArray(JSContext* cx, |
| 898 |
const ValTypeVector& valTypes) { |
| 899 |
Rooted<ArrayObject*> arrayObj(cx, NewDenseEmptyArray(cx)); |
| 900 |
if (!arrayObj) { |
| 901 |
return nullptr; |
| 902 |
} |
| 903 |
for (ValType valType : valTypes) { |
| 904 |
RootedString type(cx, TypeToString(cx, valType)); |
| 905 |
if (!type) { |
| 906 |
return nullptr; |
| 907 |
} |
| 908 |
if (!NewbornArrayPush(cx, arrayObj, StringValue(type))) { |
| 909 |
return nullptr; |
| 910 |
} |
| 911 |
} |
| 912 |
return arrayObj; |
| 913 |
} |
| 914 |
|
| 915 |
static JSObject* FuncTypeToObject(JSContext* cx, const FuncType& type) { |
| 916 |
Rooted<IdValueVector> props(cx, IdValueVector(cx)); |
| 917 |
|
| 918 |
RootedObject parametersObj(cx, ValTypesToArray(cx, type.args())); |
| 919 |
if (!parametersObj || |
| 920 |
!props.append(IdValuePair(NameToId(cx->names().parameters), |
| 921 |
ObjectValue(*parametersObj)))) { |
| 922 |
ReportOutOfMemory(cx); |
| 923 |
return nullptr; |
| 924 |
} |
| 925 |
|
| 926 |
RootedObject resultsObj(cx, ValTypesToArray(cx, type.results())); |
| 927 |
if (!resultsObj || !props.append(IdValuePair(NameToId(cx->names().results), |
| 928 |
ObjectValue(*resultsObj)))) { |
| 929 |
ReportOutOfMemory(cx); |
| 930 |
return nullptr; |
| 931 |
} |
| 932 |
|
| 933 |
return NewPlainObjectWithUniqueNames(cx, props); |
| 934 |
} |
| 935 |
|
| 936 |
static JSObject* TableTypeToObject(JSContext* cx, AddressType addressType, |
| 937 |
RefType type, uint64_t initial, |
| 938 |
Maybe<uint64_t> maximum) { |
| 939 |
Rooted<IdValueVector> props(cx, IdValueVector(cx)); |
| 940 |
|
| 941 |
RootedString elementType(cx, TypeToString(cx, type)); |
| 942 |
if (!elementType || !props.append(IdValuePair(NameToId(cx->names().element), |
| 943 |
StringValue(elementType)))) { |
| 944 |
ReportOutOfMemory(cx); |
| 945 |
return nullptr; |
| 946 |
} |
| 947 |
|
| 948 |
if (maximum.isSome()) { |
| 949 |
RootedId maximumId(cx, NameToId(cx->names().maximum)); |
| 950 |
RootedValue maximumValue(cx); |
| 951 |
if (!CreateAddressValue(cx, maximum.value(), addressType, &maximumValue)) { |
| 952 |
ReportOutOfMemory(cx); |
| 953 |
return nullptr; |
| 954 |
} |
| 955 |
if (!props.append(IdValuePair(maximumId, maximumValue))) { |
| 956 |
ReportOutOfMemory(cx); |
| 957 |
return nullptr; |
| 958 |
} |
| 959 |
} |
| 960 |
|
| 961 |
RootedId minimumId(cx, NameToId(cx->names().minimum)); |
| 962 |
RootedValue minimumValue(cx); |
| 963 |
if (!CreateAddressValue(cx, initial, addressType, &minimumValue)) { |
| 964 |
ReportOutOfMemory(cx); |
| 965 |
return nullptr; |
| 966 |
} |
| 967 |
if (!props.append(IdValuePair(minimumId, minimumValue))) { |
| 968 |
ReportOutOfMemory(cx); |
| 969 |
return nullptr; |
| 970 |
} |
| 971 |
|
| 972 |
# ifdef ENABLE_WASM_MEMORY64 |
| 973 |
RootedString at(cx, AddressTypeToString(cx, addressType)); |
| 974 |
if (!at) { |
| 975 |
return nullptr; |
| 976 |
} |
| 977 |
if (!props.append( |
| 978 |
IdValuePair(NameToId(cx->names().address), StringValue(at)))) { |
| 979 |
ReportOutOfMemory(cx); |
| 980 |
return nullptr; |
| 981 |
} |
| 982 |
# endif |
| 983 |
|
| 984 |
return NewPlainObjectWithUniqueNames(cx, props); |
| 985 |
} |
| 986 |
|
| 987 |
static JSObject* MemoryTypeToObject(JSContext* cx, bool shared, |
| 988 |
wasm::AddressType addressType, |
| 989 |
wasm::Pages minPages, |
| 990 |
Maybe<wasm::Pages> maxPages) { |
| 991 |
Rooted<IdValueVector> props(cx, IdValueVector(cx)); |
| 992 |
if (maxPages) { |
| 993 |
RootedId maximumId(cx, NameToId(cx->names().maximum)); |
| 994 |
RootedValue maximumValue(cx); |
| 995 |
if (!CreateAddressValue(cx, maxPages.value().value(), addressType, |
| 996 |
&maximumValue)) { |
| 997 |
ReportOutOfMemory(cx); |
| 998 |
return nullptr; |
| 999 |
} |
| 1000 |
if (!props.append(IdValuePair(maximumId, maximumValue))) { |
| 1001 |
ReportOutOfMemory(cx); |
| 1002 |
return nullptr; |
| 1003 |
} |
| 1004 |
} |
| 1005 |
|
| 1006 |
RootedId minimumId(cx, NameToId(cx->names().minimum)); |
| 1007 |
RootedValue minimumValue(cx); |
| 1008 |
if (!CreateAddressValue(cx, minPages.value(), addressType, &minimumValue)) { |
| 1009 |
ReportOutOfMemory(cx); |
| 1010 |
return nullptr; |
| 1011 |
} |
| 1012 |
if (!props.append(IdValuePair(minimumId, minimumValue))) { |
| 1013 |
ReportOutOfMemory(cx); |
| 1014 |
return nullptr; |
| 1015 |
} |
| 1016 |
|
| 1017 |
# ifdef ENABLE_WASM_MEMORY64 |
| 1018 |
RootedString at(cx, AddressTypeToString(cx, addressType)); |
| 1019 |
if (!at) { |
| 1020 |
return nullptr; |
| 1021 |
} |
| 1022 |
if (!props.append( |
| 1023 |
IdValuePair(NameToId(cx->names().address), StringValue(at)))) { |
| 1024 |
ReportOutOfMemory(cx); |
| 1025 |
return nullptr; |
| 1026 |
} |
| 1027 |
# endif |
| 1028 |
|
| 1029 |
if (!props.append( |
| 1030 |
IdValuePair(NameToId(cx->names().shared), BooleanValue(shared)))) { |
| 1031 |
ReportOutOfMemory(cx); |
| 1032 |
return nullptr; |
| 1033 |
} |
| 1034 |
|
| 1035 |
return NewPlainObjectWithUniqueNames(cx, props); |
| 1036 |
} |
| 1037 |
|
| 1038 |
static JSObject* GlobalTypeToObject(JSContext* cx, ValType type, |
| 1039 |
bool isMutable) { |
| 1040 |
Rooted<IdValueVector> props(cx, IdValueVector(cx)); |
| 1041 |
|
| 1042 |
if (!props.append(IdValuePair(NameToId(cx->names().mutable_), |
| 1043 |
BooleanValue(isMutable)))) { |
| 1044 |
ReportOutOfMemory(cx); |
| 1045 |
return nullptr; |
| 1046 |
} |
| 1047 |
|
| 1048 |
RootedString valueType(cx, TypeToString(cx, type)); |
| 1049 |
if (!valueType || !props.append(IdValuePair(NameToId(cx->names().value), |
| 1050 |
StringValue(valueType)))) { |
| 1051 |
ReportOutOfMemory(cx); |
| 1052 |
return nullptr; |
| 1053 |
} |
| 1054 |
|
| 1055 |
return NewPlainObjectWithUniqueNames(cx, props); |
| 1056 |
} |
| 1057 |
|
| 1058 |
static JSObject* TagTypeToObject(JSContext* cx, |
| 1059 |
const wasm::ValTypeVector& params) { |
| 1060 |
Rooted<IdValueVector> props(cx, IdValueVector(cx)); |
| 1061 |
|
| 1062 |
RootedObject parametersObj(cx, ValTypesToArray(cx, params)); |
| 1063 |
if (!parametersObj || |
| 1064 |
!props.append(IdValuePair(NameToId(cx->names().parameters), |
| 1065 |
ObjectValue(*parametersObj)))) { |
| 1066 |
ReportOutOfMemory(cx); |
| 1067 |
return nullptr; |
| 1068 |
} |
| 1069 |
|
| 1070 |
return NewPlainObjectWithUniqueNames(cx, props); |
| 1071 |
} |
| 1072 |
#endif // ENABLE_WASM_TYPE_REFLECTIONS |
| 1073 |
|
| 1074 |
// ============================================================================ |
| 1075 |
// WebAssembly.Module class and methods |
| 1076 |
|
| 1077 |
const JSClassOps WasmModuleObject::classOps_ = { |
| 1078 |
nullptr, // addProperty |
| 1079 |
nullptr, // delProperty |
| 1080 |
nullptr, // enumerate |
| 1081 |
nullptr, // newEnumerate |
| 1082 |
nullptr, // resolve |
| 1083 |
nullptr, // mayResolve |
| 1084 |
WasmModuleObject::finalize, // finalize |
| 1085 |
nullptr, // call |
| 1086 |
nullptr, // construct |
| 1087 |
nullptr, // trace |
| 1088 |
}; |
| 1089 |
|
| 1090 |
const JSClass WasmModuleObject::class_ = { |
| 1091 |
"WebAssembly.Module", |
| 1092 |
JSCLASS_DELAY_METADATA_BUILDER | |
| 1093 |
JSCLASS_HAS_RESERVED_SLOTS(WasmModuleObject::RESERVED_SLOTS) | |
| 1094 |
JSCLASS_FOREGROUND_FINALIZE, |
| 1095 |
&WasmModuleObject::classOps_, |
| 1096 |
&WasmModuleObject::classSpec_, |
| 1097 |
}; |
| 1098 |
|
| 1099 |
const JSClass& WasmModuleObject::protoClass_ = PlainObject::class_; |
| 1100 |
|
| 1101 |
static constexpr char WasmModuleName[] = "Module"; |
| 1102 |
|
| 1103 |
const ClassSpec WasmModuleObject::classSpec_ = { |
| 1104 |
CreateWasmConstructor<WasmModuleObject, WasmModuleName>, |
| 1105 |
GenericCreatePrototype<WasmModuleObject>, |
| 1106 |
WasmModuleObject::static_methods, |
| 1107 |
nullptr, |
| 1108 |
WasmModuleObject::methods, |
| 1109 |
WasmModuleObject::properties, |
| 1110 |
nullptr, |
| 1111 |
ClassSpec::DontDefineConstructor, |
| 1112 |
}; |
| 1113 |
|
| 1114 |
const JSPropertySpec WasmModuleObject::properties[] = { |
| 1115 |
JS_STRING_SYM_PS(toStringTag, "WebAssembly.Module", JSPROP_READONLY), |
| 1116 |
JS_PS_END, |
| 1117 |
}; |
| 1118 |
|
| 1119 |
const JSFunctionSpec WasmModuleObject::methods[] = { |
| 1120 |
JS_FS_END, |
| 1121 |
}; |
| 1122 |
|
| 1123 |
const JSFunctionSpec WasmModuleObject::static_methods[] = { |
| 1124 |
JS_FN("imports", WasmModuleObject::imports, 1, JSPROP_ENUMERATE), |
| 1125 |
JS_FN("exports", WasmModuleObject::exports, 1, JSPROP_ENUMERATE), |
| 1126 |
JS_FN("customSections", WasmModuleObject::customSections, 2, |
| 1127 |
JSPROP_ENUMERATE), |
| 1128 |
JS_FS_END, |
| 1129 |
}; |
| 1130 |
|
| 1131 |
/* static */ |
| 1132 |
void WasmModuleObject::finalize(JS::GCContext* gcx, JSObject* obj) { |
| 1133 |
const Module& module = obj->as<WasmModuleObject>().module(); |
| 1134 |
size_t codeMemory = module.tier1CodeMemoryUsed(); |
| 1135 |
if (codeMemory) { |
| 1136 |
obj->zone()->decJitMemory(codeMemory); |
| 1137 |
} |
| 1138 |
gcx->release(obj, &module, module.gcMallocBytesExcludingCode(), |
| 1139 |
MemoryUse::WasmModule); |
| 1140 |
} |
| 1141 |
|
| 1142 |
static bool IsModuleObject(JSObject* obj, const Module** module) { |
| 1143 |
WasmModuleObject* mobj = obj->maybeUnwrapIf<WasmModuleObject>(); |
| 1144 |
if (!mobj) { |
| 1145 |
return false; |
| 1146 |
} |
| 1147 |
|
| 1148 |
*module = &mobj->module(); |
| 1149 |
return true; |
| 1150 |
} |
| 1151 |
|
| 1152 |
static bool GetModuleArg(JSContext* cx, const CallArgs& args, |
| 1153 |
uint32_t numRequired, const char* name, |
| 1154 |
const Module** module) { |
| 1155 |
if (!args.requireAtLeast(cx, name, numRequired)) { |
| 1156 |
return false; |
| 1157 |
} |
| 1158 |
|
| 1159 |
if (!args[0].isObject() || !IsModuleObject(&args[0].toObject(), module)) { |
| 1160 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 1161 |
JSMSG_WASM_BAD_MOD_ARG); |
| 1162 |
return false; |
| 1163 |
} |
| 1164 |
|
| 1165 |
return true; |
| 1166 |
} |
| 1167 |
|
| 1168 |
struct KindNames { |
| 1169 |
Rooted<PropertyName*> kind; |
| 1170 |
Rooted<PropertyName*> table; |
| 1171 |
Rooted<PropertyName*> memory; |
| 1172 |
Rooted<PropertyName*> tag; |
| 1173 |
Rooted<PropertyName*> type; |
| 1174 |
|
| 1175 |
explicit KindNames(JSContext* cx) |
| 1176 |
: kind(cx), table(cx), memory(cx), tag(cx), type(cx) {} |
| 1177 |
}; |
| 1178 |
|
| 1179 |
static bool InitKindNames(JSContext* cx, KindNames* names) { |
| 1180 |
JSAtom* kind = Atomize(cx, "kind", strlen("kind")); |
| 1181 |
if (!kind) { |
| 1182 |
return false; |
| 1183 |
} |
| 1184 |
names->kind = kind->asPropertyName(); |
| 1185 |
|
| 1186 |
JSAtom* table = Atomize(cx, "table", strlen("table")); |
| 1187 |
if (!table) { |
| 1188 |
return false; |
| 1189 |
} |
| 1190 |
names->table = table->asPropertyName(); |
| 1191 |
|
| 1192 |
JSAtom* memory = Atomize(cx, "memory", strlen("memory")); |
| 1193 |
if (!memory) { |
| 1194 |
return false; |
| 1195 |
} |
| 1196 |
names->memory = memory->asPropertyName(); |
| 1197 |
|
| 1198 |
JSAtom* tag = Atomize(cx, "tag", strlen("tag")); |
| 1199 |
if (!tag) { |
| 1200 |
return false; |
| 1201 |
} |
| 1202 |
names->tag = tag->asPropertyName(); |
| 1203 |
|
| 1204 |
JSAtom* type = Atomize(cx, "type", strlen("type")); |
| 1205 |
if (!type) { |
| 1206 |
return false; |
| 1207 |
} |
| 1208 |
names->type = type->asPropertyName(); |
| 1209 |
|
| 1210 |
return true; |
| 1211 |
} |
| 1212 |
|
| 1213 |
static JSString* KindToString(JSContext* cx, const KindNames& names, |
| 1214 |
DefinitionKind kind) { |
| 1215 |
switch (kind) { |
| 1216 |
case DefinitionKind::Function: |
| 1217 |
return cx->names().function; |
| 1218 |
case DefinitionKind::Table: |
| 1219 |
return names.table; |
| 1220 |
case DefinitionKind::Memory: |
| 1221 |
return names.memory; |
| 1222 |
case DefinitionKind::Global: |
| 1223 |
return cx->names().global; |
| 1224 |
case DefinitionKind::Tag: |
| 1225 |
return names.tag; |
| 1226 |
} |
| 1227 |
|
| 1228 |
MOZ_CRASH("invalid kind"); |
| 1229 |
} |
| 1230 |
|
| 1231 |
/* static */ |
| 1232 |
bool WasmModuleObject::imports(JSContext* cx, unsigned argc, Value* vp) { |
| 1233 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1234 |
|
| 1235 |
const Module* module; |
| 1236 |
if (!GetModuleArg(cx, args, 1, "WebAssembly.Module.imports", &module)) { |
| 1237 |
return false; |
| 1238 |
} |
| 1239 |
|
| 1240 |
KindNames names(cx); |
| 1241 |
if (!InitKindNames(cx, &names)) { |
| 1242 |
return false; |
| 1243 |
} |
| 1244 |
|
| 1245 |
const ModuleMetadata& moduleMeta = module->moduleMeta(); |
| 1246 |
|
| 1247 |
RootedValueVector elems(cx); |
| 1248 |
if (!elems.reserve(moduleMeta.imports.length())) { |
| 1249 |
return false; |
| 1250 |
} |
| 1251 |
|
| 1252 |
#if defined(ENABLE_WASM_JS_STRING_BUILTINS) || \ |
| 1253 |
defined(ENABLE_WASM_TYPE_REFLECTIONS) |
| 1254 |
const CodeMetadata& codeMeta = module->codeMeta(); |
| 1255 |
#endif |
| 1256 |
|
| 1257 |
#if defined(ENABLE_WASM_TYPE_REFLECTIONS) |
| 1258 |
size_t numFuncImport = 0; |
| 1259 |
size_t numMemoryImport = 0; |
| 1260 |
size_t numGlobalImport = 0; |
| 1261 |
size_t numTableImport = 0; |
| 1262 |
size_t numTagImport = 0; |
| 1263 |
#endif // ENABLE_WASM_TYPE_REFLECTIONS |
| 1264 |
|
| 1265 |
for (const Import& import : moduleMeta.imports) { |
| 1266 |
#ifdef ENABLE_WASM_JS_STRING_BUILTINS |
| 1267 |
Maybe<BuiltinModuleId> builtinModule = ImportMatchesBuiltinModule( |
| 1268 |
import.module.utf8Bytes(), codeMeta.features().builtinModules); |
| 1269 |
if (builtinModule) { |
| 1270 |
continue; |
| 1271 |
} |
| 1272 |
#endif |
| 1273 |
|
| 1274 |
Rooted<IdValueVector> props(cx, IdValueVector(cx)); |
| 1275 |
if (!props.reserve(3)) { |
| 1276 |
return false; |
| 1277 |
} |
| 1278 |
|
| 1279 |
JSString* moduleStr = import.module.toAtom(cx); |
| 1280 |
if (!moduleStr) { |
| 1281 |
return false; |
| 1282 |
} |
| 1283 |
props.infallibleAppend( |
| 1284 |
IdValuePair(NameToId(cx->names().module), StringValue(moduleStr))); |
| 1285 |
|
| 1286 |
JSString* nameStr = import.field.toAtom(cx); |
| 1287 |
if (!nameStr) { |
| 1288 |
return false; |
| 1289 |
} |
| 1290 |
props.infallibleAppend( |
| 1291 |
IdValuePair(NameToId(cx->names().name), StringValue(nameStr))); |
| 1292 |
|
| 1293 |
JSString* kindStr = KindToString(cx, names, import.kind); |
| 1294 |
if (!kindStr) { |
| 1295 |
return false; |
| 1296 |
} |
| 1297 |
props.infallibleAppend( |
| 1298 |
IdValuePair(NameToId(names.kind), StringValue(kindStr))); |
| 1299 |
|
| 1300 |
#ifdef ENABLE_WASM_TYPE_REFLECTIONS |
| 1301 |
RootedObject typeObj(cx); |
| 1302 |
switch (import.kind) { |
| 1303 |
case DefinitionKind::Function: { |
| 1304 |
size_t funcIndex = numFuncImport++; |
| 1305 |
const FuncType& funcType = codeMeta.getFuncType(funcIndex); |
| 1306 |
typeObj = FuncTypeToObject(cx, funcType); |
| 1307 |
break; |
| 1308 |
} |
| 1309 |
case DefinitionKind::Table: { |
| 1310 |
size_t tableIndex = numTableImport++; |
| 1311 |
const TableDesc& table = codeMeta.tables[tableIndex]; |
| 1312 |
typeObj = |
| 1313 |
TableTypeToObject(cx, table.addressType(), table.elemType, |
| 1314 |
table.initialLength(), table.maximumLength()); |
| 1315 |
break; |
| 1316 |
} |
| 1317 |
case DefinitionKind::Memory: { |
| 1318 |
size_t memoryIndex = numMemoryImport++; |
| 1319 |
const MemoryDesc& memory = codeMeta.memories[memoryIndex]; |
| 1320 |
typeObj = |
| 1321 |
MemoryTypeToObject(cx, memory.isShared(), memory.addressType(), |
| 1322 |
memory.initialPages(), memory.maximumPages()); |
| 1323 |
break; |
| 1324 |
} |
| 1325 |
case DefinitionKind::Global: { |
| 1326 |
size_t globalIndex = numGlobalImport++; |
| 1327 |
const GlobalDesc& global = codeMeta.globals[globalIndex]; |
| 1328 |
typeObj = GlobalTypeToObject(cx, global.type(), global.isMutable()); |
| 1329 |
break; |
| 1330 |
} |
| 1331 |
case DefinitionKind::Tag: { |
| 1332 |
size_t tagIndex = numTagImport++; |
| 1333 |
const TagDesc& tag = codeMeta.tags[tagIndex]; |
| 1334 |
typeObj = TagTypeToObject(cx, tag.type->argTypes()); |
| 1335 |
break; |
| 1336 |
} |
| 1337 |
} |
| 1338 |
|
| 1339 |
if (!typeObj || !props.append(IdValuePair(NameToId(names.type), |
| 1340 |
ObjectValue(*typeObj)))) { |
| 1341 |
ReportOutOfMemory(cx); |
| 1342 |
return false; |
| 1343 |
} |
| 1344 |
#endif // ENABLE_WASM_TYPE_REFLECTIONS |
| 1345 |
|
| 1346 |
JSObject* obj = NewPlainObjectWithUniqueNames(cx, props); |
| 1347 |
if (!obj) { |
| 1348 |
return false; |
| 1349 |
} |
| 1350 |
|
| 1351 |
elems.infallibleAppend(ObjectValue(*obj)); |
| 1352 |
} |
| 1353 |
|
| 1354 |
JSObject* arr = NewDenseCopiedArray(cx, elems.length(), elems.begin()); |
| 1355 |
if (!arr) { |
| 1356 |
return false; |
| 1357 |
} |
| 1358 |
|
| 1359 |
args.rval().setObject(*arr); |
| 1360 |
return true; |
| 1361 |
} |
| 1362 |
|
| 1363 |
/* static */ |
| 1364 |
bool WasmModuleObject::exports(JSContext* cx, unsigned argc, Value* vp) { |
| 1365 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1366 |
|
| 1367 |
const Module* module; |
| 1368 |
if (!GetModuleArg(cx, args, 1, "WebAssembly.Module.exports", &module)) { |
| 1369 |
return false; |
| 1370 |
} |
| 1371 |
|
| 1372 |
KindNames names(cx); |
| 1373 |
if (!InitKindNames(cx, &names)) { |
| 1374 |
return false; |
| 1375 |
} |
| 1376 |
|
| 1377 |
const ModuleMetadata& moduleMeta = module->moduleMeta(); |
| 1378 |
|
| 1379 |
RootedValueVector elems(cx); |
| 1380 |
if (!elems.reserve(moduleMeta.exports.length())) { |
| 1381 |
return false; |
| 1382 |
} |
| 1383 |
|
| 1384 |
#ifdef ENABLE_WASM_TYPE_REFLECTIONS |
| 1385 |
const CodeMetadata& codeMeta = module->codeMeta(); |
| 1386 |
#endif // ENABLE_WASM_TYPE_REFLECTIONS |
| 1387 |
|
| 1388 |
for (const Export& exp : moduleMeta.exports) { |
| 1389 |
Rooted<IdValueVector> props(cx, IdValueVector(cx)); |
| 1390 |
if (!props.reserve(2)) { |
| 1391 |
return false; |
| 1392 |
} |
| 1393 |
|
| 1394 |
JSString* nameStr = exp.fieldName().toAtom(cx); |
| 1395 |
if (!nameStr) { |
| 1396 |
return false; |
| 1397 |
} |
| 1398 |
props.infallibleAppend( |
| 1399 |
IdValuePair(NameToId(cx->names().name), StringValue(nameStr))); |
| 1400 |
|
| 1401 |
JSString* kindStr = KindToString(cx, names, exp.kind()); |
| 1402 |
if (!kindStr) { |
| 1403 |
return false; |
| 1404 |
} |
| 1405 |
props.infallibleAppend( |
| 1406 |
IdValuePair(NameToId(names.kind), StringValue(kindStr))); |
| 1407 |
|
| 1408 |
#ifdef ENABLE_WASM_TYPE_REFLECTIONS |
| 1409 |
RootedObject typeObj(cx); |
| 1410 |
switch (exp.kind()) { |
| 1411 |
case DefinitionKind::Function: { |
| 1412 |
const FuncType& funcType = |
| 1413 |
module->codeMeta().getFuncType(exp.funcIndex()); |
| 1414 |
typeObj = FuncTypeToObject(cx, funcType); |
| 1415 |
break; |
| 1416 |
} |
| 1417 |
case DefinitionKind::Table: { |
| 1418 |
const TableDesc& table = codeMeta.tables[exp.tableIndex()]; |
| 1419 |
typeObj = |
| 1420 |
TableTypeToObject(cx, table.addressType(), table.elemType, |
| 1421 |
table.initialLength(), table.maximumLength()); |
| 1422 |
break; |
| 1423 |
} |
| 1424 |
case DefinitionKind::Memory: { |
| 1425 |
const MemoryDesc& memory = codeMeta.memories[exp.memoryIndex()]; |
| 1426 |
typeObj = |
| 1427 |
MemoryTypeToObject(cx, memory.isShared(), memory.addressType(), |
| 1428 |
memory.initialPages(), memory.maximumPages()); |
| 1429 |
break; |
| 1430 |
} |
| 1431 |
case DefinitionKind::Global: { |
| 1432 |
const GlobalDesc& global = codeMeta.globals[exp.globalIndex()]; |
| 1433 |
typeObj = GlobalTypeToObject(cx, global.type(), global.isMutable()); |
| 1434 |
break; |
| 1435 |
} |
| 1436 |
case DefinitionKind::Tag: { |
| 1437 |
const TagDesc& tag = codeMeta.tags[exp.tagIndex()]; |
| 1438 |
typeObj = TagTypeToObject(cx, tag.type->argTypes()); |
| 1439 |
break; |
| 1440 |
} |
| 1441 |
} |
| 1442 |
|
| 1443 |
if (!typeObj || !props.append(IdValuePair(NameToId(names.type), |
| 1444 |
ObjectValue(*typeObj)))) { |
| 1445 |
ReportOutOfMemory(cx); |
| 1446 |
return false; |
| 1447 |
} |
| 1448 |
#endif // ENABLE_WASM_TYPE_REFLECTIONS |
| 1449 |
|
| 1450 |
JSObject* obj = NewPlainObjectWithUniqueNames(cx, props); |
| 1451 |
if (!obj) { |
| 1452 |
return false; |
| 1453 |
} |
| 1454 |
|
| 1455 |
elems.infallibleAppend(ObjectValue(*obj)); |
| 1456 |
} |
| 1457 |
|
| 1458 |
JSObject* arr = NewDenseCopiedArray(cx, elems.length(), elems.begin()); |
| 1459 |
if (!arr) { |
| 1460 |
return false; |
| 1461 |
} |
| 1462 |
|
| 1463 |
args.rval().setObject(*arr); |
| 1464 |
return true; |
| 1465 |
} |
| 1466 |
|
| 1467 |
/* static */ |
| 1468 |
bool WasmModuleObject::customSections(JSContext* cx, unsigned argc, Value* vp) { |
| 1469 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1470 |
|
| 1471 |
const Module* module; |
| 1472 |
if (!GetModuleArg(cx, args, 2, "WebAssembly.Module.customSections", |
| 1473 |
&module)) { |
| 1474 |
return false; |
| 1475 |
} |
| 1476 |
|
| 1477 |
Vector<char, 8> name(cx); |
| 1478 |
{ |
| 1479 |
RootedString str(cx, ToString(cx, args.get(1))); |
| 1480 |
if (!str) { |
| 1481 |
return false; |
| 1482 |
} |
| 1483 |
|
| 1484 |
Rooted<JSLinearString*> linear(cx, str->ensureLinear(cx)); |
| 1485 |
if (!linear) { |
| 1486 |
return false; |
| 1487 |
} |
| 1488 |
|
| 1489 |
if (!name.initLengthUninitialized( |
| 1490 |
JS::GetDeflatedUTF8StringLength(linear))) { |
| 1491 |
return false; |
| 1492 |
} |
| 1493 |
|
| 1494 |
(void)JS::DeflateStringToUTF8Buffer(linear, |
| 1495 |
Span(name.begin(), name.length())); |
| 1496 |
} |
| 1497 |
|
| 1498 |
RootedValueVector elems(cx); |
| 1499 |
Rooted<ArrayBufferObject*> buf(cx); |
| 1500 |
for (const CustomSection& cs : module->moduleMeta().customSections) { |
| 1501 |
if (name.length() != cs.name.length()) { |
| 1502 |
continue; |
| 1503 |
} |
| 1504 |
if (memcmp(name.begin(), cs.name.begin(), name.length()) != 0) { |
| 1505 |
continue; |
| 1506 |
} |
| 1507 |
|
| 1508 |
buf = ArrayBufferObject::createZeroed(cx, cs.payload->length()); |
| 1509 |
if (!buf) { |
| 1510 |
return false; |
| 1511 |
} |
| 1512 |
|
| 1513 |
memcpy(buf->dataPointer(), cs.payload->begin(), cs.payload->length()); |
| 1514 |
if (!elems.append(ObjectValue(*buf))) { |
| 1515 |
return false; |
| 1516 |
} |
| 1517 |
} |
| 1518 |
|
| 1519 |
JSObject* arr = NewDenseCopiedArray(cx, elems.length(), elems.begin()); |
| 1520 |
if (!arr) { |
| 1521 |
return false; |
| 1522 |
} |
| 1523 |
|
| 1524 |
args.rval().setObject(*arr); |
| 1525 |
return true; |
| 1526 |
} |
| 1527 |
|
| 1528 |
/* static */ |
| 1529 |
WasmModuleObject* WasmModuleObject::create(JSContext* cx, const Module& module, |
| 1530 |
HandleObject proto) { |
| 1531 |
AutoSetNewObjectMetadata metadata(cx); |
| 1532 |
auto* obj = NewObjectWithGivenProto<WasmModuleObject>(cx, proto); |
| 1533 |
if (!obj) { |
| 1534 |
return nullptr; |
| 1535 |
} |
| 1536 |
|
| 1537 |
// The pipeline state on some architectures may retain stale instructions |
| 1538 |
// even after we invalidate the instruction cache. There is no generally |
| 1539 |
// available method to broadcast this pipeline flush to all threads after |
| 1540 |
// we've compiled new code, so conservatively perform one here when we're |
| 1541 |
// receiving a module that may have been compiled from another thread. |
| 1542 |
// |
| 1543 |
// The cost of this flush is expected to minimal enough to not be worth |
| 1544 |
// optimizing away in the case the module was compiled on this thread. |
| 1545 |
jit::FlushExecutionContext(); |
| 1546 |
|
| 1547 |
// This accounts for module allocation size (excluding code which is handled |
| 1548 |
// separately - see below). This assumes that the size of associated data |
| 1549 |
// doesn't change for the life of the WasmModuleObject. The size is counted |
| 1550 |
// once per WasmModuleObject referencing a Module. |
| 1551 |
InitReservedSlot(obj, MODULE_SLOT, const_cast<Module*>(&module), |
| 1552 |
module.gcMallocBytesExcludingCode(), MemoryUse::WasmModule); |
| 1553 |
module.AddRef(); |
| 1554 |
|
| 1555 |
// Bug 1569888: We account for the first tier here; the second tier, if |
| 1556 |
// different, also needs to be accounted for. |
| 1557 |
size_t codeMemory = module.tier1CodeMemoryUsed(); |
| 1558 |
if (codeMemory) { |
| 1559 |
cx->zone()->incJitMemory(codeMemory); |
| 1560 |
} |
| 1561 |
return obj; |
| 1562 |
} |
| 1563 |
|
| 1564 |
struct MOZ_STACK_CLASS AutoPinBufferSourceLength { |
| 1565 |
explicit AutoPinBufferSourceLength(JSContext* cx, JSObject* bufferSource) |
| 1566 |
: bufferSource_(cx, bufferSource), |
| 1567 |
wasPinned_(!JS::PinArrayBufferOrViewLength(bufferSource_, true)) {} |
| 1568 |
~AutoPinBufferSourceLength() { |
| 1569 |
if (!wasPinned_) { |
| 1570 |
JS::PinArrayBufferOrViewLength(bufferSource_, false); |
| 1571 |
} |
| 1572 |
} |
| 1573 |
|
| 1574 |
private: |
| 1575 |
Rooted<JSObject*> bufferSource_; |
| 1576 |
bool wasPinned_; |
| 1577 |
}; |
| 1578 |
|
| 1579 |
static bool GetBytecodeSource(JSContext* cx, Handle<JSObject*> obj, |
| 1580 |
unsigned errorNumber, BytecodeSource* bytecode) { |
| 1581 |
JSObject* unwrapped = CheckedUnwrapStatic(obj); |
| 1582 |
|
| 1583 |
SharedMem<uint8_t*> dataPointer; |
| 1584 |
size_t byteLength; |
| 1585 |
if (!unwrapped || |
| 1586 |
!IsBufferSource(cx, unwrapped, /*allowShared*/ false, |
| 1587 |
/*allowResizable*/ false, &dataPointer, &byteLength)) { |
| 1588 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, errorNumber); |
| 1589 |
return false; |
| 1590 |
} |
| 1591 |
|
| 1592 |
*bytecode = BytecodeSource(dataPointer.unwrap(), byteLength); |
| 1593 |
return true; |
| 1594 |
} |
| 1595 |
|
| 1596 |
static bool GetBytecodeBuffer(JSContext* cx, Handle<JSObject*> obj, |
| 1597 |
unsigned errorNumber, BytecodeBuffer* bytecode) { |
| 1598 |
BytecodeSource source; |
| 1599 |
if (!GetBytecodeSource(cx, obj, errorNumber, &source)) { |
| 1600 |
return false; |
| 1601 |
} |
| 1602 |
AutoPinBufferSourceLength pin(cx, obj); |
| 1603 |
if (!BytecodeBuffer::fromSource(source, bytecode)) { |
| 1604 |
ReportOutOfMemory(cx); |
| 1605 |
return false; |
| 1606 |
} |
| 1607 |
return true; |
| 1608 |
} |
| 1609 |
|
| 1610 |
static bool ReportCompileWarnings(JSContext* cx, |
| 1611 |
const UniqueCharsVector& warnings) { |
| 1612 |
// Avoid spamming the console. |
| 1613 |
size_t numWarnings = std::min<size_t>(warnings.length(), 3); |
| 1614 |
|
| 1615 |
for (size_t i = 0; i < numWarnings; i++) { |
| 1616 |
if (!WarnNumberASCII(cx, JSMSG_WASM_COMPILE_WARNING, warnings[i].get())) { |
| 1617 |
return false; |
| 1618 |
} |
| 1619 |
} |
| 1620 |
|
| 1621 |
if (warnings.length() > numWarnings) { |
| 1622 |
if (!WarnNumberASCII(cx, JSMSG_WASM_COMPILE_WARNING, |
| 1623 |
"other warnings suppressed")) { |
| 1624 |
return false; |
| 1625 |
} |
| 1626 |
} |
| 1627 |
|
| 1628 |
return true; |
| 1629 |
} |
| 1630 |
|
| 1631 |
/* static */ |
| 1632 |
bool WasmModuleObject::construct(JSContext* cx, unsigned argc, Value* vp) { |
| 1633 |
CallArgs callArgs = CallArgsFromVp(argc, vp); |
| 1634 |
|
| 1635 |
Log(cx, "sync new Module() started"); |
| 1636 |
|
| 1637 |
if (!ThrowIfNotConstructing(cx, callArgs, "Module")) { |
| 1638 |
return false; |
| 1639 |
} |
| 1640 |
|
| 1641 |
JS::RootedVector<JSString*> parameterStrings(cx); |
| 1642 |
JS::RootedVector<Value> parameterArgs(cx); |
| 1643 |
bool canCompileStrings = false; |
| 1644 |
if (!cx->isRuntimeCodeGenEnabled(JS::RuntimeCode::WASM, nullptr, |
| 1645 |
JS::CompilationType::Undefined, |
| 1646 |
parameterStrings, nullptr, parameterArgs, |
| 1647 |
NullHandleValue, &canCompileStrings)) { |
| 1648 |
return false; |
| 1649 |
} |
| 1650 |
if (!canCompileStrings) { |
| 1651 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 1652 |
JSMSG_CSP_BLOCKED_WASM, "WebAssembly.Module"); |
| 1653 |
return false; |
| 1654 |
} |
| 1655 |
|
| 1656 |
if (!callArgs.requireAtLeast(cx, "WebAssembly.Module", 1)) { |
| 1657 |
return false; |
| 1658 |
} |
| 1659 |
|
| 1660 |
if (!callArgs[0].isObject()) { |
| 1661 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 1662 |
JSMSG_WASM_BAD_BUF_ARG); |
| 1663 |
return false; |
| 1664 |
} |
| 1665 |
|
| 1666 |
FeatureOptions options; |
| 1667 |
if (!options.init(cx, callArgs.get(1))) { |
| 1668 |
return false; |
| 1669 |
} |
| 1670 |
|
| 1671 |
SharedCompileArgs compileArgs = |
| 1672 |
InitCompileArgs(cx, options, "WebAssembly.Module"); |
| 1673 |
if (!compileArgs) { |
| 1674 |
return false; |
| 1675 |
} |
| 1676 |
|
| 1677 |
BytecodeSource source; |
| 1678 |
Rooted<JSObject*> sourceObj(cx, &callArgs[0].toObject()); |
| 1679 |
if (!GetBytecodeSource(cx, sourceObj, JSMSG_WASM_BAD_BUF_ARG, &source)) { |
| 1680 |
return false; |
| 1681 |
} |
| 1682 |
|
| 1683 |
UniqueChars error; |
| 1684 |
UniqueCharsVector warnings; |
| 1685 |
SharedModule module; |
| 1686 |
{ |
| 1687 |
AutoPinBufferSourceLength pin(cx, sourceObj.get()); |
| 1688 |
module = CompileBuffer(*compileArgs, BytecodeBufferOrSource(source), &error, |
| 1689 |
&warnings, nullptr); |
| 1690 |
} |
| 1691 |
|
| 1692 |
if (!ReportCompileWarnings(cx, warnings)) { |
| 1693 |
return false; |
| 1694 |
} |
| 1695 |
if (!module) { |
| 1696 |
if (error) { |
| 1697 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 1698 |
JSMSG_WASM_COMPILE_ERROR, error.get()); |
| 1699 |
return false; |
| 1700 |
} |
| 1701 |
return ThrowCompileOutOfMemory(cx); |
| 1702 |
} |
| 1703 |
|
| 1704 |
RootedObject proto( |
| 1705 |
cx, GetWasmConstructorPrototype(cx, callArgs, JSProto_WasmModule)); |
| 1706 |
if (!proto) { |
| 1707 |
ReportOutOfMemory(cx); |
| 1708 |
return false; |
| 1709 |
} |
| 1710 |
|
| 1711 |
RootedObject moduleObj(cx, WasmModuleObject::create(cx, *module, proto)); |
| 1712 |
if (!moduleObj) { |
| 1713 |
return false; |
| 1714 |
} |
| 1715 |
|
| 1716 |
Log(cx, "sync new Module() succeded"); |
| 1717 |
|
| 1718 |
callArgs.rval().setObject(*moduleObj); |
| 1719 |
return true; |
| 1720 |
} |
| 1721 |
|
| 1722 |
const Module& WasmModuleObject::module() const { |
| 1723 |
MOZ_ASSERT(is<WasmModuleObject>()); |
| 1724 |
return *(const Module*)getReservedSlot(MODULE_SLOT).toPrivate(); |
| 1725 |
} |
| 1726 |
|
| 1727 |
// ============================================================================ |
| 1728 |
// WebAssembly.Instance class and methods |
| 1729 |
|
| 1730 |
const JSClassOps WasmInstanceObject::classOps_ = { |
| 1731 |
nullptr, // addProperty |
| 1732 |
nullptr, // delProperty |
| 1733 |
nullptr, // enumerate |
| 1734 |
nullptr, // newEnumerate |
| 1735 |
nullptr, // resolve |
| 1736 |
nullptr, // mayResolve |
| 1737 |
WasmInstanceObject::finalize, // finalize |
| 1738 |
nullptr, // call |
| 1739 |
nullptr, // construct |
| 1740 |
WasmInstanceObject::trace, // trace |
| 1741 |
}; |
| 1742 |
|
| 1743 |
const JSClass WasmInstanceObject::class_ = { |
| 1744 |
"WebAssembly.Instance", |
| 1745 |
JSCLASS_DELAY_METADATA_BUILDER | |
| 1746 |
JSCLASS_HAS_RESERVED_SLOTS(WasmInstanceObject::RESERVED_SLOTS) | |
| 1747 |
JSCLASS_FOREGROUND_FINALIZE, |
| 1748 |
&WasmInstanceObject::classOps_, |
| 1749 |
&WasmInstanceObject::classSpec_, |
| 1750 |
}; |
| 1751 |
|
| 1752 |
const JSClass& WasmInstanceObject::protoClass_ = PlainObject::class_; |
| 1753 |
|
| 1754 |
static constexpr char WasmInstanceName[] = "Instance"; |
| 1755 |
|
| 1756 |
const ClassSpec WasmInstanceObject::classSpec_ = { |
| 1757 |
CreateWasmConstructor<WasmInstanceObject, WasmInstanceName>, |
| 1758 |
GenericCreatePrototype<WasmInstanceObject>, |
| 1759 |
WasmInstanceObject::static_methods, |
| 1760 |
nullptr, |
| 1761 |
WasmInstanceObject::methods, |
| 1762 |
WasmInstanceObject::properties, |
| 1763 |
nullptr, |
| 1764 |
ClassSpec::DontDefineConstructor, |
| 1765 |
}; |
| 1766 |
|
| 1767 |
static bool IsInstance(HandleValue v) { |
| 1768 |
return v.isObject() && v.toObject().is<WasmInstanceObject>(); |
| 1769 |
} |
| 1770 |
|
| 1771 |
/* static */ |
| 1772 |
bool WasmInstanceObject::exportsGetterImpl(JSContext* cx, |
| 1773 |
const CallArgs& args) { |
| 1774 |
args.rval().setObject( |
| 1775 |
args.thisv().toObject().as<WasmInstanceObject>().exportsObj()); |
| 1776 |
return true; |
| 1777 |
} |
| 1778 |
|
| 1779 |
/* static */ |
| 1780 |
bool WasmInstanceObject::exportsGetter(JSContext* cx, unsigned argc, |
| 1781 |
Value* vp) { |
| 1782 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1783 |
return CallNonGenericMethod<IsInstance, exportsGetterImpl>(cx, args); |
| 1784 |
} |
| 1785 |
|
| 1786 |
const JSPropertySpec WasmInstanceObject::properties[] = { |
| 1787 |
JS_PSG("exports", WasmInstanceObject::exportsGetter, JSPROP_ENUMERATE), |
| 1788 |
JS_STRING_SYM_PS(toStringTag, "WebAssembly.Instance", JSPROP_READONLY), |
| 1789 |
JS_PS_END, |
| 1790 |
}; |
| 1791 |
|
| 1792 |
const JSFunctionSpec WasmInstanceObject::methods[] = { |
| 1793 |
JS_FS_END, |
| 1794 |
}; |
| 1795 |
|
| 1796 |
const JSFunctionSpec WasmInstanceObject::static_methods[] = { |
| 1797 |
JS_FS_END, |
| 1798 |
}; |
| 1799 |
|
| 1800 |
bool WasmInstanceObject::isNewborn() const { |
| 1801 |
MOZ_ASSERT(is<WasmInstanceObject>()); |
| 1802 |
return getReservedSlot(INSTANCE_SLOT).isUndefined(); |
| 1803 |
} |
| 1804 |
|
| 1805 |
// WeakScopeMap maps from function index to js::Scope. This maps is weak |
| 1806 |
// to avoid holding scope objects alive. The scopes are normally created |
| 1807 |
// during debugging. |
| 1808 |
// |
| 1809 |
// This is defined here in order to avoid recursive dependency between |
| 1810 |
// WasmJS.h and Scope.h. |
| 1811 |
using WasmFunctionScopeMap = |
| 1812 |
JS::WeakCache<GCHashMap<uint32_t, WeakHeapPtr<WasmFunctionScope*>, |
| 1813 |
DefaultHasher<uint32_t>, CellAllocPolicy>>; |
| 1814 |
class WasmInstanceObject::UnspecifiedScopeMap { |
| 1815 |
public: |
| 1816 |
WasmFunctionScopeMap& asWasmFunctionScopeMap() { |
| 1817 |
return *(WasmFunctionScopeMap*)this; |
| 1818 |
} |
| 1819 |
}; |
| 1820 |
|
| 1821 |
/* static */ |
| 1822 |
void WasmInstanceObject::finalize(JS::GCContext* gcx, JSObject* obj) { |
| 1823 |
WasmInstanceObject& instance = obj->as<WasmInstanceObject>(); |
| 1824 |
gcx->delete_(obj, &instance.scopes().asWasmFunctionScopeMap(), |
| 1825 |
MemoryUse::WasmInstanceScopes); |
| 1826 |
gcx->delete_(obj, &instance.indirectGlobals(), |
| 1827 |
MemoryUse::WasmInstanceGlobals); |
| 1828 |
if (!instance.isNewborn()) { |
| 1829 |
if (instance.instance().debugEnabled()) { |
| 1830 |
instance.instance().debug().finalize(gcx); |
| 1831 |
} |
| 1832 |
Instance::destroy(&instance.instance()); |
| 1833 |
gcx->removeCellMemory(obj, sizeof(Instance), |
| 1834 |
MemoryUse::WasmInstanceInstance); |
| 1835 |
} |
| 1836 |
} |
| 1837 |
|
| 1838 |
/* static */ |
| 1839 |
void WasmInstanceObject::trace(JSTracer* trc, JSObject* obj) { |
| 1840 |
WasmInstanceObject& instanceObj = obj->as<WasmInstanceObject>(); |
| 1841 |
instanceObj.indirectGlobals().trace(trc); |
| 1842 |
if (!instanceObj.isNewborn()) { |
| 1843 |
instanceObj.instance().tracePrivate(trc); |
| 1844 |
} |
| 1845 |
} |
| 1846 |
|
| 1847 |
/* static */ |
| 1848 |
WasmInstanceObject* WasmInstanceObject::create( |
| 1849 |
JSContext* cx, const SharedCode& code, |
| 1850 |
const DataSegmentVector& dataSegments, |
| 1851 |
const ModuleElemSegmentVector& elemSegments, uint32_t instanceDataLength, |
| 1852 |
Handle<WasmMemoryObjectVector> memories, SharedTableVector&& tables, |
| 1853 |
const JSObjectVector& funcImports, const GlobalDescVector& globals, |
| 1854 |
const ValVector& globalImportValues, |
| 1855 |
const WasmGlobalObjectVector& globalObjs, |
| 1856 |
const WasmTagObjectVector& tagObjs, HandleObject proto, |
| 1857 |
UniqueDebugState maybeDebug) { |
| 1858 |
UniquePtr<WasmFunctionScopeMap> scopes = |
| 1859 |
js::MakeUnique<WasmFunctionScopeMap>(cx->zone(), cx->zone()); |
| 1860 |
if (!scopes) { |
| 1861 |
ReportOutOfMemory(cx); |
| 1862 |
return nullptr; |
| 1863 |
} |
| 1864 |
// Note that `scopes` is a WeakCache, auto-linked into a sweep list on the |
| 1865 |
// Zone, and so does not require rooting. |
| 1866 |
|
| 1867 |
uint32_t indirectGlobals = 0; |
| 1868 |
|
| 1869 |
for (uint32_t i = 0; i < globalObjs.length(); i++) { |
| 1870 |
if (globalObjs[i] && globals[i].isIndirect()) { |
| 1871 |
indirectGlobals++; |
| 1872 |
} |
| 1873 |
} |
| 1874 |
|
| 1875 |
Rooted<UniquePtr<GlobalObjectVector>> indirectGlobalObjs( |
| 1876 |
cx, js::MakeUnique<GlobalObjectVector>(cx->zone())); |
| 1877 |
if (!indirectGlobalObjs || !indirectGlobalObjs->resize(indirectGlobals)) { |
| 1878 |
ReportOutOfMemory(cx); |
| 1879 |
return nullptr; |
| 1880 |
} |
| 1881 |
|
| 1882 |
{ |
| 1883 |
uint32_t next = 0; |
| 1884 |
for (uint32_t i = 0; i < globalObjs.length(); i++) { |
| 1885 |
if (globalObjs[i] && globals[i].isIndirect()) { |
| 1886 |
(*indirectGlobalObjs)[next++] = globalObjs[i]; |
| 1887 |
} |
| 1888 |
} |
| 1889 |
} |
| 1890 |
|
| 1891 |
Instance* instance = nullptr; |
| 1892 |
Rooted<WasmInstanceObject*> obj(cx); |
| 1893 |
|
| 1894 |
{ |
| 1895 |
// We must delay creating metadata for this object until after all its |
| 1896 |
// slots have been initialized. We must also create the metadata before |
| 1897 |
// calling Instance::init as that may allocate new objects. |
| 1898 |
AutoSetNewObjectMetadata metadata(cx); |
| 1899 |
obj = NewObjectWithGivenProto<WasmInstanceObject>(cx, proto); |
| 1900 |
if (!obj) { |
| 1901 |
return nullptr; |
| 1902 |
} |
| 1903 |
|
| 1904 |
MOZ_ASSERT(obj->isTenured(), "assumed by WasmTableObject write barriers"); |
| 1905 |
|
| 1906 |
InitReservedSlot(obj, SCOPES_SLOT, scopes.release(), |
| 1907 |
MemoryUse::WasmInstanceScopes); |
| 1908 |
|
| 1909 |
InitReservedSlot(obj, GLOBALS_SLOT, indirectGlobalObjs.release(), |
| 1910 |
MemoryUse::WasmInstanceGlobals); |
| 1911 |
|
| 1912 |
obj->initReservedSlot(INSTANCE_SCOPE_SLOT, UndefinedValue()); |
| 1913 |
|
| 1914 |
// The INSTANCE_SLOT may not be initialized if Instance allocation fails, |
| 1915 |
// leading to an observable "newborn" state in tracing/finalization. |
| 1916 |
MOZ_ASSERT(obj->isNewborn()); |
| 1917 |
|
| 1918 |
// Create this just before constructing Instance to avoid rooting hazards. |
| 1919 |
instance = Instance::create(cx, obj, code, instanceDataLength, |
| 1920 |
std::move(tables), std::move(maybeDebug)); |
| 1921 |
if (!instance) { |
| 1922 |
return nullptr; |
| 1923 |
} |
| 1924 |
|
| 1925 |
InitReservedSlot(obj, INSTANCE_SLOT, instance, |
| 1926 |
MemoryUse::WasmInstanceInstance); |
| 1927 |
MOZ_ASSERT(!obj->isNewborn()); |
| 1928 |
} |
| 1929 |
|
| 1930 |
if (!instance->init(cx, funcImports, globalImportValues, memories, globalObjs, |
| 1931 |
tagObjs, dataSegments, elemSegments)) { |
| 1932 |
return nullptr; |
| 1933 |
} |
| 1934 |
|
| 1935 |
return obj; |
| 1936 |
} |
| 1937 |
|
| 1938 |
void WasmInstanceObject::initExportsObj(JSObject& exportsObj) { |
| 1939 |
MOZ_ASSERT(getReservedSlot(EXPORTS_OBJ_SLOT).isUndefined()); |
| 1940 |
setReservedSlot(EXPORTS_OBJ_SLOT, ObjectValue(exportsObj)); |
| 1941 |
} |
| 1942 |
|
| 1943 |
static bool GetImportArg(JSContext* cx, HandleValue importArg, |
| 1944 |
MutableHandleObject importObj) { |
| 1945 |
if (!importArg.isUndefined()) { |
| 1946 |
if (!importArg.isObject()) { |
| 1947 |
return ThrowBadImportArg(cx); |
| 1948 |
} |
| 1949 |
importObj.set(&importArg.toObject()); |
| 1950 |
} |
| 1951 |
return true; |
| 1952 |
} |
| 1953 |
|
| 1954 |
/* static */ |
| 1955 |
bool WasmInstanceObject::construct(JSContext* cx, unsigned argc, Value* vp) { |
| 1956 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1957 |
|
| 1958 |
Log(cx, "sync new Instance() started"); |
| 1959 |
|
| 1960 |
if (!ThrowIfNotConstructing(cx, args, "Instance")) { |
| 1961 |
return false; |
| 1962 |
} |
| 1963 |
|
| 1964 |
if (!args.requireAtLeast(cx, "WebAssembly.Instance", 1)) { |
| 1965 |
return false; |
| 1966 |
} |
| 1967 |
|
| 1968 |
const Module* module; |
| 1969 |
if (!args[0].isObject() || !IsModuleObject(&args[0].toObject(), &module)) { |
| 1970 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 1971 |
JSMSG_WASM_BAD_MOD_ARG); |
| 1972 |
return false; |
| 1973 |
} |
| 1974 |
|
| 1975 |
RootedObject importObj(cx); |
| 1976 |
if (!GetImportArg(cx, args.get(1), &importObj)) { |
| 1977 |
return false; |
| 1978 |
} |
| 1979 |
|
| 1980 |
RootedObject proto( |
| 1981 |
cx, GetWasmConstructorPrototype(cx, args, JSProto_WasmInstance)); |
| 1982 |
if (!proto) { |
| 1983 |
ReportOutOfMemory(cx); |
| 1984 |
return false; |
| 1985 |
} |
| 1986 |
|
| 1987 |
Rooted<ImportValues> imports(cx); |
| 1988 |
if (!GetImports(cx, *module, importObj, imports.address())) { |
| 1989 |
return false; |
| 1990 |
} |
| 1991 |
|
| 1992 |
Rooted<WasmInstanceObject*> instanceObj(cx); |
| 1993 |
if (!module->instantiate(cx, imports.get(), proto, &instanceObj)) { |
| 1994 |
return false; |
| 1995 |
} |
| 1996 |
|
| 1997 |
Log(cx, "sync new Instance() succeeded"); |
| 1998 |
|
| 1999 |
args.rval().setObject(*instanceObj); |
| 2000 |
return true; |
| 2001 |
} |
| 2002 |
|
| 2003 |
Instance& WasmInstanceObject::instance() const { |
| 2004 |
MOZ_ASSERT(!isNewborn()); |
| 2005 |
return *(Instance*)getReservedSlot(INSTANCE_SLOT).toPrivate(); |
| 2006 |
} |
| 2007 |
|
| 2008 |
JSObject& WasmInstanceObject::exportsObj() const { |
| 2009 |
return getReservedSlot(EXPORTS_OBJ_SLOT).toObject(); |
| 2010 |
} |
| 2011 |
|
| 2012 |
WasmFunctionScope* WasmInstanceObject::getExistingFunctionScope( |
| 2013 |
uint32_t funcIndex) const { |
| 2014 |
if (auto p = scopes().asWasmFunctionScopeMap().lookup(funcIndex)) { |
| 2015 |
return p->value(); |
| 2016 |
} |
| 2017 |
|
| 2018 |
return nullptr; |
| 2019 |
} |
| 2020 |
|
| 2021 |
WasmInstanceObject::UnspecifiedScopeMap& WasmInstanceObject::scopes() const { |
| 2022 |
return *(UnspecifiedScopeMap*)(getReservedSlot(SCOPES_SLOT).toPrivate()); |
| 2023 |
} |
| 2024 |
|
| 2025 |
WasmInstanceObject::GlobalObjectVector& WasmInstanceObject::indirectGlobals() |
| 2026 |
const { |
| 2027 |
return *(GlobalObjectVector*)getReservedSlot(GLOBALS_SLOT).toPrivate(); |
| 2028 |
} |
| 2029 |
|
| 2030 |
/* static */ |
| 2031 |
bool WasmInstanceObject::getExportedFunction( |
| 2032 |
JSContext* cx, Handle<WasmInstanceObject*> instanceObj, uint32_t funcIndex, |
| 2033 |
MutableHandleFunction fun) { |
| 2034 |
Instance& instance = instanceObj->instance(); |
| 2035 |
return instance.getExportedFunction(cx, funcIndex, fun); |
| 2036 |
} |
| 2037 |
|
| 2038 |
/* static */ |
| 2039 |
WasmInstanceScope* WasmInstanceObject::getScope( |
| 2040 |
JSContext* cx, Handle<WasmInstanceObject*> instanceObj) { |
| 2041 |
if (!instanceObj->getReservedSlot(INSTANCE_SCOPE_SLOT).isUndefined()) { |
| 2042 |
return (WasmInstanceScope*)instanceObj->getReservedSlot(INSTANCE_SCOPE_SLOT) |
| 2043 |
.toGCThing(); |
| 2044 |
} |
| 2045 |
|
| 2046 |
Rooted<WasmInstanceScope*> instanceScope( |
| 2047 |
cx, WasmInstanceScope::create(cx, instanceObj)); |
| 2048 |
if (!instanceScope) { |
| 2049 |
return nullptr; |
| 2050 |
} |
| 2051 |
|
| 2052 |
instanceObj->setReservedSlot(INSTANCE_SCOPE_SLOT, |
| 2053 |
PrivateGCThingValue(instanceScope)); |
| 2054 |
|
| 2055 |
return instanceScope; |
| 2056 |
} |
| 2057 |
|
| 2058 |
/* static */ |
| 2059 |
WasmFunctionScope* WasmInstanceObject::getFunctionScope( |
| 2060 |
JSContext* cx, Handle<WasmInstanceObject*> instanceObj, |
| 2061 |
uint32_t funcIndex) { |
| 2062 |
if (auto p = |
| 2063 |
instanceObj->scopes().asWasmFunctionScopeMap().lookup(funcIndex)) { |
| 2064 |
return p->value(); |
| 2065 |
} |
| 2066 |
|
| 2067 |
Rooted<WasmInstanceScope*> instanceScope( |
| 2068 |
cx, WasmInstanceObject::getScope(cx, instanceObj)); |
| 2069 |
if (!instanceScope) { |
| 2070 |
return nullptr; |
| 2071 |
} |
| 2072 |
|
| 2073 |
Rooted<WasmFunctionScope*> funcScope( |
| 2074 |
cx, WasmFunctionScope::create(cx, instanceScope, funcIndex)); |
| 2075 |
if (!funcScope) { |
| 2076 |
return nullptr; |
| 2077 |
} |
| 2078 |
|
| 2079 |
if (!instanceObj->scopes().asWasmFunctionScopeMap().putNew(funcIndex, |
| 2080 |
funcScope)) { |
| 2081 |
ReportOutOfMemory(cx); |
| 2082 |
return nullptr; |
| 2083 |
} |
| 2084 |
|
| 2085 |
return funcScope; |
| 2086 |
} |
| 2087 |
|
| 2088 |
// ============================================================================ |
| 2089 |
// WebAssembly.Memory class and methods |
| 2090 |
|
| 2091 |
const JSClassOps WasmMemoryObject::classOps_ = { |
| 2092 |
nullptr, // addProperty |
| 2093 |
nullptr, // delProperty |
| 2094 |
nullptr, // enumerate |
| 2095 |
nullptr, // newEnumerate |
| 2096 |
nullptr, // resolve |
| 2097 |
nullptr, // mayResolve |
| 2098 |
WasmMemoryObject::finalize, // finalize |
| 2099 |
nullptr, // call |
| 2100 |
nullptr, // construct |
| 2101 |
nullptr, // trace |
| 2102 |
}; |
| 2103 |
|
| 2104 |
const JSClass WasmMemoryObject::class_ = { |
| 2105 |
"WebAssembly.Memory", |
| 2106 |
JSCLASS_DELAY_METADATA_BUILDER | |
| 2107 |
JSCLASS_HAS_RESERVED_SLOTS(WasmMemoryObject::RESERVED_SLOTS) | |
| 2108 |
JSCLASS_FOREGROUND_FINALIZE, |
| 2109 |
&WasmMemoryObject::classOps_, |
| 2110 |
&WasmMemoryObject::classSpec_, |
| 2111 |
}; |
| 2112 |
|
| 2113 |
const JSClass& WasmMemoryObject::protoClass_ = PlainObject::class_; |
| 2114 |
|
| 2115 |
static constexpr char WasmMemoryName[] = "Memory"; |
| 2116 |
|
| 2117 |
static JSObject* CreateWasmMemoryPrototype(JSContext* cx, JSProtoKey key) { |
| 2118 |
RootedObject proto(cx, GlobalObject::createBlankPrototype( |
| 2119 |
cx, cx->global(), &WasmMemoryObject::protoClass_)); |
| 2120 |
if (!proto) { |
| 2121 |
return nullptr; |
| 2122 |
} |
| 2123 |
if (MemoryControlAvailable(cx)) { |
| 2124 |
if (!JS_DefineFunctions(cx, proto, |
| 2125 |
WasmMemoryObject::memoryControlMethods)) { |
| 2126 |
return nullptr; |
| 2127 |
} |
| 2128 |
} |
| 2129 |
return proto; |
| 2130 |
} |
| 2131 |
|
| 2132 |
const ClassSpec WasmMemoryObject::classSpec_ = { |
| 2133 |
CreateWasmConstructor<WasmMemoryObject, WasmMemoryName>, |
| 2134 |
CreateWasmMemoryPrototype, |
| 2135 |
WasmMemoryObject::static_methods, |
| 2136 |
nullptr, |
| 2137 |
WasmMemoryObject::methods, |
| 2138 |
WasmMemoryObject::properties, |
| 2139 |
nullptr, |
| 2140 |
ClassSpec::DontDefineConstructor, |
| 2141 |
}; |
| 2142 |
|
| 2143 |
/* static */ |
| 2144 |
void WasmMemoryObject::finalize(JS::GCContext* gcx, JSObject* obj) { |
| 2145 |
WasmMemoryObject& memory = obj->as<WasmMemoryObject>(); |
| 2146 |
if (memory.hasObservers()) { |
| 2147 |
gcx->delete_(obj, &memory.observers(), MemoryUse::WasmMemoryObservers); |
| 2148 |
} |
| 2149 |
} |
| 2150 |
|
| 2151 |
/* static */ |
| 2152 |
WasmMemoryObject* WasmMemoryObject::create( |
| 2153 |
JSContext* cx, Handle<ArrayBufferObjectMaybeShared*> buffer, bool isHuge, |
| 2154 |
HandleObject proto) { |
| 2155 |
AutoSetNewObjectMetadata metadata(cx); |
| 2156 |
auto* obj = NewObjectWithGivenProto<WasmMemoryObject>(cx, proto); |
| 2157 |
if (!obj) { |
| 2158 |
return nullptr; |
| 2159 |
} |
| 2160 |
|
| 2161 |
obj->initReservedSlot(BUFFER_SLOT, ObjectValue(*buffer)); |
| 2162 |
obj->initReservedSlot(ISHUGE_SLOT, BooleanValue(isHuge)); |
| 2163 |
MOZ_ASSERT(!obj->hasObservers()); |
| 2164 |
|
| 2165 |
return obj; |
| 2166 |
} |
| 2167 |
|
| 2168 |
/* static */ |
| 2169 |
bool WasmMemoryObject::construct(JSContext* cx, unsigned argc, Value* vp) { |
| 2170 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2171 |
|
| 2172 |
if (!ThrowIfNotConstructing(cx, args, "Memory")) { |
| 2173 |
return false; |
| 2174 |
} |
| 2175 |
|
| 2176 |
if (!args.requireAtLeast(cx, "WebAssembly.Memory", 1)) { |
| 2177 |
return false; |
| 2178 |
} |
| 2179 |
|
| 2180 |
if (!args.get(0).isObject()) { |
| 2181 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 2182 |
JSMSG_WASM_BAD_DESC_ARG, "memory"); |
| 2183 |
return false; |
| 2184 |
} |
| 2185 |
|
| 2186 |
RootedObject obj(cx, &args[0].toObject()); |
| 2187 |
Limits limits; |
| 2188 |
if (!GetLimits(cx, obj, LimitsKind::Memory, &limits) || |
| 2189 |
!CheckLimits(cx, MaxMemoryPagesValidation(limits.addressType), |
| 2190 |
LimitsKind::Memory, &limits)) { |
| 2191 |
return false; |
| 2192 |
} |
| 2193 |
|
| 2194 |
if (Pages(limits.initial) > MaxMemoryPages(limits.addressType)) { |
| 2195 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 2196 |
JSMSG_WASM_MEM_IMP_LIMIT); |
| 2197 |
return false; |
| 2198 |
} |
| 2199 |
MemoryDesc memory(limits); |
| 2200 |
|
| 2201 |
Rooted<ArrayBufferObjectMaybeShared*> buffer(cx, |
| 2202 |
CreateWasmBuffer(cx, memory)); |
| 2203 |
if (!buffer) { |
| 2204 |
return false; |
| 2205 |
} |
| 2206 |
|
| 2207 |
RootedObject proto(cx, |
| 2208 |
GetWasmConstructorPrototype(cx, args, JSProto_WasmMemory)); |
| 2209 |
if (!proto) { |
| 2210 |
ReportOutOfMemory(cx); |
| 2211 |
return false; |
| 2212 |
} |
| 2213 |
|
| 2214 |
Rooted<WasmMemoryObject*> memoryObj( |
| 2215 |
cx, WasmMemoryObject::create( |
| 2216 |
cx, buffer, IsHugeMemoryEnabled(limits.addressType), proto)); |
| 2217 |
if (!memoryObj) { |
| 2218 |
return false; |
| 2219 |
} |
| 2220 |
|
| 2221 |
args.rval().setObject(*memoryObj); |
| 2222 |
return true; |
| 2223 |
} |
| 2224 |
|
| 2225 |
static bool IsMemory(HandleValue v) { |
| 2226 |
return v.isObject() && v.toObject().is<WasmMemoryObject>(); |
| 2227 |
} |
| 2228 |
|
| 2229 |
/* static */ |
| 2230 |
ArrayBufferObjectMaybeShared* WasmMemoryObject::refreshBuffer( |
| 2231 |
JSContext* cx, Handle<WasmMemoryObject*> memoryObj, |
| 2232 |
Handle<ArrayBufferObjectMaybeShared*> buffer) { |
| 2233 |
if (memoryObj->isShared()) { |
| 2234 |
size_t memoryLength = memoryObj->volatileMemoryLength(); |
| 2235 |
MOZ_ASSERT_IF(!buffer->is<GrowableSharedArrayBufferObject>(), |
| 2236 |
memoryLength >= buffer->byteLength()); |
| 2237 |
|
| 2238 |
// The `length` field on a fixed length SAB cannot change even if |
| 2239 |
// the underlying memory has grown. The spec therefore requires that |
| 2240 |
// accessing the buffer property will create a new fixed length SAB |
| 2241 |
// with the current length if the underlying raw buffer's length has |
| 2242 |
// changed. We don't need to do this for growable SAB. |
| 2243 |
if (!buffer->is<GrowableSharedArrayBufferObject>() && |
| 2244 |
memoryLength > buffer->byteLength()) { |
| 2245 |
Rooted<SharedArrayBufferObject*> newBuffer( |
| 2246 |
cx, SharedArrayBufferObject::New( |
| 2247 |
cx, memoryObj->sharedArrayRawBuffer(), memoryLength)); |
| 2248 |
MOZ_ASSERT(newBuffer->is<FixedLengthSharedArrayBufferObject>()); |
| 2249 |
if (!newBuffer) { |
| 2250 |
return nullptr; |
| 2251 |
} |
| 2252 |
// OK to addReference after we try to allocate because the memoryObj |
| 2253 |
// keeps the rawBuffer alive. |
| 2254 |
if (!memoryObj->sharedArrayRawBuffer()->addReference()) { |
| 2255 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 2256 |
JSMSG_SC_SAB_REFCNT_OFLO); |
| 2257 |
return nullptr; |
| 2258 |
} |
| 2259 |
memoryObj->setReservedSlot(BUFFER_SLOT, ObjectValue(*newBuffer)); |
| 2260 |
return newBuffer; |
| 2261 |
} |
| 2262 |
} |
| 2263 |
return buffer; |
| 2264 |
} |
| 2265 |
|
| 2266 |
/* static */ |
| 2267 |
bool WasmMemoryObject::bufferGetterImpl(JSContext* cx, const CallArgs& args) { |
| 2268 |
Rooted<WasmMemoryObject*> memoryObj( |
| 2269 |
cx, &args.thisv().toObject().as<WasmMemoryObject>()); |
| 2270 |
|
| 2271 |
Rooted<ArrayBufferObjectMaybeShared*> buffer(cx, &memoryObj->buffer()); |
| 2272 |
MOZ_RELEASE_ASSERT(buffer->isWasm() && !buffer->isPreparedForAsmJS()); |
| 2273 |
|
| 2274 |
ArrayBufferObjectMaybeShared* refreshedBuffer = |
| 2275 |
WasmMemoryObject::refreshBuffer(cx, memoryObj, buffer); |
| 2276 |
if (!refreshedBuffer) { |
| 2277 |
return false; |
| 2278 |
} |
| 2279 |
|
| 2280 |
args.rval().setObject(*refreshedBuffer); |
| 2281 |
return true; |
| 2282 |
} |
| 2283 |
|
| 2284 |
/* static */ |
| 2285 |
bool WasmMemoryObject::bufferGetter(JSContext* cx, unsigned argc, Value* vp) { |
| 2286 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2287 |
return CallNonGenericMethod<IsMemory, bufferGetterImpl>(cx, args); |
| 2288 |
} |
| 2289 |
|
| 2290 |
const JSPropertySpec WasmMemoryObject::properties[] = { |
| 2291 |
JS_PSG("buffer", WasmMemoryObject::bufferGetter, JSPROP_ENUMERATE), |
| 2292 |
JS_STRING_SYM_PS(toStringTag, "WebAssembly.Memory", JSPROP_READONLY), |
| 2293 |
JS_PS_END, |
| 2294 |
}; |
| 2295 |
|
| 2296 |
/* static */ |
| 2297 |
bool WasmMemoryObject::growImpl(JSContext* cx, const CallArgs& args) { |
| 2298 |
Rooted<WasmMemoryObject*> memory( |
| 2299 |
cx, &args.thisv().toObject().as<WasmMemoryObject>()); |
| 2300 |
|
| 2301 |
if (!args.requireAtLeast(cx, "WebAssembly.Memory.grow", 1)) { |
| 2302 |
return false; |
| 2303 |
} |
| 2304 |
|
| 2305 |
uint64_t delta; |
| 2306 |
if (!EnforceAddressValue(cx, args.get(0), memory->addressType(), "Memory", |
| 2307 |
"grow delta", &delta)) { |
| 2308 |
return false; |
| 2309 |
} |
| 2310 |
|
| 2311 |
uint32_t ret = grow(memory, delta, cx); |
| 2312 |
|
| 2313 |
if (ret == uint32_t(-1)) { |
| 2314 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, JSMSG_WASM_BAD_GROW, |
| 2315 |
"memory"); |
| 2316 |
return false; |
| 2317 |
} |
| 2318 |
|
| 2319 |
RootedValue result(cx); |
| 2320 |
if (!CreateAddressValue(cx, ret, memory->addressType(), &result)) { |
| 2321 |
ReportOutOfMemory(cx); |
| 2322 |
return false; |
| 2323 |
} |
| 2324 |
args.rval().set(result); |
| 2325 |
return true; |
| 2326 |
} |
| 2327 |
|
| 2328 |
/* static */ |
| 2329 |
bool WasmMemoryObject::grow(JSContext* cx, unsigned argc, Value* vp) { |
| 2330 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2331 |
return CallNonGenericMethod<IsMemory, growImpl>(cx, args); |
| 2332 |
} |
| 2333 |
|
| 2334 |
/* static */ |
| 2335 |
bool WasmMemoryObject::discardImpl(JSContext* cx, const CallArgs& args) { |
| 2336 |
Rooted<WasmMemoryObject*> memory( |
| 2337 |
cx, &args.thisv().toObject().as<WasmMemoryObject>()); |
| 2338 |
|
| 2339 |
if (!args.requireAtLeast(cx, "WebAssembly.Memory.discard", 2)) { |
| 2340 |
return false; |
| 2341 |
} |
| 2342 |
|
| 2343 |
uint64_t byteOffset; |
| 2344 |
if (!EnforceRangeU64(cx, args.get(0), "Memory", "byte offset", &byteOffset)) { |
| 2345 |
return false; |
| 2346 |
} |
| 2347 |
|
| 2348 |
uint64_t byteLen; |
| 2349 |
if (!EnforceRangeU64(cx, args.get(1), "Memory", "length", &byteLen)) { |
| 2350 |
return false; |
| 2351 |
} |
| 2352 |
|
| 2353 |
if (byteOffset % wasm::PageSize != 0 || byteLen % wasm::PageSize != 0) { |
| 2354 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 2355 |
JSMSG_WASM_UNALIGNED_ACCESS); |
| 2356 |
return false; |
| 2357 |
} |
| 2358 |
|
| 2359 |
if (!wasm::MemoryBoundsCheck(byteOffset, byteLen, |
| 2360 |
memory->volatileMemoryLength())) { |
| 2361 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 2362 |
JSMSG_WASM_OUT_OF_BOUNDS); |
| 2363 |
return false; |
| 2364 |
} |
| 2365 |
|
| 2366 |
discard(memory, byteOffset, byteLen, cx); |
| 2367 |
|
| 2368 |
args.rval().setUndefined(); |
| 2369 |
return true; |
| 2370 |
} |
| 2371 |
|
| 2372 |
/* static */ |
| 2373 |
bool WasmMemoryObject::discard(JSContext* cx, unsigned argc, Value* vp) { |
| 2374 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2375 |
return CallNonGenericMethod<IsMemory, discardImpl>(cx, args); |
| 2376 |
} |
| 2377 |
|
| 2378 |
#ifdef ENABLE_WASM_RESIZABLE_ARRAYBUFFER |
| 2379 |
/* static */ |
| 2380 |
bool WasmMemoryObject::toFixedLengthBufferImpl(JSContext* cx, |
| 2381 |
const CallArgs& args) { |
| 2382 |
Rooted<WasmMemoryObject*> memory( |
| 2383 |
cx, &args.thisv().toObject().as<WasmMemoryObject>()); |
| 2384 |
|
| 2385 |
Rooted<ArrayBufferObjectMaybeShared*> buffer(cx, &memory->buffer()); |
| 2386 |
MOZ_RELEASE_ASSERT(buffer->isWasm() && !buffer->isPreparedForAsmJS()); |
| 2387 |
// If IsFixedLengthArrayBuffer(buffer) is true, return buffer. |
| 2388 |
if (!buffer->isResizable()) { |
| 2389 |
ArrayBufferObjectMaybeShared* refreshedBuffer = |
| 2390 |
refreshBuffer(cx, memory, buffer); |
| 2391 |
args.rval().set(ObjectValue(*refreshedBuffer)); |
| 2392 |
return true; |
| 2393 |
} |
| 2394 |
|
| 2395 |
Rooted<ArrayBufferObjectMaybeShared*> fixedBuffer(cx); |
| 2396 |
if (memory->isShared()) { |
| 2397 |
Rooted<SharedArrayBufferObject*> oldBuffer( |
| 2398 |
cx, &buffer->as<SharedArrayBufferObject>()); |
| 2399 |
fixedBuffer.set(SharedArrayBufferObject::createFromWasmObject< |
| 2400 |
FixedLengthSharedArrayBufferObject>(cx, oldBuffer)); |
| 2401 |
} else { |
| 2402 |
Rooted<ArrayBufferObject*> oldBuffer(cx, &buffer->as<ArrayBufferObject>()); |
| 2403 |
fixedBuffer.set( |
| 2404 |
ArrayBufferObject::createFromWasmObject<FixedLengthArrayBufferObject>( |
| 2405 |
cx, oldBuffer)); |
| 2406 |
} |
| 2407 |
|
| 2408 |
if (!fixedBuffer) { |
| 2409 |
return false; |
| 2410 |
} |
| 2411 |
memory->setReservedSlot(BUFFER_SLOT, ObjectValue(*fixedBuffer)); |
| 2412 |
args.rval().set(ObjectValue(*fixedBuffer)); |
| 2413 |
return true; |
| 2414 |
} |
| 2415 |
|
| 2416 |
/* static */ |
| 2417 |
bool WasmMemoryObject::toFixedLengthBuffer(JSContext* cx, unsigned argc, |
| 2418 |
Value* vp) { |
| 2419 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2420 |
return CallNonGenericMethod<IsMemory, toFixedLengthBufferImpl>(cx, args); |
| 2421 |
} |
| 2422 |
|
| 2423 |
/* static */ |
| 2424 |
bool WasmMemoryObject::toResizableBufferImpl(JSContext* cx, |
| 2425 |
const CallArgs& args) { |
| 2426 |
Rooted<WasmMemoryObject*> memory( |
| 2427 |
cx, &args.thisv().toObject().as<WasmMemoryObject>()); |
| 2428 |
|
| 2429 |
Rooted<ArrayBufferObjectMaybeShared*> buffer(cx, &memory->buffer()); |
| 2430 |
// If IsFixedLengthArrayBuffer(buffer) is false, return buffer. |
| 2431 |
if (buffer->isResizable()) { |
| 2432 |
args.rval().set(ObjectValue(*buffer)); |
| 2433 |
return true; |
| 2434 |
} |
| 2435 |
|
| 2436 |
if (buffer->wasmSourceMaxPages().isNothing()) { |
| 2437 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 2438 |
JSMSG_WASM_MEMORY_NOT_RESIZABLE); |
| 2439 |
return false; |
| 2440 |
} |
| 2441 |
|
| 2442 |
Rooted<ArrayBufferObjectMaybeShared*> resizableBuffer(cx); |
| 2443 |
if (memory->isShared()) { |
| 2444 |
Rooted<SharedArrayBufferObject*> oldBuffer( |
| 2445 |
cx, &buffer->as<SharedArrayBufferObject>()); |
| 2446 |
resizableBuffer.set(SharedArrayBufferObject::createFromWasmObject< |
| 2447 |
GrowableSharedArrayBufferObject>(cx, oldBuffer)); |
| 2448 |
} else { |
| 2449 |
Rooted<ArrayBufferObject*> oldBuffer(cx, &buffer->as<ArrayBufferObject>()); |
| 2450 |
resizableBuffer.set( |
| 2451 |
ArrayBufferObject::createFromWasmObject<ResizableArrayBufferObject>( |
| 2452 |
cx, oldBuffer)); |
| 2453 |
} |
| 2454 |
|
| 2455 |
if (!resizableBuffer) { |
| 2456 |
return false; |
| 2457 |
} |
| 2458 |
memory->setReservedSlot(BUFFER_SLOT, ObjectValue(*resizableBuffer)); |
| 2459 |
args.rval().set(ObjectValue(*resizableBuffer)); |
| 2460 |
return true; |
| 2461 |
} |
| 2462 |
|
| 2463 |
/* static */ |
| 2464 |
bool WasmMemoryObject::toResizableBuffer(JSContext* cx, unsigned argc, |
| 2465 |
Value* vp) { |
| 2466 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2467 |
return CallNonGenericMethod<IsMemory, toResizableBufferImpl>(cx, args); |
| 2468 |
} |
| 2469 |
#endif // ENABLE_WASM_RESIZABLE_ARRAYBUFFER |
| 2470 |
|
| 2471 |
const JSFunctionSpec WasmMemoryObject::methods[] = { |
| 2472 |
#ifdef ENABLE_WASM_TYPE_REFLECTIONS |
| 2473 |
JS_FN("type", WasmMemoryObject::type, 0, JSPROP_ENUMERATE), |
| 2474 |
#endif |
| 2475 |
JS_FN("grow", WasmMemoryObject::grow, 1, JSPROP_ENUMERATE), |
| 2476 |
#ifdef ENABLE_WASM_RESIZABLE_ARRAYBUFFER |
| 2477 |
JS_FN("toFixedLengthBuffer", WasmMemoryObject::toFixedLengthBuffer, 0, |
| 2478 |
JSPROP_ENUMERATE), |
| 2479 |
JS_FN("toResizableBuffer", WasmMemoryObject::toResizableBuffer, 0, |
| 2480 |
JSPROP_ENUMERATE), |
| 2481 |
#endif |
| 2482 |
JS_FS_END, |
| 2483 |
}; |
| 2484 |
|
| 2485 |
const JSFunctionSpec WasmMemoryObject::memoryControlMethods[] = { |
| 2486 |
JS_FN("discard", WasmMemoryObject::discard, 2, JSPROP_ENUMERATE), |
| 2487 |
JS_FS_END, |
| 2488 |
}; |
| 2489 |
|
| 2490 |
const JSFunctionSpec WasmMemoryObject::static_methods[] = { |
| 2491 |
JS_FS_END, |
| 2492 |
}; |
| 2493 |
|
| 2494 |
ArrayBufferObjectMaybeShared& WasmMemoryObject::buffer() const { |
| 2495 |
return getReservedSlot(BUFFER_SLOT) |
| 2496 |
.toObject() |
| 2497 |
.as<ArrayBufferObjectMaybeShared>(); |
| 2498 |
} |
| 2499 |
|
| 2500 |
WasmSharedArrayRawBuffer* WasmMemoryObject::sharedArrayRawBuffer() const { |
| 2501 |
MOZ_ASSERT(isShared()); |
| 2502 |
return buffer().as<SharedArrayBufferObject>().rawWasmBufferObject(); |
| 2503 |
} |
| 2504 |
|
| 2505 |
#ifdef ENABLE_WASM_TYPE_REFLECTIONS |
| 2506 |
bool WasmMemoryObject::typeImpl(JSContext* cx, const CallArgs& args) { |
| 2507 |
Rooted<WasmMemoryObject*> memoryObj( |
| 2508 |
cx, &args.thisv().toObject().as<WasmMemoryObject>()); |
| 2509 |
RootedObject typeObj(cx, MemoryTypeToObject(cx, memoryObj->isShared(), |
| 2510 |
memoryObj->addressType(), |
| 2511 |
memoryObj->volatilePages(), |
| 2512 |
memoryObj->sourceMaxPages())); |
| 2513 |
if (!typeObj) { |
| 2514 |
return false; |
| 2515 |
} |
| 2516 |
args.rval().setObject(*typeObj); |
| 2517 |
return true; |
| 2518 |
} |
| 2519 |
|
| 2520 |
bool WasmMemoryObject::type(JSContext* cx, unsigned argc, Value* vp) { |
| 2521 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2522 |
return CallNonGenericMethod<IsMemory, typeImpl>(cx, args); |
| 2523 |
} |
| 2524 |
#endif |
| 2525 |
|
| 2526 |
size_t WasmMemoryObject::volatileMemoryLength() const { |
| 2527 |
if (isShared()) { |
| 2528 |
return sharedArrayRawBuffer()->volatileByteLength(); |
| 2529 |
} |
| 2530 |
return buffer().byteLength(); |
| 2531 |
} |
| 2532 |
|
| 2533 |
wasm::Pages WasmMemoryObject::volatilePages() const { |
| 2534 |
if (isShared()) { |
| 2535 |
return sharedArrayRawBuffer()->volatileWasmPages(); |
| 2536 |
} |
| 2537 |
return buffer().wasmPages(); |
| 2538 |
} |
| 2539 |
|
| 2540 |
wasm::Pages WasmMemoryObject::clampedMaxPages() const { |
| 2541 |
if (isShared()) { |
| 2542 |
return sharedArrayRawBuffer()->wasmClampedMaxPages(); |
| 2543 |
} |
| 2544 |
return buffer().wasmClampedMaxPages(); |
| 2545 |
} |
| 2546 |
|
| 2547 |
Maybe<wasm::Pages> WasmMemoryObject::sourceMaxPages() const { |
| 2548 |
if (isShared()) { |
| 2549 |
return Some(sharedArrayRawBuffer()->wasmSourceMaxPages()); |
| 2550 |
} |
| 2551 |
return buffer().wasmSourceMaxPages(); |
| 2552 |
} |
| 2553 |
|
| 2554 |
wasm::AddressType WasmMemoryObject::addressType() const { |
| 2555 |
if (isShared()) { |
| 2556 |
return sharedArrayRawBuffer()->wasmAddressType(); |
| 2557 |
} |
| 2558 |
return buffer().wasmAddressType(); |
| 2559 |
} |
| 2560 |
|
| 2561 |
bool WasmMemoryObject::isShared() const { |
| 2562 |
return buffer().is<SharedArrayBufferObject>(); |
| 2563 |
} |
| 2564 |
|
| 2565 |
bool WasmMemoryObject::hasObservers() const { |
| 2566 |
return !getReservedSlot(OBSERVERS_SLOT).isUndefined(); |
| 2567 |
} |
| 2568 |
|
| 2569 |
WasmMemoryObject::InstanceSet& WasmMemoryObject::observers() const { |
| 2570 |
MOZ_ASSERT(hasObservers()); |
| 2571 |
return *reinterpret_cast<InstanceSet*>( |
| 2572 |
getReservedSlot(OBSERVERS_SLOT).toPrivate()); |
| 2573 |
} |
| 2574 |
|
| 2575 |
WasmMemoryObject::InstanceSet* WasmMemoryObject::getOrCreateObservers( |
| 2576 |
JSContext* cx) { |
| 2577 |
if (!hasObservers()) { |
| 2578 |
auto observers = MakeUnique<InstanceSet>(cx->zone(), cx->zone()); |
| 2579 |
if (!observers) { |
| 2580 |
ReportOutOfMemory(cx); |
| 2581 |
return nullptr; |
| 2582 |
} |
| 2583 |
|
| 2584 |
InitReservedSlot(this, OBSERVERS_SLOT, observers.release(), |
| 2585 |
MemoryUse::WasmMemoryObservers); |
| 2586 |
} |
| 2587 |
|
| 2588 |
return &observers(); |
| 2589 |
} |
| 2590 |
|
| 2591 |
bool WasmMemoryObject::isHuge() const { |
| 2592 |
return getReservedSlot(ISHUGE_SLOT).toBoolean(); |
| 2593 |
} |
| 2594 |
|
| 2595 |
bool WasmMemoryObject::movingGrowable() const { |
| 2596 |
return !isHuge() && !buffer().wasmSourceMaxPages(); |
| 2597 |
} |
| 2598 |
|
| 2599 |
size_t WasmMemoryObject::boundsCheckLimit() const { |
| 2600 |
if (!buffer().isWasm() || isHuge()) { |
| 2601 |
return buffer().byteLength(); |
| 2602 |
} |
| 2603 |
size_t mappedSize = buffer().wasmMappedSize(); |
| 2604 |
#if !defined(JS_64BIT) |
| 2605 |
// See clamping performed in CreateSpecificWasmBuffer(). On 32-bit systems |
| 2606 |
// we do not want to overflow a uint32_t. For the other 64-bit compilers, |
| 2607 |
// all constraints are implied by the largest accepted value for a memory's |
| 2608 |
// max field. |
| 2609 |
MOZ_ASSERT(mappedSize < UINT32_MAX); |
| 2610 |
#endif |
| 2611 |
MOZ_ASSERT(mappedSize % wasm::PageSize == 0); |
| 2612 |
MOZ_ASSERT(mappedSize >= wasm::GuardSize); |
| 2613 |
MOZ_ASSERT(wasm::IsValidBoundsCheckImmediate(mappedSize - wasm::GuardSize)); |
| 2614 |
size_t limit = mappedSize - wasm::GuardSize; |
| 2615 |
MOZ_ASSERT(limit <= MaxMemoryBoundsCheckLimit(addressType())); |
| 2616 |
return limit; |
| 2617 |
} |
| 2618 |
|
| 2619 |
bool WasmMemoryObject::addMovingGrowObserver(JSContext* cx, |
| 2620 |
WasmInstanceObject* instance) { |
| 2621 |
MOZ_ASSERT(movingGrowable()); |
| 2622 |
|
| 2623 |
InstanceSet* observers = getOrCreateObservers(cx); |
| 2624 |
if (!observers) { |
| 2625 |
return false; |
| 2626 |
} |
| 2627 |
|
| 2628 |
// A memory can be imported multiple times into an instance, but we only |
| 2629 |
// register the instance as an observer once. |
| 2630 |
if (!observers->put(instance)) { |
| 2631 |
ReportOutOfMemory(cx); |
| 2632 |
return false; |
| 2633 |
} |
| 2634 |
|
| 2635 |
return true; |
| 2636 |
} |
| 2637 |
|
| 2638 |
/* static */ |
| 2639 |
uint64_t WasmMemoryObject::growShared(Handle<WasmMemoryObject*> memory, |
| 2640 |
uint64_t delta) { |
| 2641 |
WasmSharedArrayRawBuffer* rawBuf = memory->sharedArrayRawBuffer(); |
| 2642 |
WasmSharedArrayRawBuffer::Lock lock(rawBuf); |
| 2643 |
|
| 2644 |
Pages oldNumPages = rawBuf->volatileWasmPages(); |
| 2645 |
Pages newPages = oldNumPages; |
| 2646 |
if (!newPages.checkedIncrement(Pages(delta))) { |
| 2647 |
return uint64_t(int64_t(-1)); |
| 2648 |
} |
| 2649 |
|
| 2650 |
if (!rawBuf->wasmGrowToPagesInPlace(lock, memory->addressType(), newPages)) { |
| 2651 |
return uint64_t(int64_t(-1)); |
| 2652 |
} |
| 2653 |
// New buffer objects will be created lazily in all agents (including in |
| 2654 |
// this agent) by bufferGetterImpl, above, so no more work to do here. |
| 2655 |
|
| 2656 |
return oldNumPages.value(); |
| 2657 |
} |
| 2658 |
|
| 2659 |
/* static */ |
| 2660 |
uint64_t WasmMemoryObject::grow(Handle<WasmMemoryObject*> memory, |
| 2661 |
uint64_t delta, JSContext* cx) { |
| 2662 |
if (memory->isShared()) { |
| 2663 |
return growShared(memory, delta); |
| 2664 |
} |
| 2665 |
|
| 2666 |
Rooted<ArrayBufferObject*> oldBuf(cx, |
| 2667 |
&memory->buffer().as<ArrayBufferObject>()); |
| 2668 |
|
| 2669 |
#if !defined(JS_64BIT) |
| 2670 |
// TODO (large ArrayBuffer): See more information at the definition of |
| 2671 |
// MaxMemoryBytes(). |
| 2672 |
MOZ_ASSERT(MaxMemoryBytes(memory->addressType()) <= UINT32_MAX, |
| 2673 |
"Avoid 32-bit overflows"); |
| 2674 |
#endif |
| 2675 |
|
| 2676 |
Pages oldNumPages = oldBuf->wasmPages(); |
| 2677 |
Pages newPages = oldNumPages; |
| 2678 |
if (!newPages.checkedIncrement(Pages(delta))) { |
| 2679 |
return uint64_t(int64_t(-1)); |
| 2680 |
} |
| 2681 |
|
| 2682 |
ArrayBufferObject* newBuf; |
| 2683 |
if (memory->movingGrowable()) { |
| 2684 |
MOZ_ASSERT(!memory->isHuge()); |
| 2685 |
newBuf = ArrayBufferObject::wasmMovingGrowToPages(memory->addressType(), |
| 2686 |
newPages, oldBuf, cx); |
| 2687 |
} else { |
| 2688 |
newBuf = ArrayBufferObject::wasmGrowToPagesInPlace(memory->addressType(), |
| 2689 |
newPages, oldBuf, cx); |
| 2690 |
} |
| 2691 |
if (!newBuf) { |
| 2692 |
return uint64_t(int64_t(-1)); |
| 2693 |
} |
| 2694 |
|
| 2695 |
memory->setReservedSlot(BUFFER_SLOT, ObjectValue(*newBuf)); |
| 2696 |
|
| 2697 |
// Only notify moving-grow-observers after the BUFFER_SLOT has been updated |
| 2698 |
// since observers will call buffer(). |
| 2699 |
if (memory->hasObservers()) { |
| 2700 |
for (InstanceSet::Range r = memory->observers().all(); !r.empty(); |
| 2701 |
r.popFront()) { |
| 2702 |
r.front()->instance().onMovingGrowMemory(memory); |
| 2703 |
} |
| 2704 |
} |
| 2705 |
|
| 2706 |
return oldNumPages.value(); |
| 2707 |
} |
| 2708 |
|
| 2709 |
/* static */ |
| 2710 |
void WasmMemoryObject::discard(Handle<WasmMemoryObject*> memory, |
| 2711 |
uint64_t byteOffset, uint64_t byteLen, |
| 2712 |
JSContext* cx) { |
| 2713 |
if (memory->isShared()) { |
| 2714 |
Rooted<SharedArrayBufferObject*> buf( |
| 2715 |
cx, &memory->buffer().as<SharedArrayBufferObject>()); |
| 2716 |
SharedArrayBufferObject::wasmDiscard(buf, byteOffset, byteLen); |
| 2717 |
} else { |
| 2718 |
Rooted<ArrayBufferObject*> buf(cx, |
| 2719 |
&memory->buffer().as<ArrayBufferObject>()); |
| 2720 |
ArrayBufferObject::wasmDiscard(buf, byteOffset, byteLen); |
| 2721 |
} |
| 2722 |
} |
| 2723 |
|
| 2724 |
bool js::wasm::IsSharedWasmMemoryObject(JSObject* obj) { |
| 2725 |
WasmMemoryObject* mobj = obj->maybeUnwrapIf<WasmMemoryObject>(); |
| 2726 |
return mobj && mobj->isShared(); |
| 2727 |
} |
| 2728 |
|
| 2729 |
// ============================================================================ |
| 2730 |
// WebAssembly.Table class and methods |
| 2731 |
|
| 2732 |
const JSClassOps WasmTableObject::classOps_ = { |
| 2733 |
nullptr, // addProperty |
| 2734 |
nullptr, // delProperty |
| 2735 |
nullptr, // enumerate |
| 2736 |
nullptr, // newEnumerate |
| 2737 |
nullptr, // resolve |
| 2738 |
nullptr, // mayResolve |
| 2739 |
WasmTableObject::finalize, // finalize |
| 2740 |
nullptr, // call |
| 2741 |
nullptr, // construct |
| 2742 |
WasmTableObject::trace, // trace |
| 2743 |
}; |
| 2744 |
|
| 2745 |
const JSClass WasmTableObject::class_ = { |
| 2746 |
"WebAssembly.Table", |
| 2747 |
JSCLASS_DELAY_METADATA_BUILDER | |
| 2748 |
JSCLASS_HAS_RESERVED_SLOTS(WasmTableObject::RESERVED_SLOTS) | |
| 2749 |
JSCLASS_FOREGROUND_FINALIZE, |
| 2750 |
&WasmTableObject::classOps_, |
| 2751 |
&WasmTableObject::classSpec_, |
| 2752 |
}; |
| 2753 |
|
| 2754 |
const JSClass& WasmTableObject::protoClass_ = PlainObject::class_; |
| 2755 |
|
| 2756 |
static constexpr char WasmTableName[] = "Table"; |
| 2757 |
|
| 2758 |
const ClassSpec WasmTableObject::classSpec_ = { |
| 2759 |
CreateWasmConstructor<WasmTableObject, WasmTableName>, |
| 2760 |
GenericCreatePrototype<WasmTableObject>, |
| 2761 |
WasmTableObject::static_methods, |
| 2762 |
nullptr, |
| 2763 |
WasmTableObject::methods, |
| 2764 |
WasmTableObject::properties, |
| 2765 |
nullptr, |
| 2766 |
ClassSpec::DontDefineConstructor, |
| 2767 |
}; |
| 2768 |
|
| 2769 |
bool WasmTableObject::isNewborn() const { |
| 2770 |
MOZ_ASSERT(is<WasmTableObject>()); |
| 2771 |
return getReservedSlot(TABLE_SLOT).isUndefined(); |
| 2772 |
} |
| 2773 |
|
| 2774 |
/* static */ |
| 2775 |
void WasmTableObject::finalize(JS::GCContext* gcx, JSObject* obj) { |
| 2776 |
WasmTableObject& tableObj = obj->as<WasmTableObject>(); |
| 2777 |
if (!tableObj.isNewborn()) { |
| 2778 |
auto& table = tableObj.table(); |
| 2779 |
gcx->release(obj, &table, table.gcMallocBytes(), MemoryUse::WasmTableTable); |
| 2780 |
} |
| 2781 |
} |
| 2782 |
|
| 2783 |
/* static */ |
| 2784 |
void WasmTableObject::trace(JSTracer* trc, JSObject* obj) { |
| 2785 |
WasmTableObject& tableObj = obj->as<WasmTableObject>(); |
| 2786 |
if (!tableObj.isNewborn()) { |
| 2787 |
tableObj.table().tracePrivate(trc); |
| 2788 |
} |
| 2789 |
} |
| 2790 |
|
| 2791 |
// Return the JS value to use when a parameter to a function requiring a table |
| 2792 |
// value is omitted. An implementation of [1]. |
| 2793 |
// |
| 2794 |
// [1] |
| 2795 |
// https://webassembly.github.io/spec/js-api/#defaultvalue |
| 2796 |
static Value RefTypeDefaultValue(wasm::RefType tableType) { |
| 2797 |
return tableType.isExtern() ? UndefinedValue() : NullValue(); |
| 2798 |
} |
| 2799 |
|
| 2800 |
/* static */ |
| 2801 |
WasmTableObject* WasmTableObject::create(JSContext* cx, Limits limits, |
| 2802 |
wasm::RefType tableType, |
| 2803 |
HandleObject proto) { |
| 2804 |
AutoSetNewObjectMetadata metadata(cx); |
| 2805 |
Rooted<WasmTableObject*> obj( |
| 2806 |
cx, NewObjectWithGivenProto<WasmTableObject>(cx, proto)); |
| 2807 |
if (!obj) { |
| 2808 |
return nullptr; |
| 2809 |
} |
| 2810 |
|
| 2811 |
MOZ_ASSERT(obj->isNewborn()); |
| 2812 |
|
| 2813 |
TableDesc td(limits, tableType, Nothing(), |
| 2814 |
/*isAsmJS*/ false, |
| 2815 |
/*isImported=*/true, /*isExported=*/true); |
| 2816 |
|
| 2817 |
SharedTable table = Table::create(cx, td, obj); |
| 2818 |
if (!table) { |
| 2819 |
return nullptr; |
| 2820 |
} |
| 2821 |
|
| 2822 |
size_t size = table->gcMallocBytes(); |
| 2823 |
InitReservedSlot(obj, TABLE_SLOT, table.forget().take(), size, |
| 2824 |
MemoryUse::WasmTableTable); |
| 2825 |
|
| 2826 |
MOZ_ASSERT(!obj->isNewborn()); |
| 2827 |
return obj; |
| 2828 |
} |
| 2829 |
|
| 2830 |
/* static */ |
| 2831 |
bool WasmTableObject::construct(JSContext* cx, unsigned argc, Value* vp) { |
| 2832 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2833 |
|
| 2834 |
if (!ThrowIfNotConstructing(cx, args, "Table")) { |
| 2835 |
return false; |
| 2836 |
} |
| 2837 |
|
| 2838 |
if (!args.requireAtLeast(cx, "WebAssembly.Table", 1)) { |
| 2839 |
return false; |
| 2840 |
} |
| 2841 |
|
| 2842 |
if (!args.get(0).isObject()) { |
| 2843 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 2844 |
JSMSG_WASM_BAD_DESC_ARG, "table"); |
| 2845 |
return false; |
| 2846 |
} |
| 2847 |
|
| 2848 |
RootedObject obj(cx, &args[0].toObject()); |
| 2849 |
|
| 2850 |
JSAtom* elementAtom = Atomize(cx, "element", strlen("element")); |
| 2851 |
if (!elementAtom) { |
| 2852 |
return false; |
| 2853 |
} |
| 2854 |
RootedId elementId(cx, AtomToId(elementAtom)); |
| 2855 |
|
| 2856 |
RootedValue elementVal(cx); |
| 2857 |
if (!GetProperty(cx, obj, obj, elementId, &elementVal)) { |
| 2858 |
return false; |
| 2859 |
} |
| 2860 |
|
| 2861 |
RefType tableType; |
| 2862 |
if (!ToRefType(cx, elementVal, &tableType)) { |
| 2863 |
return false; |
| 2864 |
} |
| 2865 |
|
| 2866 |
Limits limits; |
| 2867 |
if (!GetLimits(cx, obj, LimitsKind::Table, &limits) || |
| 2868 |
!CheckLimits(cx, MaxTableElemsValidation(limits.addressType), |
| 2869 |
LimitsKind::Table, &limits)) { |
| 2870 |
return false; |
| 2871 |
} |
| 2872 |
|
| 2873 |
if (limits.initial > MaxTableElemsRuntime) { |
| 2874 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 2875 |
JSMSG_WASM_TABLE_IMP_LIMIT); |
| 2876 |
return false; |
| 2877 |
} |
| 2878 |
|
| 2879 |
RootedObject proto(cx, |
| 2880 |
GetWasmConstructorPrototype(cx, args, JSProto_WasmTable)); |
| 2881 |
if (!proto) { |
| 2882 |
ReportOutOfMemory(cx); |
| 2883 |
return false; |
| 2884 |
} |
| 2885 |
|
| 2886 |
Rooted<WasmTableObject*> table( |
| 2887 |
cx, WasmTableObject::create(cx, limits, tableType, proto)); |
| 2888 |
if (!table) { |
| 2889 |
return false; |
| 2890 |
} |
| 2891 |
|
| 2892 |
// Initialize the table to a default value |
| 2893 |
RootedValue initValue( |
| 2894 |
cx, args.length() < 2 ? RefTypeDefaultValue(tableType) : args[1]); |
| 2895 |
if (!CheckRefType(cx, tableType, initValue)) { |
| 2896 |
return false; |
| 2897 |
} |
| 2898 |
|
| 2899 |
// Skip initializing the table if the fill value is null, as that is the |
| 2900 |
// default value. |
| 2901 |
if (!initValue.isNull() && |
| 2902 |
!table->fillRange(cx, 0, limits.initial, initValue)) { |
| 2903 |
return false; |
| 2904 |
} |
| 2905 |
#ifdef DEBUG |
| 2906 |
// Assert that null is the default value of a new table. |
| 2907 |
if (initValue.isNull()) { |
| 2908 |
table->table().assertRangeNull(0, limits.initial); |
| 2909 |
} |
| 2910 |
if (!tableType.isNullable()) { |
| 2911 |
table->table().assertRangeNotNull(0, limits.initial); |
| 2912 |
} |
| 2913 |
#endif |
| 2914 |
|
| 2915 |
args.rval().setObject(*table); |
| 2916 |
return true; |
| 2917 |
} |
| 2918 |
|
| 2919 |
static bool IsTable(HandleValue v) { |
| 2920 |
return v.isObject() && v.toObject().is<WasmTableObject>(); |
| 2921 |
} |
| 2922 |
|
| 2923 |
/* static */ |
| 2924 |
bool WasmTableObject::lengthGetterImpl(JSContext* cx, const CallArgs& args) { |
| 2925 |
const WasmTableObject& tableObj = |
| 2926 |
args.thisv().toObject().as<WasmTableObject>(); |
| 2927 |
RootedValue length(cx); |
| 2928 |
if (!CreateAddressValue(cx, tableObj.table().length(), |
| 2929 |
tableObj.table().addressType(), &length)) { |
| 2930 |
ReportOutOfMemory(cx); |
| 2931 |
return false; |
| 2932 |
} |
| 2933 |
args.rval().set(length); |
| 2934 |
return true; |
| 2935 |
} |
| 2936 |
|
| 2937 |
/* static */ |
| 2938 |
bool WasmTableObject::lengthGetter(JSContext* cx, unsigned argc, Value* vp) { |
| 2939 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2940 |
return CallNonGenericMethod<IsTable, lengthGetterImpl>(cx, args); |
| 2941 |
} |
| 2942 |
|
| 2943 |
const JSPropertySpec WasmTableObject::properties[] = { |
| 2944 |
JS_PSG("length", WasmTableObject::lengthGetter, JSPROP_ENUMERATE), |
| 2945 |
JS_STRING_SYM_PS(toStringTag, "WebAssembly.Table", JSPROP_READONLY), |
| 2946 |
JS_PS_END, |
| 2947 |
}; |
| 2948 |
|
| 2949 |
// Gets an AddressValue parameter for a table. This differs from our general |
| 2950 |
// EnforceAddressValue because our table implementation still uses 32-bit sizes |
| 2951 |
// internally, and this function therefore returns a uint32_t. Values outside |
| 2952 |
// the 32-bit range will be clamped to UINT32_MAX, which will always trigger |
| 2953 |
// bounds checks for all Table uses of AddressValue. See |
| 2954 |
// MacroAssembler::wasmClampTable64Address and its uses. |
| 2955 |
// |
| 2956 |
// isAddress should be true if the value is an actual address, and false if it |
| 2957 |
// is a different quantity (e.g. a grow delta). |
| 2958 |
static bool EnforceTableAddressValue(JSContext* cx, HandleValue v, |
| 2959 |
const Table& table, const char* noun, |
| 2960 |
uint32_t* result, bool isAddress) { |
| 2961 |
uint64_t result64; |
| 2962 |
if (!EnforceAddressValue(cx, v, table.addressType(), "Table", noun, |
| 2963 |
&result64)) { |
| 2964 |
return false; |
| 2965 |
} |
| 2966 |
|
| 2967 |
static_assert(MaxTableElemsRuntime < UINT32_MAX); |
| 2968 |
*result = result64 > UINT32_MAX ? UINT32_MAX : uint32_t(result64); |
| 2969 |
|
| 2970 |
if (isAddress && *result >= table.length()) { |
| 2971 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 2972 |
JSMSG_WASM_BAD_RANGE, "Table", noun); |
| 2973 |
return false; |
| 2974 |
} |
| 2975 |
|
| 2976 |
return true; |
| 2977 |
} |
| 2978 |
|
| 2979 |
#ifdef ENABLE_WASM_TYPE_REFLECTIONS |
| 2980 |
/* static */ |
| 2981 |
bool WasmTableObject::typeImpl(JSContext* cx, const CallArgs& args) { |
| 2982 |
Table& table = args.thisv().toObject().as<WasmTableObject>().table(); |
| 2983 |
RootedObject typeObj( |
| 2984 |
cx, TableTypeToObject(cx, table.addressType(), table.elemType(), |
| 2985 |
table.length(), table.maximum())); |
| 2986 |
if (!typeObj) { |
| 2987 |
return false; |
| 2988 |
} |
| 2989 |
args.rval().setObject(*typeObj); |
| 2990 |
return true; |
| 2991 |
} |
| 2992 |
|
| 2993 |
/* static */ |
| 2994 |
bool WasmTableObject::type(JSContext* cx, unsigned argc, Value* vp) { |
| 2995 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2996 |
return CallNonGenericMethod<IsTable, typeImpl>(cx, args); |
| 2997 |
} |
| 2998 |
#endif |
| 2999 |
|
| 3000 |
/* static */ |
| 3001 |
bool WasmTableObject::getImpl(JSContext* cx, const CallArgs& args) { |
| 3002 |
Rooted<WasmTableObject*> tableObj( |
| 3003 |
cx, &args.thisv().toObject().as<WasmTableObject>()); |
| 3004 |
const Table& table = tableObj->table(); |
| 3005 |
|
| 3006 |
if (!args.requireAtLeast(cx, "WebAssembly.Table.get", 1)) { |
| 3007 |
return false; |
| 3008 |
} |
| 3009 |
|
| 3010 |
uint32_t address; |
| 3011 |
if (!EnforceTableAddressValue(cx, args.get(0), table, "get address", &address, |
| 3012 |
/*isAddress=*/true)) { |
| 3013 |
return false; |
| 3014 |
} |
| 3015 |
|
| 3016 |
return table.getValue(cx, address, args.rval()); |
| 3017 |
} |
| 3018 |
|
| 3019 |
/* static */ |
| 3020 |
bool WasmTableObject::get(JSContext* cx, unsigned argc, Value* vp) { |
| 3021 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3022 |
return CallNonGenericMethod<IsTable, getImpl>(cx, args); |
| 3023 |
} |
| 3024 |
|
| 3025 |
/* static */ |
| 3026 |
bool WasmTableObject::setImpl(JSContext* cx, const CallArgs& args) { |
| 3027 |
Rooted<WasmTableObject*> tableObj( |
| 3028 |
cx, &args.thisv().toObject().as<WasmTableObject>()); |
| 3029 |
Table& table = tableObj->table(); |
| 3030 |
|
| 3031 |
if (!args.requireAtLeast(cx, "WebAssembly.Table.set", 1)) { |
| 3032 |
return false; |
| 3033 |
} |
| 3034 |
|
| 3035 |
uint32_t address; |
| 3036 |
if (!EnforceTableAddressValue(cx, args.get(0), table, "set address", &address, |
| 3037 |
/*isAddress=*/true)) { |
| 3038 |
return false; |
| 3039 |
} |
| 3040 |
|
| 3041 |
RootedValue fillValue( |
| 3042 |
cx, args.length() < 2 ? RefTypeDefaultValue(table.elemType()) : args[1]); |
| 3043 |
if (!tableObj->fillRange(cx, address, 1, fillValue)) { |
| 3044 |
return false; |
| 3045 |
} |
| 3046 |
|
| 3047 |
args.rval().setUndefined(); |
| 3048 |
return true; |
| 3049 |
} |
| 3050 |
|
| 3051 |
/* static */ |
| 3052 |
bool WasmTableObject::set(JSContext* cx, unsigned argc, Value* vp) { |
| 3053 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3054 |
return CallNonGenericMethod<IsTable, setImpl>(cx, args); |
| 3055 |
} |
| 3056 |
|
| 3057 |
/* static */ |
| 3058 |
bool WasmTableObject::growImpl(JSContext* cx, const CallArgs& args) { |
| 3059 |
Rooted<WasmTableObject*> tableObj( |
| 3060 |
cx, &args.thisv().toObject().as<WasmTableObject>()); |
| 3061 |
Table& table = tableObj->table(); |
| 3062 |
|
| 3063 |
if (!args.requireAtLeast(cx, "WebAssembly.Table.grow", 1)) { |
| 3064 |
return false; |
| 3065 |
} |
| 3066 |
|
| 3067 |
uint32_t delta; |
| 3068 |
if (!EnforceTableAddressValue(cx, args.get(0), table, "grow delta", &delta, |
| 3069 |
/*isAddress=*/false)) { |
| 3070 |
return false; |
| 3071 |
} |
| 3072 |
|
| 3073 |
RootedValue fillValue( |
| 3074 |
cx, args.length() < 2 ? RefTypeDefaultValue(table.elemType()) : args[1]); |
| 3075 |
if (!CheckRefType(cx, table.elemType(), fillValue)) { |
| 3076 |
return false; |
| 3077 |
} |
| 3078 |
|
| 3079 |
uint32_t oldLength = table.grow(delta); |
| 3080 |
|
| 3081 |
if (oldLength == uint32_t(-1)) { |
| 3082 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, JSMSG_WASM_BAD_GROW, |
| 3083 |
"table"); |
| 3084 |
return false; |
| 3085 |
} |
| 3086 |
|
| 3087 |
// Skip filling the grown range of the table if the fill value is null, as |
| 3088 |
// that is the default value. |
| 3089 |
if (!fillValue.isNull() && |
| 3090 |
!tableObj->fillRange(cx, oldLength, delta, fillValue)) { |
| 3091 |
return false; |
| 3092 |
} |
| 3093 |
#ifdef DEBUG |
| 3094 |
// Assert that null is the default value of the grown range. |
| 3095 |
if (fillValue.isNull()) { |
| 3096 |
table.assertRangeNull(oldLength, delta); |
| 3097 |
} |
| 3098 |
if (!table.elemType().isNullable()) { |
| 3099 |
table.assertRangeNotNull(oldLength, delta); |
| 3100 |
} |
| 3101 |
#endif |
| 3102 |
|
| 3103 |
RootedValue result(cx); |
| 3104 |
if (!CreateAddressValue(cx, oldLength, table.addressType(), &result)) { |
| 3105 |
ReportOutOfMemory(cx); |
| 3106 |
return false; |
| 3107 |
} |
| 3108 |
args.rval().set(result); |
| 3109 |
return true; |
| 3110 |
} |
| 3111 |
|
| 3112 |
/* static */ |
| 3113 |
bool WasmTableObject::grow(JSContext* cx, unsigned argc, Value* vp) { |
| 3114 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3115 |
return CallNonGenericMethod<IsTable, growImpl>(cx, args); |
| 3116 |
} |
| 3117 |
|
| 3118 |
const JSFunctionSpec WasmTableObject::methods[] = { |
| 3119 |
#ifdef ENABLE_WASM_TYPE_REFLECTIONS |
| 3120 |
JS_FN("type", WasmTableObject::type, 0, JSPROP_ENUMERATE), |
| 3121 |
#endif |
| 3122 |
JS_FN("get", WasmTableObject::get, 1, JSPROP_ENUMERATE), |
| 3123 |
JS_FN("set", WasmTableObject::set, 2, JSPROP_ENUMERATE), |
| 3124 |
JS_FN("grow", WasmTableObject::grow, 1, JSPROP_ENUMERATE), |
| 3125 |
JS_FS_END, |
| 3126 |
}; |
| 3127 |
|
| 3128 |
const JSFunctionSpec WasmTableObject::static_methods[] = { |
| 3129 |
JS_FS_END, |
| 3130 |
}; |
| 3131 |
|
| 3132 |
Table& WasmTableObject::table() const { |
| 3133 |
return *(Table*)getReservedSlot(TABLE_SLOT).toPrivate(); |
| 3134 |
} |
| 3135 |
|
| 3136 |
bool WasmTableObject::fillRange(JSContext* cx, uint32_t index, uint32_t length, |
| 3137 |
HandleValue value) const { |
| 3138 |
Table& tab = table(); |
| 3139 |
|
| 3140 |
// All consumers are required to either bounds check or statically be in |
| 3141 |
// bounds |
| 3142 |
MOZ_ASSERT(uint64_t(index) + uint64_t(length) <= tab.length()); |
| 3143 |
|
| 3144 |
RootedAnyRef any(cx, AnyRef::null()); |
| 3145 |
if (!wasm::CheckRefType(cx, tab.elemType(), value, &any)) { |
| 3146 |
return false; |
| 3147 |
} |
| 3148 |
switch (tab.repr()) { |
| 3149 |
case TableRepr::Func: |
| 3150 |
MOZ_RELEASE_ASSERT(!tab.isAsmJS()); |
| 3151 |
tab.fillFuncRef(index, length, FuncRef::fromAnyRefUnchecked(any.get()), |
| 3152 |
cx); |
| 3153 |
break; |
| 3154 |
case TableRepr::Ref: |
| 3155 |
tab.fillAnyRef(index, length, any); |
| 3156 |
break; |
| 3157 |
} |
| 3158 |
return true; |
| 3159 |
} |
| 3160 |
|
| 3161 |
// ============================================================================ |
| 3162 |
// WebAssembly.global class and methods |
| 3163 |
|
| 3164 |
const JSClassOps WasmGlobalObject::classOps_ = { |
| 3165 |
nullptr, // addProperty |
| 3166 |
nullptr, // delProperty |
| 3167 |
nullptr, // enumerate |
| 3168 |
nullptr, // newEnumerate |
| 3169 |
nullptr, // resolve |
| 3170 |
nullptr, // mayResolve |
| 3171 |
WasmGlobalObject::finalize, // finalize |
| 3172 |
nullptr, // call |
| 3173 |
nullptr, // construct |
| 3174 |
WasmGlobalObject::trace, // trace |
| 3175 |
}; |
| 3176 |
|
| 3177 |
const JSClass WasmGlobalObject::class_ = { |
| 3178 |
"WebAssembly.Global", |
| 3179 |
JSCLASS_HAS_RESERVED_SLOTS(WasmGlobalObject::RESERVED_SLOTS) | |
| 3180 |
JSCLASS_BACKGROUND_FINALIZE, |
| 3181 |
&WasmGlobalObject::classOps_, |
| 3182 |
&WasmGlobalObject::classSpec_, |
| 3183 |
}; |
| 3184 |
|
| 3185 |
const JSClass& WasmGlobalObject::protoClass_ = PlainObject::class_; |
| 3186 |
|
| 3187 |
static constexpr char WasmGlobalName[] = "Global"; |
| 3188 |
|
| 3189 |
const ClassSpec WasmGlobalObject::classSpec_ = { |
| 3190 |
CreateWasmConstructor<WasmGlobalObject, WasmGlobalName>, |
| 3191 |
GenericCreatePrototype<WasmGlobalObject>, |
| 3192 |
WasmGlobalObject::static_methods, |
| 3193 |
nullptr, |
| 3194 |
WasmGlobalObject::methods, |
| 3195 |
WasmGlobalObject::properties, |
| 3196 |
nullptr, |
| 3197 |
ClassSpec::DontDefineConstructor, |
| 3198 |
}; |
| 3199 |
|
| 3200 |
/* static */ |
| 3201 |
void WasmGlobalObject::trace(JSTracer* trc, JSObject* obj) { |
| 3202 |
WasmGlobalObject* global = reinterpret_cast<WasmGlobalObject*>(obj); |
| 3203 |
if (global->isNewborn()) { |
| 3204 |
// This can happen while we're allocating the object, in which case |
| 3205 |
// every single slot of the object is not defined yet. In particular, |
| 3206 |
// there's nothing to trace yet. |
| 3207 |
return; |
| 3208 |
} |
| 3209 |
global->val().get().trace(trc); |
| 3210 |
} |
| 3211 |
|
| 3212 |
/* static */ |
| 3213 |
void WasmGlobalObject::finalize(JS::GCContext* gcx, JSObject* obj) { |
| 3214 |
WasmGlobalObject* global = reinterpret_cast<WasmGlobalObject*>(obj); |
| 3215 |
if (!global->isNewborn()) { |
| 3216 |
// Release the strong reference to the type definitions this global could |
| 3217 |
// be referencing. |
| 3218 |
global->type().Release(); |
| 3219 |
gcx->delete_(obj, &global->mutableVal(), MemoryUse::WasmGlobalCell); |
| 3220 |
} |
| 3221 |
} |
| 3222 |
|
| 3223 |
/* static */ |
| 3224 |
WasmGlobalObject* WasmGlobalObject::create(JSContext* cx, HandleVal value, |
| 3225 |
bool isMutable, HandleObject proto) { |
| 3226 |
Rooted<WasmGlobalObject*> obj( |
| 3227 |
cx, NewObjectWithGivenProto<WasmGlobalObject>(cx, proto)); |
| 3228 |
if (!obj) { |
| 3229 |
return nullptr; |
| 3230 |
} |
| 3231 |
|
| 3232 |
MOZ_ASSERT(obj->isNewborn()); |
| 3233 |
MOZ_ASSERT(obj->isTenured(), "assumed by global.set post barriers"); |
| 3234 |
|
| 3235 |
GCPtrVal* val = js_new<GCPtrVal>(Val()); |
| 3236 |
if (!val) { |
| 3237 |
ReportOutOfMemory(cx); |
| 3238 |
return nullptr; |
| 3239 |
} |
| 3240 |
obj->initReservedSlot(MUTABLE_SLOT, JS::BooleanValue(isMutable)); |
| 3241 |
InitReservedSlot(obj, VAL_SLOT, val, MemoryUse::WasmGlobalCell); |
| 3242 |
|
| 3243 |
// It's simpler to initialize the cell after the object has been created, |
| 3244 |
// to avoid needing to root the cell before the object creation. |
| 3245 |
// We don't use `setVal` here because the assumes the cell has already |
| 3246 |
// been initialized. |
| 3247 |
obj->mutableVal() = value.get(); |
| 3248 |
// Acquire a strong reference to a type definition this global could |
| 3249 |
// be referencing. |
| 3250 |
obj->type().AddRef(); |
| 3251 |
|
| 3252 |
MOZ_ASSERT(!obj->isNewborn()); |
| 3253 |
|
| 3254 |
return obj; |
| 3255 |
} |
| 3256 |
|
| 3257 |
/* static */ |
| 3258 |
bool WasmGlobalObject::construct(JSContext* cx, unsigned argc, Value* vp) { |
| 3259 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3260 |
|
| 3261 |
if (!ThrowIfNotConstructing(cx, args, "Global")) { |
| 3262 |
return false; |
| 3263 |
} |
| 3264 |
|
| 3265 |
if (!args.requireAtLeast(cx, "WebAssembly.Global", 1)) { |
| 3266 |
return false; |
| 3267 |
} |
| 3268 |
|
| 3269 |
if (!args.get(0).isObject()) { |
| 3270 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 3271 |
JSMSG_WASM_BAD_DESC_ARG, "global"); |
| 3272 |
return false; |
| 3273 |
} |
| 3274 |
|
| 3275 |
RootedObject obj(cx, &args[0].toObject()); |
| 3276 |
|
| 3277 |
// Extract properties in lexicographic order per spec. |
| 3278 |
|
| 3279 |
RootedValue mutableVal(cx); |
| 3280 |
if (!JS_GetProperty(cx, obj, "mutable", &mutableVal)) { |
| 3281 |
return false; |
| 3282 |
} |
| 3283 |
|
| 3284 |
RootedValue typeVal(cx); |
| 3285 |
if (!JS_GetProperty(cx, obj, "value", &typeVal)) { |
| 3286 |
return false; |
| 3287 |
} |
| 3288 |
|
| 3289 |
ValType globalType; |
| 3290 |
if (!ToValType(cx, typeVal, &globalType)) { |
| 3291 |
return false; |
| 3292 |
} |
| 3293 |
|
| 3294 |
if (!globalType.isExposable()) { |
| 3295 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 3296 |
JSMSG_WASM_BAD_VAL_TYPE); |
| 3297 |
return false; |
| 3298 |
} |
| 3299 |
|
| 3300 |
bool isMutable = ToBoolean(mutableVal); |
| 3301 |
|
| 3302 |
// Extract the initial value, or provide a suitable default. |
| 3303 |
RootedVal globalVal(cx, globalType); |
| 3304 |
|
| 3305 |
// Override with non-undefined value, if provided. |
| 3306 |
RootedValue valueVal(cx); |
| 3307 |
if (globalType.isRefType()) { |
| 3308 |
valueVal.set(args.length() < 2 ? RefTypeDefaultValue(globalType.refType()) |
| 3309 |
: args[1]); |
| 3310 |
if (!Val::fromJSValue(cx, globalType, valueVal, &globalVal)) { |
| 3311 |
return false; |
| 3312 |
} |
| 3313 |
} else { |
| 3314 |
valueVal.set(args.get(1)); |
| 3315 |
if (!valueVal.isUndefined() && |
| 3316 |
!Val::fromJSValue(cx, globalType, valueVal, &globalVal)) { |
| 3317 |
return false; |
| 3318 |
} |
| 3319 |
} |
| 3320 |
|
| 3321 |
RootedObject proto(cx, |
| 3322 |
GetWasmConstructorPrototype(cx, args, JSProto_WasmGlobal)); |
| 3323 |
if (!proto) { |
| 3324 |
ReportOutOfMemory(cx); |
| 3325 |
return false; |
| 3326 |
} |
| 3327 |
|
| 3328 |
WasmGlobalObject* global = |
| 3329 |
WasmGlobalObject::create(cx, globalVal, isMutable, proto); |
| 3330 |
if (!global) { |
| 3331 |
return false; |
| 3332 |
} |
| 3333 |
|
| 3334 |
args.rval().setObject(*global); |
| 3335 |
return true; |
| 3336 |
} |
| 3337 |
|
| 3338 |
static bool IsGlobal(HandleValue v) { |
| 3339 |
return v.isObject() && v.toObject().is<WasmGlobalObject>(); |
| 3340 |
} |
| 3341 |
|
| 3342 |
/* static */ |
| 3343 |
bool WasmGlobalObject::valueGetterImpl(JSContext* cx, const CallArgs& args) { |
| 3344 |
const WasmGlobalObject& globalObj = |
| 3345 |
args.thisv().toObject().as<WasmGlobalObject>(); |
| 3346 |
if (!globalObj.type().isExposable()) { |
| 3347 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 3348 |
JSMSG_WASM_BAD_VAL_TYPE); |
| 3349 |
return false; |
| 3350 |
} |
| 3351 |
return globalObj.val().get().toJSValue(cx, args.rval()); |
| 3352 |
} |
| 3353 |
|
| 3354 |
/* static */ |
| 3355 |
bool WasmGlobalObject::valueGetter(JSContext* cx, unsigned argc, Value* vp) { |
| 3356 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3357 |
return CallNonGenericMethod<IsGlobal, valueGetterImpl>(cx, args); |
| 3358 |
} |
| 3359 |
|
| 3360 |
/* static */ |
| 3361 |
bool WasmGlobalObject::valueSetterImpl(JSContext* cx, const CallArgs& args) { |
| 3362 |
if (!args.requireAtLeast(cx, "WebAssembly.Global setter", 1)) { |
| 3363 |
return false; |
| 3364 |
} |
| 3365 |
|
| 3366 |
Rooted<WasmGlobalObject*> global( |
| 3367 |
cx, &args.thisv().toObject().as<WasmGlobalObject>()); |
| 3368 |
if (!global->isMutable()) { |
| 3369 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 3370 |
JSMSG_WASM_GLOBAL_IMMUTABLE); |
| 3371 |
return false; |
| 3372 |
} |
| 3373 |
|
| 3374 |
RootedVal val(cx); |
| 3375 |
if (!Val::fromJSValue(cx, global->type(), args.get(0), &val)) { |
| 3376 |
return false; |
| 3377 |
} |
| 3378 |
global->setVal(val); |
| 3379 |
|
| 3380 |
args.rval().setUndefined(); |
| 3381 |
return true; |
| 3382 |
} |
| 3383 |
|
| 3384 |
/* static */ |
| 3385 |
bool WasmGlobalObject::valueSetter(JSContext* cx, unsigned argc, Value* vp) { |
| 3386 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3387 |
return CallNonGenericMethod<IsGlobal, valueSetterImpl>(cx, args); |
| 3388 |
} |
| 3389 |
|
| 3390 |
const JSPropertySpec WasmGlobalObject::properties[] = { |
| 3391 |
JS_PSGS("value", WasmGlobalObject::valueGetter, |
| 3392 |
WasmGlobalObject::valueSetter, JSPROP_ENUMERATE), |
| 3393 |
JS_STRING_SYM_PS(toStringTag, "WebAssembly.Global", JSPROP_READONLY), |
| 3394 |
JS_PS_END, |
| 3395 |
}; |
| 3396 |
|
| 3397 |
const JSFunctionSpec WasmGlobalObject::methods[] = { |
| 3398 |
#ifdef ENABLE_WASM_TYPE_REFLECTIONS |
| 3399 |
JS_FN("type", WasmGlobalObject::type, 0, JSPROP_ENUMERATE), |
| 3400 |
#endif |
| 3401 |
JS_FN("valueOf", WasmGlobalObject::valueGetter, 0, JSPROP_ENUMERATE), |
| 3402 |
JS_FS_END, |
| 3403 |
}; |
| 3404 |
|
| 3405 |
const JSFunctionSpec WasmGlobalObject::static_methods[] = { |
| 3406 |
JS_FS_END, |
| 3407 |
}; |
| 3408 |
|
| 3409 |
bool WasmGlobalObject::isMutable() const { |
| 3410 |
return getReservedSlot(MUTABLE_SLOT).toBoolean(); |
| 3411 |
} |
| 3412 |
|
| 3413 |
ValType WasmGlobalObject::type() const { return val().get().type(); } |
| 3414 |
|
| 3415 |
GCPtrVal& WasmGlobalObject::mutableVal() { |
| 3416 |
return *reinterpret_cast<GCPtrVal*>(getReservedSlot(VAL_SLOT).toPrivate()); |
| 3417 |
} |
| 3418 |
|
| 3419 |
const GCPtrVal& WasmGlobalObject::val() const { |
| 3420 |
return *reinterpret_cast<GCPtrVal*>(getReservedSlot(VAL_SLOT).toPrivate()); |
| 3421 |
} |
| 3422 |
|
| 3423 |
void WasmGlobalObject::setVal(wasm::HandleVal value) { |
| 3424 |
MOZ_ASSERT(type() == value.get().type()); |
| 3425 |
mutableVal() = value; |
| 3426 |
} |
| 3427 |
|
| 3428 |
void* WasmGlobalObject::addressOfCell() const { |
| 3429 |
return (void*)&val().get().cell(); |
| 3430 |
} |
| 3431 |
|
| 3432 |
#ifdef ENABLE_WASM_TYPE_REFLECTIONS |
| 3433 |
/* static */ |
| 3434 |
bool WasmGlobalObject::typeImpl(JSContext* cx, const CallArgs& args) { |
| 3435 |
Rooted<WasmGlobalObject*> global( |
| 3436 |
cx, &args.thisv().toObject().as<WasmGlobalObject>()); |
| 3437 |
RootedObject typeObj( |
| 3438 |
cx, GlobalTypeToObject(cx, global->type(), global->isMutable())); |
| 3439 |
if (!typeObj) { |
| 3440 |
return false; |
| 3441 |
} |
| 3442 |
args.rval().setObject(*typeObj); |
| 3443 |
return true; |
| 3444 |
} |
| 3445 |
|
| 3446 |
/* static */ |
| 3447 |
bool WasmGlobalObject::type(JSContext* cx, unsigned argc, Value* vp) { |
| 3448 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3449 |
return CallNonGenericMethod<IsGlobal, typeImpl>(cx, args); |
| 3450 |
} |
| 3451 |
#endif |
| 3452 |
|
| 3453 |
// ============================================================================ |
| 3454 |
// WebAssembly.Tag class and methods |
| 3455 |
|
| 3456 |
const JSClassOps WasmTagObject::classOps_ = { |
| 3457 |
nullptr, // addProperty |
| 3458 |
nullptr, // delProperty |
| 3459 |
nullptr, // enumerate |
| 3460 |
nullptr, // newEnumerate |
| 3461 |
nullptr, // resolve |
| 3462 |
nullptr, // mayResolve |
| 3463 |
WasmTagObject::finalize, // finalize |
| 3464 |
nullptr, // call |
| 3465 |
nullptr, // construct |
| 3466 |
nullptr, // trace |
| 3467 |
}; |
| 3468 |
|
| 3469 |
const JSClass WasmTagObject::class_ = { |
| 3470 |
"WebAssembly.Tag", |
| 3471 |
JSCLASS_HAS_RESERVED_SLOTS(WasmTagObject::RESERVED_SLOTS) | |
| 3472 |
JSCLASS_FOREGROUND_FINALIZE, |
| 3473 |
&WasmTagObject::classOps_, |
| 3474 |
&WasmTagObject::classSpec_, |
| 3475 |
}; |
| 3476 |
|
| 3477 |
const JSClass& WasmTagObject::protoClass_ = PlainObject::class_; |
| 3478 |
|
| 3479 |
static constexpr char WasmTagName[] = "Tag"; |
| 3480 |
|
| 3481 |
const ClassSpec WasmTagObject::classSpec_ = { |
| 3482 |
CreateWasmConstructor<WasmTagObject, WasmTagName>, |
| 3483 |
GenericCreatePrototype<WasmTagObject>, |
| 3484 |
WasmTagObject::static_methods, |
| 3485 |
nullptr, |
| 3486 |
WasmTagObject::methods, |
| 3487 |
WasmTagObject::properties, |
| 3488 |
nullptr, |
| 3489 |
ClassSpec::DontDefineConstructor, |
| 3490 |
}; |
| 3491 |
|
| 3492 |
/* static */ |
| 3493 |
void WasmTagObject::finalize(JS::GCContext* gcx, JSObject* obj) { |
| 3494 |
WasmTagObject& tagObj = obj->as<WasmTagObject>(); |
| 3495 |
tagObj.tagType()->Release(); |
| 3496 |
} |
| 3497 |
|
| 3498 |
static bool IsTag(HandleValue v) { |
| 3499 |
return v.isObject() && v.toObject().is<WasmTagObject>(); |
| 3500 |
} |
| 3501 |
|
| 3502 |
bool WasmTagObject::construct(JSContext* cx, unsigned argc, Value* vp) { |
| 3503 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3504 |
|
| 3505 |
if (!ThrowIfNotConstructing(cx, args, "Tag")) { |
| 3506 |
return false; |
| 3507 |
} |
| 3508 |
|
| 3509 |
if (!args.requireAtLeast(cx, "WebAssembly.Tag", 1)) { |
| 3510 |
return false; |
| 3511 |
} |
| 3512 |
|
| 3513 |
if (!args.get(0).isObject()) { |
| 3514 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 3515 |
JSMSG_WASM_BAD_DESC_ARG, "tag"); |
| 3516 |
return false; |
| 3517 |
} |
| 3518 |
|
| 3519 |
RootedObject obj(cx, &args[0].toObject()); |
| 3520 |
RootedValue paramsVal(cx); |
| 3521 |
if (!JS_GetProperty(cx, obj, "parameters", ¶msVal)) { |
| 3522 |
return false; |
| 3523 |
} |
| 3524 |
|
| 3525 |
ValTypeVector params; |
| 3526 |
if (!ParseValTypes(cx, paramsVal, params)) { |
| 3527 |
return false; |
| 3528 |
} |
| 3529 |
|
| 3530 |
RefPtr<TypeContext> types = js_new<TypeContext>(); |
| 3531 |
if (!types) { |
| 3532 |
ReportOutOfMemory(cx); |
| 3533 |
return false; |
| 3534 |
} |
| 3535 |
const TypeDef* tagTypeDef = |
| 3536 |
types->addType(FuncType(std::move(params), ValTypeVector())); |
| 3537 |
if (!tagTypeDef) { |
| 3538 |
ReportOutOfMemory(cx); |
| 3539 |
return false; |
| 3540 |
} |
| 3541 |
|
| 3542 |
wasm::MutableTagType tagType = js_new<wasm::TagType>(); |
| 3543 |
if (!tagType || !tagType->initialize(tagTypeDef)) { |
| 3544 |
ReportOutOfMemory(cx); |
| 3545 |
return false; |
| 3546 |
} |
| 3547 |
|
| 3548 |
RootedObject proto(cx, |
| 3549 |
GetWasmConstructorPrototype(cx, args, JSProto_WasmTag)); |
| 3550 |
if (!proto) { |
| 3551 |
ReportOutOfMemory(cx); |
| 3552 |
return false; |
| 3553 |
} |
| 3554 |
|
| 3555 |
Rooted<WasmTagObject*> tagObj(cx, WasmTagObject::create(cx, tagType, proto)); |
| 3556 |
if (!tagObj) { |
| 3557 |
return false; |
| 3558 |
} |
| 3559 |
|
| 3560 |
args.rval().setObject(*tagObj); |
| 3561 |
return true; |
| 3562 |
} |
| 3563 |
|
| 3564 |
/* static */ |
| 3565 |
WasmTagObject* WasmTagObject::create(JSContext* cx, |
| 3566 |
const wasm::SharedTagType& tagType, |
| 3567 |
HandleObject proto) { |
| 3568 |
Rooted<WasmTagObject*> obj(cx, |
| 3569 |
NewObjectWithGivenProto<WasmTagObject>(cx, proto)); |
| 3570 |
if (!obj) { |
| 3571 |
return nullptr; |
| 3572 |
} |
| 3573 |
|
| 3574 |
tagType.get()->AddRef(); |
| 3575 |
obj->initReservedSlot(TYPE_SLOT, PrivateValue((void*)tagType.get())); |
| 3576 |
|
| 3577 |
return obj; |
| 3578 |
} |
| 3579 |
|
| 3580 |
const JSPropertySpec WasmTagObject::properties[] = { |
| 3581 |
JS_STRING_SYM_PS(toStringTag, "WebAssembly.Tag", JSPROP_READONLY), |
| 3582 |
JS_PS_END, |
| 3583 |
}; |
| 3584 |
|
| 3585 |
#ifdef ENABLE_WASM_TYPE_REFLECTIONS |
| 3586 |
/* static */ |
| 3587 |
bool WasmTagObject::typeImpl(JSContext* cx, const CallArgs& args) { |
| 3588 |
Rooted<WasmTagObject*> tag(cx, &args.thisv().toObject().as<WasmTagObject>()); |
| 3589 |
RootedObject typeObj(cx, TagTypeToObject(cx, tag->valueTypes())); |
| 3590 |
if (!typeObj) { |
| 3591 |
return false; |
| 3592 |
} |
| 3593 |
args.rval().setObject(*typeObj); |
| 3594 |
return true; |
| 3595 |
} |
| 3596 |
|
| 3597 |
/* static */ |
| 3598 |
bool WasmTagObject::type(JSContext* cx, unsigned argc, Value* vp) { |
| 3599 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3600 |
return CallNonGenericMethod<IsTag, typeImpl>(cx, args); |
| 3601 |
} |
| 3602 |
#endif |
| 3603 |
|
| 3604 |
const JSFunctionSpec WasmTagObject::methods[] = { |
| 3605 |
#ifdef ENABLE_WASM_TYPE_REFLECTIONS |
| 3606 |
JS_FN("type", WasmTagObject::type, 0, JSPROP_ENUMERATE), |
| 3607 |
#endif |
| 3608 |
JS_FS_END, |
| 3609 |
}; |
| 3610 |
|
| 3611 |
const JSFunctionSpec WasmTagObject::static_methods[] = { |
| 3612 |
JS_FS_END, |
| 3613 |
}; |
| 3614 |
|
| 3615 |
const TagType* WasmTagObject::tagType() const { |
| 3616 |
return (const TagType*)getFixedSlot(TYPE_SLOT).toPrivate(); |
| 3617 |
}; |
| 3618 |
|
| 3619 |
const wasm::ValTypeVector& WasmTagObject::valueTypes() const { |
| 3620 |
return tagType()->argTypes(); |
| 3621 |
}; |
| 3622 |
|
| 3623 |
// ============================================================================ |
| 3624 |
// WebAssembly.Exception class and methods |
| 3625 |
|
| 3626 |
const JSClassOps WasmExceptionObject::classOps_ = { |
| 3627 |
nullptr, // addProperty |
| 3628 |
nullptr, // delProperty |
| 3629 |
nullptr, // enumerate |
| 3630 |
nullptr, // newEnumerate |
| 3631 |
nullptr, // resolve |
| 3632 |
nullptr, // mayResolve |
| 3633 |
WasmExceptionObject::finalize, // finalize |
| 3634 |
nullptr, // call |
| 3635 |
nullptr, // construct |
| 3636 |
WasmExceptionObject::trace, // trace |
| 3637 |
}; |
| 3638 |
|
| 3639 |
const JSClass WasmExceptionObject::class_ = { |
| 3640 |
"WebAssembly.Exception", |
| 3641 |
JSCLASS_HAS_RESERVED_SLOTS(WasmExceptionObject::RESERVED_SLOTS) | |
| 3642 |
JSCLASS_FOREGROUND_FINALIZE, |
| 3643 |
&WasmExceptionObject::classOps_, |
| 3644 |
&WasmExceptionObject::classSpec_, |
| 3645 |
}; |
| 3646 |
|
| 3647 |
const JSClass& WasmExceptionObject::protoClass_ = PlainObject::class_; |
| 3648 |
|
| 3649 |
static constexpr char WasmExceptionName[] = "Exception"; |
| 3650 |
|
| 3651 |
const ClassSpec WasmExceptionObject::classSpec_ = { |
| 3652 |
CreateWasmConstructor<WasmExceptionObject, WasmExceptionName>, |
| 3653 |
GenericCreatePrototype<WasmExceptionObject>, |
| 3654 |
WasmExceptionObject::static_methods, |
| 3655 |
nullptr, |
| 3656 |
WasmExceptionObject::methods, |
| 3657 |
WasmExceptionObject::properties, |
| 3658 |
nullptr, |
| 3659 |
ClassSpec::DontDefineConstructor, |
| 3660 |
}; |
| 3661 |
|
| 3662 |
/* static */ |
| 3663 |
void WasmExceptionObject::finalize(JS::GCContext* gcx, JSObject* obj) { |
| 3664 |
WasmExceptionObject& exnObj = obj->as<WasmExceptionObject>(); |
| 3665 |
if (exnObj.isNewborn()) { |
| 3666 |
return; |
| 3667 |
} |
| 3668 |
gcx->free_(obj, exnObj.typedMem(), exnObj.tagType()->tagSize(), |
| 3669 |
MemoryUse::WasmExceptionData); |
| 3670 |
exnObj.tagType()->Release(); |
| 3671 |
} |
| 3672 |
|
| 3673 |
/* static */ |
| 3674 |
void WasmExceptionObject::trace(JSTracer* trc, JSObject* obj) { |
| 3675 |
WasmExceptionObject& exnObj = obj->as<WasmExceptionObject>(); |
| 3676 |
if (exnObj.isNewborn()) { |
| 3677 |
return; |
| 3678 |
} |
| 3679 |
|
| 3680 |
wasm::SharedTagType tag = exnObj.tagType(); |
| 3681 |
const wasm::ValTypeVector& params = tag->argTypes(); |
| 3682 |
const wasm::TagOffsetVector& offsets = tag->argOffsets(); |
| 3683 |
uint8_t* typedMem = exnObj.typedMem(); |
| 3684 |
for (size_t i = 0; i < params.length(); i++) { |
| 3685 |
ValType paramType = params[i]; |
| 3686 |
if (paramType.isRefRepr()) { |
| 3687 |
GCPtr<wasm::AnyRef>* paramPtr = |
| 3688 |
reinterpret_cast<GCPtr<AnyRef>*>(typedMem + offsets[i]); |
| 3689 |
TraceNullableEdge(trc, paramPtr, "wasm exception param"); |
| 3690 |
} |
| 3691 |
} |
| 3692 |
} |
| 3693 |
|
| 3694 |
static bool IsException(HandleValue v) { |
| 3695 |
return v.isObject() && v.toObject().is<WasmExceptionObject>(); |
| 3696 |
} |
| 3697 |
|
| 3698 |
struct ExceptionOptions { |
| 3699 |
bool traceStack; |
| 3700 |
|
| 3701 |
ExceptionOptions() : traceStack(false) {} |
| 3702 |
|
| 3703 |
[[nodiscard]] bool init(JSContext* cx, HandleValue val); |
| 3704 |
}; |
| 3705 |
|
| 3706 |
bool ExceptionOptions::init(JSContext* cx, HandleValue val) { |
| 3707 |
if (val.isNullOrUndefined()) { |
| 3708 |
return true; |
| 3709 |
} |
| 3710 |
|
| 3711 |
if (!val.isObject()) { |
| 3712 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 3713 |
JSMSG_WASM_BAD_EXN_OPTIONS); |
| 3714 |
return false; |
| 3715 |
} |
| 3716 |
RootedObject obj(cx, &val.toObject()); |
| 3717 |
|
| 3718 |
// Get `traceStack` and coerce to boolean |
| 3719 |
RootedValue traceStackVal(cx); |
| 3720 |
if (!JS_GetProperty(cx, obj, "traceStack", &traceStackVal)) { |
| 3721 |
return false; |
| 3722 |
} |
| 3723 |
traceStack = ToBoolean(traceStackVal); |
| 3724 |
|
| 3725 |
return true; |
| 3726 |
} |
| 3727 |
|
| 3728 |
bool WasmExceptionObject::construct(JSContext* cx, unsigned argc, Value* vp) { |
| 3729 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3730 |
|
| 3731 |
if (!ThrowIfNotConstructing(cx, args, "Exception")) { |
| 3732 |
return false; |
| 3733 |
} |
| 3734 |
|
| 3735 |
if (!args.requireAtLeast(cx, "WebAssembly.Exception", 2)) { |
| 3736 |
return false; |
| 3737 |
} |
| 3738 |
|
| 3739 |
if (!IsTag(args[0])) { |
| 3740 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 3741 |
JSMSG_WASM_BAD_EXN_ARG); |
| 3742 |
return false; |
| 3743 |
} |
| 3744 |
Rooted<WasmTagObject*> exnTag(cx, &args[0].toObject().as<WasmTagObject>()); |
| 3745 |
|
| 3746 |
if (!args.get(1).isObject()) { |
| 3747 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 3748 |
JSMSG_WASM_BAD_EXN_PAYLOAD); |
| 3749 |
return false; |
| 3750 |
} |
| 3751 |
|
| 3752 |
JS::ForOfIterator iterator(cx); |
| 3753 |
if (!iterator.init(args.get(1), JS::ForOfIterator::ThrowOnNonIterable)) { |
| 3754 |
return false; |
| 3755 |
} |
| 3756 |
|
| 3757 |
// Get the optional 'options' parameter |
| 3758 |
ExceptionOptions options; |
| 3759 |
if (!options.init(cx, args.get(2))) { |
| 3760 |
return false; |
| 3761 |
} |
| 3762 |
|
| 3763 |
// Trace the stack if requested |
| 3764 |
RootedObject stack(cx); |
| 3765 |
if (options.traceStack && !CaptureStack(cx, &stack)) { |
| 3766 |
return false; |
| 3767 |
} |
| 3768 |
|
| 3769 |
RootedObject proto( |
| 3770 |
cx, GetWasmConstructorPrototype(cx, args, JSProto_WasmException)); |
| 3771 |
if (!proto) { |
| 3772 |
ReportOutOfMemory(cx); |
| 3773 |
return false; |
| 3774 |
} |
| 3775 |
|
| 3776 |
Rooted<WasmExceptionObject*> exnObj( |
| 3777 |
cx, WasmExceptionObject::create(cx, exnTag, stack, proto)); |
| 3778 |
if (!exnObj) { |
| 3779 |
return false; |
| 3780 |
} |
| 3781 |
|
| 3782 |
wasm::SharedTagType tagType = exnObj->tagType(); |
| 3783 |
const wasm::ValTypeVector& params = tagType->argTypes(); |
| 3784 |
const wasm::TagOffsetVector& offsets = tagType->argOffsets(); |
| 3785 |
|
| 3786 |
RootedValue nextArg(cx); |
| 3787 |
for (size_t i = 0; i < params.length(); i++) { |
| 3788 |
bool done; |
| 3789 |
if (!iterator.next(&nextArg, &done)) { |
| 3790 |
return false; |
| 3791 |
} |
| 3792 |
if (done) { |
| 3793 |
UniqueChars expected(JS_smprintf("%zu", params.length())); |
| 3794 |
UniqueChars got(JS_smprintf("%zu", i)); |
| 3795 |
if (!expected || !got) { |
| 3796 |
ReportOutOfMemory(cx); |
| 3797 |
return false; |
| 3798 |
} |
| 3799 |
|
| 3800 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 3801 |
JSMSG_WASM_BAD_EXN_PAYLOAD_LEN, expected.get(), |
| 3802 |
got.get()); |
| 3803 |
return false; |
| 3804 |
} |
| 3805 |
|
| 3806 |
if (!exnObj->initArg(cx, offsets[i], params[i], nextArg)) { |
| 3807 |
return false; |
| 3808 |
} |
| 3809 |
} |
| 3810 |
|
| 3811 |
args.rval().setObject(*exnObj); |
| 3812 |
return true; |
| 3813 |
} |
| 3814 |
|
| 3815 |
/* static */ |
| 3816 |
WasmExceptionObject* WasmExceptionObject::create(JSContext* cx, |
| 3817 |
Handle<WasmTagObject*> tag, |
| 3818 |
HandleObject stack, |
| 3819 |
HandleObject proto) { |
| 3820 |
Rooted<WasmExceptionObject*> obj( |
| 3821 |
cx, NewObjectWithGivenProto<WasmExceptionObject>(cx, proto)); |
| 3822 |
if (!obj) { |
| 3823 |
return nullptr; |
| 3824 |
} |
| 3825 |
const TagType* tagType = tag->tagType(); |
| 3826 |
|
| 3827 |
// Allocate the data buffer before initializing the object so that an OOM |
| 3828 |
// does not result in a partially constructed object. |
| 3829 |
uint8_t* data = (uint8_t*)js_calloc(tagType->tagSize()); |
| 3830 |
if (!data) { |
| 3831 |
ReportOutOfMemory(cx); |
| 3832 |
return nullptr; |
| 3833 |
} |
| 3834 |
|
| 3835 |
MOZ_ASSERT(obj->isNewborn()); |
| 3836 |
obj->initFixedSlot(TAG_SLOT, ObjectValue(*tag)); |
| 3837 |
tagType->AddRef(); |
| 3838 |
obj->initFixedSlot(TYPE_SLOT, PrivateValue((void*)tagType)); |
| 3839 |
InitReservedSlot(obj, DATA_SLOT, data, tagType->tagSize(), |
| 3840 |
MemoryUse::WasmExceptionData); |
| 3841 |
obj->initFixedSlot(STACK_SLOT, ObjectOrNullValue(stack)); |
| 3842 |
|
| 3843 |
MOZ_ASSERT(!obj->isNewborn()); |
| 3844 |
|
| 3845 |
return obj; |
| 3846 |
} |
| 3847 |
|
| 3848 |
WasmExceptionObject* WasmExceptionObject::wrapJSValue(JSContext* cx, |
| 3849 |
HandleValue value) { |
| 3850 |
Rooted<WasmNamespaceObject*> wasm(cx, WasmNamespaceObject::getOrCreate(cx)); |
| 3851 |
if (!wasm) { |
| 3852 |
return nullptr; |
| 3853 |
} |
| 3854 |
|
| 3855 |
Rooted<AnyRef> valueAnyRef(cx); |
| 3856 |
if (!AnyRef::fromJSValue(cx, value, &valueAnyRef)) { |
| 3857 |
return nullptr; |
| 3858 |
} |
| 3859 |
|
| 3860 |
Rooted<WasmTagObject*> wrappedJSValueTag(cx, wasm->wrappedJSValueTag()); |
| 3861 |
WasmExceptionObject* exn = |
| 3862 |
WasmExceptionObject::create(cx, wrappedJSValueTag, nullptr, nullptr); |
| 3863 |
if (!exn) { |
| 3864 |
return nullptr; |
| 3865 |
} |
| 3866 |
MOZ_ASSERT(exn->isWrappedJSValue()); |
| 3867 |
|
| 3868 |
exn->initRefArg(WrappedJSValueTagType_ValueOffset, valueAnyRef); |
| 3869 |
return exn; |
| 3870 |
} |
| 3871 |
|
| 3872 |
bool WasmExceptionObject::isNewborn() const { |
| 3873 |
MOZ_ASSERT(is<WasmExceptionObject>()); |
| 3874 |
return getReservedSlot(DATA_SLOT).isUndefined(); |
| 3875 |
} |
| 3876 |
|
| 3877 |
bool WasmExceptionObject::isWrappedJSValue() const { |
| 3878 |
return tagType() == sWrappedJSValueTagType; |
| 3879 |
} |
| 3880 |
|
| 3881 |
Value WasmExceptionObject::wrappedJSValue() const { |
| 3882 |
MOZ_ASSERT(isWrappedJSValue()); |
| 3883 |
return loadRefArg(WrappedJSValueTagType_ValueOffset).toJSValue(); |
| 3884 |
} |
| 3885 |
|
| 3886 |
const JSPropertySpec WasmExceptionObject::properties[] = { |
| 3887 |
JS_PSG("stack", WasmExceptionObject::getStack, 0), |
| 3888 |
JS_STRING_SYM_PS(toStringTag, "WebAssembly.Exception", JSPROP_READONLY), |
| 3889 |
JS_PS_END, |
| 3890 |
}; |
| 3891 |
|
| 3892 |
/* static */ |
| 3893 |
bool WasmExceptionObject::isImpl(JSContext* cx, const CallArgs& args) { |
| 3894 |
Rooted<WasmExceptionObject*> exnObj( |
| 3895 |
cx, &args.thisv().toObject().as<WasmExceptionObject>()); |
| 3896 |
|
| 3897 |
if (!args.requireAtLeast(cx, "WebAssembly.Exception.is", 1)) { |
| 3898 |
return false; |
| 3899 |
} |
| 3900 |
|
| 3901 |
if (!IsTag(args[0])) { |
| 3902 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 3903 |
JSMSG_WASM_BAD_EXN_ARG); |
| 3904 |
return false; |
| 3905 |
} |
| 3906 |
|
| 3907 |
Rooted<WasmTagObject*> exnTag(cx, |
| 3908 |
&args.get(0).toObject().as<WasmTagObject>()); |
| 3909 |
args.rval().setBoolean(exnTag.get() == &exnObj->tag()); |
| 3910 |
|
| 3911 |
return true; |
| 3912 |
} |
| 3913 |
|
| 3914 |
/* static */ |
| 3915 |
bool WasmExceptionObject::isMethod(JSContext* cx, unsigned argc, Value* vp) { |
| 3916 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3917 |
return CallNonGenericMethod<IsException, isImpl>(cx, args); |
| 3918 |
} |
| 3919 |
|
| 3920 |
/* static */ |
| 3921 |
bool WasmExceptionObject::getArgImpl(JSContext* cx, const CallArgs& args) { |
| 3922 |
Rooted<WasmExceptionObject*> exnObj( |
| 3923 |
cx, &args.thisv().toObject().as<WasmExceptionObject>()); |
| 3924 |
|
| 3925 |
if (!args.requireAtLeast(cx, "WebAssembly.Exception.getArg", 2)) { |
| 3926 |
return false; |
| 3927 |
} |
| 3928 |
|
| 3929 |
if (!IsTag(args[0])) { |
| 3930 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 3931 |
JSMSG_WASM_BAD_EXN_ARG); |
| 3932 |
return false; |
| 3933 |
} |
| 3934 |
|
| 3935 |
Rooted<WasmTagObject*> exnTag(cx, |
| 3936 |
&args.get(0).toObject().as<WasmTagObject>()); |
| 3937 |
if (exnTag.get() != &exnObj->tag()) { |
| 3938 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 3939 |
JSMSG_WASM_BAD_EXN_TAG); |
| 3940 |
return false; |
| 3941 |
} |
| 3942 |
|
| 3943 |
uint32_t index; |
| 3944 |
if (!EnforceRangeU32(cx, args.get(1), "Exception", "getArg index", &index)) { |
| 3945 |
return false; |
| 3946 |
} |
| 3947 |
|
| 3948 |
const wasm::ValTypeVector& params = exnTag->valueTypes(); |
| 3949 |
if (index >= params.length()) { |
| 3950 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, JSMSG_WASM_BAD_RANGE, |
| 3951 |
"Exception", "getArg index"); |
| 3952 |
return false; |
| 3953 |
} |
| 3954 |
|
| 3955 |
uint32_t offset = exnTag->tagType()->argOffsets()[index]; |
| 3956 |
RootedValue result(cx); |
| 3957 |
if (!exnObj->loadArg(cx, offset, params[index], &result)) { |
| 3958 |
return false; |
| 3959 |
} |
| 3960 |
args.rval().set(result); |
| 3961 |
return true; |
| 3962 |
} |
| 3963 |
|
| 3964 |
/* static */ |
| 3965 |
bool WasmExceptionObject::getArg(JSContext* cx, unsigned argc, Value* vp) { |
| 3966 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3967 |
return CallNonGenericMethod<IsException, getArgImpl>(cx, args); |
| 3968 |
} |
| 3969 |
|
| 3970 |
/* static */ |
| 3971 |
bool WasmExceptionObject::getStack_impl(JSContext* cx, const CallArgs& args) { |
| 3972 |
Rooted<WasmExceptionObject*> exnObj( |
| 3973 |
cx, &args.thisv().toObject().as<WasmExceptionObject>()); |
| 3974 |
RootedObject savedFrameObj(cx, exnObj->stack()); |
| 3975 |
if (!savedFrameObj) { |
| 3976 |
args.rval().setUndefined(); |
| 3977 |
return true; |
| 3978 |
} |
| 3979 |
JSPrincipals* principals = exnObj->realm()->principals(); |
| 3980 |
RootedString stackString(cx); |
| 3981 |
if (!BuildStackString(cx, principals, savedFrameObj, &stackString)) { |
| 3982 |
return false; |
| 3983 |
} |
| 3984 |
args.rval().setString(stackString); |
| 3985 |
return true; |
| 3986 |
} |
| 3987 |
|
| 3988 |
/* static */ |
| 3989 |
bool WasmExceptionObject::getStack(JSContext* cx, unsigned argc, Value* vp) { |
| 3990 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3991 |
return CallNonGenericMethod<IsException, getStack_impl>(cx, args); |
| 3992 |
} |
| 3993 |
|
| 3994 |
JSObject* WasmExceptionObject::stack() const { |
| 3995 |
return getReservedSlot(STACK_SLOT).toObjectOrNull(); |
| 3996 |
} |
| 3997 |
|
| 3998 |
uint8_t* WasmExceptionObject::typedMem() const { |
| 3999 |
return (uint8_t*)getReservedSlot(DATA_SLOT).toPrivate(); |
| 4000 |
} |
| 4001 |
|
| 4002 |
bool WasmExceptionObject::loadArg(JSContext* cx, size_t offset, |
| 4003 |
wasm::ValType type, |
| 4004 |
MutableHandleValue vp) const { |
| 4005 |
if (!type.isExposable()) { |
| 4006 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 4007 |
JSMSG_WASM_BAD_VAL_TYPE); |
| 4008 |
return false; |
| 4009 |
} |
| 4010 |
return ToJSValue(cx, typedMem() + offset, type, vp); |
| 4011 |
} |
| 4012 |
|
| 4013 |
bool WasmExceptionObject::initArg(JSContext* cx, size_t offset, |
| 4014 |
wasm::ValType type, HandleValue value) { |
| 4015 |
if (!type.isExposable()) { |
| 4016 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 4017 |
JSMSG_WASM_BAD_VAL_TYPE); |
| 4018 |
return false; |
| 4019 |
} |
| 4020 |
|
| 4021 |
// Avoid rooting hazard of `this` being live across `fromJSValue` |
| 4022 |
// which may GC. |
| 4023 |
uint8_t* dest = typedMem() + offset; |
| 4024 |
RootedVal val(cx); |
| 4025 |
if (!Val::fromJSValue(cx, type, value, &val)) { |
| 4026 |
return false; |
| 4027 |
} |
| 4028 |
val.get().writeToHeapLocation(dest); |
| 4029 |
return true; |
| 4030 |
} |
| 4031 |
|
| 4032 |
void WasmExceptionObject::initRefArg(size_t offset, wasm::AnyRef ref) { |
| 4033 |
uint8_t* dest = typedMem() + offset; |
| 4034 |
*((GCPtr<AnyRef>*)dest) = ref; |
| 4035 |
} |
| 4036 |
|
| 4037 |
wasm::AnyRef WasmExceptionObject::loadRefArg(size_t offset) const { |
| 4038 |
uint8_t* src = typedMem() + offset; |
| 4039 |
return *((GCPtr<AnyRef>*)src); |
| 4040 |
} |
| 4041 |
|
| 4042 |
const JSFunctionSpec WasmExceptionObject::methods[] = { |
| 4043 |
JS_FN("is", WasmExceptionObject::isMethod, 1, JSPROP_ENUMERATE), |
| 4044 |
JS_FN("getArg", WasmExceptionObject::getArg, 2, JSPROP_ENUMERATE), |
| 4045 |
JS_FS_END, |
| 4046 |
}; |
| 4047 |
|
| 4048 |
const JSFunctionSpec WasmExceptionObject::static_methods[] = { |
| 4049 |
JS_FS_END, |
| 4050 |
}; |
| 4051 |
|
| 4052 |
const TagType* WasmExceptionObject::tagType() const { |
| 4053 |
return (const TagType*)getReservedSlot(TYPE_SLOT).toPrivate(); |
| 4054 |
} |
| 4055 |
|
| 4056 |
WasmTagObject& WasmExceptionObject::tag() const { |
| 4057 |
return getReservedSlot(TAG_SLOT).toObject().as<WasmTagObject>(); |
| 4058 |
} |
| 4059 |
|
| 4060 |
// ============================================================================ |
| 4061 |
// WebAssembly.Function and methods |
| 4062 |
#if defined(ENABLE_WASM_TYPE_REFLECTIONS) || defined(ENABLE_WASM_JSPI) |
| 4063 |
[[nodiscard]] static bool IsWasmFunction(HandleValue v) { |
| 4064 |
if (!v.isObject()) { |
| 4065 |
return false; |
| 4066 |
} |
| 4067 |
if (!v.toObject().is<JSFunction>()) { |
| 4068 |
return false; |
| 4069 |
} |
| 4070 |
return v.toObject().as<JSFunction>().isWasm(); |
| 4071 |
} |
| 4072 |
#endif // ENABLE_WASM_TYPE_REFLECTIONS || ENABLE_WASM_JSPI |
| 4073 |
|
| 4074 |
#ifdef ENABLE_WASM_TYPE_REFLECTIONS |
| 4075 |
static JSObject* CreateWasmFunctionPrototype(JSContext* cx, JSProtoKey key) { |
| 4076 |
// WasmFunction's prototype should inherit from JSFunction's prototype. |
| 4077 |
RootedObject jsProto(cx, &cx->global()->getFunctionPrototype()); |
| 4078 |
return GlobalObject::createBlankPrototypeInheriting(cx, &PlainObject::class_, |
| 4079 |
jsProto); |
| 4080 |
} |
| 4081 |
|
| 4082 |
bool WasmFunctionTypeImpl(JSContext* cx, const CallArgs& args) { |
| 4083 |
RootedFunction function(cx, &args.thisv().toObject().as<JSFunction>()); |
| 4084 |
const FuncType& funcType = function->wasmTypeDef()->funcType(); |
| 4085 |
RootedObject typeObj(cx, FuncTypeToObject(cx, funcType)); |
| 4086 |
if (!typeObj) { |
| 4087 |
return false; |
| 4088 |
} |
| 4089 |
args.rval().setObject(*typeObj); |
| 4090 |
return true; |
| 4091 |
} |
| 4092 |
|
| 4093 |
bool WasmFunctionType(JSContext* cx, unsigned argc, Value* vp) { |
| 4094 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 4095 |
return CallNonGenericMethod<IsWasmFunction, WasmFunctionTypeImpl>(cx, args); |
| 4096 |
} |
| 4097 |
|
| 4098 |
static JSFunction* WasmFunctionCreate(JSContext* cx, HandleObject func, |
| 4099 |
wasm::ValTypeVector&& params, |
| 4100 |
wasm::ValTypeVector&& results, |
| 4101 |
HandleObject proto) { |
| 4102 |
MOZ_ASSERT(IsCallableNonCCW(ObjectValue(*func))); |
| 4103 |
|
| 4104 |
// We want to import the function to a wasm module and then export it again so |
| 4105 |
// that it behaves exactly like a normal wasm function and can be used like |
| 4106 |
// one in wasm tables. We synthesize such a module below, instantiate it, and |
| 4107 |
// then return the exported function as the result. |
| 4108 |
FeatureOptions options; |
| 4109 |
ScriptedCaller scriptedCaller; |
| 4110 |
SharedCompileArgs compileArgs = |
| 4111 |
CompileArgs::buildAndReport(cx, std::move(scriptedCaller), options); |
| 4112 |
if (!compileArgs) { |
| 4113 |
return nullptr; |
| 4114 |
} |
| 4115 |
|
| 4116 |
MutableModuleMetadata moduleMeta = js_new<ModuleMetadata>(); |
| 4117 |
if (!moduleMeta || !moduleMeta->init(*compileArgs)) { |
| 4118 |
return nullptr; |
| 4119 |
} |
| 4120 |
MutableCodeMetadata codeMeta = moduleMeta->codeMeta; |
| 4121 |
CompilerEnvironment compilerEnv(CompileMode::Once, Tier::Optimized, |
| 4122 |
DebugEnabled::False); |
| 4123 |
compilerEnv.computeParameters(); |
| 4124 |
|
| 4125 |
FuncType funcType = FuncType(std::move(params), std::move(results)); |
| 4126 |
if (!codeMeta->types->addType(std::move(funcType))) { |
| 4127 |
return nullptr; |
| 4128 |
} |
| 4129 |
|
| 4130 |
// Add an (import (func ...)) |
| 4131 |
FuncDesc funcDesc = FuncDesc(0); |
| 4132 |
if (!codeMeta->funcs.append(funcDesc)) { |
| 4133 |
return nullptr; |
| 4134 |
} |
| 4135 |
codeMeta->numFuncImports = 1; |
| 4136 |
codeMeta->funcImportsAreJS = true; |
| 4137 |
|
| 4138 |
// Add an (export (func 0)) |
| 4139 |
codeMeta->funcs[0].declareFuncExported(/* eager */ true, |
| 4140 |
/* canRefFunc */ true); |
| 4141 |
|
| 4142 |
// We will be looking up and using the function in the future by index so the |
| 4143 |
// name doesn't matter. |
| 4144 |
CacheableName fieldName; |
| 4145 |
if (!moduleMeta->exports.emplaceBack(std::move(fieldName), 0, |
| 4146 |
DefinitionKind::Function)) { |
| 4147 |
return nullptr; |
| 4148 |
} |
| 4149 |
|
| 4150 |
if (!moduleMeta->prepareForCompile(compilerEnv.mode())) { |
| 4151 |
return nullptr; |
| 4152 |
} |
| 4153 |
|
| 4154 |
ModuleGenerator mg(*codeMeta, compilerEnv, compilerEnv.initialState(), |
| 4155 |
nullptr, nullptr, nullptr); |
| 4156 |
if (!mg.initializeCompleteTier()) { |
| 4157 |
return nullptr; |
| 4158 |
} |
| 4159 |
// We're not compiling any function definitions. |
| 4160 |
if (!mg.finishFuncDefs()) { |
| 4161 |
return nullptr; |
| 4162 |
} |
| 4163 |
SharedModule module = mg.finishModule(BytecodeBufferOrSource(), *moduleMeta, |
| 4164 |
/*maybeCompleteTier2Listener=*/nullptr); |
| 4165 |
if (!module) { |
| 4166 |
return nullptr; |
| 4167 |
} |
| 4168 |
|
| 4169 |
// Instantiate the module. |
| 4170 |
Rooted<ImportValues> imports(cx); |
| 4171 |
if (!imports.get().funcs.append(func)) { |
| 4172 |
return nullptr; |
| 4173 |
} |
| 4174 |
Rooted<WasmInstanceObject*> instance(cx); |
| 4175 |
if (!module->instantiate(cx, imports.get(), nullptr, &instance)) { |
| 4176 |
MOZ_ASSERT(cx->isThrowingOutOfMemory()); |
| 4177 |
return nullptr; |
| 4178 |
} |
| 4179 |
|
| 4180 |
// Get the exported function which wraps the JS function to return. |
| 4181 |
RootedFunction wasmFunc(cx); |
| 4182 |
if (!instance->getExportedFunction(cx, instance, 0, &wasmFunc)) { |
| 4183 |
return nullptr; |
| 4184 |
} |
| 4185 |
return wasmFunc; |
| 4186 |
} |
| 4187 |
|
| 4188 |
bool WasmFunctionConstruct(JSContext* cx, unsigned argc, Value* vp) { |
| 4189 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 4190 |
|
| 4191 |
if (!ThrowIfNotConstructing(cx, args, "WebAssembly.Function")) { |
| 4192 |
return false; |
| 4193 |
} |
| 4194 |
|
| 4195 |
if (!args.requireAtLeast(cx, "WebAssembly.Function", 2)) { |
| 4196 |
return false; |
| 4197 |
} |
| 4198 |
|
| 4199 |
if (!args[0].isObject()) { |
| 4200 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 4201 |
JSMSG_WASM_BAD_DESC_ARG, "function"); |
| 4202 |
return false; |
| 4203 |
} |
| 4204 |
RootedObject typeObj(cx, &args[0].toObject()); |
| 4205 |
|
| 4206 |
// Extract properties in lexicographic order per spec. |
| 4207 |
|
| 4208 |
RootedValue parametersVal(cx); |
| 4209 |
if (!JS_GetProperty(cx, typeObj, "parameters", ¶metersVal)) { |
| 4210 |
return false; |
| 4211 |
} |
| 4212 |
|
| 4213 |
ValTypeVector params; |
| 4214 |
if (!ParseValTypes(cx, parametersVal, params)) { |
| 4215 |
return false; |
| 4216 |
} |
| 4217 |
if (params.length() > MaxParams) { |
| 4218 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 4219 |
JSMSG_WASM_BAD_FUNCTION_TYPE, "parameters"); |
| 4220 |
return false; |
| 4221 |
} |
| 4222 |
|
| 4223 |
RootedValue resultsVal(cx); |
| 4224 |
if (!JS_GetProperty(cx, typeObj, "results", &resultsVal)) { |
| 4225 |
return false; |
| 4226 |
} |
| 4227 |
|
| 4228 |
ValTypeVector results; |
| 4229 |
if (!ParseValTypes(cx, resultsVal, results)) { |
| 4230 |
return false; |
| 4231 |
} |
| 4232 |
if (results.length() > MaxResults) { |
| 4233 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 4234 |
JSMSG_WASM_BAD_FUNCTION_TYPE, "results"); |
| 4235 |
return false; |
| 4236 |
} |
| 4237 |
|
| 4238 |
// Get the target function |
| 4239 |
|
| 4240 |
if (!IsCallableNonCCW(args[1])) { |
| 4241 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 4242 |
JSMSG_WASM_BAD_FUNCTION_VALUE); |
| 4243 |
return false; |
| 4244 |
} |
| 4245 |
RootedObject func(cx, &args[1].toObject()); |
| 4246 |
|
| 4247 |
RootedObject proto( |
| 4248 |
cx, GetWasmConstructorPrototype(cx, args, JSProto_WasmFunction)); |
| 4249 |
if (!proto) { |
| 4250 |
ReportOutOfMemory(cx); |
| 4251 |
return false; |
| 4252 |
} |
| 4253 |
|
| 4254 |
RootedFunction wasmFunc(cx, WasmFunctionCreate(cx, func, std::move(params), |
| 4255 |
std::move(results), proto)); |
| 4256 |
if (!wasmFunc) { |
| 4257 |
ReportOutOfMemory(cx); |
| 4258 |
return false; |
| 4259 |
} |
| 4260 |
args.rval().setObject(*wasmFunc); |
| 4261 |
|
| 4262 |
return true; |
| 4263 |
} |
| 4264 |
|
| 4265 |
static constexpr char WasmFunctionName[] = "Function"; |
| 4266 |
|
| 4267 |
static JSObject* CreateWasmFunctionConstructor(JSContext* cx, JSProtoKey key) { |
| 4268 |
RootedObject proto(cx, &cx->global()->getFunctionConstructor()); |
| 4269 |
|
| 4270 |
Rooted<JSAtom*> className( |
| 4271 |
cx, Atomize(cx, WasmFunctionName, strlen(WasmFunctionName))); |
| 4272 |
if (!className) { |
| 4273 |
return nullptr; |
| 4274 |
} |
| 4275 |
return NewFunctionWithProto(cx, WasmFunctionConstruct, 1, |
| 4276 |
FunctionFlags::NATIVE_CTOR, nullptr, className, |
| 4277 |
proto, gc::AllocKind::FUNCTION, TenuredObject); |
| 4278 |
} |
| 4279 |
|
| 4280 |
const JSFunctionSpec WasmFunctionMethods[] = { |
| 4281 |
JS_FN("type", WasmFunctionType, 0, 0), |
| 4282 |
JS_FS_END, |
| 4283 |
}; |
| 4284 |
|
| 4285 |
const ClassSpec WasmFunctionClassSpec = { |
| 4286 |
CreateWasmFunctionConstructor, |
| 4287 |
CreateWasmFunctionPrototype, |
| 4288 |
nullptr, |
| 4289 |
nullptr, |
| 4290 |
WasmFunctionMethods, |
| 4291 |
nullptr, |
| 4292 |
nullptr, |
| 4293 |
ClassSpec::DontDefineConstructor, |
| 4294 |
}; |
| 4295 |
|
| 4296 |
const JSClass js::WasmFunctionClass = { |
| 4297 |
"WebAssembly.Function", |
| 4298 |
0, |
| 4299 |
JS_NULL_CLASS_OPS, |
| 4300 |
&WasmFunctionClassSpec, |
| 4301 |
}; |
| 4302 |
|
| 4303 |
#endif |
| 4304 |
|
| 4305 |
// ============================================================================ |
| 4306 |
// WebAssembly class and static methods |
| 4307 |
|
| 4308 |
static bool WebAssembly_toSource(JSContext* cx, unsigned argc, Value* vp) { |
| 4309 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 4310 |
args.rval().setString(cx->names().WebAssembly); |
| 4311 |
return true; |
| 4312 |
} |
| 4313 |
|
| 4314 |
static bool RejectWithPendingException(JSContext* cx, |
| 4315 |
Handle<PromiseObject*> promise) { |
| 4316 |
if (!cx->isExceptionPending()) { |
| 4317 |
return false; |
| 4318 |
} |
| 4319 |
|
| 4320 |
RootedValue rejectionValue(cx); |
| 4321 |
if (!GetAndClearException(cx, &rejectionValue)) { |
| 4322 |
return false; |
| 4323 |
} |
| 4324 |
|
| 4325 |
return PromiseObject::reject(cx, promise, rejectionValue); |
| 4326 |
} |
| 4327 |
|
| 4328 |
static bool Reject(JSContext* cx, const CompileArgs& args, |
| 4329 |
Handle<PromiseObject*> promise, const UniqueChars& error) { |
| 4330 |
if (!error) { |
| 4331 |
ThrowCompileOutOfMemory(cx); |
| 4332 |
return RejectWithPendingException(cx, promise); |
| 4333 |
} |
| 4334 |
|
| 4335 |
RootedObject stack(cx, promise->allocationSite()); |
| 4336 |
RootedString fileName(cx); |
| 4337 |
if (const char* filename = args.scriptedCaller.filename.get()) { |
| 4338 |
fileName = |
| 4339 |
JS_NewStringCopyUTF8N(cx, JS::UTF8Chars(filename, strlen(filename))); |
| 4340 |
} else { |
| 4341 |
fileName = JS_GetEmptyString(cx); |
| 4342 |
} |
| 4343 |
if (!fileName) { |
| 4344 |
return false; |
| 4345 |
} |
| 4346 |
|
| 4347 |
uint32_t line = args.scriptedCaller.line; |
| 4348 |
|
| 4349 |
// Ideally we'd report a JSMSG_WASM_COMPILE_ERROR here, but there's no easy |
| 4350 |
// way to create an ErrorObject for an arbitrary error code with multiple |
| 4351 |
// replacements. |
| 4352 |
UniqueChars str(JS_smprintf("wasm validation error: %s", error.get())); |
| 4353 |
if (!str) { |
| 4354 |
return false; |
| 4355 |
} |
| 4356 |
|
| 4357 |
size_t len = strlen(str.get()); |
| 4358 |
RootedString message(cx, NewStringCopyN<CanGC>(cx, str.get(), len)); |
| 4359 |
if (!message) { |
| 4360 |
return false; |
| 4361 |
} |
| 4362 |
|
| 4363 |
// There's no error |cause| available here. |
| 4364 |
auto cause = JS::NothingHandleValue; |
| 4365 |
|
| 4366 |
RootedObject errorObj( |
| 4367 |
cx, ErrorObject::create(cx, JSEXN_WASMCOMPILEERROR, stack, fileName, 0, |
| 4368 |
line, JS::ColumnNumberOneOrigin(), nullptr, |
| 4369 |
message, cause)); |
| 4370 |
if (!errorObj) { |
| 4371 |
return false; |
| 4372 |
} |
| 4373 |
|
| 4374 |
RootedValue rejectionValue(cx, ObjectValue(*errorObj)); |
| 4375 |
return PromiseObject::reject(cx, promise, rejectionValue); |
| 4376 |
} |
| 4377 |
|
| 4378 |
static void LogAsync(JSContext* cx, const char* funcName, |
| 4379 |
const Module& module) { |
| 4380 |
Log(cx, "async %s succeeded%s", funcName, |
| 4381 |
module.loggingDeserialized() ? " (loaded from cache)" : ""); |
| 4382 |
} |
| 4383 |
|
| 4384 |
enum class Ret { Pair, Instance }; |
| 4385 |
|
| 4386 |
class AsyncInstantiateTask : public OffThreadPromiseTask { |
| 4387 |
SharedModule module_; |
| 4388 |
PersistentRooted<ImportValues> imports_; |
| 4389 |
Ret ret_; |
| 4390 |
|
| 4391 |
public: |
| 4392 |
AsyncInstantiateTask(JSContext* cx, const Module& module, Ret ret, |
| 4393 |
Handle<PromiseObject*> promise) |
| 4394 |
: OffThreadPromiseTask(cx, promise), |
| 4395 |
module_(&module), |
| 4396 |
imports_(cx), |
| 4397 |
ret_(ret) {} |
| 4398 |
|
| 4399 |
ImportValues& imports() { return imports_.get(); } |
| 4400 |
|
| 4401 |
bool resolve(JSContext* cx, Handle<PromiseObject*> promise) override { |
| 4402 |
RootedObject instanceProto( |
| 4403 |
cx, &cx->global()->getPrototype(JSProto_WasmInstance)); |
| 4404 |
|
| 4405 |
Rooted<WasmInstanceObject*> instanceObj(cx); |
| 4406 |
if (!module_->instantiate(cx, imports_.get(), instanceProto, |
| 4407 |
&instanceObj)) { |
| 4408 |
return RejectWithPendingException(cx, promise); |
| 4409 |
} |
| 4410 |
|
| 4411 |
RootedValue resolutionValue(cx); |
| 4412 |
if (ret_ == Ret::Instance) { |
| 4413 |
resolutionValue = ObjectValue(*instanceObj); |
| 4414 |
} else { |
| 4415 |
RootedObject resultObj(cx, JS_NewPlainObject(cx)); |
| 4416 |
if (!resultObj) { |
| 4417 |
return RejectWithPendingException(cx, promise); |
| 4418 |
} |
| 4419 |
|
| 4420 |
RootedObject moduleProto(cx, |
| 4421 |
&cx->global()->getPrototype(JSProto_WasmModule)); |
| 4422 |
RootedObject moduleObj( |
| 4423 |
cx, WasmModuleObject::create(cx, *module_, moduleProto)); |
| 4424 |
if (!moduleObj) { |
| 4425 |
return RejectWithPendingException(cx, promise); |
| 4426 |
} |
| 4427 |
|
| 4428 |
RootedValue val(cx, ObjectValue(*moduleObj)); |
| 4429 |
if (!JS_DefineProperty(cx, resultObj, "module", val, JSPROP_ENUMERATE)) { |
| 4430 |
return RejectWithPendingException(cx, promise); |
| 4431 |
} |
| 4432 |
|
| 4433 |
val = ObjectValue(*instanceObj); |
| 4434 |
if (!JS_DefineProperty(cx, resultObj, "instance", val, |
| 4435 |
JSPROP_ENUMERATE)) { |
| 4436 |
return RejectWithPendingException(cx, promise); |
| 4437 |
} |
| 4438 |
|
| 4439 |
resolutionValue = ObjectValue(*resultObj); |
| 4440 |
} |
| 4441 |
|
| 4442 |
if (!PromiseObject::resolve(cx, promise, resolutionValue)) { |
| 4443 |
return RejectWithPendingException(cx, promise); |
| 4444 |
} |
| 4445 |
|
| 4446 |
LogAsync(cx, "instantiate", *module_); |
| 4447 |
return true; |
| 4448 |
} |
| 4449 |
}; |
| 4450 |
|
| 4451 |
static bool AsyncInstantiate(JSContext* cx, const Module& module, |
| 4452 |
HandleObject importObj, Ret ret, |
| 4453 |
Handle<PromiseObject*> promise) { |
| 4454 |
auto task = js::MakeUnique<AsyncInstantiateTask>(cx, module, ret, promise); |
| 4455 |
if (!task || !task->init(cx)) { |
| 4456 |
return false; |
| 4457 |
} |
| 4458 |
|
| 4459 |
if (!GetImports(cx, module, importObj, &task->imports())) { |
| 4460 |
return RejectWithPendingException(cx, promise); |
| 4461 |
} |
| 4462 |
|
| 4463 |
OffThreadPromiseTask::DispatchResolveAndDestroy(std::move(task)); |
| 4464 |
return true; |
| 4465 |
} |
| 4466 |
|
| 4467 |
static bool ResolveCompile(JSContext* cx, const Module& module, |
| 4468 |
Handle<PromiseObject*> promise) { |
| 4469 |
RootedObject proto(cx, &cx->global()->getPrototype(JSProto_WasmModule)); |
| 4470 |
RootedObject moduleObj(cx, WasmModuleObject::create(cx, module, proto)); |
| 4471 |
if (!moduleObj) { |
| 4472 |
return RejectWithPendingException(cx, promise); |
| 4473 |
} |
| 4474 |
|
| 4475 |
RootedValue resolutionValue(cx, ObjectValue(*moduleObj)); |
| 4476 |
if (!PromiseObject::resolve(cx, promise, resolutionValue)) { |
| 4477 |
return RejectWithPendingException(cx, promise); |
| 4478 |
} |
| 4479 |
|
| 4480 |
LogAsync(cx, "compile", module); |
| 4481 |
return true; |
| 4482 |
} |
| 4483 |
|
| 4484 |
struct CompileBufferTask : PromiseHelperTask { |
| 4485 |
BytecodeBuffer bytecode; |
| 4486 |
SharedCompileArgs compileArgs; |
| 4487 |
UniqueChars error; |
| 4488 |
UniqueCharsVector warnings; |
| 4489 |
SharedModule module; |
| 4490 |
bool instantiate; |
| 4491 |
PersistentRootedObject importObj; |
| 4492 |
|
| 4493 |
CompileBufferTask(JSContext* cx, Handle<PromiseObject*> promise, |
| 4494 |
HandleObject importObj) |
| 4495 |
: PromiseHelperTask(cx, promise), |
| 4496 |
instantiate(true), |
| 4497 |
importObj(cx, importObj) {} |
| 4498 |
|
| 4499 |
CompileBufferTask(JSContext* cx, Handle<PromiseObject*> promise) |
| 4500 |
: PromiseHelperTask(cx, promise), instantiate(false) {} |
| 4501 |
|
| 4502 |
bool init(JSContext* cx, FeatureOptions options, const char* introducer) { |
| 4503 |
compileArgs = InitCompileArgs(cx, options, introducer); |
| 4504 |
if (!compileArgs) { |
| 4505 |
return false; |
| 4506 |
} |
| 4507 |
return PromiseHelperTask::init(cx); |
| 4508 |
} |
| 4509 |
|
| 4510 |
void execute() override { |
| 4511 |
module = CompileBuffer(*compileArgs, BytecodeBufferOrSource(bytecode), |
| 4512 |
&error, &warnings, nullptr); |
| 4513 |
} |
| 4514 |
|
| 4515 |
bool resolve(JSContext* cx, Handle<PromiseObject*> promise) override { |
| 4516 |
if (!ReportCompileWarnings(cx, warnings)) { |
| 4517 |
return false; |
| 4518 |
} |
| 4519 |
if (!module) { |
| 4520 |
return Reject(cx, *compileArgs, promise, error); |
| 4521 |
} |
| 4522 |
if (instantiate) { |
| 4523 |
return AsyncInstantiate(cx, *module, importObj, Ret::Pair, promise); |
| 4524 |
} |
| 4525 |
return ResolveCompile(cx, *module, promise); |
| 4526 |
} |
| 4527 |
}; |
| 4528 |
|
| 4529 |
static bool RejectWithPendingException(JSContext* cx, |
| 4530 |
Handle<PromiseObject*> promise, |
| 4531 |
CallArgs& callArgs) { |
| 4532 |
if (!RejectWithPendingException(cx, promise)) { |
| 4533 |
return false; |
| 4534 |
} |
| 4535 |
|
| 4536 |
callArgs.rval().setObject(*promise); |
| 4537 |
return true; |
| 4538 |
} |
| 4539 |
|
| 4540 |
static bool EnsurePromiseSupport(JSContext* cx) { |
| 4541 |
if (!cx->runtime()->offThreadPromiseState.ref().initialized()) { |
| 4542 |
JS_ReportErrorASCII( |
| 4543 |
cx, "WebAssembly Promise APIs not supported in this runtime."); |
| 4544 |
return false; |
| 4545 |
} |
| 4546 |
return true; |
| 4547 |
} |
| 4548 |
|
| 4549 |
static bool WebAssembly_compile(JSContext* cx, unsigned argc, Value* vp) { |
| 4550 |
if (!EnsurePromiseSupport(cx)) { |
| 4551 |
return false; |
| 4552 |
} |
| 4553 |
|
| 4554 |
Log(cx, "async compile() started"); |
| 4555 |
|
| 4556 |
Rooted<PromiseObject*> promise(cx, PromiseObject::createSkippingExecutor(cx)); |
| 4557 |
if (!promise) { |
| 4558 |
return false; |
| 4559 |
} |
| 4560 |
|
| 4561 |
CallArgs callArgs = CallArgsFromVp(argc, vp); |
| 4562 |
|
| 4563 |
JS::RootedVector<JSString*> parameterStrings(cx); |
| 4564 |
JS::RootedVector<Value> parameterArgs(cx); |
| 4565 |
bool canCompileStrings = false; |
| 4566 |
if (!cx->isRuntimeCodeGenEnabled(JS::RuntimeCode::WASM, nullptr, |
| 4567 |
JS::CompilationType::Undefined, |
| 4568 |
parameterStrings, nullptr, parameterArgs, |
| 4569 |
NullHandleValue, &canCompileStrings)) { |
| 4570 |
return RejectWithPendingException(cx, promise, callArgs); |
| 4571 |
} |
| 4572 |
if (!canCompileStrings) { |
| 4573 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 4574 |
JSMSG_CSP_BLOCKED_WASM, "WebAssembly.compile"); |
| 4575 |
return RejectWithPendingException(cx, promise, callArgs); |
| 4576 |
} |
| 4577 |
|
| 4578 |
auto task = cx->make_unique<CompileBufferTask>(cx, promise); |
| 4579 |
if (!task) { |
| 4580 |
return false; |
| 4581 |
} |
| 4582 |
|
| 4583 |
if (!callArgs.requireAtLeast(cx, "WebAssembly.compile", 1)) { |
| 4584 |
return RejectWithPendingException(cx, promise, callArgs); |
| 4585 |
} |
| 4586 |
|
| 4587 |
FeatureOptions options; |
| 4588 |
if (!options.init(cx, callArgs.get(1))) { |
| 4589 |
return RejectWithPendingException(cx, promise, callArgs); |
| 4590 |
} |
| 4591 |
|
| 4592 |
if (!callArgs[0].isObject()) { |
| 4593 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 4594 |
JSMSG_WASM_BAD_BUF_ARG); |
| 4595 |
return RejectWithPendingException(cx, promise, callArgs); |
| 4596 |
} |
| 4597 |
|
| 4598 |
Rooted<JSObject*> sourceObj(cx, &callArgs[0].toObject()); |
| 4599 |
if (!GetBytecodeBuffer(cx, sourceObj, JSMSG_WASM_BAD_BUF_ARG, |
| 4600 |
&task->bytecode)) { |
| 4601 |
return RejectWithPendingException(cx, promise, callArgs); |
| 4602 |
} |
| 4603 |
|
| 4604 |
if (!task->init(cx, options, "WebAssembly.compile")) { |
| 4605 |
return false; |
| 4606 |
} |
| 4607 |
|
| 4608 |
if (!StartOffThreadPromiseHelperTask(cx, std::move(task))) { |
| 4609 |
return false; |
| 4610 |
} |
| 4611 |
|
| 4612 |
callArgs.rval().setObject(*promise); |
| 4613 |
return true; |
| 4614 |
} |
| 4615 |
|
| 4616 |
static bool GetInstantiateArgs(JSContext* cx, const CallArgs& callArgs, |
| 4617 |
MutableHandleObject firstArg, |
| 4618 |
MutableHandleObject importObj, |
| 4619 |
MutableHandleValue featureOptions) { |
| 4620 |
if (!callArgs.requireAtLeast(cx, "WebAssembly.instantiate", 1)) { |
| 4621 |
return false; |
| 4622 |
} |
| 4623 |
|
| 4624 |
if (!callArgs[0].isObject()) { |
| 4625 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 4626 |
JSMSG_WASM_BAD_BUF_MOD_ARG); |
| 4627 |
return false; |
| 4628 |
} |
| 4629 |
|
| 4630 |
firstArg.set(&callArgs[0].toObject()); |
| 4631 |
|
| 4632 |
if (!GetImportArg(cx, callArgs.get(1), importObj)) { |
| 4633 |
return false; |
| 4634 |
} |
| 4635 |
|
| 4636 |
featureOptions.set(callArgs.get(2)); |
| 4637 |
return true; |
| 4638 |
} |
| 4639 |
|
| 4640 |
static bool WebAssembly_instantiate(JSContext* cx, unsigned argc, Value* vp) { |
| 4641 |
if (!EnsurePromiseSupport(cx)) { |
| 4642 |
return false; |
| 4643 |
} |
| 4644 |
|
| 4645 |
Log(cx, "async instantiate() started"); |
| 4646 |
|
| 4647 |
Rooted<PromiseObject*> promise(cx, PromiseObject::createSkippingExecutor(cx)); |
| 4648 |
if (!promise) { |
| 4649 |
return false; |
| 4650 |
} |
| 4651 |
|
| 4652 |
CallArgs callArgs = CallArgsFromVp(argc, vp); |
| 4653 |
|
| 4654 |
RootedObject firstArg(cx); |
| 4655 |
RootedObject importObj(cx); |
| 4656 |
RootedValue featureOptions(cx); |
| 4657 |
if (!GetInstantiateArgs(cx, callArgs, &firstArg, &importObj, |
| 4658 |
&featureOptions)) { |
| 4659 |
return RejectWithPendingException(cx, promise, callArgs); |
| 4660 |
} |
| 4661 |
|
| 4662 |
const Module* module; |
| 4663 |
if (IsModuleObject(firstArg, &module)) { |
| 4664 |
if (!AsyncInstantiate(cx, *module, importObj, Ret::Instance, promise)) { |
| 4665 |
return false; |
| 4666 |
} |
| 4667 |
} else { |
| 4668 |
JS::RootedVector<JSString*> parameterStrings(cx); |
| 4669 |
JS::RootedVector<Value> parameterArgs(cx); |
| 4670 |
bool canCompileStrings = false; |
| 4671 |
if (!cx->isRuntimeCodeGenEnabled(JS::RuntimeCode::WASM, nullptr, |
| 4672 |
JS::CompilationType::Undefined, |
| 4673 |
parameterStrings, nullptr, parameterArgs, |
| 4674 |
NullHandleValue, &canCompileStrings)) { |
| 4675 |
return RejectWithPendingException(cx, promise, callArgs); |
| 4676 |
} |
| 4677 |
if (!canCompileStrings) { |
| 4678 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 4679 |
JSMSG_CSP_BLOCKED_WASM, |
| 4680 |
"WebAssembly.instantiate"); |
| 4681 |
return RejectWithPendingException(cx, promise, callArgs); |
| 4682 |
} |
| 4683 |
|
| 4684 |
FeatureOptions options; |
| 4685 |
if (!options.init(cx, featureOptions)) { |
| 4686 |
return false; |
| 4687 |
} |
| 4688 |
|
| 4689 |
auto task = cx->make_unique<CompileBufferTask>(cx, promise, importObj); |
| 4690 |
if (!task || !task->init(cx, options, "WebAssembly.instantiate")) { |
| 4691 |
return false; |
| 4692 |
} |
| 4693 |
|
| 4694 |
if (!GetBytecodeBuffer(cx, firstArg, JSMSG_WASM_BAD_BUF_MOD_ARG, |
| 4695 |
&task->bytecode)) { |
| 4696 |
return RejectWithPendingException(cx, promise, callArgs); |
| 4697 |
} |
| 4698 |
|
| 4699 |
if (!StartOffThreadPromiseHelperTask(cx, std::move(task))) { |
| 4700 |
return false; |
| 4701 |
} |
| 4702 |
} |
| 4703 |
|
| 4704 |
callArgs.rval().setObject(*promise); |
| 4705 |
return true; |
| 4706 |
} |
| 4707 |
|
| 4708 |
static bool WebAssembly_validate(JSContext* cx, unsigned argc, Value* vp) { |
| 4709 |
CallArgs callArgs = CallArgsFromVp(argc, vp); |
| 4710 |
|
| 4711 |
if (!callArgs.requireAtLeast(cx, "WebAssembly.validate", 1)) { |
| 4712 |
return false; |
| 4713 |
} |
| 4714 |
|
| 4715 |
FeatureOptions options; |
| 4716 |
if (!options.init(cx, callArgs.get(1))) { |
| 4717 |
return false; |
| 4718 |
} |
| 4719 |
|
| 4720 |
if (!callArgs[0].isObject()) { |
| 4721 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 4722 |
JSMSG_WASM_BAD_BUF_ARG); |
| 4723 |
return false; |
| 4724 |
} |
| 4725 |
|
| 4726 |
BytecodeSource source; |
| 4727 |
Rooted<JSObject*> sourceObj(cx, &callArgs[0].toObject()); |
| 4728 |
if (!GetBytecodeSource(cx, sourceObj, JSMSG_WASM_BAD_BUF_ARG, &source)) { |
| 4729 |
return false; |
| 4730 |
} |
| 4731 |
|
| 4732 |
UniqueChars error; |
| 4733 |
bool validated; |
| 4734 |
{ |
| 4735 |
AutoPinBufferSourceLength pin(cx, sourceObj.get()); |
| 4736 |
validated = Validate(cx, source, options, &error); |
| 4737 |
} |
| 4738 |
|
| 4739 |
// If the reason for validation failure was OOM (signalled by null error |
| 4740 |
// message), report out-of-memory so that validate's return is always |
| 4741 |
// correct. |
| 4742 |
if (!validated && !error) { |
| 4743 |
ReportOutOfMemory(cx); |
| 4744 |
return false; |
| 4745 |
} |
| 4746 |
|
| 4747 |
if (error) { |
| 4748 |
MOZ_ASSERT(!validated); |
| 4749 |
Log(cx, "validate() failed with: %s", error.get()); |
| 4750 |
} |
| 4751 |
|
| 4752 |
callArgs.rval().setBoolean(validated); |
| 4753 |
return true; |
| 4754 |
} |
| 4755 |
|
| 4756 |
static bool EnsureStreamSupport(JSContext* cx) { |
| 4757 |
// This should match wasm::StreamingCompilationAvailable(). |
| 4758 |
|
| 4759 |
if (!EnsurePromiseSupport(cx)) { |
| 4760 |
return false; |
| 4761 |
} |
| 4762 |
|
| 4763 |
if (!CanUseExtraThreads()) { |
| 4764 |
JS_ReportErrorASCII( |
| 4765 |
cx, "WebAssembly.compileStreaming not supported with --no-threads"); |
| 4766 |
return false; |
| 4767 |
} |
| 4768 |
|
| 4769 |
if (!cx->runtime()->consumeStreamCallback) { |
| 4770 |
JS_ReportErrorASCII(cx, |
| 4771 |
"WebAssembly streaming not supported in this runtime"); |
| 4772 |
return false; |
| 4773 |
} |
| 4774 |
|
| 4775 |
return true; |
| 4776 |
} |
| 4777 |
|
| 4778 |
// This value is chosen and asserted to be disjoint from any host error code. |
| 4779 |
static const size_t StreamOOMCode = 0; |
| 4780 |
|
| 4781 |
static bool RejectWithStreamErrorNumber(JSContext* cx, size_t errorCode, |
| 4782 |
Handle<PromiseObject*> promise) { |
| 4783 |
if (errorCode == StreamOOMCode) { |
| 4784 |
ReportOutOfMemory(cx); |
| 4785 |
return false; |
| 4786 |
} |
| 4787 |
|
| 4788 |
cx->runtime()->reportStreamErrorCallback(cx, errorCode); |
| 4789 |
return RejectWithPendingException(cx, promise); |
| 4790 |
} |
| 4791 |
|
| 4792 |
class CompileStreamTask : public PromiseHelperTask, public JS::StreamConsumer { |
| 4793 |
// The stream progresses monotonically through these states; the helper |
| 4794 |
// thread wait()s for streamState_ to reach Closed. |
| 4795 |
enum StreamState { Env, Code, Tail, Closed }; |
| 4796 |
ExclusiveWaitableData<StreamState> streamState_; |
| 4797 |
|
| 4798 |
// Total number of bytes streamed so far. Written and read on the stream |
| 4799 |
// thread only; used to cap the total module size (see consumeChunk). |
| 4800 |
size_t bytesLength_; |
| 4801 |
|
| 4802 |
// Immutable: |
| 4803 |
const bool instantiate_; |
| 4804 |
const PersistentRootedObject importObj_; |
| 4805 |
|
| 4806 |
// Immutable after noteResponseURLs() which is called at most once before |
| 4807 |
// first call on stream thread: |
| 4808 |
const MutableCompileArgs compileArgs_; |
| 4809 |
|
| 4810 |
// Immutable after Env state: |
| 4811 |
MutableBytes envBytes_; |
| 4812 |
BytecodeRange codeSection_; |
| 4813 |
|
| 4814 |
// The code section vector is resized once during the Env state and filled |
| 4815 |
// in chunk by chunk during the Code state, updating the end-pointer after |
| 4816 |
// each chunk: |
| 4817 |
MutableBytes codeBytes_; |
| 4818 |
uint8_t* codeBytesEnd_; |
| 4819 |
ExclusiveBytesPtr exclusiveCodeBytesEnd_; |
| 4820 |
|
| 4821 |
// Immutable after Tail state: |
| 4822 |
MutableBytes tailBytes_; |
| 4823 |
ExclusiveStreamEndData exclusiveStreamEnd_; |
| 4824 |
|
| 4825 |
// Written once before Closed state and read in Closed state on main thread: |
| 4826 |
SharedModule module_; |
| 4827 |
Maybe<size_t> streamError_; |
| 4828 |
UniqueChars compileError_; |
| 4829 |
UniqueCharsVector warnings_; |
| 4830 |
|
| 4831 |
// Set on stream thread and read racily on helper thread to abort compilation: |
| 4832 |
mozilla::Atomic<bool> streamFailed_; |
| 4833 |
|
| 4834 |
// Called on some thread before consumeChunk(), streamEnd(), streamError()): |
| 4835 |
|
| 4836 |
void noteResponseURLs(const char* url, const char* sourceMapUrl) override { |
| 4837 |
if (url) { |
| 4838 |
compileArgs_->scriptedCaller.filename = DuplicateString(url); |
| 4839 |
compileArgs_->scriptedCaller.filenameIsURL = true; |
| 4840 |
} |
| 4841 |
if (sourceMapUrl) { |
| 4842 |
compileArgs_->sourceMapURL = DuplicateString(sourceMapUrl); |
| 4843 |
} |
| 4844 |
} |
| 4845 |
|
| 4846 |
// Called on a stream thread: |
| 4847 |
|
| 4848 |
// Until StartOffThreadPromiseHelperTask succeeds, we are responsible for |
| 4849 |
// dispatching ourselves back to the JS thread. |
| 4850 |
// |
| 4851 |
// Warning: After this function returns, 'this' can be deleted at any time, so |
| 4852 |
// the caller must immediately return from the stream callback. |
| 4853 |
void setClosedAndDestroyBeforeHelperThreadStarted() { |
| 4854 |
streamState_.lock().get() = Closed; |
| 4855 |
dispatchResolveAndDestroy(); |
| 4856 |
} |
| 4857 |
|
| 4858 |
// See setClosedAndDestroyBeforeHelperThreadStarted() comment. |
| 4859 |
bool rejectAndDestroyBeforeHelperThreadStarted(size_t errorNumber) { |
| 4860 |
MOZ_ASSERT(streamState_.lock() == Env); |
| 4861 |
MOZ_ASSERT(!streamError_); |
| 4862 |
streamError_ = Some(errorNumber); |
| 4863 |
setClosedAndDestroyBeforeHelperThreadStarted(); |
| 4864 |
return false; |
| 4865 |
} |
| 4866 |
|
| 4867 |
// Once StartOffThreadPromiseHelperTask succeeds, the helper thread will |
| 4868 |
// dispatchResolveAndDestroy() after execute() returns, but execute() |
| 4869 |
// wait()s for state to be Closed. |
| 4870 |
// |
| 4871 |
// Warning: After this function returns, 'this' can be deleted at any time, so |
| 4872 |
// the caller must immediately return from the stream callback. |
| 4873 |
void setClosedAndDestroyAfterHelperThreadStarted() { |
| 4874 |
auto streamState = streamState_.lock(); |
| 4875 |
MOZ_ASSERT(streamState != Closed); |
| 4876 |
streamState.get() = Closed; |
| 4877 |
streamState.notify_one(/* stream closed */); |
| 4878 |
} |
| 4879 |
|
| 4880 |
// See setClosedAndDestroyAfterHelperThreadStarted() comment. |
| 4881 |
bool rejectAndDestroyAfterHelperThreadStarted(size_t errorNumber) { |
| 4882 |
MOZ_ASSERT(!streamError_); |
| 4883 |
streamError_ = Some(errorNumber); |
| 4884 |
streamFailed_ = true; |
| 4885 |
exclusiveCodeBytesEnd_.lock().notify_one(); |
| 4886 |
exclusiveStreamEnd_.lock().notify_one(); |
| 4887 |
setClosedAndDestroyAfterHelperThreadStarted(); |
| 4888 |
return false; |
| 4889 |
} |
| 4890 |
|
| 4891 |
bool consumeChunk(const uint8_t* begin, size_t length) override { |
| 4892 |
// Enforce the MaxModuleBytes limit early. |
| 4893 |
if (length > MaxModuleBytes - bytesLength_) { |
| 4894 |
// The state tells us whether we are before or after the helper thread |
| 4895 |
// started. |
| 4896 |
if (streamState_.lock().get() == Env) { |
| 4897 |
return rejectAndDestroyBeforeHelperThreadStarted(StreamOOMCode); |
| 4898 |
} |
| 4899 |
return rejectAndDestroyAfterHelperThreadStarted(StreamOOMCode); |
| 4900 |
} |
| 4901 |
bytesLength_ += length; |
| 4902 |
return consumeChunkImpl(begin, length); |
| 4903 |
} |
| 4904 |
|
| 4905 |
// The chunk-processing worker. consumeChunk() re-dispatches trailing bytes to |
| 4906 |
// the next state through this method so that they are counted once, above. |
| 4907 |
bool consumeChunkImpl(const uint8_t* begin, size_t length) { |
| 4908 |
switch (streamState_.lock().get()) { |
| 4909 |
case Env: { |
| 4910 |
if (!envBytes_->append(begin, length)) { |
| 4911 |
return rejectAndDestroyBeforeHelperThreadStarted(StreamOOMCode); |
| 4912 |
} |
| 4913 |
|
| 4914 |
if (!StartsCodeSection(envBytes_->begin(), envBytes_->end(), |
| 4915 |
&codeSection_)) { |
| 4916 |
return true; |
| 4917 |
} |
| 4918 |
|
| 4919 |
uint32_t extraBytes = envBytes_->length() - codeSection_.start; |
| 4920 |
if (extraBytes) { |
| 4921 |
envBytes_->shrinkTo(codeSection_.start); |
| 4922 |
} |
| 4923 |
|
| 4924 |
if (codeSection_.size() > MaxCodeSectionBytes) { |
| 4925 |
return rejectAndDestroyBeforeHelperThreadStarted(StreamOOMCode); |
| 4926 |
} |
| 4927 |
|
| 4928 |
if (!codeBytes_->vector.resize(codeSection_.size())) { |
| 4929 |
return rejectAndDestroyBeforeHelperThreadStarted(StreamOOMCode); |
| 4930 |
} |
| 4931 |
|
| 4932 |
codeBytesEnd_ = codeBytes_->begin(); |
| 4933 |
exclusiveCodeBytesEnd_.lock().get() = codeBytesEnd_; |
| 4934 |
|
| 4935 |
if (!StartOffThreadPromiseHelperTask(this)) { |
| 4936 |
return rejectAndDestroyBeforeHelperThreadStarted(StreamOOMCode); |
| 4937 |
} |
| 4938 |
|
| 4939 |
// Set the state to Code iff StartOffThreadPromiseHelperTask() |
| 4940 |
// succeeds so that the state tells us whether we are before or |
| 4941 |
// after the helper thread started. |
| 4942 |
streamState_.lock().get() = Code; |
| 4943 |
|
| 4944 |
if (extraBytes) { |
| 4945 |
return consumeChunkImpl(begin + length - extraBytes, extraBytes); |
| 4946 |
} |
| 4947 |
|
| 4948 |
return true; |
| 4949 |
} |
| 4950 |
case Code: { |
| 4951 |
size_t copyLength = |
| 4952 |
std::min<size_t>(length, codeBytes_->end() - codeBytesEnd_); |
| 4953 |
memcpy(codeBytesEnd_, begin, copyLength); |
| 4954 |
codeBytesEnd_ += copyLength; |
| 4955 |
|
| 4956 |
{ |
| 4957 |
auto codeStreamEnd = exclusiveCodeBytesEnd_.lock(); |
| 4958 |
codeStreamEnd.get() = codeBytesEnd_; |
| 4959 |
codeStreamEnd.notify_one(); |
| 4960 |
} |
| 4961 |
|
| 4962 |
if (codeBytesEnd_ != codeBytes_->end()) { |
| 4963 |
return true; |
| 4964 |
} |
| 4965 |
|
| 4966 |
streamState_.lock().get() = Tail; |
| 4967 |
|
| 4968 |
if (uint32_t extraBytes = length - copyLength) { |
| 4969 |
return consumeChunkImpl(begin + copyLength, extraBytes); |
| 4970 |
} |
| 4971 |
|
| 4972 |
return true; |
| 4973 |
} |
| 4974 |
case Tail: { |
| 4975 |
if (!tailBytes_->append(begin, length)) { |
| 4976 |
return rejectAndDestroyAfterHelperThreadStarted(StreamOOMCode); |
| 4977 |
} |
| 4978 |
|
| 4979 |
return true; |
| 4980 |
} |
| 4981 |
case Closed: |
| 4982 |
MOZ_CRASH("consumeChunk() in Closed state"); |
| 4983 |
} |
| 4984 |
MOZ_CRASH("unreachable"); |
| 4985 |
} |
| 4986 |
|
| 4987 |
void streamEnd( |
| 4988 |
JS::OptimizedEncodingListener* completeTier2Listener) override { |
| 4989 |
switch (streamState_.lock().get()) { |
| 4990 |
case Env: { |
| 4991 |
BytecodeBuffer bytecode(envBytes_, nullptr, nullptr); |
| 4992 |
module_ = CompileBuffer(*compileArgs_, BytecodeBufferOrSource(bytecode), |
| 4993 |
&compileError_, &warnings_, nullptr); |
| 4994 |
setClosedAndDestroyBeforeHelperThreadStarted(); |
| 4995 |
return; |
| 4996 |
} |
| 4997 |
case Code: |
| 4998 |
case Tail: |
| 4999 |
// Unlock exclusiveStreamEnd_ before locking streamState_. |
| 5000 |
{ |
| 5001 |
auto streamEnd = exclusiveStreamEnd_.lock(); |
| 5002 |
MOZ_ASSERT(!streamEnd->reached); |
| 5003 |
streamEnd->reached = true; |
| 5004 |
streamEnd->tailBytes = tailBytes_; |
| 5005 |
streamEnd->completeTier2Listener = completeTier2Listener; |
| 5006 |
streamEnd.notify_one(); |
| 5007 |
} |
| 5008 |
setClosedAndDestroyAfterHelperThreadStarted(); |
| 5009 |
return; |
| 5010 |
case Closed: |
| 5011 |
MOZ_CRASH("streamEnd() in Closed state"); |
| 5012 |
} |
| 5013 |
} |
| 5014 |
|
| 5015 |
void streamError(size_t errorCode) override { |
| 5016 |
MOZ_ASSERT(errorCode != StreamOOMCode); |
| 5017 |
switch (streamState_.lock().get()) { |
| 5018 |
case Env: |
| 5019 |
rejectAndDestroyBeforeHelperThreadStarted(errorCode); |
| 5020 |
return; |
| 5021 |
case Tail: |
| 5022 |
case Code: |
| 5023 |
rejectAndDestroyAfterHelperThreadStarted(errorCode); |
| 5024 |
return; |
| 5025 |
case Closed: |
| 5026 |
MOZ_CRASH("streamError() in Closed state"); |
| 5027 |
} |
| 5028 |
} |
| 5029 |
|
| 5030 |
void consumeOptimizedEncoding(const uint8_t* begin, size_t length) override { |
| 5031 |
module_ = Module::deserialize(begin, length); |
| 5032 |
|
| 5033 |
MOZ_ASSERT(streamState_.lock().get() == Env); |
| 5034 |
setClosedAndDestroyBeforeHelperThreadStarted(); |
| 5035 |
} |
| 5036 |
|
| 5037 |
// Called on a helper thread: |
| 5038 |
|
| 5039 |
void execute() override { |
| 5040 |
module_ = CompileStreaming(*compileArgs_, *envBytes_, *codeBytes_, |
| 5041 |
exclusiveCodeBytesEnd_, exclusiveStreamEnd_, |
| 5042 |
streamFailed_, &compileError_, &warnings_); |
| 5043 |
|
| 5044 |
// When execute() returns, the CompileStreamTask will be dispatched |
| 5045 |
// back to its JS thread to call resolve() and then be destroyed. We |
| 5046 |
// can't let this happen until the stream has been closed lest |
| 5047 |
// consumeChunk() or streamEnd() be called on a dead object. |
| 5048 |
auto streamState = streamState_.lock(); |
| 5049 |
while (streamState != Closed) { |
| 5050 |
streamState.wait(/* stream closed */); |
| 5051 |
} |
| 5052 |
} |
| 5053 |
|
| 5054 |
// Called on a JS thread after streaming compilation completes/errors: |
| 5055 |
|
| 5056 |
bool resolve(JSContext* cx, Handle<PromiseObject*> promise) override { |
| 5057 |
MOZ_ASSERT(streamState_.lock() == Closed); |
| 5058 |
|
| 5059 |
if (!ReportCompileWarnings(cx, warnings_)) { |
| 5060 |
return false; |
| 5061 |
} |
| 5062 |
if (module_) { |
| 5063 |
MOZ_ASSERT(!streamFailed_ && !streamError_ && !compileError_); |
| 5064 |
if (instantiate_) { |
| 5065 |
return AsyncInstantiate(cx, *module_, importObj_, Ret::Pair, promise); |
| 5066 |
} |
| 5067 |
return ResolveCompile(cx, *module_, promise); |
| 5068 |
} |
| 5069 |
|
| 5070 |
if (streamError_) { |
| 5071 |
return RejectWithStreamErrorNumber(cx, *streamError_, promise); |
| 5072 |
} |
| 5073 |
|
| 5074 |
return Reject(cx, *compileArgs_, promise, compileError_); |
| 5075 |
} |
| 5076 |
|
| 5077 |
public: |
| 5078 |
CompileStreamTask(JSContext* cx, Handle<PromiseObject*> promise, |
| 5079 |
CompileArgs& compileArgs, bool instantiate, |
| 5080 |
HandleObject importObj) |
| 5081 |
: PromiseHelperTask(cx, promise), |
| 5082 |
streamState_(mutexid::WasmStreamStatus, Env), |
| 5083 |
bytesLength_(0), |
| 5084 |
instantiate_(instantiate), |
| 5085 |
importObj_(cx, importObj), |
| 5086 |
compileArgs_(&compileArgs), |
| 5087 |
codeSection_{}, |
| 5088 |
codeBytesEnd_(nullptr), |
| 5089 |
exclusiveCodeBytesEnd_(mutexid::WasmCodeBytesEnd, nullptr), |
| 5090 |
exclusiveStreamEnd_(mutexid::WasmStreamEnd), |
| 5091 |
streamFailed_(false) { |
| 5092 |
MOZ_ASSERT_IF(importObj_, instantiate_); |
| 5093 |
} |
| 5094 |
|
| 5095 |
[[nodiscard]] bool init(JSContext* cx) { |
| 5096 |
envBytes_ = cx->new_<ShareableBytes>(); |
| 5097 |
if (!envBytes_) { |
| 5098 |
return false; |
| 5099 |
} |
| 5100 |
|
| 5101 |
codeBytes_ = js_new<ShareableBytes>(); |
| 5102 |
if (!codeBytes_) { |
| 5103 |
return false; |
| 5104 |
} |
| 5105 |
|
| 5106 |
tailBytes_ = js_new<ShareableBytes>(); |
| 5107 |
if (!tailBytes_) { |
| 5108 |
return false; |
| 5109 |
} |
| 5110 |
|
| 5111 |
return PromiseHelperTask::init(cx); |
| 5112 |
} |
| 5113 |
}; |
| 5114 |
|
| 5115 |
// A short-lived object that captures the arguments of a |
| 5116 |
// WebAssembly.{compileStreaming,instantiateStreaming} while waiting for |
| 5117 |
// the Promise<Response> to resolve to a (hopefully) Promise. |
| 5118 |
class ResolveResponseClosure : public NativeObject { |
| 5119 |
static const unsigned COMPILE_ARGS_SLOT = 0; |
| 5120 |
static const unsigned PROMISE_OBJ_SLOT = 1; |
| 5121 |
static const unsigned INSTANTIATE_SLOT = 2; |
| 5122 |
static const unsigned IMPORT_OBJ_SLOT = 3; |
| 5123 |
static const JSClassOps classOps_; |
| 5124 |
|
| 5125 |
static void finalize(JS::GCContext* gcx, JSObject* obj) { |
| 5126 |
auto& closure = obj->as<ResolveResponseClosure>(); |
| 5127 |
gcx->release(obj, &closure.compileArgs(), |
| 5128 |
MemoryUse::WasmResolveResponseClosure); |
| 5129 |
} |
| 5130 |
|
| 5131 |
public: |
| 5132 |
static const unsigned RESERVED_SLOTS = 4; |
| 5133 |
static const JSClass class_; |
| 5134 |
|
| 5135 |
static ResolveResponseClosure* create(JSContext* cx, const CompileArgs& args, |
| 5136 |
HandleObject promise, bool instantiate, |
| 5137 |
HandleObject importObj) { |
| 5138 |
MOZ_ASSERT_IF(importObj, instantiate); |
| 5139 |
|
| 5140 |
AutoSetNewObjectMetadata metadata(cx); |
| 5141 |
auto* obj = NewObjectWithGivenProto<ResolveResponseClosure>(cx, nullptr); |
| 5142 |
if (!obj) { |
| 5143 |
return nullptr; |
| 5144 |
} |
| 5145 |
|
| 5146 |
args.AddRef(); |
| 5147 |
InitReservedSlot(obj, COMPILE_ARGS_SLOT, const_cast<CompileArgs*>(&args), |
| 5148 |
MemoryUse::WasmResolveResponseClosure); |
| 5149 |
obj->setReservedSlot(PROMISE_OBJ_SLOT, ObjectValue(*promise)); |
| 5150 |
obj->setReservedSlot(INSTANTIATE_SLOT, BooleanValue(instantiate)); |
| 5151 |
obj->setReservedSlot(IMPORT_OBJ_SLOT, ObjectOrNullValue(importObj)); |
| 5152 |
return obj; |
| 5153 |
} |
| 5154 |
|
| 5155 |
CompileArgs& compileArgs() const { |
| 5156 |
return *(CompileArgs*)getReservedSlot(COMPILE_ARGS_SLOT).toPrivate(); |
| 5157 |
} |
| 5158 |
PromiseObject& promise() const { |
| 5159 |
return getReservedSlot(PROMISE_OBJ_SLOT).toObject().as<PromiseObject>(); |
| 5160 |
} |
| 5161 |
bool instantiate() const { |
| 5162 |
return getReservedSlot(INSTANTIATE_SLOT).toBoolean(); |
| 5163 |
} |
| 5164 |
JSObject* importObj() const { |
| 5165 |
return getReservedSlot(IMPORT_OBJ_SLOT).toObjectOrNull(); |
| 5166 |
} |
| 5167 |
}; |
| 5168 |
|
| 5169 |
const JSClassOps ResolveResponseClosure::classOps_ = { |
| 5170 |
nullptr, // addProperty |
| 5171 |
nullptr, // delProperty |
| 5172 |
nullptr, // enumerate |
| 5173 |
nullptr, // newEnumerate |
| 5174 |
nullptr, // resolve |
| 5175 |
nullptr, // mayResolve |
| 5176 |
ResolveResponseClosure::finalize, // finalize |
| 5177 |
nullptr, // call |
| 5178 |
nullptr, // construct |
| 5179 |
nullptr, // trace |
| 5180 |
}; |
| 5181 |
|
| 5182 |
const JSClass ResolveResponseClosure::class_ = { |
| 5183 |
"WebAssembly ResolveResponseClosure", |
| 5184 |
JSCLASS_DELAY_METADATA_BUILDER | |
| 5185 |
JSCLASS_HAS_RESERVED_SLOTS(ResolveResponseClosure::RESERVED_SLOTS) | |
| 5186 |
JSCLASS_FOREGROUND_FINALIZE, |
| 5187 |
&ResolveResponseClosure::classOps_, |
| 5188 |
}; |
| 5189 |
|
| 5190 |
static ResolveResponseClosure* ToResolveResponseClosure(const CallArgs& args) { |
| 5191 |
return &args.callee() |
| 5192 |
.as<JSFunction>() |
| 5193 |
.getExtendedSlot(0) |
| 5194 |
.toObject() |
| 5195 |
.as<ResolveResponseClosure>(); |
| 5196 |
} |
| 5197 |
|
| 5198 |
static bool RejectWithErrorNumber(JSContext* cx, uint32_t errorNumber, |
| 5199 |
Handle<PromiseObject*> promise) { |
| 5200 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, errorNumber); |
| 5201 |
return RejectWithPendingException(cx, promise); |
| 5202 |
} |
| 5203 |
|
| 5204 |
static bool ResolveResponse_OnFulfilled(JSContext* cx, unsigned argc, |
| 5205 |
Value* vp) { |
| 5206 |
CallArgs callArgs = CallArgsFromVp(argc, vp); |
| 5207 |
|
| 5208 |
Rooted<ResolveResponseClosure*> closure(cx, |
| 5209 |
ToResolveResponseClosure(callArgs)); |
| 5210 |
Rooted<PromiseObject*> promise(cx, &closure->promise()); |
| 5211 |
CompileArgs& compileArgs = closure->compileArgs(); |
| 5212 |
bool instantiate = closure->instantiate(); |
| 5213 |
Rooted<JSObject*> importObj(cx, closure->importObj()); |
| 5214 |
|
| 5215 |
auto task = cx->make_unique<CompileStreamTask>(cx, promise, compileArgs, |
| 5216 |
instantiate, importObj); |
| 5217 |
if (!task || !task->init(cx)) { |
| 5218 |
return false; |
| 5219 |
} |
| 5220 |
|
| 5221 |
if (!callArgs.get(0).isObject()) { |
| 5222 |
return RejectWithErrorNumber(cx, JSMSG_WASM_BAD_RESPONSE_VALUE, promise); |
| 5223 |
} |
| 5224 |
|
| 5225 |
RootedObject response(cx, &callArgs.get(0).toObject()); |
| 5226 |
if (!cx->runtime()->consumeStreamCallback(cx, response, JS::MimeType::Wasm, |
| 5227 |
task.get())) { |
| 5228 |
return RejectWithPendingException(cx, promise); |
| 5229 |
} |
| 5230 |
|
| 5231 |
(void)task.release(); |
| 5232 |
|
| 5233 |
callArgs.rval().setUndefined(); |
| 5234 |
return true; |
| 5235 |
} |
| 5236 |
|
| 5237 |
static bool ResolveResponse_OnRejected(JSContext* cx, unsigned argc, |
| 5238 |
Value* vp) { |
| 5239 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5240 |
|
| 5241 |
Rooted<ResolveResponseClosure*> closure(cx, ToResolveResponseClosure(args)); |
| 5242 |
Rooted<PromiseObject*> promise(cx, &closure->promise()); |
| 5243 |
|
| 5244 |
if (!PromiseObject::reject(cx, promise, args.get(0))) { |
| 5245 |
return false; |
| 5246 |
} |
| 5247 |
|
| 5248 |
args.rval().setUndefined(); |
| 5249 |
return true; |
| 5250 |
} |
| 5251 |
|
| 5252 |
static bool ResolveResponse(JSContext* cx, Handle<Value> responsePromise, |
| 5253 |
Handle<Value> featureOptions, |
| 5254 |
Handle<PromiseObject*> resultPromise, |
| 5255 |
bool instantiate = false, |
| 5256 |
HandleObject importObj = nullptr) { |
| 5257 |
MOZ_ASSERT_IF(importObj, instantiate); |
| 5258 |
|
| 5259 |
const char* introducer = instantiate ? "WebAssembly.instantiateStreaming" |
| 5260 |
: "WebAssembly.compileStreaming"; |
| 5261 |
|
| 5262 |
FeatureOptions options; |
| 5263 |
if (!options.init(cx, featureOptions)) { |
| 5264 |
return false; |
| 5265 |
} |
| 5266 |
|
| 5267 |
SharedCompileArgs compileArgs = InitCompileArgs(cx, options, introducer); |
| 5268 |
if (!compileArgs) { |
| 5269 |
return false; |
| 5270 |
} |
| 5271 |
|
| 5272 |
RootedObject closure( |
| 5273 |
cx, ResolveResponseClosure::create(cx, *compileArgs, resultPromise, |
| 5274 |
instantiate, importObj)); |
| 5275 |
if (!closure) { |
| 5276 |
return false; |
| 5277 |
} |
| 5278 |
|
| 5279 |
RootedFunction onResolved( |
| 5280 |
cx, NewNativeFunction(cx, ResolveResponse_OnFulfilled, 1, nullptr, |
| 5281 |
gc::AllocKind::FUNCTION_EXTENDED, GenericObject)); |
| 5282 |
if (!onResolved) { |
| 5283 |
return false; |
| 5284 |
} |
| 5285 |
|
| 5286 |
RootedFunction onRejected( |
| 5287 |
cx, NewNativeFunction(cx, ResolveResponse_OnRejected, 1, nullptr, |
| 5288 |
gc::AllocKind::FUNCTION_EXTENDED, GenericObject)); |
| 5289 |
if (!onRejected) { |
| 5290 |
return false; |
| 5291 |
} |
| 5292 |
|
| 5293 |
onResolved->setExtendedSlot(0, ObjectValue(*closure)); |
| 5294 |
onRejected->setExtendedSlot(0, ObjectValue(*closure)); |
| 5295 |
|
| 5296 |
RootedObject resolve(cx, |
| 5297 |
PromiseObject::unforgeableResolve(cx, responsePromise)); |
| 5298 |
if (!resolve) { |
| 5299 |
return false; |
| 5300 |
} |
| 5301 |
|
| 5302 |
return JS::AddPromiseReactions(cx, resolve, onResolved, onRejected); |
| 5303 |
} |
| 5304 |
|
| 5305 |
static bool WebAssembly_compileStreaming(JSContext* cx, unsigned argc, |
| 5306 |
Value* vp) { |
| 5307 |
if (!EnsureStreamSupport(cx)) { |
| 5308 |
return false; |
| 5309 |
} |
| 5310 |
|
| 5311 |
Log(cx, "async compileStreaming() started"); |
| 5312 |
|
| 5313 |
Rooted<PromiseObject*> resultPromise( |
| 5314 |
cx, PromiseObject::createSkippingExecutor(cx)); |
| 5315 |
if (!resultPromise) { |
| 5316 |
return false; |
| 5317 |
} |
| 5318 |
|
| 5319 |
CallArgs callArgs = CallArgsFromVp(argc, vp); |
| 5320 |
|
| 5321 |
JS::RootedVector<JSString*> parameterStrings(cx); |
| 5322 |
JS::RootedVector<Value> parameterArgs(cx); |
| 5323 |
bool canCompileStrings = false; |
| 5324 |
if (!cx->isRuntimeCodeGenEnabled(JS::RuntimeCode::WASM, nullptr, |
| 5325 |
JS::CompilationType::Undefined, |
| 5326 |
parameterStrings, nullptr, parameterArgs, |
| 5327 |
NullHandleValue, &canCompileStrings)) { |
| 5328 |
return RejectWithPendingException(cx, resultPromise, callArgs); |
| 5329 |
} |
| 5330 |
if (!canCompileStrings) { |
| 5331 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 5332 |
JSMSG_CSP_BLOCKED_WASM, |
| 5333 |
"WebAssembly.compileStreaming"); |
| 5334 |
return RejectWithPendingException(cx, resultPromise, callArgs); |
| 5335 |
} |
| 5336 |
|
| 5337 |
Rooted<Value> responsePromise(cx, callArgs.get(0)); |
| 5338 |
Rooted<Value> featureOptions(cx, callArgs.get(1)); |
| 5339 |
if (!ResolveResponse(cx, responsePromise, featureOptions, resultPromise)) { |
| 5340 |
return RejectWithPendingException(cx, resultPromise, callArgs); |
| 5341 |
} |
| 5342 |
|
| 5343 |
callArgs.rval().setObject(*resultPromise); |
| 5344 |
return true; |
| 5345 |
} |
| 5346 |
|
| 5347 |
static bool WebAssembly_instantiateStreaming(JSContext* cx, unsigned argc, |
| 5348 |
Value* vp) { |
| 5349 |
if (!EnsureStreamSupport(cx)) { |
| 5350 |
return false; |
| 5351 |
} |
| 5352 |
|
| 5353 |
Log(cx, "async instantiateStreaming() started"); |
| 5354 |
|
| 5355 |
Rooted<PromiseObject*> resultPromise( |
| 5356 |
cx, PromiseObject::createSkippingExecutor(cx)); |
| 5357 |
if (!resultPromise) { |
| 5358 |
return false; |
| 5359 |
} |
| 5360 |
|
| 5361 |
CallArgs callArgs = CallArgsFromVp(argc, vp); |
| 5362 |
|
| 5363 |
JS::RootedVector<JSString*> parameterStrings(cx); |
| 5364 |
JS::RootedVector<Value> parameterArgs(cx); |
| 5365 |
bool canCompileStrings = false; |
| 5366 |
if (!cx->isRuntimeCodeGenEnabled(JS::RuntimeCode::WASM, nullptr, |
| 5367 |
JS::CompilationType::Undefined, |
| 5368 |
parameterStrings, nullptr, parameterArgs, |
| 5369 |
NullHandleValue, &canCompileStrings)) { |
| 5370 |
return RejectWithPendingException(cx, resultPromise, callArgs); |
| 5371 |
} |
| 5372 |
if (!canCompileStrings) { |
| 5373 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 5374 |
JSMSG_CSP_BLOCKED_WASM, |
| 5375 |
"WebAssembly.instantiateStreaming"); |
| 5376 |
return RejectWithPendingException(cx, resultPromise, callArgs); |
| 5377 |
} |
| 5378 |
|
| 5379 |
Rooted<JSObject*> firstArg(cx); |
| 5380 |
Rooted<JSObject*> importObj(cx); |
| 5381 |
Rooted<Value> featureOptions(cx); |
| 5382 |
if (!GetInstantiateArgs(cx, callArgs, &firstArg, &importObj, |
| 5383 |
&featureOptions)) { |
| 5384 |
return RejectWithPendingException(cx, resultPromise, callArgs); |
| 5385 |
} |
| 5386 |
Rooted<Value> responsePromise(cx, ObjectValue(*firstArg.get())); |
| 5387 |
|
| 5388 |
if (!ResolveResponse(cx, responsePromise, featureOptions, resultPromise, true, |
| 5389 |
importObj)) { |
| 5390 |
return RejectWithPendingException(cx, resultPromise, callArgs); |
| 5391 |
} |
| 5392 |
|
| 5393 |
callArgs.rval().setObject(*resultPromise); |
| 5394 |
return true; |
| 5395 |
} |
| 5396 |
|
| 5397 |
#ifdef ENABLE_WASM_JSPI |
| 5398 |
const ClassSpec WasmSuspendingObject::classSpec_ = { |
| 5399 |
GenericCreateConstructor<construct, 1, gc::AllocKind::FUNCTION>, |
| 5400 |
GenericCreatePrototype<WasmSuspendingObject>, |
| 5401 |
nullptr, |
| 5402 |
nullptr, |
| 5403 |
nullptr, |
| 5404 |
nullptr, |
| 5405 |
nullptr, |
| 5406 |
ClassSpec::DontDefineConstructor, |
| 5407 |
}; |
| 5408 |
|
| 5409 |
const JSClass WasmSuspendingObject::class_ = { |
| 5410 |
"Suspending", |
| 5411 |
JSCLASS_HAS_RESERVED_SLOTS(WasmSuspendingObject::RESERVED_SLOTS), |
| 5412 |
JS_NULL_CLASS_OPS, |
| 5413 |
&classSpec_, |
| 5414 |
}; |
| 5415 |
|
| 5416 |
const JSClass& WasmSuspendingObject::protoClass_ = PlainObject::class_; |
| 5417 |
|
| 5418 |
/* static */ |
| 5419 |
bool WasmSuspendingObject::construct(JSContext* cx, unsigned argc, Value* vp) { |
| 5420 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5421 |
|
| 5422 |
if (!ThrowIfNotConstructing(cx, args, "WebAssembly.Suspending")) { |
| 5423 |
return false; |
| 5424 |
} |
| 5425 |
|
| 5426 |
if (!args.requireAtLeast(cx, "WebAssembly.Suspending", 1)) { |
| 5427 |
return false; |
| 5428 |
} |
| 5429 |
|
| 5430 |
if (!IsCallableNonCCW(args[0])) { |
| 5431 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 5432 |
JSMSG_WASM_BAD_FUNCTION_VALUE); |
| 5433 |
return false; |
| 5434 |
} |
| 5435 |
|
| 5436 |
RootedObject callable(cx, &args[0].toObject()); |
| 5437 |
Rooted<WasmSuspendingObject*> suspending( |
| 5438 |
cx, NewBuiltinClassInstance<WasmSuspendingObject>(cx)); |
| 5439 |
if (!suspending) { |
| 5440 |
return false; |
| 5441 |
} |
| 5442 |
suspending->setWrappedFunction(callable); |
| 5443 |
args.rval().setObject(*suspending); |
| 5444 |
return true; |
| 5445 |
} |
| 5446 |
|
| 5447 |
static bool WebAssembly_promising(JSContext* cx, unsigned argc, Value* vp) { |
| 5448 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5449 |
|
| 5450 |
if (!args.requireAtLeast(cx, "WebAssembly.promising", 1)) { |
| 5451 |
return false; |
| 5452 |
} |
| 5453 |
|
| 5454 |
if (!IsWasmFunction(args[0])) { |
| 5455 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 5456 |
JSMSG_WASM_BAD_FUNCTION_VALUE); |
| 5457 |
return false; |
| 5458 |
} |
| 5459 |
|
| 5460 |
RootedObject func(cx, &args[0].toObject()); |
| 5461 |
RootedFunction promise( |
| 5462 |
cx, WasmPromisingFunctionCreate(cx, func, wasm::ValTypeVector(), |
| 5463 |
wasm::ValTypeVector())); |
| 5464 |
if (!promise) { |
| 5465 |
return false; |
| 5466 |
} |
| 5467 |
args.rval().setObject(*promise); |
| 5468 |
return true; |
| 5469 |
} |
| 5470 |
|
| 5471 |
static const JSFunctionSpec WebAssembly_jspi_methods[] = { |
| 5472 |
JS_FN("promising", WebAssembly_promising, 1, JSPROP_ENUMERATE), |
| 5473 |
JS_FS_END, |
| 5474 |
}; |
| 5475 |
|
| 5476 |
bool js::IsWasmSuspendingObject(JSObject* obj) { |
| 5477 |
return obj->is<WasmSuspendingObject>(); |
| 5478 |
} |
| 5479 |
|
| 5480 |
JSObject* js::MaybeUnwrapSuspendingObject(JSObject* wrapper) { |
| 5481 |
if (!wrapper->is<WasmSuspendingObject>()) { |
| 5482 |
return nullptr; |
| 5483 |
} |
| 5484 |
return wrapper->as<WasmSuspendingObject>().wrappedFunction(); |
| 5485 |
} |
| 5486 |
#else |
| 5487 |
bool js::IsWasmSuspendingObject(JSObject* obj) { return false; } |
| 5488 |
#endif // ENABLE_WASM_JSPI |
| 5489 |
|
| 5490 |
#ifdef ENABLE_WASM_MOZ_INTGEMM |
| 5491 |
|
| 5492 |
static bool WebAssembly_mozIntGemm(JSContext* cx, unsigned argc, Value* vp) { |
| 5493 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5494 |
|
| 5495 |
Rooted<WasmModuleObject*> module(cx); |
| 5496 |
if (!wasm::CompileBuiltinModule(cx, wasm::BuiltinModuleId::IntGemm, |
| 5497 |
&module)) { |
| 5498 |
ReportOutOfMemory(cx); |
| 5499 |
return false; |
| 5500 |
} |
| 5501 |
args.rval().set(ObjectValue(*module.get())); |
| 5502 |
return true; |
| 5503 |
} |
| 5504 |
|
| 5505 |
static const JSFunctionSpec WebAssembly_mozIntGemm_methods[] = { |
| 5506 |
JS_FN("mozIntGemm", WebAssembly_mozIntGemm, 0, JSPROP_ENUMERATE), |
| 5507 |
JS_FS_END, |
| 5508 |
}; |
| 5509 |
|
| 5510 |
#endif // ENABLE_WASM_MOZ_INTGEMM |
| 5511 |
|
| 5512 |
static const JSFunctionSpec WebAssembly_static_methods[] = { |
| 5513 |
JS_FN("toSource", WebAssembly_toSource, 0, 0), |
| 5514 |
JS_FN("compile", WebAssembly_compile, 1, JSPROP_ENUMERATE), |
| 5515 |
JS_FN("instantiate", WebAssembly_instantiate, 1, JSPROP_ENUMERATE), |
| 5516 |
JS_FN("validate", WebAssembly_validate, 1, JSPROP_ENUMERATE), |
| 5517 |
JS_FN("compileStreaming", WebAssembly_compileStreaming, 1, |
| 5518 |
JSPROP_ENUMERATE), |
| 5519 |
JS_FN("instantiateStreaming", WebAssembly_instantiateStreaming, 1, |
| 5520 |
JSPROP_ENUMERATE), |
| 5521 |
JS_FS_END, |
| 5522 |
}; |
| 5523 |
|
| 5524 |
static const JSPropertySpec WebAssembly_static_properties[] = { |
| 5525 |
JS_STRING_SYM_PS(toStringTag, "WebAssembly", JSPROP_READONLY), |
| 5526 |
JS_PS_END, |
| 5527 |
}; |
| 5528 |
|
| 5529 |
static JSObject* CreateWebAssemblyObject(JSContext* cx, JSProtoKey key) { |
| 5530 |
MOZ_RELEASE_ASSERT(HasSupport(cx)); |
| 5531 |
|
| 5532 |
RootedObject proto(cx, &cx->global()->getObjectPrototype()); |
| 5533 |
return NewTenuredObjectWithGivenProto(cx, &WasmNamespaceObject::class_, |
| 5534 |
proto); |
| 5535 |
} |
| 5536 |
|
| 5537 |
struct NameAndProtoKey { |
| 5538 |
const char* const name; |
| 5539 |
JSProtoKey key; |
| 5540 |
}; |
| 5541 |
|
| 5542 |
static bool WebAssemblyDefineConstructor(JSContext* cx, |
| 5543 |
Handle<WasmNamespaceObject*> wasm, |
| 5544 |
NameAndProtoKey entry, |
| 5545 |
MutableHandleValue ctorValue, |
| 5546 |
MutableHandleId id) { |
| 5547 |
JSObject* ctor = GlobalObject::getOrCreateConstructor(cx, entry.key); |
| 5548 |
if (!ctor) { |
| 5549 |
return false; |
| 5550 |
} |
| 5551 |
ctorValue.setObject(*ctor); |
| 5552 |
|
| 5553 |
JSAtom* className = Atomize(cx, entry.name, strlen(entry.name)); |
| 5554 |
if (!className) { |
| 5555 |
return false; |
| 5556 |
} |
| 5557 |
id.set(AtomToId(className)); |
| 5558 |
|
| 5559 |
return DefineDataProperty(cx, wasm, id, ctorValue, 0); |
| 5560 |
} |
| 5561 |
|
| 5562 |
static bool WebAssemblyClassFinish(JSContext* cx, HandleObject object, |
| 5563 |
HandleObject proto) { |
| 5564 |
Handle<WasmNamespaceObject*> wasm = object.as<WasmNamespaceObject>(); |
| 5565 |
|
| 5566 |
constexpr NameAndProtoKey entries[] = { |
| 5567 |
{"Module", JSProto_WasmModule}, |
| 5568 |
{"Instance", JSProto_WasmInstance}, |
| 5569 |
{"Memory", JSProto_WasmMemory}, |
| 5570 |
{"Table", JSProto_WasmTable}, |
| 5571 |
{"Global", JSProto_WasmGlobal}, |
| 5572 |
{"CompileError", GetExceptionProtoKey(JSEXN_WASMCOMPILEERROR)}, |
| 5573 |
{"LinkError", GetExceptionProtoKey(JSEXN_WASMLINKERROR)}, |
| 5574 |
{"RuntimeError", GetExceptionProtoKey(JSEXN_WASMRUNTIMEERROR)}, |
| 5575 |
#ifdef ENABLE_WASM_TYPE_REFLECTIONS |
| 5576 |
{"Function", JSProto_WasmFunction}, |
| 5577 |
#endif |
| 5578 |
}; |
| 5579 |
RootedValue ctorValue(cx); |
| 5580 |
RootedId id(cx); |
| 5581 |
for (const auto& entry : entries) { |
| 5582 |
if (!WebAssemblyDefineConstructor(cx, wasm, entry, &ctorValue, &id)) { |
| 5583 |
return false; |
| 5584 |
} |
| 5585 |
} |
| 5586 |
|
| 5587 |
constexpr NameAndProtoKey exceptionEntries[] = { |
| 5588 |
{"Tag", JSProto_WasmTag}, |
| 5589 |
{"Exception", JSProto_WasmException}, |
| 5590 |
}; |
| 5591 |
for (const auto& entry : exceptionEntries) { |
| 5592 |
if (!WebAssemblyDefineConstructor(cx, wasm, entry, &ctorValue, &id)) { |
| 5593 |
return false; |
| 5594 |
} |
| 5595 |
} |
| 5596 |
|
| 5597 |
RootedObject tagProto( |
| 5598 |
cx, GlobalObject::getOrCreatePrototype(cx, JSProto_WasmTag)); |
| 5599 |
if (!tagProto) { |
| 5600 |
ReportOutOfMemory(cx); |
| 5601 |
return false; |
| 5602 |
} |
| 5603 |
|
| 5604 |
SharedTagType wrappedJSValueTagType(sWrappedJSValueTagType); |
| 5605 |
WasmTagObject* wrappedJSValueTagObject = |
| 5606 |
WasmTagObject::create(cx, wrappedJSValueTagType, tagProto); |
| 5607 |
if (!wrappedJSValueTagObject) { |
| 5608 |
return false; |
| 5609 |
} |
| 5610 |
|
| 5611 |
wasm->setWrappedJSValueTag(wrappedJSValueTagObject); |
| 5612 |
|
| 5613 |
if (ExnRefAvailable(cx)) { |
| 5614 |
RootedId jsTagName(cx, NameToId(cx->names().jsTag)); |
| 5615 |
RootedValue jsTagValue(cx, ObjectValue(*wrappedJSValueTagObject)); |
| 5616 |
if (!DefineDataProperty(cx, wasm, jsTagName, jsTagValue, |
| 5617 |
JSPROP_READONLY | JSPROP_ENUMERATE)) { |
| 5618 |
return false; |
| 5619 |
} |
| 5620 |
} |
| 5621 |
|
| 5622 |
#ifdef ENABLE_WASM_JSPI |
| 5623 |
constexpr NameAndProtoKey jspiEntries[] = { |
| 5624 |
{"Suspending", JSProto_WasmSuspending}, |
| 5625 |
{"SuspendError", GetExceptionProtoKey(JSEXN_WASMSUSPENDERROR)}, |
| 5626 |
}; |
| 5627 |
if (JSPromiseIntegrationAvailable(cx)) { |
| 5628 |
if (!JS_DefineFunctions(cx, wasm, WebAssembly_jspi_methods)) { |
| 5629 |
return false; |
| 5630 |
} |
| 5631 |
for (const auto& entry : jspiEntries) { |
| 5632 |
if (!WebAssemblyDefineConstructor(cx, wasm, entry, &ctorValue, &id)) { |
| 5633 |
return false; |
| 5634 |
} |
| 5635 |
} |
| 5636 |
} |
| 5637 |
#endif |
| 5638 |
|
| 5639 |
#ifdef ENABLE_WASM_MOZ_INTGEMM |
| 5640 |
if (MozIntGemmAvailable(cx) && |
| 5641 |
!JS_DefineFunctions(cx, wasm, WebAssembly_mozIntGemm_methods)) { |
| 5642 |
return false; |
| 5643 |
} |
| 5644 |
#endif |
| 5645 |
|
| 5646 |
return true; |
| 5647 |
} |
| 5648 |
|
| 5649 |
WasmNamespaceObject* WasmNamespaceObject::getOrCreate(JSContext* cx) { |
| 5650 |
JSObject* wasm = |
| 5651 |
GlobalObject::getOrCreateConstructor(cx, JSProto_WebAssembly); |
| 5652 |
if (!wasm) { |
| 5653 |
return nullptr; |
| 5654 |
} |
| 5655 |
return &wasm->as<WasmNamespaceObject>(); |
| 5656 |
} |
| 5657 |
|
| 5658 |
static const ClassSpec WebAssemblyClassSpec = { |
| 5659 |
CreateWebAssemblyObject, nullptr, WebAssembly_static_methods, |
| 5660 |
WebAssembly_static_properties, nullptr, nullptr, |
| 5661 |
WebAssemblyClassFinish, |
| 5662 |
}; |
| 5663 |
|
| 5664 |
const JSClass js::WasmNamespaceObject::class_ = { |
| 5665 |
"WebAssembly", |
| 5666 |
JSCLASS_HAS_CACHED_PROTO(JSProto_WebAssembly) | |
| 5667 |
JSCLASS_HAS_RESERVED_SLOTS(WasmNamespaceObject::RESERVED_SLOTS), |
| 5668 |
JS_NULL_CLASS_OPS, |
| 5669 |
&WebAssemblyClassSpec, |
| 5670 |
}; |
| 5671 |
|
| 5672 |
// Sundry |