test-wasm.cpp 12 KB

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