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