Debian Codegraph @

js/src/wasm/WasmModule.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 *
4 * Copyright 2015 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/WasmModule.h"
20
21 #include <chrono>
22
23 #include "js/BuildId.h" // JS::BuildIdCharVector
24 #include "js/experimental/TypedData.h" // JS_NewUint8Array
25 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
26 #include "js/Printf.h" // JS_smprintf
27 #include "js/PropertyAndElement.h" // JS_DefineProperty, JS_DefinePropertyById
28 #include "js/StreamConsumer.h"
29 #include "threading/LockGuard.h"
30 #include "threading/Thread.h"
31 #include "util/DifferentialTesting.h"
32 #include "vm/HelperThreadState.h" // Tier2GeneratorTask
33 #include "vm/PlainObject.h" // js::PlainObject
34 #include "vm/Warnings.h" // WarnNumberASCII
35 #include "wasm/WasmBaselineCompile.h"
36 #include "wasm/WasmCompile.h"
37 #include "wasm/WasmDebug.h"
38 #include "wasm/WasmInstance.h"
39 #include "wasm/WasmIonCompile.h"
40 #include "wasm/WasmJS.h"
41 #include "wasm/WasmModuleTypes.h"
42 #include "wasm/WasmPI.h"
43 #include "wasm/WasmSerialize.h"
44 #include "wasm/WasmUtility.h"
45
46 #include "debugger/DebugAPI-inl.h"
47 #include "vm/ArrayBufferObject-inl.h"
48 #include "vm/JSAtomUtils-inl.h" // AtomToId
49 #include "wasm/WasmInstance-inl.h"
50
51 using namespace js;
52 using namespace js::jit;
53 using namespace js::wasm;
54
55 static UniqueChars Tier2ResultsContext(const ScriptedCaller& scriptedCaller) {
56 return scriptedCaller.filename
57 ? JS_smprintf("%s:%d", scriptedCaller.filename.get(),
58 scriptedCaller.line)
59 : UniqueChars();
60 }
61
62 void js::wasm::ReportTier2ResultsOffThread(bool cancelled, bool success,
63 Maybe<uint32_t> maybeFuncIndex,
64 const ScriptedCaller& scriptedCaller,
65 const UniqueChars& error,
66 const UniqueCharsVector& warnings) {
67 // Get context to describe this tier-2 task.
68 UniqueChars context = Tier2ResultsContext(scriptedCaller);
69 const char* contextString = context ? context.get() : "unknown";
70
71 // Display the main error, if any.
72 if (!success || cancelled) {
73 const char* errorString = error ? error.get()
74 : cancelled ? "compilation cancelled"
75 : "out of memory";
76 if (maybeFuncIndex.isSome()) {
77 LogOffThread(
78 "'%s': wasm partial tier-2 (func index %u) failed with '%s'.\n",
79 contextString, maybeFuncIndex.value(), errorString);
80 } else {
81 LogOffThread("'%s': wasm complete tier-2 failed with '%s'.\n",
82 contextString, errorString);
83 }
84 }
85
86 // Display warnings as a follow-up, avoiding spamming the console.
87 size_t numWarnings = std::min<size_t>(warnings.length(), 3);
88
89 for (size_t i = 0; i < numWarnings; i++) {
90 // Per the assertion above, we won't get warnings for partial tier-2.
91 LogOffThread("'%s': wasm complete tier-2 warning: '%s'.\n'.", contextString,
92 warnings[i].get());
93 }
94 if (warnings.length() > numWarnings) {
95 LogOffThread("'%s': other warnings suppressed.\n", contextString);
96 }
97 }
98
99 class Module::CompleteTier2GeneratorTaskImpl
100 : public CompleteTier2GeneratorTask {
101 SharedBytes codeSection_;
102 SharedModule module_;
103 mozilla::Atomic<bool> cancelled_;
104
105 public:
106 CompleteTier2GeneratorTaskImpl(const ShareableBytes* codeSection,
107 Module& module)
108 : codeSection_(codeSection), module_(&module), cancelled_(false) {}
109
110 ~CompleteTier2GeneratorTaskImpl() override {
111 module_->completeTier2Listener_ = nullptr;
112 module_->testingTier2Active_ = false;
113 }
114
115 void cancel() override { cancelled_ = true; }
116
117 void runHelperThreadTask(AutoLockHelperThreadState& locked) override {
118 {
119 AutoUnlockHelperThreadState unlock(locked);
120
121 // Compile complete tier-2 and report any warning/errors as long as it's
122 // not a cancellation. Encountering a warning/error during compilation
123 // and being cancelled may race with each other, but the only observable
124 // race should be being cancelled after a warning/error is set, and
125 // that's okay.
126 UniqueChars error;
127 UniqueCharsVector warnings;
128 bool success = CompileCompleteTier2(codeSection_, *module_, &error,
129 &warnings, &cancelled_);
130 if (!cancelled_) {
131 // We could try to dispatch a runnable to the thread that started this
132 // compilation, so as to report the warning/error using a JSContext*.
133 // For now we just report to stderr.
134 ReportTier2ResultsOffThread(cancelled_, success, mozilla::Nothing(),
135 module_->codeMeta().scriptedCaller(), error,
136 warnings);
137 }
138 }
139
140 // During shutdown the main thread will wait for any ongoing (cancelled)
141 // complete tier-2 generation to shut down normally. To do so, it waits on
142 // the HelperThreadState's condition variable for the count of finished
143 // generators to rise.
144 HelperThreadState().incWasmCompleteTier2GeneratorsFinished(locked);
145
146 // The task is finished, release it.
147 js_delete(this);
148 }
149
150 ThreadType threadType() override {
151 return ThreadType::THREAD_TYPE_WASM_GENERATOR_COMPLETE_TIER2;
152 }
153 };
154
155 Module::~Module() {
156 // Note: Modules can be destroyed on any thread.
157 MOZ_ASSERT(!completeTier2Listener_);
158 MOZ_ASSERT(!testingTier2Active_);
159 }
160
161 void Module::startTier2(const ShareableBytes* codeSection,
162 JS::OptimizedEncodingListener* listener) {
163 MOZ_ASSERT(!testingTier2Active_);
164 MOZ_ASSERT_IF(codeMeta().codeSectionRange.isSome(), codeSection);
165
166 auto task = MakeUnique<CompleteTier2GeneratorTaskImpl>(codeSection, *this);
167 if (!task) {
168 return;
169 }
170
171 // These will be cleared asynchronously by ~CompleteTier2GeneratorTaskImpl()
172 // if not sooner by finishTier2().
173 completeTier2Listener_ = listener;
174 testingTier2Active_ = true;
175
176 StartOffThreadWasmCompleteTier2Generator(std::move(task));
177 }
178
179 bool Module::finishTier2(UniqueCodeBlock tier2CodeBlock,
180 UniqueLinkData tier2LinkData,
181 const CompileAndLinkStats& tier2Stats) const {
182 if (!code_->finishTier2(std::move(tier2CodeBlock), std::move(tier2LinkData),
183 tier2Stats)) {
184 return false;
185 }
186
187 // Tier-2 is done; let everyone know. Mark tier-2 active for testing
188 // purposes so that wasmHasTier2CompilationCompleted() only returns true
189 // after tier-2 has been fully cached.
190
191 if (completeTier2Listener_ && canSerialize()) {
192 Bytes bytes;
193 if (serialize(&bytes)) {
194 completeTier2Listener_->storeOptimizedEncoding(bytes.begin(),
195 bytes.length());
196 }
197 completeTier2Listener_ = nullptr;
198 }
199 testingTier2Active_ = false;
200
201 return true;
202 }
203
204 void Module::testingBlockOnTier2Complete() const {
205 while (testingTier2Active_) {
206 ThisThread::SleepMilliseconds(1);
207 }
208 }
209
210 /* virtual */
211 JSObject* Module::createObject(JSContext* cx) const {
212 if (!GlobalObject::ensureConstructor(cx, cx->global(), JSProto_WebAssembly)) {
213 return nullptr;
214 }
215
216 JS::RootedVector<JSString*> parameterStrings(cx);
217 JS::RootedVector<Value> parameterArgs(cx);
218 bool canCompileStrings = false;
219 if (!cx->isRuntimeCodeGenEnabled(JS::RuntimeCode::WASM, nullptr,
220 JS::CompilationType::Undefined,
221 parameterStrings, nullptr, parameterArgs,
222 NullHandleValue, &canCompileStrings)) {
223 return nullptr;
224 }
225 if (!canCompileStrings) {
226 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
227 JSMSG_CSP_BLOCKED_WASM, "WebAssembly.Module");
228 return nullptr;
229 }
230
231 RootedObject proto(cx, &cx->global()->getPrototype(JSProto_WasmModule));
232 return WasmModuleObject::create(cx, *this, proto);
233 }
234
235 /* virtual */
236 JSObject* Module::createObjectForAsmJS(JSContext* cx) const {
237 // Use nullptr to get the default object prototype. These objects are never
238 // exposed to script for asm.js.
239 return WasmModuleObject::create(cx, *this, nullptr);
240 }
241
242 bool wasm::GetOptimizedEncodingBuildId(JS::BuildIdCharVector* buildId) {
243 // From a JS API perspective, the "build id" covers everything that can
244 // cause machine code to become invalid, so include both the actual build-id
245 // and cpu-id.
246
247 if (!GetBuildId || !GetBuildId(buildId)) {
248 return false;
249 }
250
251 uint32_t cpu = ObservedCPUFeatures();
252
253 if (!buildId->reserve(buildId->length() +
254 13 /* "()" + 8 nibbles + "m[+-][+-]" */)) {
255 return false;
256 }
257
258 buildId->infallibleAppend('(');
259 while (cpu) {
260 buildId->infallibleAppend('0' + (cpu & 0xf));
261 cpu >>= 4;
262 }
263 buildId->infallibleAppend(')');
264
265 buildId->infallibleAppend('m');
266 buildId->infallibleAppend(wasm::IsHugeMemoryEnabled(AddressType::I32) ? '+'
267 : '-');
268 buildId->infallibleAppend(wasm::IsHugeMemoryEnabled(AddressType::I64) ? '+'
269 : '-');
270
271 return true;
272 }
273
274 /* virtual */
275 void Module::addSizeOfMisc(mozilla::MallocSizeOf mallocSizeOf,
276 CodeMetadata::SeenSet* seenCodeMeta,
277 CodeMetadataForAsmJS::SeenSet* seenCodeMetaForAsmJS,
278 Code::SeenSet* seenCode, size_t* code,
279 size_t* data) const {
280 code_->addSizeOfMiscIfNotSeen(mallocSizeOf, seenCodeMeta,
281 seenCodeMetaForAsmJS, seenCode, code, data);
282 *data += mallocSizeOf(this);
283 }
284
285 // Extracting machine code as JS object. The result has the "code" property, as
286 // a Uint8Array, and the "segments" property as array objects. The objects
287 // contain offsets in the "code" array and basic information about a code
288 // segment/function body.
289 bool Module::extractCode(JSContext* cx, Tier tier,
290 MutableHandleValue vp) const {
291 Rooted<PlainObject*> result(cx, NewPlainObject(cx));
292 if (!result) {
293 return false;
294 }
295
296 // This function is only used for testing purposes so we can simply
297 // block on tiered compilation to complete.
298 testingBlockOnTier2Complete();
299
300 if (!code_->hasCompleteTier(tier)) {
301 vp.setNull();
302 return true;
303 }
304
305 const CodeBlock& codeBlock = code_->completeTierCodeBlock(tier);
306 const CodeSegment& codeSegment = *codeBlock.segment;
307 RootedObject codeObj(cx, JS_NewUint8Array(cx, codeSegment.lengthBytes()));
308 if (!codeObj) {
309 return false;
310 }
311
312 memcpy(codeObj->as<TypedArrayObject>().dataPointerUnshared(),
313 codeSegment.base(), codeSegment.lengthBytes());
314
315 RootedValue value(cx, ObjectValue(*codeObj));
316 if (!JS_DefineProperty(cx, result, "code", value, JSPROP_ENUMERATE)) {
317 return false;
318 }
319
320 RootedObject segments(cx, NewDenseEmptyArray(cx));
321 if (!segments) {
322 return false;
323 }
324
325 for (const CodeRange& p : codeBlock.codeRanges) {
326 RootedObject segment(cx, NewPlainObjectWithProto(cx, nullptr));
327 if (!segment) {
328 return false;
329 }
330
331 value.setNumber((uint32_t)p.begin());
332 if (!JS_DefineProperty(cx, segment, "begin", value, JSPROP_ENUMERATE)) {
333 return false;
334 }
335
336 value.setNumber((uint32_t)p.end());
337 if (!JS_DefineProperty(cx, segment, "end", value, JSPROP_ENUMERATE)) {
338 return false;
339 }
340
341 value.setNumber((uint32_t)p.kind());
342 if (!JS_DefineProperty(cx, segment, "kind", value, JSPROP_ENUMERATE)) {
343 return false;
344 }
345
346 if (p.isFunction()) {
347 value.setNumber((uint32_t)p.funcIndex());
348 if (!JS_DefineProperty(cx, segment, "funcIndex", value,
349 JSPROP_ENUMERATE)) {
350 return false;
351 }
352
353 value.setNumber((uint32_t)p.funcUncheckedCallEntry());
354 if (!JS_DefineProperty(cx, segment, "funcBodyBegin", value,
355 JSPROP_ENUMERATE)) {
356 return false;
357 }
358
359 value.setNumber((uint32_t)p.end());
360 if (!JS_DefineProperty(cx, segment, "funcBodyEnd", value,
361 JSPROP_ENUMERATE)) {
362 return false;
363 }
364 }
365
366 if (!NewbornArrayPush(cx, segments, ObjectValue(*segment))) {
367 return false;
368 }
369 }
370
371 value.setObject(*segments);
372 if (!JS_DefineProperty(cx, result, "segments", value, JSPROP_ENUMERATE)) {
373 return false;
374 }
375
376 vp.setObject(*result);
377 return true;
378 }
379
380 static const Import& FindImportFunction(const ImportVector& imports,
381 uint32_t funcImportIndex) {
382 for (const Import& import : imports) {
383 if (import.kind != DefinitionKind::Function) {
384 continue;
385 }
386 if (funcImportIndex == 0) {
387 return import;
388 }
389 funcImportIndex--;
390 }
391 MOZ_CRASH("ran out of imports");
392 }
393
394 bool Module::instantiateFunctions(JSContext* cx,
395 const JSObjectVector& funcImports) const {
396 #ifdef DEBUG
397 MOZ_ASSERT(funcImports.length() == code().funcImports().length());
398 #endif
399
400 if (codeMeta().isAsmJS()) {
401 return true;
402 }
403
404 for (size_t i = 0; i < code().funcImports().length(); i++) {
405 if (!funcImports[i]->is<JSFunction>()) {
406 continue;
407 }
408
409 JSFunction* f = &funcImports[i]->as<JSFunction>();
410 if (!f->isWasm() || codeMeta().funcImportsAreJS) {
411 continue;
412 }
413
414 const TypeDef& exportFuncType = *f->wasmTypeDef();
415 const TypeDef& importFuncType = code().codeMeta().getFuncTypeDef(i);
416
417 if (!TypeDef::isSubTypeOf(&exportFuncType, &importFuncType)) {
418 const Import& import = FindImportFunction(moduleMeta().imports, i);
419 UniqueChars importModuleName = import.module.toQuotedString(cx);
420 UniqueChars importFieldName = import.field.toQuotedString(cx);
421 if (!importFieldName || !importModuleName) {
422 ReportOutOfMemory(cx);
423 return false;
424 }
425 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
426 JSMSG_WASM_BAD_IMPORT_SIG,
427 importModuleName.get(), importFieldName.get());
428 return false;
429 }
430 }
431
432 return true;
433 }
434
435 template <typename T>
436 static bool CheckLimits(JSContext* cx, T declaredMin,
437 const mozilla::Maybe<T>& declaredMax, T defaultMax,
438 T actualLength, const mozilla::Maybe<T>& actualMax,
439 bool isAsmJS, const char* kind) {
440 if (isAsmJS) {
441 MOZ_ASSERT(actualLength >= declaredMin);
442 MOZ_ASSERT(!declaredMax);
443 MOZ_ASSERT(actualLength == actualMax.value());
444 return true;
445 }
446
447 if (actualLength < declaredMin ||
448 actualLength > declaredMax.valueOr(defaultMax)) {
449 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
450 JSMSG_WASM_BAD_IMP_SIZE, kind);
451 return false;
452 }
453
454 if ((actualMax && declaredMax && *actualMax > *declaredMax) ||
455 (!actualMax && declaredMax)) {
456 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
457 JSMSG_WASM_BAD_IMP_MAX, kind);
458 return false;
459 }
460
461 return true;
462 }
463
464 static bool CheckSharing(JSContext* cx, bool declaredShared, bool isShared) {
465 if (isShared &&
466 !cx->realm()->creationOptions().getSharedMemoryAndAtomicsEnabled()) {
467 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
468 JSMSG_WASM_NO_SHMEM_LINK);
469 return false;
470 }
471
472 if (declaredShared && !isShared) {
473 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
474 JSMSG_WASM_IMP_SHARED_REQD);
475 return false;
476 }
477
478 if (!declaredShared && isShared) {
479 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
480 JSMSG_WASM_IMP_SHARED_BANNED);
481 return false;
482 }
483
484 return true;
485 }
486
487 // asm.js module instantiation supplies its own buffer, but for wasm, create and
488 // initialize the buffer if one is requested. Either way, the buffer is wrapped
489 // in a WebAssembly.Memory object which is what the Instance stores.
490 bool Module::instantiateMemories(
491 JSContext* cx, const WasmMemoryObjectVector& memoryImports,
492 MutableHandle<WasmMemoryObjectVector> memoryObjs) const {
493 for (uint32_t memoryIndex = 0; memoryIndex < codeMeta().memories.length();
494 memoryIndex++) {
495 const MemoryDesc& desc = codeMeta().memories[memoryIndex];
496
497 Rooted<WasmMemoryObject*> memory(cx);
498 if (memoryIndex < memoryImports.length()) {
499 memory = memoryImports[memoryIndex];
500 MOZ_ASSERT_IF(codeMeta().isAsmJS(),
501 memory->buffer().isPreparedForAsmJS());
502 MOZ_ASSERT_IF(!codeMeta().isAsmJS(), memory->buffer().isWasm());
503
504 if (memory->addressType() != desc.addressType()) {
505 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
506 JSMSG_WASM_BAD_IMP_ADDRESS, "memory",
507 ToString(memory->addressType()));
508 return false;
509 }
510
511 if (!CheckLimits(cx, desc.initialPages(), desc.maximumPages(),
512 /* defaultMax */ MaxMemoryPages(desc.addressType()),
513 /* actualLength */
514 memory->volatilePages(), memory->sourceMaxPages(),
515 codeMeta().isAsmJS(), "Memory")) {
516 return false;
517 }
518
519 if (!CheckSharing(cx, desc.isShared(), memory->isShared())) {
520 return false;
521 }
522 } else {
523 MOZ_ASSERT(!codeMeta().isAsmJS());
524
525 if (desc.initialPages() > MaxMemoryPages(desc.addressType())) {
526 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
527 JSMSG_WASM_MEM_IMP_LIMIT);
528 return false;
529 }
530
531 Rooted<ArrayBufferObjectMaybeShared*> buffer(cx,
532 CreateWasmBuffer(cx, desc));
533 if (!buffer) {
534 return false;
535 }
536
537 RootedObject proto(cx, &cx->global()->getPrototype(JSProto_WasmMemory));
538 memory = WasmMemoryObject::create(
539 cx, buffer, IsHugeMemoryEnabled(desc.addressType()), proto);
540 if (!memory) {
541 return false;
542 }
543 }
544
545 MOZ_RELEASE_ASSERT(codeMeta().isAsmJS() ||
546 memory->isHuge() ==
547 IsHugeMemoryEnabled(desc.addressType()));
548
549 if (!memoryObjs.get().append(memory)) {
550 ReportOutOfMemory(cx);
551 return false;
552 }
553 }
554 return true;
555 }
556
557 bool Module::instantiateTags(JSContext* cx,
558 WasmTagObjectVector& tagObjs) const {
559 size_t tagLength = codeMeta().tags.length();
560 if (tagLength == 0) {
561 return true;
562 }
563 size_t importedTagsLength = tagObjs.length();
564 if (tagObjs.length() <= tagLength && !tagObjs.resize(tagLength)) {
565 ReportOutOfMemory(cx);
566 return false;
567 }
568
569 uint32_t tagIndex = 0;
570 RootedObject proto(cx, &cx->global()->getPrototype(JSProto_WasmTag));
571 for (const TagDesc& desc : codeMeta().tags) {
572 if (tagIndex >= importedTagsLength) {
573 Rooted<WasmTagObject*> tagObj(
574 cx, WasmTagObject::create(cx, desc.type, proto));
575 if (!tagObj) {
576 return false;
577 }
578 tagObjs[tagIndex] = tagObj;
579 }
580 tagIndex++;
581 }
582 return true;
583 }
584
585 bool Module::instantiateImportedTable(JSContext* cx, const TableDesc& td,
586 Handle<WasmTableObject*> tableObj,
587 WasmTableObjectVector* tableObjs,
588 SharedTableVector* tables) const {
589 MOZ_ASSERT(tableObj);
590 MOZ_ASSERT(!codeMeta().isAsmJS());
591
592 Table& table = tableObj->table();
593 if (table.addressType() != td.addressType()) {
594 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
595 JSMSG_WASM_BAD_IMP_ADDRESS, "table",
596 ToString(tableObj->table().addressType()));
597 return false;
598 }
599 if (!CheckLimits(cx, /*declaredMin=*/td.initialLength(),
600 /*declaredMax=*/td.maximumLength(),
601 /*defaultMax=*/MaxTableElemsValidation(td.addressType()),
602 /*actualLength=*/uint64_t(table.length()),
603 /*actualMax=*/table.maximum(), codeMeta().isAsmJS(),
604 "Table")) {
605 return false;
606 }
607
608 if (!tables->append(&table)) {
609 ReportOutOfMemory(cx);
610 return false;
611 }
612
613 if (!tableObjs->append(tableObj)) {
614 ReportOutOfMemory(cx);
615 return false;
616 }
617
618 return true;
619 }
620
621 bool Module::instantiateLocalTable(JSContext* cx, const TableDesc& td,
622 WasmTableObjectVector* tableObjs,
623 SharedTableVector* tables) const {
624 if (td.initialLength() > MaxTableElemsRuntime) {
625 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
626 JSMSG_WASM_TABLE_IMP_LIMIT);
627 return false;
628 }
629
630 SharedTable table;
631 Rooted<WasmTableObject*> tableObj(cx);
632 if (td.isExported) {
633 RootedObject proto(cx, &cx->global()->getPrototype(JSProto_WasmTable));
634 tableObj.set(WasmTableObject::create(cx, td.limits, td.elemType, proto));
635 if (!tableObj) {
636 return false;
637 }
638 table = &tableObj->table();
639 } else {
640 table = Table::create(cx, td, /* Handle<WasmTableObject*> = */ nullptr);
641 if (!table) {
642 return false;
643 }
644 }
645
646 // Note, appending a null pointer for non-exported local tables.
647 if (!tableObjs->append(tableObj.get())) {
648 ReportOutOfMemory(cx);
649 return false;
650 }
651
652 if (!tables->emplaceBack(table)) {
653 ReportOutOfMemory(cx);
654 return false;
655 }
656
657 return true;
658 }
659
660 bool Module::instantiateTables(JSContext* cx,
661 const WasmTableObjectVector& tableImports,
662 MutableHandle<WasmTableObjectVector> tableObjs,
663 SharedTableVector* tables) const {
664 uint32_t tableIndex = 0;
665 for (const TableDesc& td : codeMeta().tables) {
666 if (tableIndex < tableImports.length()) {
667 Rooted<WasmTableObject*> tableObj(cx, tableImports[tableIndex]);
668
669 if (!instantiateImportedTable(cx, td, tableObj, &tableObjs.get(),
670 tables)) {
671 return false;
672 }
673 } else {
674 if (!instantiateLocalTable(cx, td, &tableObjs.get(), tables)) {
675 return false;
676 }
677 }
678 tableIndex++;
679 }
680 return true;
681 }
682
683 static bool EnsureExportedGlobalObject(JSContext* cx,
684 const ValVector& globalImportValues,
685 size_t globalIndex,
686 const GlobalDesc& global,
687 WasmGlobalObjectVector& globalObjs) {
688 if (globalIndex < globalObjs.length() && globalObjs[globalIndex]) {
689 return true;
690 }
691
692 RootedVal val(cx);
693 if (global.kind() == GlobalKind::Import) {
694 // If this is an import, then this must be a constant global that was
695 // provided without a global object. We must initialize it with the
696 // provided value while we still can differentiate this case.
697 MOZ_ASSERT(!global.isMutable());
698 val.set(Val(globalImportValues[globalIndex]));
699 } else {
700 // If this is not an import, then the initial value will be set by
701 // Instance::init() for indirect globals or else by CreateExportObject().
702 // In either case, we initialize with a default value here.
703 val.set(Val(global.type()));
704 }
705
706 RootedObject proto(cx, &cx->global()->getPrototype(JSProto_WasmGlobal));
707 Rooted<WasmGlobalObject*> go(
708 cx, WasmGlobalObject::create(cx, val, global.isMutable(), proto));
709 if (!go) {
710 return false;
711 }
712
713 if (globalObjs.length() <= globalIndex &&
714 !globalObjs.resize(globalIndex + 1)) {
715 ReportOutOfMemory(cx);
716 return false;
717 }
718
719 globalObjs[globalIndex] = go;
720 return true;
721 }
722
723 bool Module::instantiateGlobals(JSContext* cx,
724 const ValVector& globalImportValues,
725 WasmGlobalObjectVector& globalObjs) const {
726 // If there are exported globals that aren't in globalObjs because they
727 // originate in this module or because they were immutable imports that came
728 // in as primitive values then we must create cells in the globalObjs for
729 // them here, as WasmInstanceObject::create() and CreateExportObject() will
730 // need the cells to exist.
731
732 const GlobalDescVector& globals = codeMeta().globals;
733
734 for (const Export& exp : moduleMeta().exports) {
735 if (exp.kind() != DefinitionKind::Global) {
736 continue;
737 }
738 unsigned globalIndex = exp.globalIndex();
739 const GlobalDesc& global = globals[globalIndex];
740 if (!EnsureExportedGlobalObject(cx, globalImportValues, globalIndex, global,
741 globalObjs)) {
742 return false;
743 }
744 }
745
746 // Imported globals that are not re-exported may also have received only a
747 // primitive value; these globals are always immutable. Assert that we do
748 // not need to create any additional Global objects for such imports.
749
750 #ifdef DEBUG
751 size_t numGlobalImports = 0;
752 for (const Import& import : moduleMeta().imports) {
753 if (import.kind != DefinitionKind::Global) {
754 continue;
755 }
756 size_t globalIndex = numGlobalImports++;
757 const GlobalDesc& global = globals[globalIndex];
758 MOZ_ASSERT(global.importIndex() == globalIndex);
759 MOZ_ASSERT_IF(global.isIndirect(),
760 globalIndex < globalObjs.length() || globalObjs[globalIndex]);
761 }
762 MOZ_ASSERT_IF(!codeMeta().isAsmJS(),
763 numGlobalImports == globals.length() ||
764 !globals[numGlobalImports].isImport());
765 #endif
766 return true;
767 }
768
769 static bool GetGlobalExport(JSContext* cx,
770 Handle<WasmInstanceObject*> instanceObj,
771 const JSObjectVector& funcImports,
772 const GlobalDesc& global, uint32_t globalIndex,
773 const ValVector& globalImportValues,
774 const WasmGlobalObjectVector& globalObjs,
775 MutableHandleValue val) {
776 // A global object for this index is guaranteed to exist by
777 // instantiateGlobals.
778 Rooted<WasmGlobalObject*> globalObj(cx, globalObjs[globalIndex]);
779 val.setObject(*globalObj);
780
781 // We are responsible to set the initial value of the global object here if
782 // it's not imported or indirect. Imported global objects have their initial
783 // value set by their defining module, or are set by
784 // EnsureExportedGlobalObject when a constant value is provided as an import.
785 // Indirect exported globals that are not imported, are initialized in
786 // Instance::init.
787 if (global.isIndirect() || global.isImport()) {
788 return true;
789 }
790
791 // This must be an exported immutable global defined in this module. The
792 // instance either has compiled the value into the code or has its own copy
793 // in its global data area. Either way, we must initialize the global object
794 // with the same initial value.
795 MOZ_ASSERT(!global.isMutable());
796 MOZ_RELEASE_ASSERT(!global.isImport());
797 RootedVal globalVal(cx);
798 instanceObj->instance().constantGlobalGet(globalIndex, &globalVal);
799 globalObj->setVal(globalVal);
800 return true;
801 }
802
803 static bool CreateExportObject(
804 JSContext* cx, Handle<WasmInstanceObject*> instanceObj,
805 const JSObjectVector& funcImports, const WasmTableObjectVector& tableObjs,
806 const WasmMemoryObjectVector& memoryObjs,
807 const WasmTagObjectVector& tagObjs, const ValVector& globalImportValues,
808 const WasmGlobalObjectVector& globalObjs, const ExportVector& exports) {
809 Instance& instance = instanceObj->instance();
810 const CodeMetadata& codeMeta = instance.codeMeta();
811 const GlobalDescVector& globals = codeMeta.globals;
812
813 if (codeMeta.isAsmJS() && exports.length() == 1 &&
814 exports[0].fieldName().isEmpty()) {
815 RootedFunction func(cx);
816 if (!instance.getExportedFunction(cx, exports[0].funcIndex(), &func)) {
817 return false;
818 }
819 instanceObj->initExportsObj(*func.get());
820 return true;
821 }
822
823 RootedObject exportObj(cx);
824 uint8_t propertyAttr = JSPROP_ENUMERATE;
825
826 if (codeMeta.isAsmJS()) {
827 exportObj = NewPlainObject(cx);
828 } else {
829 exportObj = NewPlainObjectWithProto(cx, nullptr);
830 propertyAttr |= JSPROP_READONLY | JSPROP_PERMANENT;
831 }
832 if (!exportObj) {
833 return false;
834 }
835
836 for (const Export& exp : exports) {
837 JSAtom* atom = exp.fieldName().toAtom(cx);
838 if (!atom) {
839 return false;
840 }
841
842 RootedId id(cx, AtomToId(atom));
843 RootedValue val(cx);
844 switch (exp.kind()) {
845 case DefinitionKind::Function: {
846 RootedFunction func(cx);
847 if (!instance.getExportedFunction(cx, exp.funcIndex(), &func)) {
848 return false;
849 }
850 val = ObjectValue(*func);
851 break;
852 }
853 case DefinitionKind::Table: {
854 val = ObjectValue(*tableObjs[exp.tableIndex()]);
855 break;
856 }
857 case DefinitionKind::Memory: {
858 val = ObjectValue(*memoryObjs[exp.memoryIndex()]);
859 break;
860 }
861 case DefinitionKind::Global: {
862 const GlobalDesc& global = globals[exp.globalIndex()];
863 if (!GetGlobalExport(cx, instanceObj, funcImports, global,
864 exp.globalIndex(), globalImportValues, globalObjs,
865 &val)) {
866 return false;
867 }
868 break;
869 }
870 case DefinitionKind::Tag: {
871 val = ObjectValue(*tagObjs[exp.tagIndex()]);
872 break;
873 }
874 }
875
876 if (!JS_DefinePropertyById(cx, exportObj, id, val, propertyAttr)) {
877 return false;
878 }
879 }
880
881 if (!codeMeta.isAsmJS()) {
882 if (!PreventExtensions(cx, exportObj)) {
883 return false;
884 }
885 }
886
887 instanceObj->initExportsObj(*exportObj);
888 return true;
889 }
890
891 bool Module::instantiate(JSContext* cx, ImportValues& imports,
892 HandleObject instanceProto,
893 MutableHandle<WasmInstanceObject*> instance) const {
894 MOZ_RELEASE_ASSERT(cx->wasm().haveSignalHandlers);
895
896 if (!instantiateFunctions(cx, imports.funcs)) {
897 return false;
898 }
899
900 Rooted<WasmMemoryObjectVector> memories(cx);
901 if (!instantiateMemories(cx, imports.memories, &memories)) {
902 return false;
903 }
904
905 // Note that the following will extend imports.exceptionObjs with wrappers for
906 // the local (non-imported) exceptions of the module.
907 // The resulting vector is sparse, i.e., it will be null in slots that contain
908 // exceptions that are neither exported or imported.
909 // On the contrary, all the slots of exceptionTags will be filled with
910 // unique tags.
911
912 if (!instantiateTags(cx, imports.tagObjs)) {
913 return false;
914 }
915
916 // Note that tableObjs is sparse: it will be null in slots that contain
917 // tables that are neither exported nor imported.
918
919 Rooted<WasmTableObjectVector> tableObjs(cx);
920 SharedTableVector tables;
921 if (!instantiateTables(cx, imports.tables, &tableObjs, &tables)) {
922 return false;
923 }
924
925 if (!instantiateGlobals(cx, imports.globalValues, imports.globalObjs)) {
926 return false;
927 }
928
929 UniqueDebugState maybeDebug;
930 if (code().debugEnabled()) {
931 maybeDebug = cx->make_unique<DebugState>(*code_, *this);
932 if (!maybeDebug) {
933 ReportOutOfMemory(cx);
934 return false;
935 }
936 }
937
938 instance.set(WasmInstanceObject::create(
939 cx, code_, moduleMeta().dataSegments, moduleMeta().elemSegments,
940 codeMeta().instanceDataLength, memories, std::move(tables), imports.funcs,
941 codeMeta().globals, imports.globalValues, imports.globalObjs,
942 imports.tagObjs, instanceProto, std::move(maybeDebug)));
943 if (!instance) {
944 return false;
945 }
946
947 if (!CreateExportObject(cx, instance, imports.funcs, tableObjs.get(),
948 memories.get(), imports.tagObjs, imports.globalValues,
949 imports.globalObjs, moduleMeta().exports)) {
950 return false;
951 }
952
953 // Register the instance with the Realm so that it can find out about global
954 // events like profiling being enabled in the realm. Registration does not
955 // require a fully-initialized instance and must precede initSegments as the
956 // final pre-requisite for a live instance.
957
958 if (!cx->realm()->wasm.registerInstance(cx, instance)) {
959 ReportOutOfMemory(cx);
960 return false;
961 }
962
963 // Perform initialization as the final step after the instance is fully
964 // constructed since this can make the instance live to content (even if the
965 // start function fails).
966
967 if (!instance->instance().initSegments(cx, moduleMeta().dataSegments,
968 moduleMeta().elemSegments)) {
969 return false;
970 }
971
972 // Now that the instance is fully live and initialized, the start function.
973 // Note that failure may cause instantiation to throw, but the instance may
974 // still be live via edges created by initSegments or the start function.
975
976 if (codeMeta().startFuncIndex) {
977 FixedInvokeArgs<0> args(cx);
978 if (!instance->instance().callExport(cx, *codeMeta().startFuncIndex,
979 args)) {
980 return false;
981 }
982 }
983
984 JSUseCounter useCounter =
985 codeMeta().isAsmJS() ? JSUseCounter::ASMJS : JSUseCounter::WASM;
986 cx->runtime()->setUseCounter(instance, useCounter);
987 SetUseCountersForFeatureUsage(cx, instance, moduleMeta().featureUsage);
988
989 // Warn for deprecated features. Don't do this with differential testing as
990 // that will think these warnings are significant.
991 if (!js::SupportDifferentialTesting()) {
992 // Warn if the user is using the legacy exceptions proposal.
993 if (moduleMeta().featureUsage & FeatureUsage::LegacyExceptions) {
994 if (!js::WarnNumberASCII(cx, JSMSG_WASM_LEGACY_EXCEPTIONS_DEPRECATED)) {
995 if (cx->isExceptionPending()) {
996 cx->clearPendingException();
997 }
998 }
999 }
1000
1001 // Warn if the user is using asm.js still.
1002 if (JS::Prefs::warn_asmjs_deprecation() && codeMeta().isAsmJS()) {
1003 if (!js::WarnNumberASCII(cx, JSMSG_USE_ASM_DEPRECATED)) {
1004 if (cx->isExceptionPending()) {
1005 cx->clearPendingException();
1006 }
1007 }
1008 }
1009 }
1010
1011 if (cx->options().testWasmAwaitTier2() &&
1012 code().mode() != CompileMode::LazyTiering) {
1013 testingBlockOnTier2Complete();
1014 }
1015
1016 return true;
1017 }