WebAssembly.cpp 21 KB

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