test-wasm.cpp 12 KB

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