WebAssembly.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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. ByteString::formatted("func{}", resolved_imports.size()),
  184. };
  185. auto address = cache.abstract_machine().store().allocate(move(host_function));
  186. dbgln("Resolved to {}", address->value());
  187. // FIXME: LinkError instead.
  188. VERIFY(address.has_value());
  189. resolved_imports.set(import_name, Wasm::ExternValue { Wasm::FunctionAddress { *address } });
  190. return {};
  191. },
  192. [&](Wasm::GlobalType const& type) -> JS::ThrowCompletionOr<void> {
  193. Optional<Wasm::GlobalAddress> address;
  194. // https://webassembly.github.io/spec/js-api/#read-the-imports step 5.1
  195. if (import_.is_number() || import_.is_bigint()) {
  196. if (import_.is_number() && type.type().kind() == Wasm::ValueType::I64) {
  197. // FIXME: Throw a LinkError instead.
  198. return vm.throw_completion<JS::TypeError>("LinkError: Import resolution attempted to cast a Number to a BigInteger"sv);
  199. }
  200. if (import_.is_bigint() && type.type().kind() != Wasm::ValueType::I64) {
  201. // FIXME: Throw a LinkError instead.
  202. return vm.throw_completion<JS::TypeError>("LinkError: Import resolution attempted to cast a BigInteger to a Number"sv);
  203. }
  204. auto cast_value = TRY(to_webassembly_value(vm, import_, type.type()));
  205. address = cache.abstract_machine().store().allocate({ type.type(), false }, cast_value);
  206. } else {
  207. // FIXME: https://webassembly.github.io/spec/js-api/#read-the-imports step 5.2
  208. // if v implements Global
  209. // let globaladdr be v.[[Global]]
  210. // FIXME: Throw a LinkError instead
  211. return vm.throw_completion<JS::TypeError>("LinkError: Invalid value for global type"sv);
  212. }
  213. resolved_imports.set(import_name, Wasm::ExternValue { *address });
  214. return {};
  215. },
  216. [&](Wasm::MemoryType const&) -> JS::ThrowCompletionOr<void> {
  217. if (!import_.is_object() || !is<WebAssembly::Memory>(import_.as_object())) {
  218. // FIXME: Throw a LinkError instead
  219. return vm.throw_completion<JS::TypeError>("LinkError: Expected an instance of WebAssembly.Memory for a memory import"sv);
  220. }
  221. auto address = static_cast<WebAssembly::Memory const&>(import_.as_object()).address();
  222. resolved_imports.set(import_name, Wasm::ExternValue { address });
  223. return {};
  224. },
  225. [&](Wasm::TableType const&) -> JS::ThrowCompletionOr<void> {
  226. if (!import_.is_object() || !is<WebAssembly::Table>(import_.as_object())) {
  227. // FIXME: Throw a LinkError instead
  228. return vm.throw_completion<JS::TypeError>("LinkError: Expected an instance of WebAssembly.Table for a table import"sv);
  229. }
  230. auto address = static_cast<WebAssembly::Table const&>(import_.as_object()).address();
  231. resolved_imports.set(import_name, Wasm::ExternValue { address });
  232. return {};
  233. },
  234. [&](auto const&) -> JS::ThrowCompletionOr<void> {
  235. // FIXME: Implement these.
  236. dbgln("Unimplemented import of non-function attempted");
  237. return vm.throw_completion<JS::TypeError>("LinkError: Not Implemented"sv);
  238. }));
  239. }
  240. }
  241. linker.link(resolved_imports);
  242. auto link_result = linker.finish();
  243. if (link_result.is_error()) {
  244. // FIXME: Throw a LinkError.
  245. StringBuilder builder;
  246. builder.append("LinkError: Missing "sv);
  247. builder.join(' ', link_result.error().missing_imports);
  248. return vm.throw_completion<JS::TypeError>(MUST(builder.to_string()));
  249. }
  250. auto instance_result = cache.abstract_machine().instantiate(module, link_result.release_value());
  251. if (instance_result.is_error()) {
  252. // FIXME: Throw a LinkError instead.
  253. return vm.throw_completion<JS::TypeError>(instance_result.error().error);
  254. }
  255. return instance_result.release_value();
  256. }
  257. JS::ThrowCompletionOr<NonnullRefPtr<CompiledWebAssemblyModule>> 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. auto& cache = get_cache(*vm.current_realm());
  285. if (auto validation_result = cache.abstract_machine().validate(module_result.value()); validation_result.is_error()) {
  286. // FIXME: Throw CompileError instead.
  287. return vm.throw_completion<JS::TypeError>(validation_result.error().error_string);
  288. }
  289. auto compiled_module = make_ref_counted<CompiledWebAssemblyModule>(module_result.release_value());
  290. cache.add_compiled_module(compiled_module);
  291. return compiled_module;
  292. }
  293. JS::NativeFunction* create_native_function(JS::VM& vm, Wasm::FunctionAddress address, ByteString const& name, Instance* instance)
  294. {
  295. auto& realm = *vm.current_realm();
  296. Optional<Wasm::FunctionType> type;
  297. auto& cache = get_cache(realm);
  298. cache.abstract_machine().store().get(address)->visit([&](auto const& value) { type = value.type(); });
  299. if (auto entry = cache.get_function_instance(address); entry.has_value())
  300. return *entry;
  301. auto function = JS::NativeFunction::create(
  302. realm,
  303. name,
  304. [address, type = type.release_value(), instance](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
  305. (void)instance;
  306. auto& realm = *vm.current_realm();
  307. Vector<Wasm::Value> values;
  308. values.ensure_capacity(type.parameters().size());
  309. // Grab as many values as needed and convert them.
  310. size_t index = 0;
  311. for (auto& type : type.parameters())
  312. values.append(TRY(to_webassembly_value(vm, vm.argument(index++), type)));
  313. auto& cache = get_cache(realm);
  314. auto result = cache.abstract_machine().invoke(address, move(values));
  315. // FIXME: Use the convoluted mapping of errors defined in the spec.
  316. if (result.is_trap())
  317. return vm.throw_completion<JS::TypeError>(TRY_OR_THROW_OOM(vm, String::formatted("Wasm execution trapped (WIP): {}", result.trap().reason)));
  318. if (result.values().is_empty())
  319. return JS::js_undefined();
  320. if (result.values().size() == 1)
  321. return to_js_value(vm, result.values().first());
  322. return JS::Value(JS::Array::create_from<Wasm::Value>(realm, result.values(), [&](Wasm::Value value) {
  323. return to_js_value(vm, value);
  324. }));
  325. });
  326. cache.add_function_instance(address, function);
  327. return function;
  328. }
  329. JS::ThrowCompletionOr<Wasm::Value> to_webassembly_value(JS::VM& vm, JS::Value value, Wasm::ValueType const& type)
  330. {
  331. static ::Crypto::SignedBigInteger two_64 = "1"_sbigint.shift_left(64);
  332. switch (type.kind()) {
  333. case Wasm::ValueType::I64: {
  334. auto bigint = TRY(value.to_bigint(vm));
  335. auto value = bigint->big_integer().divided_by(two_64).remainder;
  336. VERIFY(value.unsigned_value().trimmed_length() <= 2);
  337. i64 integer = static_cast<i64>(value.unsigned_value().to_u64());
  338. if (value.is_negative())
  339. integer = -integer;
  340. return Wasm::Value { integer };
  341. }
  342. case Wasm::ValueType::I32: {
  343. auto _i32 = TRY(value.to_i32(vm));
  344. return Wasm::Value { static_cast<i32>(_i32) };
  345. }
  346. case Wasm::ValueType::F64: {
  347. auto number = TRY(value.to_double(vm));
  348. return Wasm::Value { static_cast<double>(number) };
  349. }
  350. case Wasm::ValueType::F32: {
  351. auto number = TRY(value.to_double(vm));
  352. return Wasm::Value { static_cast<float>(number) };
  353. }
  354. case Wasm::ValueType::FunctionReference: {
  355. if (value.is_null())
  356. return Wasm::Value { Wasm::ValueType(Wasm::ValueType::FunctionReference), 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. TODO();
  369. case Wasm::ValueType::V128:
  370. return vm.throw_completion<JS::TypeError>("Cannot convert a vector value to a javascript value"sv);
  371. }
  372. VERIFY_NOT_REACHED();
  373. }
  374. JS::Value to_js_value(JS::VM& vm, Wasm::Value& wasm_value)
  375. {
  376. auto& realm = *vm.current_realm();
  377. switch (wasm_value.type().kind()) {
  378. case Wasm::ValueType::I64:
  379. return realm.heap().allocate<JS::BigInt>(realm, ::Crypto::SignedBigInteger { wasm_value.to<i64>().value() });
  380. case Wasm::ValueType::I32:
  381. return JS::Value(wasm_value.to<i32>().value());
  382. case Wasm::ValueType::F64:
  383. return JS::Value(wasm_value.to<double>().value());
  384. case Wasm::ValueType::F32:
  385. return JS::Value(static_cast<double>(wasm_value.to<float>().value()));
  386. case Wasm::ValueType::FunctionReference: {
  387. auto address = wasm_value.to<Wasm::Reference::Func>().value().address;
  388. auto& cache = get_cache(realm);
  389. auto* function = cache.abstract_machine().store().get(address);
  390. auto name = function->visit(
  391. [&](Wasm::WasmFunction& wasm_function) {
  392. auto index = *wasm_function.module().functions().find_first_index(address);
  393. return ByteString::formatted("func{}", index);
  394. },
  395. [](Wasm::HostFunction& host_function) {
  396. return host_function.name();
  397. });
  398. return create_native_function(vm, address, name);
  399. }
  400. case Wasm::ValueType::V128:
  401. case Wasm::ValueType::ExternReference:
  402. TODO();
  403. }
  404. VERIFY_NOT_REACHED();
  405. }
  406. }
  407. }