| 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 2021 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/WasmBuiltinModule.h" |
| 20 |
|
| 21 |
#include "util/Text.h" |
| 22 |
#include "vm/GlobalObject.h" |
| 23 |
|
| 24 |
#include "wasm/WasmBuiltinModuleGenerated.h" |
| 25 |
#include "wasm/WasmFeatures.h" |
| 26 |
#include "wasm/WasmGenerator.h" |
| 27 |
#include "wasm/WasmJS.h" |
| 28 |
#include "wasm/WasmModule.h" |
| 29 |
#include "wasm/WasmOpIter.h" |
| 30 |
#include "wasm/WasmStaticTypeDefs.h" |
| 31 |
#include "wasm/WasmValidate.h" |
| 32 |
|
| 33 |
using namespace js; |
| 34 |
using namespace js::wasm; |
| 35 |
|
| 36 |
using mozilla::Maybe; |
| 37 |
using mozilla::Nothing; |
| 38 |
using mozilla::Some; |
| 39 |
|
| 40 |
BuiltinModuleFuncs* BuiltinModuleFuncs::singleton_ = nullptr; |
| 41 |
|
| 42 |
[[nodiscard]] bool BuiltinModuleFunc::init( |
| 43 |
const RefPtr<TypeContext>& types, mozilla::Span<const ValType> params, |
| 44 |
Maybe<ValType> result, bool usesMemory, const SymbolicAddressSignature* sig, |
| 45 |
BuiltinInlineOp inlineOp, const char* exportName) { |
| 46 |
// This builtin must not have been initialized yet. |
| 47 |
MOZ_ASSERT(!recGroup_); |
| 48 |
|
| 49 |
// Initialize the basic fields |
| 50 |
exportName_ = exportName; |
| 51 |
sig_ = sig; |
| 52 |
usesMemory_ = usesMemory; |
| 53 |
inlineOp_ = inlineOp; |
| 54 |
|
| 55 |
// Create a function type for the given params and result |
| 56 |
ValTypeVector paramVec; |
| 57 |
if (!paramVec.append(params.data(), params.data() + params.size())) { |
| 58 |
return false; |
| 59 |
} |
| 60 |
ValTypeVector resultVec; |
| 61 |
if (result.isSome() && !resultVec.append(*result)) { |
| 62 |
return false; |
| 63 |
} |
| 64 |
const TypeDef* typeDef = |
| 65 |
types->addType(FuncType(std::move(paramVec), std::move(resultVec))); |
| 66 |
if (!typeDef) { |
| 67 |
return false; |
| 68 |
} |
| 69 |
recGroup_ = &typeDef->recGroup(); |
| 70 |
return true; |
| 71 |
} |
| 72 |
|
| 73 |
bool BuiltinModuleFuncs::init() { |
| 74 |
singleton_ = js_new<BuiltinModuleFuncs>(); |
| 75 |
if (!singleton_) { |
| 76 |
return false; |
| 77 |
} |
| 78 |
|
| 79 |
RefPtr<TypeContext> types = js_new<TypeContext>(); |
| 80 |
if (!types) { |
| 81 |
return false; |
| 82 |
} |
| 83 |
|
| 84 |
#define VISIT_BUILTIN_FUNC(op, export, sa_name, abitype, entry, uses_memory, \ |
| 85 |
inline_op, ...) \ |
| 86 |
const ValType op##Params[] = \ |
| 87 |
DECLARE_BUILTIN_MODULE_FUNC_PARAM_VALTYPES_##op; \ |
| 88 |
Maybe<ValType> op##Result = DECLARE_BUILTIN_MODULE_FUNC_RESULT_VALTYPE_##op; \ |
| 89 |
if (!singleton_->funcs_[BuiltinModuleFuncId::op].init( \ |
| 90 |
types, mozilla::Span<const ValType>(op##Params), op##Result, \ |
| 91 |
uses_memory, &SASig##sa_name, inline_op, export)) { \ |
| 92 |
return false; \ |
| 93 |
} |
| 94 |
FOR_EACH_BUILTIN_MODULE_FUNC(VISIT_BUILTIN_FUNC) |
| 95 |
#undef VISIT_BUILTIN_FUNC |
| 96 |
|
| 97 |
return true; |
| 98 |
} |
| 99 |
|
| 100 |
void BuiltinModuleFuncs::destroy() { |
| 101 |
if (!singleton_) { |
| 102 |
return; |
| 103 |
} |
| 104 |
js_delete(singleton_); |
| 105 |
singleton_ = nullptr; |
| 106 |
} |
| 107 |
|
| 108 |
bool EncodeFuncBody(const BuiltinModuleFunc& builtinModuleFunc, |
| 109 |
BuiltinModuleFuncId id, Bytes* body) { |
| 110 |
Encoder encoder(*body); |
| 111 |
if (!EncodeLocalEntries(encoder, ValTypeVector())) { |
| 112 |
return false; |
| 113 |
} |
| 114 |
const FuncType* funcType = builtinModuleFunc.funcType(); |
| 115 |
for (uint32_t i = 0; i < funcType->args().length(); i++) { |
| 116 |
if (!encoder.writeOp(Op::LocalGet) || !encoder.writeVarU32(i)) { |
| 117 |
return false; |
| 118 |
} |
| 119 |
} |
| 120 |
if (!encoder.writeOp(MozOp::CallBuiltinModuleFunc)) { |
| 121 |
return false; |
| 122 |
} |
| 123 |
if (!encoder.writeVarU32(uint32_t(id))) { |
| 124 |
return false; |
| 125 |
} |
| 126 |
return encoder.writeOp(Op::End); |
| 127 |
} |
| 128 |
|
| 129 |
bool CompileBuiltinModule(JSContext* cx, |
| 130 |
const mozilla::Span<BuiltinModuleFuncId> ids, |
| 131 |
mozilla::Maybe<Shareable> memory, |
| 132 |
MutableHandle<WasmModuleObject*> result) { |
| 133 |
// Create the options manually, enabling intrinsics |
| 134 |
FeatureOptions featureOptions; |
| 135 |
featureOptions.isBuiltinModule = true; |
| 136 |
|
| 137 |
// Initialize the compiler environment, choosing the best tier possible |
| 138 |
SharedCompileArgs compileArgs = CompileArgs::buildAndReport( |
| 139 |
cx, ScriptedCaller(), featureOptions, /* reportOOM */ true); |
| 140 |
if (!compileArgs) { |
| 141 |
return false; |
| 142 |
} |
| 143 |
CompilerEnvironment compilerEnv( |
| 144 |
CompileMode::Once, IonAvailable(cx) ? Tier::Optimized : Tier::Baseline, |
| 145 |
DebugEnabled::False); |
| 146 |
compilerEnv.computeParameters(); |
| 147 |
|
| 148 |
// Build a module metadata struct |
| 149 |
MutableModuleMetadata moduleMeta = js_new<ModuleMetadata>(); |
| 150 |
if (!moduleMeta || !moduleMeta->init(*compileArgs)) { |
| 151 |
ReportOutOfMemory(cx); |
| 152 |
return false; |
| 153 |
} |
| 154 |
MutableCodeMetadata codeMeta = moduleMeta->codeMeta; |
| 155 |
|
| 156 |
if (memory.isSome()) { |
| 157 |
// Add (import (memory 0)) |
| 158 |
CacheableName emptyString; |
| 159 |
CacheableName memoryString; |
| 160 |
if (!CacheableName::fromUTF8Chars("memory", &memoryString)) { |
| 161 |
ReportOutOfMemory(cx); |
| 162 |
return false; |
| 163 |
} |
| 164 |
if (!moduleMeta->imports.append(Import(std::move(emptyString), |
| 165 |
std::move(memoryString), |
| 166 |
DefinitionKind::Memory))) { |
| 167 |
ReportOutOfMemory(cx); |
| 168 |
return false; |
| 169 |
} |
| 170 |
if (!codeMeta->memories.append(MemoryDesc(Limits(0, Nothing(), *memory)))) { |
| 171 |
ReportOutOfMemory(cx); |
| 172 |
return false; |
| 173 |
} |
| 174 |
} |
| 175 |
|
| 176 |
// Add (type (func (params ...))) for each func. The function types will |
| 177 |
// be deduplicated by the runtime. |
| 178 |
for (uint32_t funcIndex = 0; funcIndex < ids.size(); funcIndex++) { |
| 179 |
const BuiltinModuleFuncId& id = ids[funcIndex]; |
| 180 |
const BuiltinModuleFunc& builtinModuleFunc = |
| 181 |
BuiltinModuleFuncs::getFromId(id); |
| 182 |
|
| 183 |
SharedRecGroup recGroup = builtinModuleFunc.recGroup(); |
| 184 |
MOZ_ASSERT(recGroup->numTypes() == 1); |
| 185 |
if (!codeMeta->types->addRecGroup(recGroup)) { |
| 186 |
ReportOutOfMemory(cx); |
| 187 |
return false; |
| 188 |
} |
| 189 |
} |
| 190 |
|
| 191 |
// Add all static type defs to the type context so that we can always look up |
| 192 |
// their index. This must come after the func types so as not to interfere |
| 193 |
// with funcIndex. |
| 194 |
if (!StaticTypeDefs::addAllToTypeContext(codeMeta->types)) { |
| 195 |
ReportOutOfMemory(cx); |
| 196 |
return false; |
| 197 |
} |
| 198 |
|
| 199 |
// Add (func (type $i)) declarations. Do this after all types have been added |
| 200 |
// as the function declaration metadata uses pointers into the type vectors |
| 201 |
// that must be stable. |
| 202 |
for (uint32_t funcIndex = 0; funcIndex < ids.size(); funcIndex++) { |
| 203 |
FuncDesc decl(funcIndex); |
| 204 |
if (!codeMeta->funcs.append(decl)) { |
| 205 |
ReportOutOfMemory(cx); |
| 206 |
return false; |
| 207 |
} |
| 208 |
codeMeta->funcs[funcIndex].declareFuncExported(/* eager */ true, |
| 209 |
/* canRefFunc */ true); |
| 210 |
} |
| 211 |
|
| 212 |
// Add (export "$name" (func $i)) declarations. |
| 213 |
for (uint32_t funcIndex = 0; funcIndex < ids.size(); funcIndex++) { |
| 214 |
const BuiltinModuleFunc& builtinModuleFunc = |
| 215 |
BuiltinModuleFuncs::getFromId(ids[funcIndex]); |
| 216 |
|
| 217 |
CacheableName exportName; |
| 218 |
if (!CacheableName::fromUTF8Chars(builtinModuleFunc.exportName(), |
| 219 |
&exportName) || |
| 220 |
!moduleMeta->exports.append(Export(std::move(exportName), funcIndex, |
| 221 |
DefinitionKind::Function))) { |
| 222 |
ReportOutOfMemory(cx); |
| 223 |
return false; |
| 224 |
} |
| 225 |
} |
| 226 |
|
| 227 |
if (!moduleMeta->prepareForCompile(compilerEnv.mode())) { |
| 228 |
return false; |
| 229 |
} |
| 230 |
|
| 231 |
// Compile the module functions |
| 232 |
UniqueChars error; |
| 233 |
ModuleGenerator mg(*codeMeta, compilerEnv, compilerEnv.initialState(), |
| 234 |
nullptr, &error, nullptr); |
| 235 |
if (!mg.initializeCompleteTier()) { |
| 236 |
ReportOutOfMemory(cx); |
| 237 |
return false; |
| 238 |
} |
| 239 |
|
| 240 |
// Prepare and compile function bodies |
| 241 |
Vector<Bytes, 1, SystemAllocPolicy> bodies; |
| 242 |
if (!bodies.reserve(ids.size())) { |
| 243 |
ReportOutOfMemory(cx); |
| 244 |
return false; |
| 245 |
} |
| 246 |
uint32_t funcBytecodeOffset = CallSite::FIRST_VALID_BYTECODE_OFFSET; |
| 247 |
for (uint32_t funcIndex = 0; funcIndex < ids.size(); funcIndex++) { |
| 248 |
BuiltinModuleFuncId id = ids[funcIndex]; |
| 249 |
const BuiltinModuleFunc& builtinModuleFunc = |
| 250 |
BuiltinModuleFuncs::getFromId(ids[funcIndex]); |
| 251 |
|
| 252 |
// Compilation may be done using other threads, ModuleGenerator requires |
| 253 |
// that function bodies live until after finishFuncDefs(). |
| 254 |
bodies.infallibleAppend(Bytes()); |
| 255 |
Bytes& bytecode = bodies.back(); |
| 256 |
|
| 257 |
// Encode function body that will call the builtinModuleFunc using our |
| 258 |
// builtin opcode, and launch a compile task |
| 259 |
if (!EncodeFuncBody(builtinModuleFunc, id, &bytecode) || |
| 260 |
!mg.compileFuncDef(funcIndex, funcBytecodeOffset, bytecode.begin(), |
| 261 |
bytecode.begin() + bytecode.length())) { |
| 262 |
// This must be an OOM and will be reported by the caller |
| 263 |
MOZ_ASSERT(!error); |
| 264 |
ReportOutOfMemory(cx); |
| 265 |
return false; |
| 266 |
} |
| 267 |
funcBytecodeOffset += bytecode.length(); |
| 268 |
} |
| 269 |
|
| 270 |
// Finish and block on function compilation |
| 271 |
if (!mg.finishFuncDefs()) { |
| 272 |
// This must be an OOM and will be reported by the caller |
| 273 |
MOZ_ASSERT(!error); |
| 274 |
ReportOutOfMemory(cx); |
| 275 |
return false; |
| 276 |
} |
| 277 |
|
| 278 |
// Finish the module |
| 279 |
SharedModule module = mg.finishModule(BytecodeBufferOrSource(), *moduleMeta, |
| 280 |
/*maybeCompleteTier2Listener=*/nullptr); |
| 281 |
if (!module) { |
| 282 |
ReportOutOfMemory(cx); |
| 283 |
return false; |
| 284 |
} |
| 285 |
|
| 286 |
// Create a WasmModuleObject for the module, and return it |
| 287 |
RootedObject proto( |
| 288 |
cx, GlobalObject::getOrCreatePrototype(cx, JSProto_WasmModule)); |
| 289 |
if (!proto) { |
| 290 |
ReportOutOfMemory(cx); |
| 291 |
return false; |
| 292 |
} |
| 293 |
result.set(WasmModuleObject::create(cx, *module, proto)); |
| 294 |
return !!result; |
| 295 |
} |
| 296 |
|
| 297 |
static BuiltinModuleFuncId SelfTestFuncs[] = {BuiltinModuleFuncId::I8VecMul}; |
| 298 |
|
| 299 |
#ifdef ENABLE_WASM_MOZ_INTGEMM |
| 300 |
static BuiltinModuleFuncId IntGemmFuncs[] = { |
| 301 |
BuiltinModuleFuncId::I8PrepareB, |
| 302 |
BuiltinModuleFuncId::I8PrepareBFromTransposed, |
| 303 |
BuiltinModuleFuncId::I8PrepareBFromQuantizedTransposed, |
| 304 |
BuiltinModuleFuncId::I8PrepareA, |
| 305 |
BuiltinModuleFuncId::I8PrepareBias, |
| 306 |
BuiltinModuleFuncId::I8MultiplyAndAddBias, |
| 307 |
BuiltinModuleFuncId::I8SelectColumnsOfB}; |
| 308 |
#endif // ENABLE_WASM_MOZ_INTGEMM |
| 309 |
|
| 310 |
#ifdef ENABLE_WASM_JS_STRING_BUILTINS |
| 311 |
static BuiltinModuleFuncId JSStringFuncs[] = { |
| 312 |
BuiltinModuleFuncId::StringTest, |
| 313 |
BuiltinModuleFuncId::StringCast, |
| 314 |
BuiltinModuleFuncId::StringFromCharCodeArray, |
| 315 |
BuiltinModuleFuncId::StringIntoCharCodeArray, |
| 316 |
BuiltinModuleFuncId::StringFromCharCode, |
| 317 |
BuiltinModuleFuncId::StringFromCodePoint, |
| 318 |
BuiltinModuleFuncId::StringCharCodeAt, |
| 319 |
BuiltinModuleFuncId::StringCodePointAt, |
| 320 |
BuiltinModuleFuncId::StringLength, |
| 321 |
BuiltinModuleFuncId::StringConcat, |
| 322 |
BuiltinModuleFuncId::StringSubstring, |
| 323 |
BuiltinModuleFuncId::StringEquals, |
| 324 |
BuiltinModuleFuncId::StringCompare}; |
| 325 |
static const char* JSStringModuleName = "wasm:js-string"; |
| 326 |
#endif // ENABLE_WASM_JS_STRING_BUILTINS |
| 327 |
|
| 328 |
Maybe<BuiltinModuleId> wasm::ImportMatchesBuiltinModule( |
| 329 |
mozilla::Span<const char> importName, BuiltinModuleIds enabledBuiltins) { |
| 330 |
#ifdef ENABLE_WASM_JS_STRING_BUILTINS |
| 331 |
if (enabledBuiltins.jsString && |
| 332 |
importName == mozilla::MakeStringSpan(JSStringModuleName)) { |
| 333 |
return Some(BuiltinModuleId::JSString); |
| 334 |
} |
| 335 |
if (enabledBuiltins.jsStringConstants && |
| 336 |
importName == |
| 337 |
mozilla::MakeStringSpan( |
| 338 |
enabledBuiltins.jsStringConstantsNamespace->chars.get())) { |
| 339 |
return Some(BuiltinModuleId::JSStringConstants); |
| 340 |
} |
| 341 |
#endif // ENABLE_WASM_JS_STRING_BUILTINS |
| 342 |
// Not supported for implicit instantiation yet |
| 343 |
MOZ_RELEASE_ASSERT(!enabledBuiltins.selfTest && !enabledBuiltins.intGemm); |
| 344 |
return Nothing(); |
| 345 |
} |
| 346 |
|
| 347 |
bool wasm::ImportMatchesBuiltinModuleFunc(mozilla::Span<const char> importName, |
| 348 |
BuiltinModuleId module, |
| 349 |
const BuiltinModuleFunc** matchedFunc, |
| 350 |
BuiltinModuleFuncId* matchedFuncId) { |
| 351 |
#ifdef ENABLE_WASM_JS_STRING_BUILTINS |
| 352 |
// Imported string constants don't define any functions |
| 353 |
if (module == BuiltinModuleId::JSStringConstants) { |
| 354 |
return false; |
| 355 |
} |
| 356 |
|
| 357 |
// Only the wasm:js-string module defines functions at this point, and is |
| 358 |
// supported by implicit instantiation. |
| 359 |
MOZ_RELEASE_ASSERT(module == BuiltinModuleId::JSString); |
| 360 |
for (BuiltinModuleFuncId funcId : JSStringFuncs) { |
| 361 |
const BuiltinModuleFunc& func = BuiltinModuleFuncs::getFromId(funcId); |
| 362 |
if (importName == mozilla::MakeStringSpan(func.exportName())) { |
| 363 |
*matchedFunc = &func; |
| 364 |
*matchedFuncId = funcId; |
| 365 |
return true; |
| 366 |
} |
| 367 |
} |
| 368 |
#endif // ENABLE_WASM_JS_STRING_BUILTINS |
| 369 |
return false; |
| 370 |
} |
| 371 |
|
| 372 |
bool wasm::CompileBuiltinModule(JSContext* cx, BuiltinModuleId module, |
| 373 |
MutableHandle<WasmModuleObject*> result) { |
| 374 |
// NOTE(bvisness): If you update the memory descriptors here, pay attention to |
| 375 |
// CheckBuiltinImportsHaveMemory in WasmValidate.cpp. |
| 376 |
switch (module) { |
| 377 |
case BuiltinModuleId::SelfTest: |
| 378 |
return CompileBuiltinModule(cx, SelfTestFuncs, Some(Shareable::False), |
| 379 |
result); |
| 380 |
#ifdef ENABLE_WASM_MOZ_INTGEMM |
| 381 |
case BuiltinModuleId::IntGemm: |
| 382 |
return CompileBuiltinModule(cx, IntGemmFuncs, Some(Shareable::False), |
| 383 |
result); |
| 384 |
#endif // ENABLE_WASM_MOZ_INTGEMM |
| 385 |
#ifdef ENABLE_WASM_JS_STRING_BUILTINS |
| 386 |
case BuiltinModuleId::JSString: |
| 387 |
return CompileBuiltinModule(cx, JSStringFuncs, Nothing(), result); |
| 388 |
case BuiltinModuleId::JSStringConstants: |
| 389 |
MOZ_CRASH(); |
| 390 |
#endif // ENABLE_WASM_JS_STRING_BUILTINS |
| 391 |
default: |
| 392 |
MOZ_CRASH(); |
| 393 |
} |
| 394 |
} |
| 395 |
|
| 396 |
bool wasm::InstantiateBuiltinModule(JSContext* cx, BuiltinModuleId module, |
| 397 |
MutableHandleObject result) { |
| 398 |
Rooted<WasmModuleObject*> moduleObj(cx); |
| 399 |
if (!CompileBuiltinModule(cx, module, &moduleObj)) { |
| 400 |
ReportOutOfMemory(cx); |
| 401 |
return false; |
| 402 |
} |
| 403 |
ImportValues imports; |
| 404 |
Rooted<WasmInstanceObject*> instanceObj(cx); |
| 405 |
RootedObject instanceProto(cx); |
| 406 |
if (!moduleObj->module().instantiate(cx, imports, instanceProto, |
| 407 |
&instanceObj)) { |
| 408 |
return false; |
| 409 |
} |
| 410 |
result.set(&instanceObj->exportsObj()); |
| 411 |
return true; |
| 412 |
} |