WebAssemblyObject.cpp 20 KB

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