WebAssemblyObject.cpp 17 KB

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