WebAssembly.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. /*
  2. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  3. * Copyright (c) 2023, Tim Flynn <trflynn89@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/MemoryStream.h>
  8. #include <AK/ScopeGuard.h>
  9. #include <LibJS/Runtime/Array.h>
  10. #include <LibJS/Runtime/ArrayBuffer.h>
  11. #include <LibJS/Runtime/BigInt.h>
  12. #include <LibJS/Runtime/DataView.h>
  13. #include <LibJS/Runtime/IteratorOperations.h>
  14. #include <LibJS/Runtime/NativeFunction.h>
  15. #include <LibJS/Runtime/Object.h>
  16. #include <LibJS/Runtime/Promise.h>
  17. #include <LibJS/Runtime/ThrowableStringBuilder.h>
  18. #include <LibJS/Runtime/TypedArray.h>
  19. #include <LibJS/Runtime/VM.h>
  20. #include <LibWasm/AbstractMachine/Validator.h>
  21. #include <LibWeb/WebAssembly/Instance.h>
  22. #include <LibWeb/WebAssembly/Memory.h>
  23. #include <LibWeb/WebAssembly/Module.h>
  24. #include <LibWeb/WebAssembly/Table.h>
  25. #include <LibWeb/WebAssembly/WebAssembly.h>
  26. namespace Web::WebAssembly {
  27. namespace Detail {
  28. Vector<NonnullOwnPtr<CompiledWebAssemblyModule>> s_compiled_modules;
  29. Vector<NonnullOwnPtr<Wasm::ModuleInstance>> s_instantiated_modules;
  30. Vector<ModuleCache> s_module_caches;
  31. GlobalModuleCache s_global_cache;
  32. Wasm::AbstractMachine s_abstract_machine;
  33. }
  34. void visit_edges(JS::Cell::Visitor& visitor)
  35. {
  36. for (auto& entry : Detail::s_global_cache.function_instances)
  37. visitor.visit(entry.value);
  38. for (auto& module_cache : Detail::s_module_caches) {
  39. for (auto& entry : module_cache.function_instances)
  40. visitor.visit(entry.value);
  41. for (auto& entry : module_cache.memory_instances)
  42. visitor.visit(entry.value);
  43. for (auto& entry : module_cache.table_instances)
  44. visitor.visit(entry.value);
  45. }
  46. }
  47. // https://webassembly.github.io/spec/js-api/#dom-webassembly-validate
  48. bool validate(JS::VM& vm, JS::Handle<JS::Object>& bytes)
  49. {
  50. // 1. Let stableBytes be a copy of the bytes held by the buffer bytes.
  51. // Note: There's no need to copy the bytes here as the buffer data cannot change while we're compiling the module.
  52. // 2. Compile stableBytes as a WebAssembly module and store the results as module.
  53. auto maybe_module = Detail::parse_module(vm, bytes.cell());
  54. // 3. If module is error, return false.
  55. if (maybe_module.is_error())
  56. return false;
  57. // Drop the module from the cache, we're never going to refer to it.
  58. ScopeGuard drop_from_cache { [&] { (void)Detail::s_compiled_modules.take_last(); } };
  59. // 3 continued - our "compile" step is lazy with validation, explicitly do the validation.
  60. if (Detail::s_abstract_machine.validate(Detail::s_compiled_modules[maybe_module.value()]->module).is_error())
  61. return false;
  62. // 4. Return true.
  63. return true;
  64. }
  65. // https://webassembly.github.io/spec/js-api/#dom-webassembly-compile
  66. WebIDL::ExceptionOr<JS::Value> compile(JS::VM& vm, JS::Handle<JS::Object>& bytes)
  67. {
  68. auto& realm = *vm.current_realm();
  69. // FIXME: This shouldn't block!
  70. auto module = Detail::parse_module(vm, bytes.cell());
  71. auto promise = JS::Promise::create(realm);
  72. if (module.is_error()) {
  73. promise->reject(*module.release_error().value());
  74. } else {
  75. auto module_object = MUST_OR_THROW_OOM(vm.heap().allocate<Module>(realm, realm, module.release_value()));
  76. promise->fulfill(module_object);
  77. }
  78. return promise;
  79. }
  80. // https://webassembly.github.io/spec/js-api/#dom-webassembly-instantiate
  81. WebIDL::ExceptionOr<JS::Value> instantiate(JS::VM& vm, JS::Handle<JS::Object>& bytes, Optional<JS::Handle<JS::Object>>& import_object)
  82. {
  83. // FIXME: Implement the importObject parameter.
  84. (void)import_object;
  85. auto& realm = *vm.current_realm();
  86. // FIXME: This shouldn't block!
  87. auto module = Detail::parse_module(vm, bytes.cell());
  88. auto promise = JS::Promise::create(realm);
  89. if (module.is_error()) {
  90. promise->reject(*module.release_error().value());
  91. return promise;
  92. }
  93. auto const& compiled_module = Detail::s_compiled_modules.at(module.release_value())->module;
  94. auto result = Detail::instantiate_module(vm, compiled_module);
  95. if (result.is_error()) {
  96. promise->reject(*result.release_error().value());
  97. } else {
  98. auto module_object = MUST_OR_THROW_OOM(vm.heap().allocate<Module>(realm, realm, Detail::s_compiled_modules.size() - 1));
  99. auto instance_object = MUST_OR_THROW_OOM(vm.heap().allocate<Instance>(realm, realm, result.release_value()));
  100. auto object = JS::Object::create(realm, nullptr);
  101. object->define_direct_property("module", module_object, JS::default_attributes);
  102. object->define_direct_property("instance", instance_object, JS::default_attributes);
  103. promise->fulfill(object);
  104. }
  105. return promise;
  106. }
  107. // https://webassembly.github.io/spec/js-api/#dom-webassembly-instantiate-moduleobject-importobject
  108. WebIDL::ExceptionOr<JS::Value> instantiate(JS::VM& vm, Module const& module_object, Optional<JS::Handle<JS::Object>>& import_object)
  109. {
  110. // FIXME: Implement the importObject parameter.
  111. (void)import_object;
  112. auto& realm = *vm.current_realm();
  113. auto promise = JS::Promise::create(realm);
  114. auto const& compiled_module = module_object.module();
  115. auto result = Detail::instantiate_module(vm, compiled_module);
  116. if (result.is_error()) {
  117. promise->reject(*result.release_error().value());
  118. } else {
  119. auto instance_object = MUST_OR_THROW_OOM(vm.heap().allocate<Instance>(realm, realm, result.release_value()));
  120. promise->fulfill(instance_object);
  121. }
  122. return promise;
  123. }
  124. namespace Detail {
  125. JS::ThrowCompletionOr<size_t> instantiate_module(JS::VM& vm, Wasm::Module const& module)
  126. {
  127. Wasm::Linker linker { module };
  128. HashMap<Wasm::Linker::Name, Wasm::ExternValue> resolved_imports;
  129. auto import_argument = vm.argument(1);
  130. if (!import_argument.is_undefined()) {
  131. auto import_object = TRY(import_argument.to_object(vm));
  132. dbgln("Trying to resolve stuff because import object was specified");
  133. for (Wasm::Linker::Name const& import_name : linker.unresolved_imports()) {
  134. dbgln("Trying to resolve {}::{}", import_name.module, import_name.name);
  135. auto value_or_error = import_object->get(import_name.module);
  136. if (value_or_error.is_error())
  137. break;
  138. auto value = value_or_error.release_value();
  139. auto object_or_error = value.to_object(vm);
  140. if (object_or_error.is_error())
  141. break;
  142. auto object = object_or_error.release_value();
  143. auto import_or_error = object->get(import_name.name);
  144. if (import_or_error.is_error())
  145. break;
  146. auto import_ = import_or_error.release_value();
  147. TRY(import_name.type.visit(
  148. [&](Wasm::TypeIndex index) -> JS::ThrowCompletionOr<void> {
  149. dbgln("Trying to resolve a function {}::{}, type index {}", import_name.module, import_name.name, index.value());
  150. auto& type = module.type(index);
  151. // FIXME: IsCallable()
  152. if (!import_.is_function())
  153. return {};
  154. auto& function = import_.as_function();
  155. // FIXME: If this is a function created by create_native_function(),
  156. // just extract its address and resolve to that.
  157. Wasm::HostFunction host_function {
  158. [&](auto&, auto& arguments) -> Wasm::Result {
  159. JS::MarkedVector<JS::Value> argument_values { vm.heap() };
  160. for (auto& entry : arguments)
  161. argument_values.append(to_js_value(vm, entry));
  162. auto result = TRY(JS::call(vm, function, JS::js_undefined(), move(argument_values)));
  163. if (type.results().is_empty())
  164. return Wasm::Result { Vector<Wasm::Value> {} };
  165. if (type.results().size() == 1)
  166. return Wasm::Result { Vector<Wasm::Value> { TRY(to_webassembly_value(vm, result, type.results().first())) } };
  167. auto method = TRY(result.get_method(vm, vm.names.iterator));
  168. if (method == JS::js_undefined())
  169. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotIterable, TRY_OR_THROW_OOM(vm, result.to_string_without_side_effects()));
  170. auto values = TRY(JS::iterable_to_list(vm, result, method));
  171. if (values.size() != type.results().size())
  172. return vm.throw_completion<JS::TypeError>(DeprecatedString::formatted("Invalid number of return values for multi-value wasm return of {} objects", type.results().size()));
  173. Vector<Wasm::Value> wasm_values;
  174. TRY_OR_THROW_OOM(vm, wasm_values.try_ensure_capacity(values.size()));
  175. size_t i = 0;
  176. for (auto& value : values)
  177. wasm_values.append(TRY(to_webassembly_value(vm, value, type.results()[i++])));
  178. return Wasm::Result { move(wasm_values) };
  179. },
  180. type
  181. };
  182. auto address = s_abstract_machine.store().allocate(move(host_function));
  183. dbgln("Resolved to {}", address->value());
  184. // FIXME: LinkError instead.
  185. VERIFY(address.has_value());
  186. resolved_imports.set(import_name, Wasm::ExternValue { Wasm::FunctionAddress { *address } });
  187. return {};
  188. },
  189. [&](Wasm::GlobalType const& type) -> JS::ThrowCompletionOr<void> {
  190. Optional<Wasm::GlobalAddress> address;
  191. // https://webassembly.github.io/spec/js-api/#read-the-imports step 5.1
  192. if (import_.is_number() || import_.is_bigint()) {
  193. if (import_.is_number() && type.type().kind() == Wasm::ValueType::I64) {
  194. // FIXME: Throw a LinkError instead.
  195. return vm.throw_completion<JS::TypeError>("LinkError: Import resolution attempted to cast a Number to a BigInteger"sv);
  196. }
  197. if (import_.is_bigint() && type.type().kind() != Wasm::ValueType::I64) {
  198. // FIXME: Throw a LinkError instead.
  199. return vm.throw_completion<JS::TypeError>("LinkError: Import resolution attempted to cast a BigInteger to a Number"sv);
  200. }
  201. auto cast_value = TRY(to_webassembly_value(vm, import_, type.type()));
  202. address = s_abstract_machine.store().allocate({ type.type(), false }, cast_value);
  203. } else {
  204. // FIXME: https://webassembly.github.io/spec/js-api/#read-the-imports step 5.2
  205. // if v implements Global
  206. // let globaladdr be v.[[Global]]
  207. // FIXME: Throw a LinkError instead
  208. return vm.throw_completion<JS::TypeError>("LinkError: Invalid value for global type"sv);
  209. }
  210. resolved_imports.set(import_name, Wasm::ExternValue { *address });
  211. return {};
  212. },
  213. [&](Wasm::MemoryType const&) -> JS::ThrowCompletionOr<void> {
  214. if (!import_.is_object() || !is<WebAssembly::Memory>(import_.as_object())) {
  215. // FIXME: Throw a LinkError instead
  216. return vm.throw_completion<JS::TypeError>("LinkError: Expected an instance of WebAssembly.Memory for a memory import"sv);
  217. }
  218. auto address = static_cast<WebAssembly::Memory const&>(import_.as_object()).address();
  219. resolved_imports.set(import_name, Wasm::ExternValue { address });
  220. return {};
  221. },
  222. [&](Wasm::TableType const&) -> JS::ThrowCompletionOr<void> {
  223. if (!import_.is_object() || !is<WebAssembly::Table>(import_.as_object())) {
  224. // FIXME: Throw a LinkError instead
  225. return vm.throw_completion<JS::TypeError>("LinkError: Expected an instance of WebAssembly.Table for a table import"sv);
  226. }
  227. auto address = static_cast<WebAssembly::Table const&>(import_.as_object()).address();
  228. resolved_imports.set(import_name, Wasm::ExternValue { address });
  229. return {};
  230. },
  231. [&](auto const&) -> JS::ThrowCompletionOr<void> {
  232. // FIXME: Implement these.
  233. dbgln("Unimplemented import of non-function attempted");
  234. return vm.throw_completion<JS::TypeError>("LinkError: Not Implemented"sv);
  235. }));
  236. }
  237. }
  238. linker.link(resolved_imports);
  239. auto link_result = linker.finish();
  240. if (link_result.is_error()) {
  241. // FIXME: Throw a LinkError.
  242. JS::ThrowableStringBuilder builder(vm);
  243. MUST_OR_THROW_OOM(builder.append("LinkError: Missing "sv));
  244. MUST_OR_THROW_OOM(builder.join(' ', link_result.error().missing_imports));
  245. return vm.throw_completion<JS::TypeError>(MUST_OR_THROW_OOM(builder.to_string()));
  246. }
  247. auto instance_result = s_abstract_machine.instantiate(module, link_result.release_value());
  248. if (instance_result.is_error()) {
  249. // FIXME: Throw a LinkError instead.
  250. return vm.throw_completion<JS::TypeError>(instance_result.error().error);
  251. }
  252. s_instantiated_modules.append(instance_result.release_value());
  253. s_module_caches.empend();
  254. return s_instantiated_modules.size() - 1;
  255. }
  256. JS::ThrowCompletionOr<size_t> parse_module(JS::VM& vm, JS::Object* buffer_object)
  257. {
  258. ReadonlyBytes data;
  259. if (is<JS::ArrayBuffer>(buffer_object)) {
  260. auto& buffer = static_cast<JS::ArrayBuffer&>(*buffer_object);
  261. data = buffer.buffer();
  262. } else if (is<JS::TypedArrayBase>(buffer_object)) {
  263. auto& buffer = static_cast<JS::TypedArrayBase&>(*buffer_object);
  264. data = buffer.viewed_array_buffer()->buffer().span().slice(buffer.byte_offset(), buffer.byte_length());
  265. } else if (is<JS::DataView>(buffer_object)) {
  266. auto& buffer = static_cast<JS::DataView&>(*buffer_object);
  267. data = buffer.viewed_array_buffer()->buffer().span().slice(buffer.byte_offset(), buffer.byte_length());
  268. } else {
  269. return vm.throw_completion<JS::TypeError>("Not a BufferSource"sv);
  270. }
  271. FixedMemoryStream stream { data };
  272. auto module_result = Wasm::Module::parse(stream);
  273. if (module_result.is_error()) {
  274. // FIXME: Throw CompileError instead.
  275. return vm.throw_completion<JS::TypeError>(Wasm::parse_error_to_deprecated_string(module_result.error()));
  276. }
  277. if (auto validation_result = s_abstract_machine.validate(module_result.value()); validation_result.is_error()) {
  278. // FIXME: Throw CompileError instead.
  279. return vm.throw_completion<JS::TypeError>(validation_result.error().error_string);
  280. }
  281. s_compiled_modules.append(make<CompiledWebAssemblyModule>(module_result.release_value()));
  282. return s_compiled_modules.size() - 1;
  283. }
  284. JS::NativeFunction* create_native_function(JS::VM& vm, Wasm::FunctionAddress address, DeprecatedString const& name)
  285. {
  286. auto& realm = *vm.current_realm();
  287. Optional<Wasm::FunctionType> type;
  288. s_abstract_machine.store().get(address)->visit([&](auto const& value) { type = value.type(); });
  289. if (auto entry = s_global_cache.function_instances.get(address); entry.has_value())
  290. return *entry;
  291. auto function = JS::NativeFunction::create(
  292. realm,
  293. name,
  294. [address, type = type.release_value()](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
  295. auto& realm = *vm.current_realm();
  296. Vector<Wasm::Value> values;
  297. values.ensure_capacity(type.parameters().size());
  298. // Grab as many values as needed and convert them.
  299. size_t index = 0;
  300. for (auto& type : type.parameters())
  301. values.append(TRY(to_webassembly_value(vm, vm.argument(index++), type)));
  302. auto result = s_abstract_machine.invoke(address, move(values));
  303. // FIXME: Use the convoluted mapping of errors defined in the spec.
  304. if (result.is_trap())
  305. return vm.throw_completion<JS::TypeError>(TRY_OR_THROW_OOM(vm, String::formatted("Wasm execution trapped (WIP): {}", result.trap().reason)));
  306. if (result.values().is_empty())
  307. return JS::js_undefined();
  308. if (result.values().size() == 1)
  309. return to_js_value(vm, result.values().first());
  310. return JS::Value(JS::Array::create_from<Wasm::Value>(realm, result.values(), [&](Wasm::Value value) {
  311. return to_js_value(vm, value);
  312. }));
  313. });
  314. s_global_cache.function_instances.set(address, function);
  315. return function;
  316. }
  317. JS::ThrowCompletionOr<Wasm::Value> to_webassembly_value(JS::VM& vm, JS::Value value, Wasm::ValueType const& type)
  318. {
  319. static ::Crypto::SignedBigInteger two_64 = "1"_sbigint.shift_left(64);
  320. switch (type.kind()) {
  321. case Wasm::ValueType::I64: {
  322. auto bigint = TRY(value.to_bigint(vm));
  323. auto value = bigint->big_integer().divided_by(two_64).remainder;
  324. VERIFY(value.unsigned_value().trimmed_length() <= 2);
  325. i64 integer = static_cast<i64>(value.unsigned_value().to_u64());
  326. if (value.is_negative())
  327. integer = -integer;
  328. return Wasm::Value { integer };
  329. }
  330. case Wasm::ValueType::I32: {
  331. auto _i32 = TRY(value.to_i32(vm));
  332. return Wasm::Value { static_cast<i32>(_i32) };
  333. }
  334. case Wasm::ValueType::F64: {
  335. auto number = TRY(value.to_double(vm));
  336. return Wasm::Value { static_cast<double>(number) };
  337. }
  338. case Wasm::ValueType::F32: {
  339. auto number = TRY(value.to_double(vm));
  340. return Wasm::Value { static_cast<float>(number) };
  341. }
  342. case Wasm::ValueType::FunctionReference:
  343. case Wasm::ValueType::NullFunctionReference: {
  344. if (value.is_null())
  345. return Wasm::Value { Wasm::ValueType(Wasm::ValueType::NullExternReference), 0ull };
  346. if (value.is_function()) {
  347. auto& function = value.as_function();
  348. for (auto& entry : s_global_cache.function_instances) {
  349. if (entry.value == &function)
  350. return Wasm::Value { Wasm::Reference { Wasm::Reference::Func { entry.key } } };
  351. }
  352. }
  353. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Exported function");
  354. }
  355. case Wasm::ValueType::ExternReference:
  356. case Wasm::ValueType::NullExternReference:
  357. TODO();
  358. }
  359. VERIFY_NOT_REACHED();
  360. }
  361. JS::Value to_js_value(JS::VM& vm, Wasm::Value& wasm_value)
  362. {
  363. auto& realm = *vm.current_realm();
  364. switch (wasm_value.type().kind()) {
  365. case Wasm::ValueType::I64:
  366. return realm.heap().allocate<JS::BigInt>(realm, ::Crypto::SignedBigInteger { wasm_value.to<i64>().value() }).release_allocated_value_but_fixme_should_propagate_errors();
  367. case Wasm::ValueType::I32:
  368. return JS::Value(wasm_value.to<i32>().value());
  369. case Wasm::ValueType::F64:
  370. return JS::Value(wasm_value.to<double>().value());
  371. case Wasm::ValueType::F32:
  372. return JS::Value(static_cast<double>(wasm_value.to<float>().value()));
  373. case Wasm::ValueType::FunctionReference:
  374. // FIXME: What's the name of a function reference that isn't exported?
  375. return create_native_function(vm, wasm_value.to<Wasm::Reference::Func>().value().address, "FIXME_IHaveNoIdeaWhatThisShouldBeCalled");
  376. case Wasm::ValueType::NullFunctionReference:
  377. return JS::js_null();
  378. case Wasm::ValueType::ExternReference:
  379. case Wasm::ValueType::NullExternReference:
  380. TODO();
  381. }
  382. VERIFY_NOT_REACHED();
  383. }
  384. }
  385. }