WebAssemblyObject.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. /*
  2. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/Array.h>
  7. #include <LibJS/Runtime/ArrayBuffer.h>
  8. #include <LibJS/Runtime/BigInt.h>
  9. #include <LibJS/Runtime/TypedArray.h>
  10. #include <LibWasm/AbstractMachine/Interpreter.h>
  11. #include <LibWeb/WebAssembly/WebAssemblyObject.h>
  12. namespace Web::Bindings {
  13. WebAssemblyObject::WebAssemblyObject(JS::GlobalObject& global_object)
  14. : Object(*global_object.object_prototype())
  15. {
  16. }
  17. void WebAssemblyObject::initialize(JS::GlobalObject& global_object)
  18. {
  19. Object::initialize(global_object);
  20. define_native_function("validate", validate, 1);
  21. define_native_function("compile", compile, 1);
  22. define_native_function("instantiate", instantiate, 1);
  23. }
  24. NonnullOwnPtrVector<WebAssemblyObject::CompiledWebAssemblyModule> WebAssemblyObject::s_compiled_modules;
  25. NonnullOwnPtrVector<Wasm::ModuleInstance> WebAssemblyObject::s_instantiated_modules;
  26. Wasm::AbstractMachine WebAssemblyObject::s_abstract_machine;
  27. JS_DEFINE_NATIVE_FUNCTION(WebAssemblyObject::validate)
  28. {
  29. // FIXME: Implement this once module validation is implemented in LibWasm.
  30. dbgln("Hit WebAssemblyObject::validate() stub!");
  31. return JS::Value { true };
  32. }
  33. static Result<size_t, JS::Value> parse_module(JS::GlobalObject& global_object, JS::Object* buffer)
  34. {
  35. ByteBuffer* bytes;
  36. if (is<JS::ArrayBuffer>(buffer)) {
  37. auto array_buffer = static_cast<JS::ArrayBuffer*>(buffer);
  38. bytes = &array_buffer->buffer();
  39. } else if (is<JS::TypedArrayBase>(buffer)) {
  40. auto array = static_cast<JS::TypedArrayBase*>(buffer);
  41. bytes = &array->viewed_array_buffer()->buffer();
  42. } else {
  43. auto error = JS::TypeError::create(global_object, String::formatted("{} is not an ArrayBuffer", buffer->class_name()));
  44. return JS::Value { error };
  45. }
  46. InputMemoryStream stream { *bytes };
  47. auto module_result = Wasm::Module::parse(stream);
  48. if (module_result.is_error()) {
  49. // FIXME: Throw CompileError instead.
  50. auto error = JS::TypeError::create(global_object, Wasm::parse_error_to_string(module_result.error()));
  51. return JS::Value { error };
  52. }
  53. WebAssemblyObject::s_compiled_modules.append(make<WebAssemblyObject::CompiledWebAssemblyModule>(module_result.release_value()));
  54. return WebAssemblyObject::s_compiled_modules.size() - 1;
  55. }
  56. JS_DEFINE_NATIVE_FUNCTION(WebAssemblyObject::compile)
  57. {
  58. // FIXME: This shouldn't block!
  59. auto buffer = vm.argument(0).to_object(global_object);
  60. JS::Value rejection_value;
  61. if (vm.exception()) {
  62. rejection_value = vm.exception()->value();
  63. vm.clear_exception();
  64. }
  65. auto promise = JS::Promise::create(global_object);
  66. if (!rejection_value.is_empty()) {
  67. promise->reject(rejection_value);
  68. return promise;
  69. }
  70. auto result = parse_module(global_object, buffer);
  71. if (result.is_error())
  72. promise->reject(result.error());
  73. else
  74. promise->fulfill(vm.heap().allocate<WebAssemblyModuleObject>(global_object, global_object, result.value()));
  75. return promise;
  76. }
  77. JS_DEFINE_NATIVE_FUNCTION(WebAssemblyObject::instantiate)
  78. {
  79. // FIXME: This shouldn't block!
  80. auto buffer = vm.argument(0).to_object(global_object);
  81. JS::Value rejection_value;
  82. if (vm.exception()) {
  83. rejection_value = vm.exception()->value();
  84. vm.clear_exception();
  85. }
  86. auto promise = JS::Promise::create(global_object);
  87. if (!rejection_value.is_empty()) {
  88. promise->reject(rejection_value);
  89. return promise;
  90. }
  91. const Wasm::Module* module { nullptr };
  92. if (is<JS::ArrayBuffer>(buffer) || is<JS::TypedArrayBase>(buffer)) {
  93. auto result = parse_module(global_object, buffer);
  94. if (result.is_error()) {
  95. promise->reject(result.error());
  96. return promise;
  97. }
  98. module = &WebAssemblyObject::s_compiled_modules.at(result.value()).module;
  99. } else if (is<WebAssemblyModuleObject>(buffer)) {
  100. module = &static_cast<WebAssemblyModuleObject*>(buffer)->module();
  101. } else {
  102. auto error = JS::TypeError::create(global_object, String::formatted("{} is not an ArrayBuffer or a Module", buffer->class_name()));
  103. promise->reject(error);
  104. return promise;
  105. }
  106. VERIFY(module);
  107. HashMap<Wasm::Linker::Name, Wasm::ExternValue> import_values;
  108. auto import_argument = vm.argument(1);
  109. if (!import_argument.is_undefined()) {
  110. [[maybe_unused]] auto import_object = import_argument.to_object(global_object);
  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. // FIXME: Populate the import values.
  121. }
  122. Wasm::Linker linker { *module };
  123. linker.link(import_values);
  124. auto link_result = linker.finish();
  125. if (link_result.is_error()) {
  126. // FIXME: Throw a LinkError.
  127. StringBuilder builder;
  128. builder.append("LinkError: Missing ");
  129. builder.join(' ', link_result.error().missing_imports);
  130. auto error = JS::TypeError::create(global_object, builder.build());
  131. promise->reject(error);
  132. return promise;
  133. }
  134. auto instance_result = s_abstract_machine.instantiate(*module, link_result.release_value());
  135. if (instance_result.is_error()) {
  136. auto error = JS::TypeError::create(global_object, instance_result.error().error);
  137. promise->reject(error);
  138. return promise;
  139. }
  140. s_instantiated_modules.append(instance_result.release_value());
  141. promise->fulfill(vm.heap().allocate<WebAssemblyInstanceObject>(global_object, global_object, s_instantiated_modules.size() - 1));
  142. return promise;
  143. }
  144. WebAssemblyModuleObject::WebAssemblyModuleObject(JS::GlobalObject& global_object, size_t index)
  145. : Object(*global_object.object_prototype())
  146. , m_index(index)
  147. {
  148. }
  149. WebAssemblyInstanceObject::WebAssemblyInstanceObject(JS::GlobalObject& global_object, size_t index)
  150. : Object(*global_object.object_prototype())
  151. , m_index(index)
  152. {
  153. }
  154. static JS::NativeFunction* create_native_function(Wasm::FunctionAddress address, String name, JS::GlobalObject& global_object);
  155. static JS::Value to_js_value(Wasm::Value& wasm_value, JS::GlobalObject& global_object)
  156. {
  157. switch (wasm_value.type().kind()) {
  158. case Wasm::ValueType::I64:
  159. // FIXME: This is extremely silly...
  160. return global_object.heap().allocate<JS::BigInt>(global_object, Crypto::SignedBigInteger::from_base10(String::number(wasm_value.to<i64>().value())));
  161. case Wasm::ValueType::I32:
  162. return JS::Value(wasm_value.to<i32>().value());
  163. case Wasm::ValueType::F64:
  164. return JS::Value(static_cast<double>(wasm_value.to<float>().value()));
  165. case Wasm::ValueType::F32:
  166. return JS::Value(wasm_value.to<double>().value());
  167. case Wasm::ValueType::FunctionReference:
  168. // FIXME: What's the name of a function reference that isn't exported?
  169. return create_native_function(wasm_value.to<Wasm::FunctionAddress>().value(), "FIXME_IHaveNoIdeaWhatThisShouldBeCalled", global_object);
  170. case Wasm::ValueType::ExternReference:
  171. TODO();
  172. }
  173. VERIFY_NOT_REACHED();
  174. }
  175. static Optional<Wasm::Value> to_webassembly_value(JS::Value value, const Wasm::ValueType& type, JS::GlobalObject& global_object)
  176. {
  177. static Crypto::SignedBigInteger two_64 = "1"_sbigint.shift_left(64);
  178. auto& vm = global_object.vm();
  179. switch (type.kind()) {
  180. case Wasm::ValueType::I64: {
  181. auto bigint = value.to_bigint(global_object);
  182. if (vm.exception())
  183. return {};
  184. auto value = bigint->big_integer().divided_by(two_64).remainder;
  185. VERIFY(value.trimmed_length() <= 2);
  186. BigEndian<i64> integer { 0 };
  187. value.export_data({ &integer, 2 });
  188. return Wasm::Value { static_cast<i64>(integer) };
  189. }
  190. case Wasm::ValueType::I32: {
  191. auto _i32 = value.to_i32(global_object);
  192. if (vm.exception())
  193. return {};
  194. return Wasm::Value { static_cast<i32>(_i32) };
  195. }
  196. case Wasm::ValueType::F64: {
  197. auto number = value.to_double(global_object);
  198. if (vm.exception())
  199. return {};
  200. return Wasm::Value { static_cast<double>(number) };
  201. }
  202. case Wasm::ValueType::F32: {
  203. auto number = value.to_double(global_object);
  204. if (vm.exception())
  205. return {};
  206. return Wasm::Value { static_cast<float>(number) };
  207. }
  208. case Wasm::ValueType::FunctionReference:
  209. case Wasm::ValueType::ExternReference:
  210. TODO();
  211. }
  212. VERIFY_NOT_REACHED();
  213. }
  214. JS::NativeFunction* create_native_function(Wasm::FunctionAddress address, String name, JS::GlobalObject& global_object)
  215. {
  216. // FIXME: Cache these.
  217. return JS::NativeFunction::create(
  218. global_object,
  219. name,
  220. [address](JS::VM& vm, JS::GlobalObject& global_object) -> JS::Value {
  221. Vector<Wasm::Value> values;
  222. Optional<Wasm::FunctionType> type;
  223. WebAssemblyObject::s_abstract_machine.store().get(address)->visit([&](const auto& value) { type = value.type(); });
  224. // Grab as many values as needed and convert them.
  225. size_t index = 0;
  226. for (auto& type : type.value().parameters()) {
  227. auto result = to_webassembly_value(vm.argument(index++), type, global_object);
  228. if (result.has_value())
  229. values.append(result.release_value());
  230. else
  231. return {};
  232. }
  233. auto result = WebAssemblyObject::s_abstract_machine.invoke(address, move(values));
  234. // FIXME: Use the convoluted mapping of errors defined in the spec.
  235. if (result.is_trap()) {
  236. vm.throw_exception<JS::TypeError>(global_object, "Wasm execution trapped (WIP)");
  237. return {};
  238. }
  239. if (result.values().is_empty())
  240. return JS::js_undefined();
  241. if (result.values().size() == 1)
  242. return to_js_value(result.values().first(), global_object);
  243. Vector<JS::Value> result_values;
  244. for (auto& entry : result.values())
  245. result_values.append(to_js_value(entry, global_object));
  246. return JS::Array::create_from(global_object, result_values);
  247. });
  248. }
  249. void WebAssemblyInstancePrototype::initialize(JS::GlobalObject& global_object)
  250. {
  251. Object::initialize(global_object);
  252. define_native_property("exports", exports_getter, nullptr);
  253. }
  254. void WebAssemblyInstanceObject::initialize(JS::GlobalObject& global_object)
  255. {
  256. Object::initialize(global_object);
  257. VERIFY(!m_exports_object);
  258. m_exports_object = JS::Object::create_empty(global_object);
  259. m_exports_object->set_prototype(nullptr);
  260. auto& instance = this->instance();
  261. for (auto& export_ : instance.exports()) {
  262. export_.value().visit(
  263. [&](const Wasm::FunctionAddress& address) {
  264. auto function = create_native_function(address, export_.name(), global_object);
  265. m_exports_object->define_property(export_.name(), function);
  266. },
  267. [&](const auto&) {
  268. // FIXME: Implement other exports!
  269. });
  270. }
  271. m_exports_object->set_integrity_level(IntegrityLevel::Frozen);
  272. }
  273. JS_DEFINE_NATIVE_GETTER(WebAssemblyInstancePrototype::exports_getter)
  274. {
  275. auto this_value = vm.this_value(global_object);
  276. auto this_object = this_value.to_object(global_object);
  277. if (vm.exception())
  278. return {};
  279. if (!is<WebAssemblyInstanceObject>(this_object)) {
  280. vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotAn, "WebAssemblyInstance");
  281. return {};
  282. }
  283. auto object = static_cast<WebAssemblyInstanceObject*>(this_object);
  284. return object->m_exports_object;
  285. }
  286. void WebAssemblyInstanceObject::visit_edges(Cell::Visitor& visitor)
  287. {
  288. Object::visit_edges(visitor);
  289. visitor.visit(m_exports_object);
  290. }
  291. }