AbstractMachine.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. /*
  2. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Function.h>
  8. #include <AK/HashMap.h>
  9. #include <AK/HashTable.h>
  10. #include <AK/OwnPtr.h>
  11. #include <AK/Result.h>
  12. #include <LibWasm/Types.h>
  13. // NOTE: Special case for Wasm::Result.
  14. #include <LibJS/Runtime/Completion.h>
  15. namespace Wasm {
  16. class Configuration;
  17. struct Interpreter;
  18. struct InstantiationError {
  19. DeprecatedString error { "Unknown error" };
  20. };
  21. struct LinkError {
  22. enum OtherErrors {
  23. InvalidImportedModule,
  24. };
  25. Vector<DeprecatedString> missing_imports;
  26. Vector<OtherErrors> other_errors;
  27. };
  28. AK_TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, FunctionAddress, Arithmetic, Comparison, Increment);
  29. AK_TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, ExternAddress, Arithmetic, Comparison, Increment);
  30. AK_TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, TableAddress, Arithmetic, Comparison, Increment);
  31. AK_TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, GlobalAddress, Arithmetic, Comparison, Increment);
  32. AK_TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, ElementAddress, Arithmetic, Comparison, Increment);
  33. AK_TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, DataAddress, Arithmetic, Comparison, Increment);
  34. AK_TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, MemoryAddress, Arithmetic, Comparison, Increment);
  35. // FIXME: These should probably be made generic/virtual if/when we decide to do something more
  36. // fancy than just a dumb interpreter.
  37. class Reference {
  38. public:
  39. struct Null {
  40. ValueType type;
  41. };
  42. struct Func {
  43. FunctionAddress address;
  44. };
  45. struct Extern {
  46. ExternAddress address;
  47. };
  48. using RefType = Variant<Null, Func, Extern>;
  49. explicit Reference(RefType ref)
  50. : m_ref(move(ref))
  51. {
  52. }
  53. auto& ref() const { return m_ref; }
  54. private:
  55. RefType m_ref;
  56. };
  57. class Value {
  58. public:
  59. Value()
  60. : m_value(0)
  61. {
  62. }
  63. using AnyValueType = Variant<i32, i64, float, double, Reference>;
  64. explicit Value(AnyValueType value)
  65. : m_value(move(value))
  66. {
  67. }
  68. template<typename T>
  69. requires(sizeof(T) == sizeof(u64)) explicit Value(ValueType type, T raw_value)
  70. : m_value(0)
  71. {
  72. switch (type.kind()) {
  73. case ValueType::Kind::ExternReference:
  74. m_value = Reference { Reference::Extern { { bit_cast<u64>(raw_value) } } };
  75. break;
  76. case ValueType::Kind::FunctionReference:
  77. m_value = Reference { Reference::Func { { bit_cast<u64>(raw_value) } } };
  78. break;
  79. case ValueType::Kind::I32:
  80. m_value = static_cast<i32>(bit_cast<i64>(raw_value));
  81. break;
  82. case ValueType::Kind::I64:
  83. m_value = static_cast<i64>(bit_cast<u64>(raw_value));
  84. break;
  85. case ValueType::Kind::F32:
  86. m_value = static_cast<float>(bit_cast<double>(raw_value));
  87. break;
  88. case ValueType::Kind::F64:
  89. m_value = bit_cast<double>(raw_value);
  90. break;
  91. case ValueType::Kind::NullFunctionReference:
  92. VERIFY(raw_value == 0);
  93. m_value = Reference { Reference::Null { ValueType(ValueType::Kind::FunctionReference) } };
  94. break;
  95. case ValueType::Kind::NullExternReference:
  96. VERIFY(raw_value == 0);
  97. m_value = Reference { Reference::Null { ValueType(ValueType::Kind::ExternReference) } };
  98. break;
  99. default:
  100. VERIFY_NOT_REACHED();
  101. }
  102. }
  103. ALWAYS_INLINE Value(Value const& value) = default;
  104. ALWAYS_INLINE Value(Value&& value) = default;
  105. ALWAYS_INLINE Value& operator=(Value&& value) = default;
  106. ALWAYS_INLINE Value& operator=(Value const& value) = default;
  107. template<typename T>
  108. ALWAYS_INLINE Optional<T> to() const
  109. {
  110. Optional<T> result;
  111. m_value.visit(
  112. [&](auto value) {
  113. if constexpr (IsSame<T, decltype(value)> || (!IsFloatingPoint<T> && IsSame<decltype(value), MakeSigned<T>>)) {
  114. result = static_cast<T>(value);
  115. } else if constexpr (!IsFloatingPoint<T> && IsConvertible<decltype(value), T>) {
  116. if (AK::is_within_range<T>(value))
  117. result = static_cast<T>(value);
  118. }
  119. },
  120. [&](Reference const& value) {
  121. if constexpr (IsSame<T, Reference>) {
  122. result = value;
  123. } else if constexpr (IsSame<T, Reference::Func>) {
  124. if (auto ptr = value.ref().template get_pointer<Reference::Func>())
  125. result = *ptr;
  126. } else if constexpr (IsSame<T, Reference::Extern>) {
  127. if (auto ptr = value.ref().template get_pointer<Reference::Extern>())
  128. result = *ptr;
  129. } else if constexpr (IsSame<T, Reference::Null>) {
  130. if (auto ptr = value.ref().template get_pointer<Reference::Null>())
  131. result = *ptr;
  132. }
  133. });
  134. return result;
  135. }
  136. ValueType type() const
  137. {
  138. return ValueType(m_value.visit(
  139. [](i32) { return ValueType::Kind::I32; },
  140. [](i64) { return ValueType::Kind::I64; },
  141. [](float) { return ValueType::Kind::F32; },
  142. [](double) { return ValueType::Kind::F64; },
  143. [&](Reference const& type) {
  144. return type.ref().visit(
  145. [](Reference::Func const&) { return ValueType::Kind::FunctionReference; },
  146. [](Reference::Null const& null_type) {
  147. return null_type.type.kind() == ValueType::ExternReference ? ValueType::Kind::NullExternReference : ValueType::Kind::NullFunctionReference;
  148. },
  149. [](Reference::Extern const&) { return ValueType::Kind::ExternReference; });
  150. }));
  151. }
  152. auto& value() const { return m_value; }
  153. private:
  154. AnyValueType m_value;
  155. };
  156. struct Trap {
  157. DeprecatedString reason;
  158. };
  159. // A variant of Result that does not include external reasons for error (JS::Completion, for now).
  160. class PureResult {
  161. public:
  162. explicit PureResult(Vector<Value> values)
  163. : m_result(move(values))
  164. {
  165. }
  166. PureResult(Trap trap)
  167. : m_result(move(trap))
  168. {
  169. }
  170. auto is_trap() const { return m_result.has<Trap>(); }
  171. auto& values() const { return m_result.get<Vector<Value>>(); }
  172. auto& values() { return m_result.get<Vector<Value>>(); }
  173. auto& trap() const { return m_result.get<Trap>(); }
  174. auto& trap() { return m_result.get<Trap>(); }
  175. private:
  176. friend class Result;
  177. explicit PureResult(Variant<Vector<Value>, Trap>&& result)
  178. : m_result(move(result))
  179. {
  180. }
  181. Variant<Vector<Value>, Trap> m_result;
  182. };
  183. class Result {
  184. public:
  185. explicit Result(Vector<Value> values)
  186. : m_result(move(values))
  187. {
  188. }
  189. Result(Trap trap)
  190. : m_result(move(trap))
  191. {
  192. }
  193. Result(JS::Completion completion)
  194. : m_result(move(completion))
  195. {
  196. VERIFY(m_result.get<JS::Completion>().is_abrupt());
  197. }
  198. Result(PureResult&& result)
  199. : m_result(result.m_result.downcast<decltype(m_result)>())
  200. {
  201. }
  202. auto is_trap() const { return m_result.has<Trap>(); }
  203. auto is_completion() const { return m_result.has<JS::Completion>(); }
  204. auto& values() const { return m_result.get<Vector<Value>>(); }
  205. auto& values() { return m_result.get<Vector<Value>>(); }
  206. auto& trap() const { return m_result.get<Trap>(); }
  207. auto& trap() { return m_result.get<Trap>(); }
  208. auto& completion() { return m_result.get<JS::Completion>(); }
  209. auto& completion() const { return m_result.get<JS::Completion>(); }
  210. PureResult assert_wasm_result() &&
  211. {
  212. VERIFY(!is_completion());
  213. return PureResult(move(m_result).downcast<Vector<Value>, Trap>());
  214. }
  215. private:
  216. Variant<Vector<Value>, Trap, JS::Completion> m_result;
  217. };
  218. using ExternValue = Variant<FunctionAddress, TableAddress, MemoryAddress, GlobalAddress>;
  219. class ExportInstance {
  220. public:
  221. explicit ExportInstance(DeprecatedString name, ExternValue value)
  222. : m_name(move(name))
  223. , m_value(move(value))
  224. {
  225. }
  226. auto& name() const { return m_name; }
  227. auto& value() const { return m_value; }
  228. private:
  229. DeprecatedString m_name;
  230. ExternValue m_value;
  231. };
  232. class ModuleInstance {
  233. public:
  234. explicit ModuleInstance(
  235. Vector<FunctionType> types, Vector<FunctionAddress> function_addresses, Vector<TableAddress> table_addresses,
  236. Vector<MemoryAddress> memory_addresses, Vector<GlobalAddress> global_addresses, Vector<DataAddress> data_addresses,
  237. Vector<ExportInstance> exports)
  238. : m_types(move(types))
  239. , m_functions(move(function_addresses))
  240. , m_tables(move(table_addresses))
  241. , m_memories(move(memory_addresses))
  242. , m_globals(move(global_addresses))
  243. , m_datas(move(data_addresses))
  244. , m_exports(move(exports))
  245. {
  246. }
  247. ModuleInstance() = default;
  248. auto& types() const { return m_types; }
  249. auto& functions() const { return m_functions; }
  250. auto& tables() const { return m_tables; }
  251. auto& memories() const { return m_memories; }
  252. auto& globals() const { return m_globals; }
  253. auto& elements() const { return m_elements; }
  254. auto& datas() const { return m_datas; }
  255. auto& exports() const { return m_exports; }
  256. auto& types() { return m_types; }
  257. auto& functions() { return m_functions; }
  258. auto& tables() { return m_tables; }
  259. auto& memories() { return m_memories; }
  260. auto& globals() { return m_globals; }
  261. auto& elements() { return m_elements; }
  262. auto& datas() { return m_datas; }
  263. auto& exports() { return m_exports; }
  264. private:
  265. Vector<FunctionType> m_types;
  266. Vector<FunctionAddress> m_functions;
  267. Vector<TableAddress> m_tables;
  268. Vector<MemoryAddress> m_memories;
  269. Vector<GlobalAddress> m_globals;
  270. Vector<ElementAddress> m_elements;
  271. Vector<DataAddress> m_datas;
  272. Vector<ExportInstance> m_exports;
  273. };
  274. class WasmFunction {
  275. public:
  276. explicit WasmFunction(FunctionType const& type, ModuleInstance const& module, Module::Function const& code)
  277. : m_type(type)
  278. , m_module(module)
  279. , m_code(code)
  280. {
  281. }
  282. auto& type() const { return m_type; }
  283. auto& module() const { return m_module; }
  284. auto& code() const { return m_code; }
  285. private:
  286. FunctionType m_type;
  287. ModuleInstance const& m_module;
  288. Module::Function const& m_code;
  289. };
  290. class HostFunction {
  291. public:
  292. explicit HostFunction(AK::Function<Result(Configuration&, Vector<Value>&)> function, FunctionType const& type)
  293. : m_function(move(function))
  294. , m_type(type)
  295. {
  296. }
  297. auto& function() { return m_function; }
  298. auto& type() const { return m_type; }
  299. private:
  300. AK::Function<Result(Configuration&, Vector<Value>&)> m_function;
  301. FunctionType m_type;
  302. };
  303. using FunctionInstance = Variant<WasmFunction, HostFunction>;
  304. class TableInstance {
  305. public:
  306. explicit TableInstance(TableType const& type, Vector<Optional<Reference>> elements)
  307. : m_elements(move(elements))
  308. , m_type(type)
  309. {
  310. }
  311. auto& elements() const { return m_elements; }
  312. auto& elements() { return m_elements; }
  313. auto& type() const { return m_type; }
  314. bool grow(size_t size_to_grow, Reference const& fill_value)
  315. {
  316. if (size_to_grow == 0)
  317. return true;
  318. auto new_size = m_elements.size() + size_to_grow;
  319. if (auto max = m_type.limits().max(); max.has_value()) {
  320. if (max.value() < new_size)
  321. return false;
  322. }
  323. auto previous_size = m_elements.size();
  324. if (m_elements.try_resize(new_size).is_error())
  325. return false;
  326. for (size_t i = previous_size; i < m_elements.size(); ++i)
  327. m_elements[i] = fill_value;
  328. return true;
  329. }
  330. private:
  331. Vector<Optional<Reference>> m_elements;
  332. TableType const& m_type;
  333. };
  334. class MemoryInstance {
  335. public:
  336. static ErrorOr<MemoryInstance> create(MemoryType const& type)
  337. {
  338. MemoryInstance instance { type };
  339. if (!instance.grow(type.limits().min() * Constants::page_size))
  340. return Error::from_string_literal("Failed to grow to requested size");
  341. return { move(instance) };
  342. }
  343. auto& type() const { return m_type; }
  344. auto size() const { return m_size; }
  345. auto& data() const { return m_data; }
  346. auto& data() { return m_data; }
  347. enum class InhibitGrowCallback {
  348. No,
  349. Yes,
  350. };
  351. bool grow(size_t size_to_grow, InhibitGrowCallback inhibit_callback = InhibitGrowCallback::No)
  352. {
  353. if (size_to_grow == 0)
  354. return true;
  355. u64 new_size = m_data.size() + size_to_grow;
  356. // Can't grow past 2^16 pages.
  357. if (new_size >= Constants::page_size * 65536)
  358. return false;
  359. if (auto max = m_type.limits().max(); max.has_value()) {
  360. if (max.value() * Constants::page_size < new_size)
  361. return false;
  362. }
  363. auto previous_size = m_size;
  364. if (m_data.try_resize(new_size).is_error())
  365. return false;
  366. m_size = new_size;
  367. // The spec requires that we zero out everything on grow
  368. __builtin_memset(m_data.offset_pointer(previous_size), 0, size_to_grow);
  369. // NOTE: This exists because wasm-js-api wants to execute code after a successful grow,
  370. // See [this issue](https://github.com/WebAssembly/spec/issues/1635) for more details.
  371. if (inhibit_callback == InhibitGrowCallback::No && successful_grow_hook)
  372. successful_grow_hook();
  373. return true;
  374. }
  375. Function<void()> successful_grow_hook;
  376. private:
  377. explicit MemoryInstance(MemoryType const& type)
  378. : m_type(type)
  379. {
  380. }
  381. MemoryType const& m_type;
  382. size_t m_size { 0 };
  383. ByteBuffer m_data;
  384. };
  385. class GlobalInstance {
  386. public:
  387. explicit GlobalInstance(Value value, bool is_mutable)
  388. : m_mutable(is_mutable)
  389. , m_value(move(value))
  390. {
  391. }
  392. auto is_mutable() const { return m_mutable; }
  393. auto& value() const { return m_value; }
  394. GlobalType type() const { return { m_value.type(), is_mutable() }; }
  395. void set_value(Value value)
  396. {
  397. VERIFY(is_mutable());
  398. m_value = move(value);
  399. }
  400. private:
  401. bool m_mutable { false };
  402. Value m_value;
  403. };
  404. class DataInstance {
  405. public:
  406. explicit DataInstance(Vector<u8> data)
  407. : m_data(move(data))
  408. {
  409. }
  410. size_t size() const { return m_data.size(); }
  411. Vector<u8>& data() { return m_data; }
  412. Vector<u8> const& data() const { return m_data; }
  413. private:
  414. Vector<u8> m_data;
  415. };
  416. class ElementInstance {
  417. public:
  418. explicit ElementInstance(ValueType type, Vector<Reference> references)
  419. : m_type(move(type))
  420. , m_references(move(references))
  421. {
  422. }
  423. auto& type() const { return m_type; }
  424. auto& references() const { return m_references; }
  425. private:
  426. ValueType m_type;
  427. Vector<Reference> m_references;
  428. };
  429. class Store {
  430. public:
  431. Store() = default;
  432. Optional<FunctionAddress> allocate(ModuleInstance& module, Module::Function const& function);
  433. Optional<FunctionAddress> allocate(HostFunction&&);
  434. Optional<TableAddress> allocate(TableType const&);
  435. Optional<MemoryAddress> allocate(MemoryType const&);
  436. Optional<DataAddress> allocate_data(Vector<u8>);
  437. Optional<GlobalAddress> allocate(GlobalType const&, Value);
  438. Optional<ElementAddress> allocate(ValueType const&, Vector<Reference>);
  439. FunctionInstance* get(FunctionAddress);
  440. TableInstance* get(TableAddress);
  441. MemoryInstance* get(MemoryAddress);
  442. GlobalInstance* get(GlobalAddress);
  443. DataInstance* get(DataAddress);
  444. ElementInstance* get(ElementAddress);
  445. private:
  446. Vector<FunctionInstance> m_functions;
  447. Vector<TableInstance> m_tables;
  448. Vector<MemoryInstance> m_memories;
  449. Vector<GlobalInstance> m_globals;
  450. Vector<ElementInstance> m_elements;
  451. Vector<DataInstance> m_datas;
  452. };
  453. class Label {
  454. public:
  455. explicit Label(size_t arity, InstructionPointer continuation)
  456. : m_arity(arity)
  457. , m_continuation(continuation)
  458. {
  459. }
  460. auto continuation() const { return m_continuation; }
  461. auto arity() const { return m_arity; }
  462. private:
  463. size_t m_arity { 0 };
  464. InstructionPointer m_continuation { 0 };
  465. };
  466. class Frame {
  467. public:
  468. explicit Frame(ModuleInstance const& module, Vector<Value> locals, Expression const& expression, size_t arity)
  469. : m_module(module)
  470. , m_locals(move(locals))
  471. , m_expression(expression)
  472. , m_arity(arity)
  473. {
  474. }
  475. auto& module() const { return m_module; }
  476. auto& locals() const { return m_locals; }
  477. auto& locals() { return m_locals; }
  478. auto& expression() const { return m_expression; }
  479. auto arity() const { return m_arity; }
  480. private:
  481. ModuleInstance const& m_module;
  482. Vector<Value> m_locals;
  483. Expression const& m_expression;
  484. size_t m_arity { 0 };
  485. };
  486. class Stack {
  487. public:
  488. using EntryType = Variant<Value, Label, Frame>;
  489. Stack() = default;
  490. [[nodiscard]] ALWAYS_INLINE bool is_empty() const { return m_data.is_empty(); }
  491. ALWAYS_INLINE void push(EntryType entry) { m_data.append(move(entry)); }
  492. ALWAYS_INLINE auto pop() { return m_data.take_last(); }
  493. ALWAYS_INLINE auto& peek() const { return m_data.last(); }
  494. ALWAYS_INLINE auto& peek() { return m_data.last(); }
  495. ALWAYS_INLINE auto size() const { return m_data.size(); }
  496. ALWAYS_INLINE auto& entries() const { return m_data; }
  497. ALWAYS_INLINE auto& entries() { return m_data; }
  498. private:
  499. Vector<EntryType, 1024> m_data;
  500. };
  501. using InstantiationResult = AK::Result<NonnullOwnPtr<ModuleInstance>, InstantiationError>;
  502. class AbstractMachine {
  503. public:
  504. explicit AbstractMachine() = default;
  505. // Validate a module; permanently sets the module's validity status.
  506. ErrorOr<void, ValidationError> validate(Module&);
  507. // Load and instantiate a module, and link it into this interpreter.
  508. InstantiationResult instantiate(Module const&, Vector<ExternValue>);
  509. Result invoke(FunctionAddress, Vector<Value>);
  510. Result invoke(Interpreter&, FunctionAddress, Vector<Value>);
  511. auto& store() const { return m_store; }
  512. auto& store() { return m_store; }
  513. void enable_instruction_count_limit() { m_should_limit_instruction_count = true; }
  514. private:
  515. Optional<InstantiationError> allocate_all_initial_phase(Module const&, ModuleInstance&, Vector<ExternValue>&, Vector<Value>& global_values);
  516. Optional<InstantiationError> allocate_all_final_phase(Module const&, ModuleInstance&, Vector<Vector<Reference>>& elements);
  517. Store m_store;
  518. bool m_should_limit_instruction_count { false };
  519. };
  520. class Linker {
  521. public:
  522. struct Name {
  523. DeprecatedString module;
  524. DeprecatedString name;
  525. ImportSection::Import::ImportDesc type;
  526. };
  527. explicit Linker(Module const& module)
  528. : m_module(module)
  529. {
  530. }
  531. // Link a module, the import 'module name' is ignored with this.
  532. void link(ModuleInstance const&);
  533. // Link a bunch of qualified values, also matches 'module name'.
  534. void link(HashMap<Name, ExternValue> const&);
  535. auto& unresolved_imports()
  536. {
  537. populate();
  538. return m_unresolved_imports;
  539. }
  540. AK::Result<Vector<ExternValue>, LinkError> finish();
  541. private:
  542. void populate();
  543. Module const& m_module;
  544. HashMap<Name, ExternValue> m_resolved_imports;
  545. HashTable<Name> m_unresolved_imports;
  546. Vector<Name> m_ordered_imports;
  547. Optional<LinkError> m_error;
  548. };
  549. }
  550. template<>
  551. struct AK::Traits<Wasm::Linker::Name> : public AK::GenericTraits<Wasm::Linker::Name> {
  552. static constexpr bool is_trivial() { return false; }
  553. static unsigned hash(Wasm::Linker::Name const& entry) { return pair_int_hash(entry.module.hash(), entry.name.hash()); }
  554. static bool equals(Wasm::Linker::Name const& a, Wasm::Linker::Name const& b) { return a.name == b.name && a.module == b.module; }
  555. };