1/*
2 * Copyright (C) 2016-2019 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#include "config.h"
27#include "WasmBBQPlan.h"
28
29#if ENABLE(WEBASSEMBLY)
30
31#include "B3Compilation.h"
32#include "WasmAirIRGenerator.h"
33#include "WasmB3IRGenerator.h"
34#include "WasmBinding.h"
35#include "WasmCallee.h"
36#include "WasmCallingConvention.h"
37#include "WasmFaultSignalHandler.h"
38#include "WasmMemory.h"
39#include "WasmModuleParser.h"
40#include "WasmSignatureInlines.h"
41#include "WasmTierUpCount.h"
42#include "WasmValidate.h"
43#include <wtf/DataLog.h>
44#include <wtf/Locker.h>
45#include <wtf/MonotonicTime.h>
46#include <wtf/StdLibExtras.h>
47#include <wtf/SystemTracing.h>
48#include <wtf/text/StringConcatenateNumbers.h>
49
50namespace JSC { namespace Wasm {
51
52namespace WasmBBQPlanInternal {
53static const bool verbose = false;
54}
55
56BBQPlan::BBQPlan(Context* context, Ref<ModuleInformation> info, AsyncWork work, CompletionTask&& task, CreateEmbedderWrapper&& createEmbedderWrapper, ThrowWasmException throwWasmException)
57 : Base(context, WTFMove(info), WTFMove(task), WTFMove(createEmbedderWrapper), throwWasmException)
58 , m_state(State::Validated)
59 , m_asyncWork(work)
60{
61}
62
63BBQPlan::BBQPlan(Context* context, Vector<uint8_t>&& source, AsyncWork work, CompletionTask&& task, CreateEmbedderWrapper&& createEmbedderWrapper, ThrowWasmException throwWasmException)
64 : Base(context, ModuleInformation::create(), WTFMove(task), WTFMove(createEmbedderWrapper), throwWasmException)
65 , m_source(WTFMove(source))
66 , m_state(State::Initial)
67 , m_asyncWork(work)
68{
69}
70
71BBQPlan::BBQPlan(Context* context, AsyncWork work, CompletionTask&& task)
72 : Base(context, WTFMove(task))
73 , m_state(State::Initial)
74 , m_asyncWork(work)
75{
76}
77
78const char* BBQPlan::stateString(State state)
79{
80 switch (state) {
81 case State::Initial: return "Initial";
82 case State::Validated: return "Validated";
83 case State::Prepared: return "Prepared";
84 case State::Compiled: return "Compiled";
85 case State::Completed: return "Completed";
86 }
87 RELEASE_ASSERT_NOT_REACHED();
88}
89
90void BBQPlan::moveToState(State state)
91{
92 ASSERT(state >= m_state);
93 dataLogLnIf(WasmBBQPlanInternal::verbose && state != m_state, "moving to state: ", stateString(state), " from state: ", stateString(m_state));
94 m_state = state;
95}
96
97bool BBQPlan::parseAndValidateModule(const uint8_t* source, size_t sourceLength)
98{
99 if (m_state != State::Initial)
100 return true;
101
102 dataLogLnIf(WasmBBQPlanInternal::verbose, "starting validation");
103 MonotonicTime startTime;
104 if (WasmBBQPlanInternal::verbose || Options::reportCompileTimes())
105 startTime = MonotonicTime::now();
106
107 {
108 ModuleParser moduleParser(source, sourceLength, m_moduleInformation);
109 auto parseResult = moduleParser.parse();
110 if (!parseResult) {
111 Base::fail(holdLock(m_lock), WTFMove(parseResult.error()));
112 return false;
113 }
114 }
115
116 const auto& functions = m_moduleInformation->functions;
117 for (unsigned functionIndex = 0; functionIndex < functions.size(); ++functionIndex) {
118 const auto& function = functions[functionIndex];
119 dataLogLnIf(WasmBBQPlanInternal::verbose, "Processing function starting at: ", function.start, " and ending at: ", function.end);
120 size_t functionLength = function.end - function.start;
121 ASSERT(functionLength <= sourceLength);
122 ASSERT(functionLength == function.data.size());
123 SignatureIndex signatureIndex = m_moduleInformation->internalFunctionSignatureIndices[functionIndex];
124 const Signature& signature = SignatureInformation::get(signatureIndex);
125
126 auto validationResult = validateFunction(function.data.data(), function.data.size(), signature, m_moduleInformation.get());
127 if (!validationResult) {
128 if (WasmBBQPlanInternal::verbose) {
129 for (unsigned i = 0; i < functionLength; ++i)
130 dataLog(RawPointer(reinterpret_cast<void*>(function.data[i])), ", ");
131 dataLogLn();
132 }
133 Base::fail(holdLock(m_lock), makeString(validationResult.error(), ", in function at index ", String::number(functionIndex))); // FIXME make this an Expected.
134 return false;
135 }
136 }
137
138 if (WasmBBQPlanInternal::verbose || Options::reportCompileTimes())
139 dataLogLn("Took ", (MonotonicTime::now() - startTime).microseconds(), " us to validate module");
140
141 moveToState(State::Validated);
142 if (m_asyncWork == Validation)
143 complete(holdLock(m_lock));
144 return true;
145}
146
147void BBQPlan::prepare()
148{
149 ASSERT(m_state == State::Validated);
150 dataLogLnIf(WasmBBQPlanInternal::verbose, "Starting preparation");
151
152 auto tryReserveCapacity = [this] (auto& vector, size_t size, const char* what) {
153 if (UNLIKELY(!vector.tryReserveCapacity(size))) {
154 fail(holdLock(m_lock), WTF::makeString("Failed allocating enough space for ", size, what));
155 return false;
156 }
157 return true;
158 };
159
160 const auto& functions = m_moduleInformation->functions;
161 if (!tryReserveCapacity(m_wasmToWasmExitStubs, m_moduleInformation->importFunctionSignatureIndices.size(), " WebAssembly to JavaScript stubs")
162 || !tryReserveCapacity(m_unlinkedWasmToWasmCalls, functions.size(), " unlinked WebAssembly to WebAssembly calls")
163 || !tryReserveCapacity(m_wasmInternalFunctions, functions.size(), " WebAssembly functions")
164 || !tryReserveCapacity(m_compilationContexts, functions.size(), " compilation contexts")
165 || !tryReserveCapacity(m_tierUpCounts, functions.size(), " tier-up counts"))
166 return;
167
168 m_unlinkedWasmToWasmCalls.resize(functions.size());
169 m_wasmInternalFunctions.resize(functions.size());
170 m_compilationContexts.resize(functions.size());
171 m_tierUpCounts.resize(functions.size());
172
173 for (unsigned importIndex = 0; importIndex < m_moduleInformation->imports.size(); ++importIndex) {
174 Import* import = &m_moduleInformation->imports[importIndex];
175 if (import->kind != ExternalKind::Function)
176 continue;
177 unsigned importFunctionIndex = m_wasmToWasmExitStubs.size();
178 dataLogLnIf(WasmBBQPlanInternal::verbose, "Processing import function number ", importFunctionIndex, ": ", makeString(import->module), ": ", makeString(import->field));
179 auto binding = wasmToWasm(importFunctionIndex);
180 if (UNLIKELY(!binding)) {
181 switch (binding.error()) {
182 case BindingFailure::OutOfMemory:
183 return fail(holdLock(m_lock), makeString("Out of executable memory at import ", String::number(importIndex)));
184 }
185 RELEASE_ASSERT_NOT_REACHED();
186 }
187 m_wasmToWasmExitStubs.uncheckedAppend(binding.value());
188 }
189
190 const uint32_t importFunctionCount = m_moduleInformation->importFunctionCount();
191 for (const auto& exp : m_moduleInformation->exports) {
192 if (exp.kindIndex >= importFunctionCount)
193 m_exportedFunctionIndices.add(exp.kindIndex - importFunctionCount);
194 }
195
196 for (const auto& element : m_moduleInformation->elements) {
197 for (const uint32_t elementIndex : element.functionIndices) {
198 if (elementIndex >= importFunctionCount)
199 m_exportedFunctionIndices.add(elementIndex - importFunctionCount);
200 }
201 }
202
203 if (m_moduleInformation->startFunctionIndexSpace && m_moduleInformation->startFunctionIndexSpace >= importFunctionCount)
204 m_exportedFunctionIndices.add(*m_moduleInformation->startFunctionIndexSpace - importFunctionCount);
205
206 moveToState(State::Prepared);
207}
208
209// We don't have a semaphore class... and this does kinda interesting things.
210class BBQPlan::ThreadCountHolder {
211public:
212 ThreadCountHolder(BBQPlan& plan)
213 : m_plan(plan)
214 {
215 LockHolder locker(m_plan.m_lock);
216 m_plan.m_numberOfActiveThreads++;
217 }
218
219 ~ThreadCountHolder()
220 {
221 LockHolder locker(m_plan.m_lock);
222 m_plan.m_numberOfActiveThreads--;
223
224 if (!m_plan.m_numberOfActiveThreads && !m_plan.hasWork())
225 m_plan.complete(locker);
226 }
227
228 BBQPlan& m_plan;
229};
230
231void BBQPlan::compileFunctions(CompilationEffort effort)
232{
233 ASSERT(m_state >= State::Prepared);
234 dataLogLnIf(WasmBBQPlanInternal::verbose, "Starting compilation");
235
236 if (!hasWork())
237 return;
238
239 Optional<TraceScope> traceScope;
240 if (Options::useTracePoints())
241 traceScope.emplace(WebAssemblyCompileStart, WebAssemblyCompileEnd);
242 ThreadCountHolder holder(*this);
243
244 size_t bytesCompiled = 0;
245 const auto& functions = m_moduleInformation->functions;
246 while (true) {
247 if (effort == Partial && bytesCompiled >= Options::webAssemblyPartialCompileLimit())
248 return;
249
250 uint32_t functionIndex;
251 {
252 auto locker = holdLock(m_lock);
253 if (m_currentIndex >= functions.size()) {
254 if (hasWork())
255 moveToState(State::Compiled);
256 return;
257 }
258 functionIndex = m_currentIndex;
259 ++m_currentIndex;
260 }
261
262 const auto& function = functions[functionIndex];
263 SignatureIndex signatureIndex = m_moduleInformation->internalFunctionSignatureIndices[functionIndex];
264 const Signature& signature = SignatureInformation::get(signatureIndex);
265 unsigned functionIndexSpace = m_wasmToWasmExitStubs.size() + functionIndex;
266 ASSERT_UNUSED(functionIndexSpace, m_moduleInformation->signatureIndexFromFunctionIndexSpace(functionIndexSpace) == signatureIndex);
267 ASSERT(validateFunction(function.data.data(), function.data.size(), signature, m_moduleInformation.get()));
268
269 m_unlinkedWasmToWasmCalls[functionIndex] = Vector<UnlinkedWasmToWasmCall>();
270 TierUpCount* tierUp = Options::useBBQTierUpChecks() ? &m_tierUpCounts[functionIndex] : nullptr;
271 Expected<std::unique_ptr<InternalFunction>, String> parseAndCompileResult;
272 if (Options::wasmBBQUsesAir())
273 parseAndCompileResult = parseAndCompileAir(m_compilationContexts[functionIndex], function.data.data(), function.data.size(), signature, m_unlinkedWasmToWasmCalls[functionIndex], m_moduleInformation.get(), m_mode, functionIndex, tierUp, m_throwWasmException);
274 else
275 parseAndCompileResult = parseAndCompile(m_compilationContexts[functionIndex], function.data.data(), function.data.size(), signature, m_unlinkedWasmToWasmCalls[functionIndex], m_moduleInformation.get(), m_mode, CompilationMode::BBQMode, functionIndex, tierUp, m_throwWasmException);
276
277 if (UNLIKELY(!parseAndCompileResult)) {
278 auto locker = holdLock(m_lock);
279 if (!m_errorMessage) {
280 // Multiple compiles could fail simultaneously. We arbitrarily choose the first.
281 fail(locker, makeString(parseAndCompileResult.error(), ", in function at index ", String::number(functionIndex))); // FIXME make this an Expected.
282 }
283 m_currentIndex = functions.size();
284 return;
285 }
286
287 m_wasmInternalFunctions[functionIndex] = WTFMove(*parseAndCompileResult);
288
289 if (m_exportedFunctionIndices.contains(functionIndex)) {
290 auto locker = holdLock(m_lock);
291 auto result = m_embedderToWasmInternalFunctions.add(functionIndex, m_createEmbedderWrapper(m_compilationContexts[functionIndex], signature, &m_unlinkedWasmToWasmCalls[functionIndex], m_moduleInformation.get(), m_mode, functionIndex));
292 ASSERT_UNUSED(result, result.isNewEntry);
293 }
294
295 bytesCompiled += function.data.size();
296 }
297}
298
299void BBQPlan::complete(const AbstractLocker& locker)
300{
301 ASSERT(m_state != State::Compiled || m_currentIndex >= m_moduleInformation->functions.size());
302 dataLogLnIf(WasmBBQPlanInternal::verbose, "Starting Completion");
303
304 if (!failed() && m_state == State::Compiled) {
305 for (uint32_t functionIndex = 0; functionIndex < m_moduleInformation->functions.size(); functionIndex++) {
306 CompilationContext& context = m_compilationContexts[functionIndex];
307 SignatureIndex signatureIndex = m_moduleInformation->internalFunctionSignatureIndices[functionIndex];
308 const Signature& signature = SignatureInformation::get(signatureIndex);
309 {
310 LinkBuffer linkBuffer(*context.wasmEntrypointJIT, nullptr, JITCompilationCanFail);
311 if (UNLIKELY(linkBuffer.didFailToAllocate())) {
312 Base::fail(locker, makeString("Out of executable memory in function at index ", String::number(functionIndex)));
313 return;
314 }
315
316 m_wasmInternalFunctions[functionIndex]->entrypoint.compilation = std::make_unique<B3::Compilation>(
317 FINALIZE_CODE(linkBuffer, B3CompilationPtrTag, "WebAssembly BBQ function[%i] %s", functionIndex, signature.toString().ascii().data()),
318 WTFMove(context.wasmEntrypointByproducts));
319 }
320
321 if (auto embedderToWasmInternalFunction = m_embedderToWasmInternalFunctions.get(functionIndex)) {
322 LinkBuffer linkBuffer(*context.embedderEntrypointJIT, nullptr, JITCompilationCanFail);
323 if (UNLIKELY(linkBuffer.didFailToAllocate())) {
324 Base::fail(locker, makeString("Out of executable memory in function entrypoint at index ", String::number(functionIndex)));
325 return;
326 }
327
328 embedderToWasmInternalFunction->entrypoint.compilation = std::make_unique<B3::Compilation>(
329 FINALIZE_CODE(linkBuffer, B3CompilationPtrTag, "Embedder->WebAssembly entrypoint[%i] %s", functionIndex, signature.toString().ascii().data()),
330 WTFMove(context.embedderEntrypointByproducts));
331 }
332 }
333
334 for (auto& unlinked : m_unlinkedWasmToWasmCalls) {
335 for (auto& call : unlinked) {
336 MacroAssemblerCodePtr<WasmEntryPtrTag> executableAddress;
337 if (m_moduleInformation->isImportedFunctionFromFunctionIndexSpace(call.functionIndexSpace)) {
338 // FIXME imports could have been linked in B3, instead of generating a patchpoint. This condition should be replaced by a RELEASE_ASSERT. https://bugs.webkit.org/show_bug.cgi?id=166462
339 executableAddress = m_wasmToWasmExitStubs.at(call.functionIndexSpace).code();
340 } else
341 executableAddress = m_wasmInternalFunctions.at(call.functionIndexSpace - m_moduleInformation->importFunctionCount())->entrypoint.compilation->code().retagged<WasmEntryPtrTag>();
342 MacroAssembler::repatchNearCall(call.callLocation, CodeLocationLabel<WasmEntryPtrTag>(executableAddress));
343 }
344 }
345 }
346
347 if (!isComplete()) {
348 moveToState(State::Completed);
349 runCompletionTasks(locker);
350 }
351}
352
353void BBQPlan::work(CompilationEffort effort)
354{
355 switch (m_state) {
356 case State::Initial:
357 parseAndValidateModule(m_source.data(), m_source.size());
358 if (!hasWork()) {
359 ASSERT(isComplete());
360 return;
361 }
362 FALLTHROUGH;
363 case State::Validated:
364 prepare();
365 return;
366 case State::Prepared:
367 compileFunctions(effort);
368 return;
369 default:
370 break;
371 }
372 return;
373}
374
375} } // namespace JSC::Wasm
376
377#endif // ENABLE(WEBASSEMBLY)
378