WebAssembly.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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. HashMap<JS::GCPtr<JS::Object>, WebAssemblyCache> s_caches;
  30. WebAssemblyCache& get_cache(JS::Realm& realm)
  31. {
  32. return s_caches.ensure(realm.global_object());
  33. }
  34. }
  35. void visit_edges(JS::Object& object, JS::Cell::Visitor& visitor)
  36. {
  37. auto& global_object = HTML::relevant_global_object(object);
  38. if (auto maybe_cache = Detail::s_caches.get(global_object); maybe_cache.has_value()) {
  39. auto& cache = maybe_cache.release_value();
  40. visitor.visit(cache.function_instances());
  41. }
  42. }
  43. void finalize(JS::Object& object)
  44. {
  45. auto& global_object = HTML::relevant_global_object(object);
  46. Detail::s_caches.remove(global_object);
  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 module_or_error = Detail::parse_module(vm, bytes->raw_object());
  55. // 3. If module is error, return false.
  56. if (module_or_error.is_error())
  57. return false;
  58. // 3 continued - our "compile" step is lazy with validation, explicitly do the validation.
  59. auto compiled_module = module_or_error.release_value();
  60. auto& cache = Detail::get_cache(*vm.current_realm());
  61. if (cache.abstract_machine().validate(compiled_module->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 compiled_module_or_error = Detail::parse_module(vm, bytes->raw_object());
  72. auto promise = JS::Promise::create(realm);
  73. if (compiled_module_or_error.is_error()) {
  74. promise->reject(*compiled_module_or_error.release_error().value());
  75. } else {
  76. auto module_object = vm.heap().allocate<Module>(realm, realm, compiled_module_or_error.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 compiled_module_or_error = Detail::parse_module(vm, bytes->raw_object());
  89. auto promise = JS::Promise::create(realm);
  90. if (compiled_module_or_error.is_error()) {
  91. promise->reject(*compiled_module_or_error.release_error().value());
  92. return promise;
  93. }
  94. auto compiled_module = compiled_module_or_error.release_value();
  95. auto result = Detail::instantiate_module(vm, compiled_module->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, move(compiled_module));
  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.compiled_module();
  116. auto result = Detail::instantiate_module(vm, compiled_module->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<NonnullOwnPtr<Wasm::ModuleInstance>> 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. auto& cache = get_cache(*vm.current_realm());
  132. if (!import_argument.is_undefined()) {
  133. auto import_object = TRY(import_argument.to_object(vm));
  134. dbgln("Trying to resolve stuff because import object was specified");
  135. for (Wasm::Linker::Name const& import_name : linker.unresolved_imports()) {
  136. dbgln("Trying to resolve {}::{}", import_name.module, import_name.name);
  137. auto value_or_error = import_object->get(import_name.module);
  138. if (value_or_error.is_error())
  139. break;
  140. auto value = value_or_error.release_value();
  141. auto object_or_error = value.to_object(vm);
  142. if (object_or_error.is_error())
  143. break;
  144. auto object = object_or_error.release_value();
  145. auto import_or_error = object->get(import_name.name);
  146. if (import_or_error.is_error())
  147. break;
  148. auto import_ = import_or_error.release_value();
  149. TRY(import_name.type.visit(
  150. [&](Wasm::TypeIndex index) -> JS::ThrowCompletionOr<void> {
  151. dbgln("Trying to resolve a function {}::{}, type index {}", import_name.module, import_name.name, index.value());
  152. auto& type = module.type(index);
  153. // FIXME: IsCallable()
  154. if (!import_.is_function())
  155. return {};
  156. auto& function = import_.as_function();
  157. // FIXME: If this is a function created by create_native_function(),
  158. // just extract its address and resolve to that.
  159. Wasm::HostFunction host_function {
  160. [&](auto&, auto& arguments) -> Wasm::Result {
  161. JS::MarkedVector<JS::Value> argument_values { vm.heap() };
  162. for (auto& entry : arguments)
  163. argument_values.append(to_js_value(vm, entry));
  164. auto result = TRY(JS::call(vm, function, JS::js_undefined(), argument_values.span()));
  165. if (type.results().is_empty())
  166. return Wasm::Result { Vector<Wasm::Value> {} };
  167. if (type.results().size() == 1)
  168. return Wasm::Result { Vector<Wasm::Value> { TRY(to_webassembly_value(vm, result, type.results().first())) } };
  169. auto method = TRY(result.get_method(vm, vm.names.iterator));
  170. if (method == JS::js_undefined())
  171. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotIterable, result.to_string_without_side_effects());
  172. auto values = TRY(JS::iterator_to_list(vm, TRY(JS::get_iterator_from_method(vm, result, *method))));
  173. if (values.size() != type.results().size())
  174. return vm.throw_completion<JS::TypeError>(ByteString::formatted("Invalid number of return values for multi-value wasm return of {} objects", type.results().size()));
  175. Vector<Wasm::Value> wasm_values;
  176. TRY_OR_THROW_OOM(vm, wasm_values.try_ensure_capacity(values.size()));
  177. size_t i = 0;
  178. for (auto& value : values)
  179. wasm_values.append(TRY(to_webassembly_value(vm, value, type.results()[i++])));
  180. return Wasm::Result { move(wasm_values) };
  181. },
  182. type
  183. };
  184. auto address = cache.abstract_machine().store().allocate(move(host_function));
  185. dbgln("Resolved to {}", address->value());
  186. // FIXME: LinkError instead.
  187. VERIFY(address.has_value());
  188. resolved_imports.set(import_name, Wasm::ExternValue { Wasm::FunctionAddress { *address } });
  189. return {};
  190. },
  191. [&](Wasm::GlobalType const& type) -> JS::ThrowCompletionOr<void> {
  192. Optional<Wasm::GlobalAddress> address;
  193. // https://webassembly.github.io/spec/js-api/#read-the-imports step 5.1
  194. if (import_.is_number() || import_.is_bigint()) {
  195. if (import_.is_number() && type.type().kind() == Wasm::ValueType::I64) {
  196. // FIXME: Throw a LinkError instead.
  197. return vm.throw_completion<JS::TypeError>("LinkError: Import resolution attempted to cast a Number to a BigInteger"sv);
  198. }
  199. if (import_.is_bigint() && type.type().kind() != Wasm::ValueType::I64) {
  200. // FIXME: Throw a LinkError instead.
  201. return vm.throw_completion<JS::TypeError>("LinkError: Import resolution attempted to cast a BigInteger to a Number"sv);
  202. }
  203. auto cast_value = TRY(to_webassembly_value(vm, import_, type.type()));
  204. address = cache.abstract_machine().store().allocate({ type.type(), false }, cast_value);
  205. } else {
  206. // FIXME: https://webassembly.github.io/spec/js-api/#read-the-imports step 5.2
  207. // if v implements Global
  208. // let globaladdr be v.[[Global]]
  209. // FIXME: Throw a LinkError instead
  210. return vm.throw_completion<JS::TypeError>("LinkError: Invalid value for global type"sv);
  211. }
  212. resolved_imports.set(import_name, Wasm::ExternValue { *address });
  213. return {};
  214. },
  215. [&](Wasm::MemoryType const&) -> JS::ThrowCompletionOr<void> {
  216. if (!import_.is_object() || !is<WebAssembly::Memory>(import_.as_object())) {
  217. // FIXME: Throw a LinkError instead
  218. return vm.throw_completion<JS::TypeError>("LinkError: Expected an instance of WebAssembly.Memory for a memory import"sv);
  219. }
  220. auto address = static_cast<WebAssembly::Memory const&>(import_.as_object()).address();
  221. resolved_imports.set(import_name, Wasm::ExternValue { address });
  222. return {};
  223. },
  224. [&](Wasm::TableType const&) -> JS::ThrowCompletionOr<void> {
  225. if (!import_.is_object() || !is<WebAssembly::Table>(import_.as_object())) {
  226. // FIXME: Throw a LinkError instead
  227. return vm.throw_completion<JS::TypeError>("LinkError: Expected an instance of WebAssembly.Table for a table import"sv);
  228. }
  229. auto address = static_cast<WebAssembly::Table const&>(import_.as_object()).address();
  230. resolved_imports.set(import_name, Wasm::ExternValue { address });
  231. return {};
  232. },
  233. [&](auto const&) -> JS::ThrowCompletionOr<void> {
  234. // FIXME: Implement these.
  235. dbgln("Unimplemented import of non-function attempted");
  236. return vm.throw_completion<JS::TypeError>("LinkError: Not Implemented"sv);
  237. }));
  238. }
  239. }
  240. linker.link(resolved_imports);
  241. auto link_result = linker.finish();
  242. if (link_result.is_error()) {
  243. // FIXME: Throw a LinkError.
  244. StringBuilder builder;
  245. builder.append("LinkError: Missing "sv);
  246. builder.join(' ', link_result.error().missing_imports);
  247. return vm.throw_completion<JS::TypeError>(MUST(builder.to_string()));
  248. }
  249. auto instance_result = cache.abstract_machine().instantiate(module, link_result.release_value());
  250. if (instance_result.is_error()) {
  251. // FIXME: Throw a LinkError instead.
  252. return vm.throw_completion<JS::TypeError>(instance_result.error().error);
  253. }
  254. return instance_result.release_value();
  255. }
  256. JS::ThrowCompletionOr<NonnullRefPtr<CompiledWebAssemblyModule>> 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. auto typed_array_record = JS::make_typed_array_with_buffer_witness_record(buffer, JS::ArrayBuffer::Order::SeqCst);
  265. if (JS::is_typed_array_out_of_bounds(typed_array_record))
  266. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BufferOutOfBounds, "TypedArray"sv);
  267. data = buffer.viewed_array_buffer()->buffer().span().slice(buffer.byte_offset(), JS::typed_array_byte_length(typed_array_record));
  268. } else if (is<JS::DataView>(buffer_object)) {
  269. auto& buffer = static_cast<JS::DataView&>(*buffer_object);
  270. auto view_record = JS::make_data_view_with_buffer_witness_record(buffer, JS::ArrayBuffer::Order::SeqCst);
  271. if (JS::is_view_out_of_bounds(view_record))
  272. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BufferOutOfBounds, "DataView"sv);
  273. data = buffer.viewed_array_buffer()->buffer().span().slice(buffer.byte_offset(), JS::get_view_byte_length(view_record));
  274. } else {
  275. return vm.throw_completion<JS::TypeError>("Not a BufferSource"sv);
  276. }
  277. FixedMemoryStream stream { data };
  278. auto module_result = Wasm::Module::parse(stream);
  279. if (module_result.is_error()) {
  280. // FIXME: Throw CompileError instead.
  281. return vm.throw_completion<JS::TypeError>(Wasm::parse_error_to_byte_string(module_result.error()));
  282. }
  283. auto& cache = get_cache(*vm.current_realm());
  284. if (auto validation_result = cache.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. auto compiled_module = make_ref_counted<CompiledWebAssemblyModule>(module_result.release_value());
  289. cache.add_compiled_module(compiled_module);
  290. return compiled_module;
  291. }
  292. JS::NativeFunction* create_native_function(JS::VM& vm, Wasm::FunctionAddress address, ByteString const& name, Instance* instance)
  293. {
  294. auto& realm = *vm.current_realm();
  295. Optional<Wasm::FunctionType> type;
  296. auto& cache = get_cache(realm);
  297. cache.abstract_machine().store().get(address)->visit([&](auto const& value) { type = value.type(); });
  298. if (auto entry = cache.get_function_instance(address); entry.has_value())
  299. return *entry;
  300. auto function = JS::NativeFunction::create(
  301. realm,
  302. name,
  303. [address, type = type.release_value(), instance](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
  304. (void)instance;
  305. auto& realm = *vm.current_realm();
  306. Vector<Wasm::Value> values;
  307. values.ensure_capacity(type.parameters().size());
  308. // Grab as many values as needed and convert them.
  309. size_t index = 0;
  310. for (auto& type : type.parameters())
  311. values.append(TRY(to_webassembly_value(vm, vm.argument(index++), type)));
  312. auto& cache = get_cache(realm);
  313. auto result = cache.abstract_machine().invoke(address, move(values));
  314. // FIXME: Use the convoluted mapping of errors defined in the spec.
  315. if (result.is_trap())
  316. return vm.throw_completion<JS::TypeError>(TRY_OR_THROW_OOM(vm, String::formatted("Wasm execution trapped (WIP): {}", result.trap().reason)));
  317. if (result.values().is_empty())
  318. return JS::js_undefined();
  319. if (result.values().size() == 1)
  320. return to_js_value(vm, result.values().first());
  321. return JS::Value(JS::Array::create_from<Wasm::Value>(realm, result.values(), [&](Wasm::Value value) {
  322. return to_js_value(vm, value);
  323. }));
  324. });
  325. cache.add_function_instance(address, function);
  326. return function;
  327. }
  328. JS::ThrowCompletionOr<Wasm::Value> to_webassembly_value(JS::VM& vm, JS::Value value, Wasm::ValueType const& type)
  329. {
  330. static ::Crypto::SignedBigInteger two_64 = "1"_sbigint.shift_left(64);
  331. switch (type.kind()) {
  332. case Wasm::ValueType::I64: {
  333. auto bigint = TRY(value.to_bigint(vm));
  334. auto value = bigint->big_integer().divided_by(two_64).remainder;
  335. VERIFY(value.unsigned_value().trimmed_length() <= 2);
  336. i64 integer = static_cast<i64>(value.unsigned_value().to_u64());
  337. if (value.is_negative())
  338. integer = -integer;
  339. return Wasm::Value { integer };
  340. }
  341. case Wasm::ValueType::I32: {
  342. auto _i32 = TRY(value.to_i32(vm));
  343. return Wasm::Value { static_cast<i32>(_i32) };
  344. }
  345. case Wasm::ValueType::F64: {
  346. auto number = TRY(value.to_double(vm));
  347. return Wasm::Value { static_cast<double>(number) };
  348. }
  349. case Wasm::ValueType::F32: {
  350. auto number = TRY(value.to_double(vm));
  351. return Wasm::Value { static_cast<float>(number) };
  352. }
  353. case Wasm::ValueType::FunctionReference:
  354. case Wasm::ValueType::NullFunctionReference: {
  355. if (value.is_null())
  356. return Wasm::Value { Wasm::ValueType(Wasm::ValueType::NullExternReference), 0ull };
  357. if (value.is_function()) {
  358. auto& function = value.as_function();
  359. auto& cache = get_cache(*vm.current_realm());
  360. for (auto& entry : cache.function_instances()) {
  361. if (entry.value == &function)
  362. return Wasm::Value { Wasm::Reference { Wasm::Reference::Func { entry.key } } };
  363. }
  364. }
  365. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Exported function");
  366. }
  367. case Wasm::ValueType::ExternReference:
  368. case Wasm::ValueType::NullExternReference:
  369. TODO();
  370. case Wasm::ValueType::V128:
  371. return vm.throw_completion<JS::TypeError>("Cannot convert a vector value to a javascript value"sv);
  372. }
  373. VERIFY_NOT_REACHED();
  374. }
  375. JS::Value to_js_value(JS::VM& vm, Wasm::Value& wasm_value)
  376. {
  377. auto& realm = *vm.current_realm();
  378. switch (wasm_value.type().kind()) {
  379. case Wasm::ValueType::I64:
  380. return realm.heap().allocate<JS::BigInt>(realm, ::Crypto::SignedBigInteger { wasm_value.to<i64>().value() });
  381. case Wasm::ValueType::I32:
  382. return JS::Value(wasm_value.to<i32>().value());
  383. case Wasm::ValueType::F64:
  384. return JS::Value(wasm_value.to<double>().value());
  385. case Wasm::ValueType::F32:
  386. return JS::Value(static_cast<double>(wasm_value.to<float>().value()));
  387. case Wasm::ValueType::FunctionReference:
  388. // FIXME: What's the name of a function reference that isn't exported?
  389. return create_native_function(vm, wasm_value.to<Wasm::Reference::Func>().value().address, "FIXME_IHaveNoIdeaWhatThisShouldBeCalled");
  390. case Wasm::ValueType::NullFunctionReference:
  391. return JS::js_null();
  392. case Wasm::ValueType::V128:
  393. case Wasm::ValueType::ExternReference:
  394. case Wasm::ValueType::NullExternReference:
  395. TODO();
  396. }
  397. VERIFY_NOT_REACHED();
  398. }
  399. }
  400. }