WebAssemblyObject.cpp 23 KB

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