WebAssembly.cpp 21 KB

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