test-wasm.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. /*
  2. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibCore/File.h>
  7. #include <LibTest/JavaScriptTestRunner.h>
  8. #include <LibWasm/AbstractMachine/BytecodeInterpreter.h>
  9. #include <LibWasm/Types.h>
  10. TEST_ROOT("Userland/Libraries/LibWasm/Tests");
  11. TESTJS_GLOBAL_FUNCTION(read_binary_wasm_file, readBinaryWasmFile)
  12. {
  13. auto filename = vm.argument(0).to_string(global_object);
  14. if (vm.exception())
  15. return {};
  16. auto file = Core::File::open(filename, Core::OpenMode::ReadOnly);
  17. if (file.is_error()) {
  18. vm.throw_exception<JS::TypeError>(global_object, file.error().string());
  19. return {};
  20. }
  21. auto contents = file.value()->read_all();
  22. auto array = JS::Uint8Array::create(global_object, contents.size());
  23. contents.span().copy_to(array->data());
  24. return array;
  25. }
  26. class WebAssemblyModule final : public JS::Object {
  27. JS_OBJECT(WebAssemblyModule, JS::Object);
  28. public:
  29. explicit WebAssemblyModule(JS::Object& prototype)
  30. : JS::Object(prototype)
  31. {
  32. m_machine.enable_instruction_count_limit();
  33. }
  34. static Wasm::AbstractMachine& machine() { return m_machine; }
  35. Wasm::Module& module() { return *m_module; }
  36. Wasm::ModuleInstance& module_instance() { return *m_module_instance; }
  37. static WebAssemblyModule* create(JS::GlobalObject& global_object, Wasm::Module module, HashMap<Wasm::Linker::Name, Wasm::ExternValue> const& imports)
  38. {
  39. auto instance = global_object.heap().allocate<WebAssemblyModule>(global_object, *global_object.object_prototype());
  40. instance->m_module = move(module);
  41. Wasm::Linker linker(*instance->m_module);
  42. linker.link(imports);
  43. linker.link(spec_test_namespace());
  44. auto link_result = linker.finish();
  45. if (link_result.is_error()) {
  46. global_object.vm().throw_exception<JS::TypeError>(global_object, "Link failed");
  47. } else {
  48. if (auto result = machine().instantiate(*instance->m_module, link_result.release_value()); result.is_error())
  49. global_object.vm().throw_exception<JS::TypeError>(global_object, result.release_error().error);
  50. else
  51. instance->m_module_instance = result.release_value();
  52. }
  53. return instance;
  54. }
  55. void initialize(JS::GlobalObject&) override;
  56. ~WebAssemblyModule() override = default;
  57. private:
  58. JS_DECLARE_NATIVE_FUNCTION(get_export);
  59. JS_DECLARE_NATIVE_FUNCTION(wasm_invoke);
  60. static HashMap<Wasm::Linker::Name, Wasm::ExternValue> const& spec_test_namespace()
  61. {
  62. if (!s_spec_test_namespace.is_empty())
  63. return s_spec_test_namespace;
  64. Wasm::FunctionType print_i32_type { { Wasm::ValueType(Wasm::ValueType::I32) }, {} };
  65. auto address = m_machine.store().allocate(Wasm::HostFunction {
  66. [](auto&, auto&) -> Wasm::Result {
  67. // Noop, this just needs to exist.
  68. return Wasm::Result { Vector<Wasm::Value> {} };
  69. },
  70. print_i32_type });
  71. s_spec_test_namespace.set({ "spectest", "print_i32", print_i32_type }, Wasm::ExternValue { *address });
  72. return s_spec_test_namespace;
  73. }
  74. static HashMap<Wasm::Linker::Name, Wasm::ExternValue> s_spec_test_namespace;
  75. static Wasm::AbstractMachine m_machine;
  76. Optional<Wasm::Module> m_module;
  77. OwnPtr<Wasm::ModuleInstance> m_module_instance;
  78. };
  79. Wasm::AbstractMachine WebAssemblyModule::m_machine;
  80. HashMap<Wasm::Linker::Name, Wasm::ExternValue> WebAssemblyModule::s_spec_test_namespace;
  81. TESTJS_GLOBAL_FUNCTION(parse_webassembly_module, parseWebAssemblyModule)
  82. {
  83. auto object = vm.argument(0).to_object(global_object);
  84. if (vm.exception())
  85. return {};
  86. if (!is<JS::Uint8Array>(object)) {
  87. vm.throw_exception<JS::TypeError>(global_object, "Expected a Uint8Array argument to parse_webassembly_module");
  88. return {};
  89. }
  90. auto& array = static_cast<JS::Uint8Array&>(*object);
  91. InputMemoryStream stream { array.data() };
  92. auto result = Wasm::Module::parse(stream);
  93. if (result.is_error()) {
  94. vm.throw_exception<JS::SyntaxError>(global_object, Wasm::parse_error_to_string(result.error()));
  95. return {};
  96. }
  97. if (stream.handle_any_error()) {
  98. vm.throw_exception<JS::SyntaxError>(global_object, "Bianry stream contained errors");
  99. return {};
  100. }
  101. HashMap<Wasm::Linker::Name, Wasm::ExternValue> imports;
  102. auto import_value = vm.argument(1);
  103. if (import_value.is_object()) {
  104. auto& import_object = import_value.as_object();
  105. for (auto& property : import_object.shape().property_table()) {
  106. auto value = import_object.get_without_side_effects(property.key);
  107. if (!value.is_object() || !is<WebAssemblyModule>(value.as_object()))
  108. continue;
  109. auto& module_object = static_cast<WebAssemblyModule&>(value.as_object());
  110. for (auto& entry : module_object.module_instance().exports()) {
  111. // FIXME: Don't pretend that everything is a function
  112. imports.set({ property.key.as_string(), entry.name(), Wasm::TypeIndex(0) }, entry.value());
  113. }
  114. }
  115. }
  116. return WebAssemblyModule::create(global_object, result.release_value(), imports);
  117. }
  118. TESTJS_GLOBAL_FUNCTION(compare_typed_arrays, compareTypedArrays)
  119. {
  120. auto lhs = vm.argument(0).to_object(global_object);
  121. if (vm.exception())
  122. return {};
  123. if (!is<JS::TypedArrayBase>(lhs)) {
  124. vm.throw_exception<JS::TypeError>(global_object, "Expected a TypedArray");
  125. return {};
  126. }
  127. auto& lhs_array = static_cast<JS::TypedArrayBase&>(*lhs);
  128. auto rhs = vm.argument(1).to_object(global_object);
  129. if (vm.exception())
  130. return {};
  131. if (!is<JS::TypedArrayBase>(rhs)) {
  132. vm.throw_exception<JS::TypeError>(global_object, "Expected a TypedArray");
  133. return {};
  134. }
  135. auto& rhs_array = static_cast<JS::TypedArrayBase&>(*rhs);
  136. return JS::Value(lhs_array.viewed_array_buffer()->buffer() == rhs_array.viewed_array_buffer()->buffer());
  137. }
  138. void WebAssemblyModule::initialize(JS::GlobalObject& global_object)
  139. {
  140. Base::initialize(global_object);
  141. define_native_function("getExport", get_export, 1, JS::default_attributes);
  142. define_native_function("invoke", wasm_invoke, 1, JS::default_attributes);
  143. }
  144. JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::get_export)
  145. {
  146. auto name = vm.argument(0).to_string(global_object);
  147. if (vm.exception())
  148. return {};
  149. auto this_value = vm.this_value(global_object);
  150. auto object = this_value.to_object(global_object);
  151. if (vm.exception())
  152. return {};
  153. if (!object || !is<WebAssemblyModule>(object)) {
  154. vm.throw_exception<JS::TypeError>(global_object, "Not a WebAssemblyModule");
  155. return {};
  156. }
  157. auto instance = static_cast<WebAssemblyModule*>(object);
  158. for (auto& entry : instance->module_instance().exports()) {
  159. if (entry.name() == name) {
  160. auto& value = entry.value();
  161. if (auto ptr = value.get_pointer<Wasm::FunctionAddress>())
  162. return JS::Value(static_cast<unsigned long>(ptr->value()));
  163. if (auto v = value.get_pointer<Wasm::GlobalAddress>()) {
  164. return m_machine.store().get(*v)->value().value().visit(
  165. [&](const auto& value) -> JS::Value { return JS::Value(static_cast<double>(value)); },
  166. [&](const Wasm::Reference& reference) -> JS::Value {
  167. return reference.ref().visit(
  168. [&](const Wasm::Reference::Null&) -> JS::Value { return JS::js_null(); },
  169. [&](const auto& ref) -> JS::Value { return JS::Value(static_cast<double>(ref.address.value())); });
  170. });
  171. }
  172. vm.throw_exception<JS::TypeError>(global_object, String::formatted("'{}' does not refer to a function or a global", name));
  173. return {};
  174. }
  175. }
  176. vm.throw_exception<JS::TypeError>(global_object, String::formatted("'{}' could not be found", name));
  177. return {};
  178. }
  179. JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::wasm_invoke)
  180. {
  181. auto address = static_cast<unsigned long>(vm.argument(0).to_double(global_object));
  182. if (vm.exception())
  183. return {};
  184. Wasm::FunctionAddress function_address { address };
  185. auto function_instance = WebAssemblyModule::machine().store().get(function_address);
  186. if (!function_instance) {
  187. vm.throw_exception<JS::TypeError>(global_object, "Invalid function address");
  188. return {};
  189. }
  190. const Wasm::FunctionType* type { nullptr };
  191. function_instance->visit([&](auto& value) { type = &value.type(); });
  192. if (!type) {
  193. vm.throw_exception<JS::TypeError>(global_object, "Invalid function found at given address");
  194. return {};
  195. }
  196. Vector<Wasm::Value> arguments;
  197. if (type->parameters().size() + 1 > vm.argument_count()) {
  198. vm.throw_exception<JS::TypeError>(global_object, String::formatted("Expected {} arguments for call, but found {}", type->parameters().size() + 1, vm.argument_count()));
  199. return {};
  200. }
  201. size_t index = 1;
  202. for (auto& param : type->parameters()) {
  203. auto value = vm.argument(index++).to_double(global_object);
  204. switch (param.kind()) {
  205. case Wasm::ValueType::Kind::I32:
  206. arguments.append(Wasm::Value(param, static_cast<u64>(value)));
  207. break;
  208. case Wasm::ValueType::Kind::I64:
  209. arguments.append(Wasm::Value(param, static_cast<u64>(value)));
  210. break;
  211. case Wasm::ValueType::Kind::F32:
  212. arguments.append(Wasm::Value(static_cast<float>(value)));
  213. break;
  214. case Wasm::ValueType::Kind::F64:
  215. arguments.append(Wasm::Value(static_cast<double>(value)));
  216. break;
  217. case Wasm::ValueType::Kind::FunctionReference:
  218. arguments.append(Wasm::Value(Wasm::Reference { Wasm::Reference::Func { static_cast<u64>(value) } }));
  219. break;
  220. case Wasm::ValueType::Kind::ExternReference:
  221. arguments.append(Wasm::Value(Wasm::Reference { Wasm::Reference::Func { static_cast<u64>(value) } }));
  222. break;
  223. case Wasm::ValueType::Kind::NullFunctionReference:
  224. arguments.append(Wasm::Value(Wasm::Reference { Wasm::Reference::Null { Wasm::ValueType(Wasm::ValueType::Kind::FunctionReference) } }));
  225. break;
  226. case Wasm::ValueType::Kind::NullExternReference:
  227. arguments.append(Wasm::Value(Wasm::Reference { Wasm::Reference::Null { Wasm::ValueType(Wasm::ValueType::Kind::ExternReference) } }));
  228. break;
  229. }
  230. }
  231. auto result = WebAssemblyModule::machine().invoke(function_address, arguments);
  232. if (result.is_trap()) {
  233. vm.throw_exception<JS::TypeError>(global_object, String::formatted("Execution trapped: {}", result.trap().reason));
  234. return {};
  235. }
  236. if (result.values().is_empty())
  237. return JS::js_null();
  238. JS::Value return_value;
  239. result.values().first().value().visit(
  240. [&](const auto& value) { return_value = JS::Value(static_cast<double>(value)); },
  241. [&](const Wasm::Reference& reference) {
  242. reference.ref().visit(
  243. [&](const Wasm::Reference::Null&) { return_value = JS::js_null(); },
  244. [&](const auto& ref) { return_value = JS::Value(static_cast<double>(ref.address.value())); });
  245. });
  246. return return_value;
  247. }