WebAssemblyObject.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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/MemoryStream.h>
  14. #include <AK/ScopeGuard.h>
  15. #include <LibJS/Runtime/Array.h>
  16. #include <LibJS/Runtime/ArrayBuffer.h>
  17. #include <LibJS/Runtime/BigInt.h>
  18. #include <LibJS/Runtime/DataView.h>
  19. #include <LibJS/Runtime/ThrowableStringBuilder.h>
  20. #include <LibJS/Runtime/TypedArray.h>
  21. #include <LibWasm/AbstractMachine/Interpreter.h>
  22. #include <LibWasm/AbstractMachine/Validator.h>
  23. #include <LibWeb/Bindings/Intrinsics.h>
  24. #include <LibWeb/WebAssembly/WebAssemblyInstanceConstructor.h>
  25. #include <LibWeb/WebAssembly/WebAssemblyObject.h>
  26. namespace Web::Bindings {
  27. WebAssemblyObject::WebAssemblyObject(JS::Realm& realm)
  28. : Object(ConstructWithPrototypeTag::Tag, *realm.intrinsics().object_prototype())
  29. {
  30. s_abstract_machine.enable_instruction_count_limit();
  31. }
  32. JS::ThrowCompletionOr<void> WebAssemblyObject::initialize(JS::Realm& realm)
  33. {
  34. MUST_OR_THROW_OOM(Object::initialize(realm));
  35. u8 attr = JS::Attribute::Configurable | JS::Attribute::Writable | JS::Attribute::Enumerable;
  36. define_native_function(realm, "validate", validate, 1, attr);
  37. define_native_function(realm, "compile", compile, 1, attr);
  38. define_native_function(realm, "instantiate", instantiate, 1, attr);
  39. auto& memory_constructor = Bindings::ensure_web_constructor<WebAssemblyMemoryPrototype>(realm, "WebAssembly.Memory"sv);
  40. define_direct_property("Memory", &memory_constructor, JS::Attribute::Writable | JS::Attribute::Configurable);
  41. auto& instance_constructor = Bindings::ensure_web_constructor<WebAssemblyInstancePrototype>(realm, "WebAssembly.Instance"sv);
  42. define_direct_property("Instance", &instance_constructor, JS::Attribute::Writable | JS::Attribute::Configurable);
  43. auto& module_constructor = Bindings::ensure_web_constructor<WebAssemblyModulePrototype>(realm, "WebAssembly.Module"sv);
  44. define_direct_property("Module", &module_constructor, JS::Attribute::Writable | JS::Attribute::Configurable);
  45. auto& table_constructor = Bindings::ensure_web_constructor<WebAssemblyTablePrototype>(realm, "WebAssembly.Table"sv);
  46. define_direct_property("Table", &table_constructor, JS::Attribute::Writable | JS::Attribute::Configurable);
  47. return {};
  48. }
  49. NonnullOwnPtrVector<WebAssemblyObject::CompiledWebAssemblyModule> WebAssemblyObject::s_compiled_modules;
  50. NonnullOwnPtrVector<Wasm::ModuleInstance> WebAssemblyObject::s_instantiated_modules;
  51. Vector<WebAssemblyObject::ModuleCache> WebAssemblyObject::s_module_caches;
  52. WebAssemblyObject::GlobalModuleCache WebAssemblyObject::s_global_cache;
  53. Wasm::AbstractMachine WebAssemblyObject::s_abstract_machine;
  54. void WebAssemblyObject::visit_edges(Visitor& visitor)
  55. {
  56. Base::visit_edges(visitor);
  57. for (auto& entry : s_global_cache.function_instances)
  58. visitor.visit(entry.value);
  59. for (auto& module_cache : s_module_caches) {
  60. for (auto& entry : module_cache.function_instances)
  61. visitor.visit(entry.value);
  62. for (auto& entry : module_cache.memory_instances)
  63. visitor.visit(entry.value);
  64. for (auto& entry : module_cache.table_instances)
  65. visitor.visit(entry.value);
  66. }
  67. }
  68. JS_DEFINE_NATIVE_FUNCTION(WebAssemblyObject::validate)
  69. {
  70. // 1. Let stableBytes be a copy of the bytes held by the buffer bytes.
  71. // Note: There's no need to copy the bytes here as the buffer data cannot change while we're compiling the module.
  72. auto buffer = TRY(vm.argument(0).to_object(vm));
  73. // 2. Compile stableBytes as a WebAssembly module and store the results as module.
  74. auto maybe_module = parse_module(vm, buffer);
  75. // 3. If module is error, return false.
  76. if (maybe_module.is_error())
  77. return JS::Value(false);
  78. // Drop the module from the cache, we're never going to refer to it.
  79. ScopeGuard drop_from_cache {
  80. [&] {
  81. (void)s_compiled_modules.take_last();
  82. }
  83. };
  84. // 3 continued - our "compile" step is lazy with validation, explicitly do the validation.
  85. if (s_abstract_machine.validate(s_compiled_modules[maybe_module.value()].module).is_error())
  86. return JS::Value(false);
  87. // 4. Return true.
  88. return JS::Value(true);
  89. }
  90. JS::ThrowCompletionOr<size_t> parse_module(JS::VM& vm, JS::Object* buffer_object)
  91. {
  92. ReadonlyBytes data;
  93. if (is<JS::ArrayBuffer>(buffer_object)) {
  94. auto& buffer = static_cast<JS::ArrayBuffer&>(*buffer_object);
  95. data = buffer.buffer();
  96. } else if (is<JS::TypedArrayBase>(buffer_object)) {
  97. auto& buffer = static_cast<JS::TypedArrayBase&>(*buffer_object);
  98. data = buffer.viewed_array_buffer()->buffer().span().slice(buffer.byte_offset(), buffer.byte_length());
  99. } else if (is<JS::DataView>(buffer_object)) {
  100. auto& buffer = static_cast<JS::DataView&>(*buffer_object);
  101. data = buffer.viewed_array_buffer()->buffer().span().slice(buffer.byte_offset(), buffer.byte_length());
  102. } else {
  103. return vm.throw_completion<JS::TypeError>("Not a BufferSource"sv);
  104. }
  105. FixedMemoryStream stream { data };
  106. auto module_result = Wasm::Module::parse(stream);
  107. if (module_result.is_error()) {
  108. // FIXME: Throw CompileError instead.
  109. return vm.throw_completion<JS::TypeError>(Wasm::parse_error_to_deprecated_string(module_result.error()));
  110. }
  111. if (auto validation_result = WebAssemblyObject::s_abstract_machine.validate(module_result.value()); validation_result.is_error()) {
  112. // FIXME: Throw CompileError instead.
  113. return vm.throw_completion<JS::TypeError>(validation_result.error().error_string);
  114. }
  115. WebAssemblyObject::s_compiled_modules.append(make<WebAssemblyObject::CompiledWebAssemblyModule>(module_result.release_value()));
  116. return WebAssemblyObject::s_compiled_modules.size() - 1;
  117. }
  118. JS_DEFINE_NATIVE_FUNCTION(WebAssemblyObject::compile)
  119. {
  120. auto& realm = *vm.current_realm();
  121. // FIXME: This shouldn't block!
  122. auto buffer_or_error = vm.argument(0).to_object(vm);
  123. JS::Value rejection_value;
  124. if (buffer_or_error.is_error())
  125. rejection_value = *buffer_or_error.throw_completion().value();
  126. auto promise = JS::Promise::create(realm);
  127. if (!rejection_value.is_empty()) {
  128. promise->reject(rejection_value);
  129. return promise;
  130. }
  131. auto* buffer = buffer_or_error.release_value();
  132. auto result = parse_module(vm, buffer);
  133. if (result.is_error())
  134. promise->reject(*result.release_error().value());
  135. else
  136. promise->fulfill(MUST_OR_THROW_OOM(vm.heap().allocate<WebAssemblyModuleObject>(realm, realm, result.release_value())));
  137. return promise;
  138. }
  139. JS::ThrowCompletionOr<size_t> WebAssemblyObject::instantiate_module(JS::VM& vm, Wasm::Module const& module)
  140. {
  141. Wasm::Linker linker { module };
  142. HashMap<Wasm::Linker::Name, Wasm::ExternValue> resolved_imports;
  143. auto import_argument = vm.argument(1);
  144. if (!import_argument.is_undefined()) {
  145. auto* import_object = TRY(import_argument.to_object(vm));
  146. dbgln("Trying to resolve stuff because import object was specified");
  147. for (Wasm::Linker::Name const& import_name : linker.unresolved_imports()) {
  148. dbgln("Trying to resolve {}::{}", import_name.module, import_name.name);
  149. auto value_or_error = import_object->get(import_name.module);
  150. if (value_or_error.is_error())
  151. break;
  152. auto value = value_or_error.release_value();
  153. auto object_or_error = value.to_object(vm);
  154. if (object_or_error.is_error())
  155. break;
  156. auto* object = object_or_error.release_value();
  157. auto import_or_error = object->get(import_name.name);
  158. if (import_or_error.is_error())
  159. break;
  160. auto import_ = import_or_error.release_value();
  161. TRY(import_name.type.visit(
  162. [&](Wasm::TypeIndex index) -> JS::ThrowCompletionOr<void> {
  163. dbgln("Trying to resolve a function {}::{}, type index {}", import_name.module, import_name.name, index.value());
  164. auto& type = module.type(index);
  165. // FIXME: IsCallable()
  166. if (!import_.is_function())
  167. return {};
  168. auto& function = import_.as_function();
  169. // FIXME: If this is a function created by create_native_function(),
  170. // just extract its address and resolve to that.
  171. Wasm::HostFunction host_function {
  172. [&](auto&, auto& arguments) -> Wasm::Result {
  173. JS::MarkedVector<JS::Value> argument_values { vm.heap() };
  174. for (auto& entry : arguments)
  175. argument_values.append(to_js_value(vm, entry));
  176. auto result = TRY(JS::call(vm, function, JS::js_undefined(), move(argument_values)));
  177. if (type.results().is_empty())
  178. return Wasm::Result { Vector<Wasm::Value> {} };
  179. if (type.results().size() == 1)
  180. return Wasm::Result { Vector<Wasm::Value> { TRY(to_webassembly_value(vm, result, type.results().first())) } };
  181. // FIXME: Multiple returns
  182. TODO();
  183. },
  184. type
  185. };
  186. auto address = s_abstract_machine.store().allocate(move(host_function));
  187. dbgln("Resolved to {}", address->value());
  188. // FIXME: LinkError instead.
  189. VERIFY(address.has_value());
  190. resolved_imports.set(import_name, Wasm::ExternValue { Wasm::FunctionAddress { *address } });
  191. return {};
  192. },
  193. [&](Wasm::GlobalType const& type) -> JS::ThrowCompletionOr<void> {
  194. Optional<Wasm::GlobalAddress> address;
  195. // https://webassembly.github.io/spec/js-api/#read-the-imports step 5.1
  196. if (import_.is_number() || import_.is_bigint()) {
  197. if (import_.is_number() && type.type().kind() == Wasm::ValueType::I64) {
  198. // FIXME: Throw a LinkError instead.
  199. return vm.throw_completion<JS::TypeError>("LinkError: Import resolution attempted to cast a Number to a BigInteger"sv);
  200. }
  201. if (import_.is_bigint() && type.type().kind() != Wasm::ValueType::I64) {
  202. // FIXME: Throw a LinkError instead.
  203. return vm.throw_completion<JS::TypeError>("LinkError: Import resolution attempted to cast a BigInteger to a Number"sv);
  204. }
  205. auto cast_value = TRY(to_webassembly_value(vm, import_, type.type()));
  206. address = s_abstract_machine.store().allocate({ type.type(), false }, cast_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. return vm.throw_completion<JS::TypeError>("LinkError: Invalid value for global type"sv);
  213. }
  214. resolved_imports.set(import_name, Wasm::ExternValue { *address });
  215. return {};
  216. },
  217. [&](Wasm::MemoryType const&) -> JS::ThrowCompletionOr<void> {
  218. if (!import_.is_object() || !is<WebAssemblyMemoryObject>(import_.as_object())) {
  219. // FIXME: Throw a LinkError instead
  220. return vm.throw_completion<JS::TypeError>("LinkError: Expected an instance of WebAssembly.Memory for a memory import"sv);
  221. }
  222. auto address = static_cast<WebAssemblyMemoryObject const&>(import_.as_object()).address();
  223. resolved_imports.set(import_name, Wasm::ExternValue { address });
  224. return {};
  225. },
  226. [&](Wasm::TableType const&) -> JS::ThrowCompletionOr<void> {
  227. if (!import_.is_object() || !is<WebAssemblyTableObject>(import_.as_object())) {
  228. // FIXME: Throw a LinkError instead
  229. return vm.throw_completion<JS::TypeError>("LinkError: Expected an instance of WebAssembly.Table for a table import"sv);
  230. }
  231. auto address = static_cast<WebAssemblyTableObject const&>(import_.as_object()).address();
  232. resolved_imports.set(import_name, Wasm::ExternValue { address });
  233. return {};
  234. },
  235. [&](auto const&) -> JS::ThrowCompletionOr<void> {
  236. // FIXME: Implement these.
  237. dbgln("Unimplemented import of non-function attempted");
  238. return vm.throw_completion<JS::TypeError>("LinkError: Not Implemented"sv);
  239. }));
  240. }
  241. }
  242. linker.link(resolved_imports);
  243. auto link_result = linker.finish();
  244. if (link_result.is_error()) {
  245. // FIXME: Throw a LinkError.
  246. JS::ThrowableStringBuilder builder(vm);
  247. MUST_OR_THROW_OOM(builder.append("LinkError: Missing "sv));
  248. MUST_OR_THROW_OOM(builder.join(' ', link_result.error().missing_imports));
  249. return vm.throw_completion<JS::TypeError>(MUST_OR_THROW_OOM(builder.to_string()));
  250. }
  251. auto instance_result = s_abstract_machine.instantiate(module, link_result.release_value());
  252. if (instance_result.is_error()) {
  253. // FIXME: Throw a LinkError instead.
  254. return vm.throw_completion<JS::TypeError>(instance_result.error().error);
  255. }
  256. s_instantiated_modules.append(instance_result.release_value());
  257. s_module_caches.empend();
  258. return s_instantiated_modules.size() - 1;
  259. }
  260. JS_DEFINE_NATIVE_FUNCTION(WebAssemblyObject::instantiate)
  261. {
  262. auto& realm = *vm.current_realm();
  263. // FIXME: This shouldn't block!
  264. auto buffer_or_error = vm.argument(0).to_object(vm);
  265. auto promise = JS::Promise::create(realm);
  266. bool should_return_module = false;
  267. if (buffer_or_error.is_error()) {
  268. auto rejection_value = *buffer_or_error.throw_completion().value();
  269. promise->reject(rejection_value);
  270. return promise;
  271. }
  272. auto* buffer = buffer_or_error.release_value();
  273. Wasm::Module const* module { nullptr };
  274. if (is<JS::ArrayBuffer>(buffer) || is<JS::TypedArrayBase>(buffer)) {
  275. auto result = parse_module(vm, buffer);
  276. if (result.is_error()) {
  277. promise->reject(*result.release_error().value());
  278. return promise;
  279. }
  280. module = &WebAssemblyObject::s_compiled_modules.at(result.release_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(realm, TRY_OR_THROW_OOM(vm, 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(vm, *module);
  291. if (result.is_error()) {
  292. promise->reject(*result.release_error().value());
  293. } else {
  294. auto instance_object = MUST_OR_THROW_OOM(vm.heap().allocate<WebAssemblyInstanceObject>(realm, realm, result.release_value()));
  295. if (should_return_module) {
  296. auto object = JS::Object::create(realm, nullptr);
  297. object->define_direct_property("module", MUST_OR_THROW_OOM(vm.heap().allocate<WebAssemblyModuleObject>(realm, realm, 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(JS::VM& vm, Wasm::Value& wasm_value)
  307. {
  308. auto& realm = *vm.current_realm();
  309. switch (wasm_value.type().kind()) {
  310. case Wasm::ValueType::I64:
  311. return realm.heap().allocate<JS::BigInt>(realm, ::Crypto::SignedBigInteger { wasm_value.to<i64>().value() }).release_allocated_value_but_fixme_should_propagate_errors();
  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(vm, wasm_value.to<Wasm::Reference::Func>().value().address, "FIXME_IHaveNoIdeaWhatThisShouldBeCalled");
  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. 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. case Wasm::ValueType::NullFunctionReference: {
  356. if (value.is_null())
  357. return Wasm::Value { Wasm::ValueType(Wasm::ValueType::NullExternReference), 0ull };
  358. if (value.is_function()) {
  359. auto& function = value.as_function();
  360. for (auto& entry : WebAssemblyObject::s_global_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. case Wasm::ValueType::NullExternReference:
  369. TODO();
  370. }
  371. VERIFY_NOT_REACHED();
  372. }
  373. JS::NativeFunction* create_native_function(JS::VM& vm, Wasm::FunctionAddress address, DeprecatedString const& name)
  374. {
  375. auto& realm = *vm.current_realm();
  376. Optional<Wasm::FunctionType> type;
  377. WebAssemblyObject::s_abstract_machine.store().get(address)->visit([&](auto const& value) { type = value.type(); });
  378. if (auto entry = WebAssemblyObject::s_global_cache.function_instances.get(address); entry.has_value())
  379. return *entry;
  380. auto function = JS::NativeFunction::create(
  381. realm,
  382. name,
  383. [address, type = type.release_value()](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
  384. auto& realm = *vm.current_realm();
  385. Vector<Wasm::Value> values;
  386. values.ensure_capacity(type.parameters().size());
  387. // Grab as many values as needed and convert them.
  388. size_t index = 0;
  389. for (auto& type : type.parameters())
  390. values.append(TRY(to_webassembly_value(vm, vm.argument(index++), type)));
  391. auto result = WebAssemblyObject::s_abstract_machine.invoke(address, move(values));
  392. // FIXME: Use the convoluted mapping of errors defined in the spec.
  393. if (result.is_trap())
  394. return vm.throw_completion<JS::TypeError>(TRY_OR_THROW_OOM(vm, String::formatted("Wasm execution trapped (WIP): {}", result.trap().reason)));
  395. if (result.values().is_empty())
  396. return JS::js_undefined();
  397. if (result.values().size() == 1)
  398. return to_js_value(vm, result.values().first());
  399. Vector<JS::Value> result_values;
  400. for (auto& entry : result.values())
  401. result_values.append(to_js_value(vm, entry));
  402. return JS::Value(JS::Array::create_from(realm, result_values));
  403. });
  404. WebAssemblyObject::s_global_cache.function_instances.set(address, function);
  405. return function;
  406. }
  407. WebAssemblyMemoryObject::WebAssemblyMemoryObject(JS::Realm& realm, Wasm::MemoryAddress address)
  408. : Object(ConstructWithPrototypeTag::Tag, Bindings::ensure_web_prototype<WebAssemblyMemoryPrototype>(realm, "WebAssembly.Memory"))
  409. , m_address(address)
  410. {
  411. }
  412. }