WebAssembly.cpp 24 KB

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