WebAssemblyObject.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. /*
  2. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "WebAssemblyInstanceObject.h"
  7. #include "WebAssemblyMemoryPrototype.h"
  8. #include "WebAssemblyModuleConstructor.h"
  9. #include "WebAssemblyModuleObject.h"
  10. #include "WebAssemblyModulePrototype.h"
  11. #include <AK/ScopeGuard.h>
  12. #include <LibJS/Runtime/Array.h>
  13. #include <LibJS/Runtime/ArrayBuffer.h>
  14. #include <LibJS/Runtime/BigInt.h>
  15. #include <LibJS/Runtime/DataView.h>
  16. #include <LibJS/Runtime/TypedArray.h>
  17. #include <LibWasm/AbstractMachine/Interpreter.h>
  18. #include <LibWeb/Bindings/WindowObject.h>
  19. #include <LibWeb/WebAssembly/WebAssemblyInstanceConstructor.h>
  20. #include <LibWeb/WebAssembly/WebAssemblyObject.h>
  21. namespace Web::Bindings {
  22. WebAssemblyObject::WebAssemblyObject(JS::GlobalObject& global_object)
  23. : Object(*global_object.object_prototype())
  24. {
  25. }
  26. void WebAssemblyObject::initialize(JS::GlobalObject& global_object)
  27. {
  28. Object::initialize(global_object);
  29. u8 attr = JS::Attribute::Configurable | JS::Attribute::Writable | JS::Attribute::Enumerable;
  30. define_native_function("validate", validate, 1, attr);
  31. define_native_function("compile", compile, 1, attr);
  32. define_native_function("instantiate", instantiate, 1, attr);
  33. auto& vm = global_object.vm();
  34. auto& window = static_cast<WindowObject&>(global_object);
  35. auto& memory_constructor = window.ensure_web_constructor<WebAssemblyMemoryConstructor>("WebAssembly.Memory");
  36. memory_constructor.define_direct_property(vm.names.name, js_string(vm, "WebAssembly.Memory"), JS::Attribute::Configurable);
  37. auto& memory_prototype = window.ensure_web_prototype<WebAssemblyMemoryPrototype>("WebAssemblyMemoryPrototype");
  38. memory_prototype.define_direct_property(vm.names.constructor, &memory_constructor, JS::Attribute::Writable | JS::Attribute::Configurable);
  39. define_direct_property("Memory", &memory_constructor, JS::Attribute::Writable | JS::Attribute::Configurable);
  40. auto& instance_constructor = window.ensure_web_constructor<WebAssemblyInstanceConstructor>("WebAssembly.Instance");
  41. instance_constructor.define_direct_property(vm.names.name, js_string(vm, "WebAssembly.Instance"), JS::Attribute::Configurable);
  42. auto& instance_prototype = window.ensure_web_prototype<WebAssemblyInstancePrototype>("WebAssemblyInstancePrototype");
  43. instance_prototype.define_direct_property(vm.names.constructor, &instance_constructor, JS::Attribute::Writable | JS::Attribute::Configurable);
  44. define_direct_property("Instance", &instance_constructor, JS::Attribute::Writable | JS::Attribute::Configurable);
  45. auto& module_constructor = window.ensure_web_constructor<WebAssemblyModuleConstructor>("WebAssembly.Module");
  46. module_constructor.define_direct_property(vm.names.name, js_string(vm, "WebAssembly.Module"), JS::Attribute::Configurable);
  47. auto& module_prototype = window.ensure_web_prototype<WebAssemblyModulePrototype>("WebAssemblyModulePrototype");
  48. module_prototype.define_direct_property(vm.names.constructor, &module_constructor, JS::Attribute::Writable | JS::Attribute::Configurable);
  49. define_direct_property("Module", &module_constructor, JS::Attribute::Writable | JS::Attribute::Configurable);
  50. }
  51. NonnullOwnPtrVector<WebAssemblyObject::CompiledWebAssemblyModule> WebAssemblyObject::s_compiled_modules;
  52. NonnullOwnPtrVector<Wasm::ModuleInstance> WebAssemblyObject::s_instantiated_modules;
  53. Vector<WebAssemblyObject::ModuleCache> WebAssemblyObject::s_module_caches;
  54. WebAssemblyObject::GlobalModuleCache WebAssemblyObject::s_global_cache;
  55. Wasm::AbstractMachine WebAssemblyObject::s_abstract_machine;
  56. void WebAssemblyObject::visit_edges(Visitor& visitor)
  57. {
  58. Base::visit_edges(visitor);
  59. for (auto& entry : s_global_cache.function_instances)
  60. visitor.visit(entry.value);
  61. for (auto& module_cache : s_module_caches) {
  62. for (auto& entry : module_cache.function_instances)
  63. visitor.visit(entry.value);
  64. for (auto& entry : module_cache.memory_instances)
  65. visitor.visit(entry.value);
  66. }
  67. }
  68. JS_DEFINE_NATIVE_FUNCTION(WebAssemblyObject::validate)
  69. {
  70. // FIXME: Implement this once module validation is implemented in LibWasm.
  71. dbgln("Hit WebAssemblyObject::validate() stub!");
  72. return JS::Value { true };
  73. }
  74. Result<size_t, JS::Value> parse_module(JS::GlobalObject& global_object, JS::Object* buffer_object)
  75. {
  76. ReadonlyBytes data;
  77. if (is<JS::ArrayBuffer>(buffer_object)) {
  78. auto& buffer = static_cast<JS::ArrayBuffer&>(*buffer_object);
  79. data = buffer.buffer();
  80. } else if (is<JS::TypedArrayBase>(buffer_object)) {
  81. auto& buffer = static_cast<JS::TypedArrayBase&>(*buffer_object);
  82. data = buffer.viewed_array_buffer()->buffer().span().slice(buffer.byte_offset(), buffer.byte_length());
  83. } else if (is<JS::DataView>(buffer_object)) {
  84. auto& buffer = static_cast<JS::DataView&>(*buffer_object);
  85. data = buffer.viewed_array_buffer()->buffer().span().slice(buffer.byte_offset(), buffer.byte_length());
  86. } else {
  87. auto error = JS::TypeError::create(global_object, "Not a BufferSource");
  88. return JS::Value { error };
  89. }
  90. InputMemoryStream stream { data };
  91. auto module_result = Wasm::Module::parse(stream);
  92. ScopeGuard drain_errors {
  93. [&] {
  94. stream.handle_any_error();
  95. }
  96. };
  97. if (module_result.is_error()) {
  98. // FIXME: Throw CompileError instead.
  99. auto error = JS::TypeError::create(global_object, Wasm::parse_error_to_string(module_result.error()));
  100. return JS::Value { error };
  101. }
  102. WebAssemblyObject::s_compiled_modules.append(make<WebAssemblyObject::CompiledWebAssemblyModule>(module_result.release_value()));
  103. return WebAssemblyObject::s_compiled_modules.size() - 1;
  104. }
  105. JS_DEFINE_NATIVE_FUNCTION(WebAssemblyObject::compile)
  106. {
  107. // FIXME: This shouldn't block!
  108. auto buffer = vm.argument(0).to_object(global_object);
  109. JS::Value rejection_value;
  110. if (vm.exception()) {
  111. rejection_value = vm.exception()->value();
  112. vm.clear_exception();
  113. }
  114. auto promise = JS::Promise::create(global_object);
  115. if (!rejection_value.is_empty()) {
  116. promise->reject(rejection_value);
  117. return promise;
  118. }
  119. auto result = parse_module(global_object, buffer);
  120. if (result.is_error())
  121. promise->reject(result.error());
  122. else
  123. promise->fulfill(vm.heap().allocate<WebAssemblyModuleObject>(global_object, global_object, result.value()));
  124. return promise;
  125. }
  126. Result<size_t, JS::Value> WebAssemblyObject::instantiate_module(Wasm::Module const& module, JS::VM& vm, JS::GlobalObject& global_object)
  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. [[maybe_unused]] auto import_object = import_argument.to_object(global_object);
  133. if (auto exception = vm.exception()) {
  134. vm.clear_exception();
  135. return exception->value();
  136. }
  137. dbgln("Trying to resolve stuff because import object was specified");
  138. for (const Wasm::Linker::Name& import_name : linker.unresolved_imports()) {
  139. dbgln("Trying to resolve {}::{}", import_name.module, import_name.name);
  140. auto value = import_object->get(import_name.module);
  141. if (vm.exception())
  142. break;
  143. auto object = value.to_object(global_object);
  144. if (vm.exception())
  145. break;
  146. auto import_ = object->get(import_name.name);
  147. if (vm.exception())
  148. break;
  149. import_name.type.visit(
  150. [&](Wasm::TypeIndex index) {
  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::MarkedValueList argument_values { vm.heap() };
  162. for (auto& entry : arguments)
  163. argument_values.append(to_js_value(entry, global_object));
  164. auto result = vm.call(function, JS::js_undefined(), move(argument_values));
  165. if (vm.exception()) {
  166. vm.clear_exception();
  167. return Wasm::Trap();
  168. }
  169. if (type.results().is_empty())
  170. return Wasm::Result { Vector<Wasm::Value> {} };
  171. if (type.results().size() == 1) {
  172. auto value = to_webassembly_value(result, type.results().first(), global_object);
  173. if (!value.has_value())
  174. return Wasm::Trap {};
  175. return Wasm::Result { Vector<Wasm::Value> { value.release_value() } };
  176. }
  177. // FIXME: Multiple returns
  178. TODO();
  179. },
  180. type
  181. };
  182. auto address = s_abstract_machine.store().allocate(move(host_function));
  183. dbgln("Resolved to {}", address->value());
  184. // FIXME: LinkError instead.
  185. VERIFY(address.has_value());
  186. resolved_imports.set(import_name, Wasm::ExternValue { Wasm::FunctionAddress { *address } });
  187. },
  188. [&](Wasm::GlobalType const& type) {
  189. Optional<Wasm::GlobalAddress> address;
  190. // https://webassembly.github.io/spec/js-api/#read-the-imports step 5.1
  191. if (import_.is_number() || import_.is_bigint()) {
  192. if (import_.is_number() && type.type().kind() == Wasm::ValueType::I64) {
  193. // FIXME: Throw a LinkError instead.
  194. vm.throw_exception<JS::TypeError>(global_object, "LinkError: Import resolution attempted to cast a Number to a BigInteger");
  195. return;
  196. }
  197. if (import_.is_bigint() && type.type().kind() != Wasm::ValueType::I64) {
  198. // FIXME: Throw a LinkError instead.
  199. vm.throw_exception<JS::TypeError>(global_object, "LinkError: Import resolution attempted to cast a BigInteger to a Number");
  200. return;
  201. }
  202. auto cast_value = to_webassembly_value(import_, type.type(), global_object);
  203. if (!cast_value.has_value())
  204. return;
  205. address = s_abstract_machine.store().allocate({ type.type(), false }, cast_value.release_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. vm.throw_exception<JS::TypeError>(global_object, "LinkError: Invalid value for global type");
  212. return;
  213. }
  214. resolved_imports.set(import_name, Wasm::ExternValue { *address });
  215. },
  216. [&](Wasm::MemoryType const&) {
  217. if (!import_.is_object() || !is<WebAssemblyMemoryObject>(import_.as_object())) {
  218. // FIXME: Throw a LinkError instead
  219. vm.throw_exception<JS::TypeError>(global_object, "LinkError: Expected an instance of WebAssembly.Memory for a memory import");
  220. return;
  221. }
  222. auto address = static_cast<WebAssemblyMemoryObject const&>(import_.as_object()).address();
  223. resolved_imports.set(import_name, Wasm::ExternValue { address });
  224. },
  225. [&](const auto&) {
  226. // FIXME: Implement these.
  227. dbgln("Unimplemented import of non-function attempted");
  228. vm.throw_exception<JS::TypeError>(global_object, "LinkError: Not Implemented");
  229. });
  230. if (vm.exception())
  231. break;
  232. }
  233. if (auto exception = vm.exception()) {
  234. vm.clear_exception();
  235. return exception->value();
  236. }
  237. }
  238. linker.link(resolved_imports);
  239. auto link_result = linker.finish();
  240. if (link_result.is_error()) {
  241. // FIXME: Throw a LinkError.
  242. StringBuilder builder;
  243. builder.append("LinkError: Missing ");
  244. builder.join(' ', link_result.error().missing_imports);
  245. return JS::Value(JS::TypeError::create(global_object, builder.build()));
  246. }
  247. auto instance_result = s_abstract_machine.instantiate(module, link_result.release_value());
  248. if (instance_result.is_error()) {
  249. // FIXME: Throw a LinkError instead.
  250. return JS::Value(JS::TypeError::create(global_object, instance_result.error().error));
  251. }
  252. s_instantiated_modules.append(instance_result.release_value());
  253. s_module_caches.empend();
  254. return s_instantiated_modules.size() - 1;
  255. }
  256. JS_DEFINE_NATIVE_FUNCTION(WebAssemblyObject::instantiate)
  257. {
  258. // FIXME: This shouldn't block!
  259. auto buffer = vm.argument(0).to_object(global_object);
  260. auto promise = JS::Promise::create(global_object);
  261. bool should_return_module = false;
  262. auto take_exception_and_reject_if_needed = [&] {
  263. if (vm.exception()) {
  264. auto rejection_value = vm.exception()->value();
  265. vm.clear_exception();
  266. promise->reject(rejection_value);
  267. return true;
  268. }
  269. return false;
  270. };
  271. if (take_exception_and_reject_if_needed())
  272. return promise;
  273. const Wasm::Module* module { nullptr };
  274. if (is<JS::ArrayBuffer>(buffer) || is<JS::TypedArrayBase>(buffer)) {
  275. auto result = parse_module(global_object, buffer);
  276. if (result.is_error()) {
  277. promise->reject(result.error());
  278. return promise;
  279. }
  280. module = &WebAssemblyObject::s_compiled_modules.at(result.value()).module;
  281. should_return_module = true;
  282. } else if (is<WebAssemblyModuleObject>(buffer)) {
  283. module = &static_cast<WebAssemblyModuleObject*>(buffer)->module();
  284. } else {
  285. auto error = JS::TypeError::create(global_object, String::formatted("{} is not an ArrayBuffer or a Module", buffer->class_name()));
  286. promise->reject(error);
  287. return promise;
  288. }
  289. VERIFY(module);
  290. auto result = instantiate_module(*module, vm, global_object);
  291. if (result.is_error()) {
  292. promise->reject(result.release_error());
  293. } else {
  294. auto instance_object = vm.heap().allocate<WebAssemblyInstanceObject>(global_object, global_object, result.value());
  295. if (should_return_module) {
  296. auto object = JS::Object::create(global_object, nullptr);
  297. object->define_direct_property("module", vm.heap().allocate<WebAssemblyModuleObject>(global_object, global_object, s_compiled_modules.size() - 1), JS::default_attributes);
  298. object->define_direct_property("instance", instance_object, JS::default_attributes);
  299. promise->fulfill(object);
  300. } else {
  301. promise->fulfill(instance_object);
  302. }
  303. }
  304. return promise;
  305. }
  306. JS::Value to_js_value(Wasm::Value& wasm_value, JS::GlobalObject& global_object)
  307. {
  308. switch (wasm_value.type().kind()) {
  309. case Wasm::ValueType::I64:
  310. return global_object.heap().allocate<JS::BigInt>(global_object, Crypto::SignedBigInteger::create_from(wasm_value.to<i64>().value()));
  311. case Wasm::ValueType::I32:
  312. return JS::Value(wasm_value.to<i32>().value());
  313. case Wasm::ValueType::F64:
  314. return JS::Value(static_cast<double>(wasm_value.to<float>().value()));
  315. case Wasm::ValueType::F32:
  316. return JS::Value(wasm_value.to<double>().value());
  317. case Wasm::ValueType::FunctionReference:
  318. // FIXME: What's the name of a function reference that isn't exported?
  319. return create_native_function(wasm_value.to<Wasm::FunctionAddress>().value(), "FIXME_IHaveNoIdeaWhatThisShouldBeCalled", global_object);
  320. case Wasm::ValueType::NullFunctionReference:
  321. return JS::js_null();
  322. case Wasm::ValueType::ExternReference:
  323. case Wasm::ValueType::NullExternReference:
  324. TODO();
  325. }
  326. VERIFY_NOT_REACHED();
  327. }
  328. Optional<Wasm::Value> to_webassembly_value(JS::Value value, const Wasm::ValueType& type, JS::GlobalObject& global_object)
  329. {
  330. static Crypto::SignedBigInteger two_64 = "1"_sbigint.shift_left(64);
  331. auto& vm = global_object.vm();
  332. switch (type.kind()) {
  333. case Wasm::ValueType::I64: {
  334. auto bigint = value.to_bigint(global_object);
  335. if (vm.exception())
  336. return {};
  337. auto value = bigint->big_integer().divided_by(two_64).remainder;
  338. VERIFY(value.trimmed_length() <= 2);
  339. BigEndian<i64> integer { 0 };
  340. value.export_data({ &integer, 2 });
  341. return Wasm::Value { static_cast<i64>(integer) };
  342. }
  343. case Wasm::ValueType::I32: {
  344. auto _i32 = value.to_i32(global_object);
  345. if (vm.exception())
  346. return {};
  347. return Wasm::Value { static_cast<i32>(_i32) };
  348. }
  349. case Wasm::ValueType::F64: {
  350. auto number = value.to_double(global_object);
  351. if (vm.exception())
  352. return {};
  353. return Wasm::Value { static_cast<double>(number) };
  354. }
  355. case Wasm::ValueType::F32: {
  356. auto number = value.to_double(global_object);
  357. if (vm.exception())
  358. return {};
  359. return Wasm::Value { static_cast<float>(number) };
  360. }
  361. case Wasm::ValueType::FunctionReference:
  362. case Wasm::ValueType::ExternReference:
  363. case Wasm::ValueType::NullFunctionReference:
  364. case Wasm::ValueType::NullExternReference:
  365. TODO();
  366. }
  367. VERIFY_NOT_REACHED();
  368. }
  369. JS::NativeFunction* create_native_function(Wasm::FunctionAddress address, String name, JS::GlobalObject& global_object)
  370. {
  371. Optional<Wasm::FunctionType> type;
  372. WebAssemblyObject::s_abstract_machine.store().get(address)->visit([&](const auto& value) { type = value.type(); });
  373. if (auto entry = WebAssemblyObject::s_global_cache.function_instances.get(address); entry.has_value())
  374. return *entry;
  375. auto function = JS::NativeFunction::create(
  376. global_object,
  377. name,
  378. [address, type = type.release_value()](JS::VM& vm, JS::GlobalObject& global_object) -> JS::Value {
  379. Vector<Wasm::Value> values;
  380. values.ensure_capacity(type.parameters().size());
  381. // Grab as many values as needed and convert them.
  382. size_t index = 0;
  383. for (auto& type : type.parameters()) {
  384. auto result = to_webassembly_value(vm.argument(index++), type, global_object);
  385. if (result.has_value())
  386. values.append(result.release_value());
  387. else
  388. return {};
  389. }
  390. auto result = WebAssemblyObject::s_abstract_machine.invoke(address, move(values));
  391. // FIXME: Use the convoluted mapping of errors defined in the spec.
  392. if (result.is_trap()) {
  393. vm.throw_exception<JS::TypeError>(global_object, String::formatted("Wasm execution trapped (WIP): {}", result.trap().reason));
  394. return {};
  395. }
  396. if (result.values().is_empty())
  397. return JS::js_undefined();
  398. if (result.values().size() == 1)
  399. return to_js_value(result.values().first(), global_object);
  400. Vector<JS::Value> result_values;
  401. for (auto& entry : result.values())
  402. result_values.append(to_js_value(entry, global_object));
  403. return JS::Array::create_from(global_object, result_values);
  404. });
  405. WebAssemblyObject::s_global_cache.function_instances.set(address, function);
  406. return function;
  407. }
  408. WebAssemblyMemoryObject::WebAssemblyMemoryObject(JS::GlobalObject& global_object, Wasm::MemoryAddress address)
  409. : Object(static_cast<WindowObject&>(global_object).ensure_web_prototype<WebAssemblyMemoryPrototype>("WebAssemblyMemoryPrototype"))
  410. , m_address(address)
  411. {
  412. }
  413. }