AbstractMachine.h 20 KB

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