WebAssemblyObject.cpp 21 KB

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