1/*
2 * Copyright (C) 2017-2018 Apple Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26#pragma once
27
28#if ENABLE(WEBASSEMBLY)
29
30#include "WasmFormat.h"
31#include "WasmMemory.h"
32#include "WasmModule.h"
33#include "WasmTable.h"
34#include "WriteBarrier.h"
35#include <wtf/BitVector.h>
36#include <wtf/RefPtr.h>
37#include <wtf/ThreadSafeRefCounted.h>
38
39namespace JSC {
40
41class LLIntOffsetsExtractor;
42class JSWebAssemblyInstance;
43
44namespace Wasm {
45
46struct Context;
47class Instance;
48
49class Instance : public ThreadSafeRefCounted<Instance>, public CanMakeWeakPtr<Instance> {
50 friend LLIntOffsetsExtractor;
51
52public:
53 using StoreTopCallFrameCallback = WTF::Function<void(void*)>;
54 using FunctionWrapperMap = HashMap<uint32_t, WriteBarrier<Unknown>, IntHash<uint32_t>, WTF::UnsignedWithZeroKeyHashTraits<uint32_t>>;
55
56 static Ref<Instance> create(Context*, Ref<Module>&&, EntryFrame** pointerToTopEntryFrame, void** pointerToActualStackLimit, StoreTopCallFrameCallback&&);
57
58 void finalizeCreation(void* owner, Ref<CodeBlock>&& codeBlock)
59 {
60 m_owner = owner;
61 m_codeBlock = WTFMove(codeBlock);
62 }
63
64 JS_EXPORT_PRIVATE ~Instance();
65
66 template<typename T> T* owner() const { return reinterpret_cast<T*>(m_owner); }
67 static ptrdiff_t offsetOfOwner() { return OBJECT_OFFSETOF(Instance, m_owner); }
68
69 size_t extraMemoryAllocated() const;
70
71 Wasm::Context* context() const { return m_context; }
72
73 Module& module() { return m_module.get(); }
74 CodeBlock* codeBlock() { return m_codeBlock.get(); }
75 Memory* memory() { return m_memory.get(); }
76 Table* table(unsigned);
77 void setTable(unsigned, Ref<Table>&&);
78
79 void* cachedMemory() const { return m_cachedMemory.getMayBeNull(cachedMemorySize()); }
80 size_t cachedMemorySize() const { return m_cachedMemorySize; }
81
82 void setMemory(Ref<Memory>&& memory)
83 {
84 m_memory = WTFMove(memory);
85 m_memory.get()->registerInstance(this);
86 updateCachedMemory();
87 }
88 void updateCachedMemory()
89 {
90 if (m_memory != nullptr) {
91 m_cachedMemory = CagedPtr<Gigacage::Primitive, void, tagCagedPtr>(memory()->memory(), memory()->size());
92 m_cachedMemorySize = memory()->size();
93 }
94 }
95
96 int32_t loadI32Global(unsigned i) const { return m_globals.get()[i].primitive; }
97 int64_t loadI64Global(unsigned i) const { return m_globals.get()[i].primitive; }
98 float loadF32Global(unsigned i) const { return bitwise_cast<float>(loadI32Global(i)); }
99 double loadF64Global(unsigned i) const { return bitwise_cast<double>(loadI64Global(i)); }
100 void setGlobal(unsigned i, int64_t bits) { m_globals.get()[i].primitive = bits; }
101 void setGlobal(unsigned, JSValue);
102 const BitVector& globalsToMark() { return m_globalsToMark; }
103 JSValue getFunctionWrapper(unsigned) const;
104 typename FunctionWrapperMap::ValuesConstIteratorRange functionWrappers() const { return m_functionWrappers.values(); }
105 void setFunctionWrapper(unsigned, JSValue);
106
107 static ptrdiff_t offsetOfMemory() { return OBJECT_OFFSETOF(Instance, m_memory); }
108 static ptrdiff_t offsetOfGlobals() { return OBJECT_OFFSETOF(Instance, m_globals); }
109 static ptrdiff_t offsetOfCachedMemory() { return OBJECT_OFFSETOF(Instance, m_cachedMemory); }
110 static ptrdiff_t offsetOfCachedMemorySize() { return OBJECT_OFFSETOF(Instance, m_cachedMemorySize); }
111 static ptrdiff_t offsetOfPointerToTopEntryFrame() { return OBJECT_OFFSETOF(Instance, m_pointerToTopEntryFrame); }
112
113 static ptrdiff_t offsetOfPointerToActualStackLimit() { return OBJECT_OFFSETOF(Instance, m_pointerToActualStackLimit); }
114 static ptrdiff_t offsetOfCachedStackLimit() { return OBJECT_OFFSETOF(Instance, m_cachedStackLimit); }
115 void* cachedStackLimit() const
116 {
117 ASSERT(*m_pointerToActualStackLimit == m_cachedStackLimit);
118 return m_cachedStackLimit;
119 }
120 void setCachedStackLimit(void* limit)
121 {
122 ASSERT(*m_pointerToActualStackLimit == limit || bitwise_cast<void*>(std::numeric_limits<uintptr_t>::max()) == limit);
123 m_cachedStackLimit = limit;
124 }
125
126 // Tail accessors.
127 static constexpr size_t offsetOfTail() { return WTF::roundUpToMultipleOf<sizeof(uint64_t)>(sizeof(Instance)); }
128 struct ImportFunctionInfo {
129 // Target instance and entrypoint are only set for wasm->wasm calls, and are otherwise nullptr. The embedder-specific logic occurs through import function.
130 Instance* targetInstance { nullptr };
131 WasmToWasmImportableFunction::LoadLocation wasmEntrypointLoadLocation { nullptr };
132 MacroAssemblerCodePtr<WasmEntryPtrTag> wasmToEmbedderStub;
133 void* importFunction { nullptr }; // In a JS embedding, this is a WriteBarrier<JSObject>.
134 };
135 unsigned numImportFunctions() const { return m_numImportFunctions; }
136 ImportFunctionInfo* importFunctionInfo(size_t importFunctionNum)
137 {
138 RELEASE_ASSERT(importFunctionNum < m_numImportFunctions);
139 return &bitwise_cast<ImportFunctionInfo*>(bitwise_cast<char*>(this) + offsetOfTail())[importFunctionNum];
140 }
141 static size_t offsetOfTargetInstance(size_t importFunctionNum) { return offsetOfTail() + importFunctionNum * sizeof(ImportFunctionInfo) + OBJECT_OFFSETOF(ImportFunctionInfo, targetInstance); }
142 static size_t offsetOfWasmEntrypointLoadLocation(size_t importFunctionNum) { return offsetOfTail() + importFunctionNum * sizeof(ImportFunctionInfo) + OBJECT_OFFSETOF(ImportFunctionInfo, wasmEntrypointLoadLocation); }
143 static size_t offsetOfWasmToEmbedderStub(size_t importFunctionNum) { return offsetOfTail() + importFunctionNum * sizeof(ImportFunctionInfo) + OBJECT_OFFSETOF(ImportFunctionInfo, wasmToEmbedderStub); }
144 static size_t offsetOfImportFunction(size_t importFunctionNum) { return offsetOfTail() + importFunctionNum * sizeof(ImportFunctionInfo) + OBJECT_OFFSETOF(ImportFunctionInfo, importFunction); }
145 template<typename T> T* importFunction(unsigned importFunctionNum) { return reinterpret_cast<T*>(&importFunctionInfo(importFunctionNum)->importFunction); }
146
147 static_assert(sizeof(ImportFunctionInfo) == WTF::roundUpToMultipleOf<sizeof(uint64_t)>(sizeof(ImportFunctionInfo)), "We rely on this for the alignment to be correct");
148 static constexpr size_t offsetOfTablePtr(unsigned numImportFunctions, unsigned i) { return offsetOfTail() + sizeof(ImportFunctionInfo) * numImportFunctions + sizeof(Table*) * i; }
149
150 void storeTopCallFrame(void* callFrame)
151 {
152 m_storeTopCallFrame(callFrame);
153 }
154
155private:
156 Instance(Context*, Ref<Module>&&, EntryFrame**, void**, StoreTopCallFrameCallback&&);
157
158 static size_t allocationSize(Checked<size_t> numImportFunctions, Checked<size_t> numTables)
159 {
160 return (offsetOfTail() + sizeof(ImportFunctionInfo) * numImportFunctions + sizeof(Table*) * numTables).unsafeGet();
161 }
162 void* m_owner { nullptr }; // In a JS embedding, this is a JSWebAssemblyInstance*.
163 Context* m_context { nullptr };
164 CagedPtr<Gigacage::Primitive, void, tagCagedPtr> m_cachedMemory;
165 size_t m_cachedMemorySize { 0 };
166 Ref<Module> m_module;
167 RefPtr<CodeBlock> m_codeBlock;
168 RefPtr<Memory> m_memory;
169
170 union GlobalValue {
171 WriteBarrier<Unknown> anyref;
172 uint64_t primitive;
173 };
174 MallocPtr<GlobalValue> m_globals;
175 FunctionWrapperMap m_functionWrappers;
176 BitVector m_globalsToMark;
177 EntryFrame** m_pointerToTopEntryFrame { nullptr };
178 void** m_pointerToActualStackLimit { nullptr };
179 void* m_cachedStackLimit { bitwise_cast<void*>(std::numeric_limits<uintptr_t>::max()) };
180 StoreTopCallFrameCallback m_storeTopCallFrame;
181 unsigned m_numImportFunctions { 0 };
182};
183
184} } // namespace JSC::Wasm
185
186#endif // ENABLE(WEBASSEMBLY)
187