AbstractMachine.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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. namespace Wasm {
  14. class Configuration;
  15. struct Interpreter;
  16. struct InstantiationError {
  17. String error { "Unknown error" };
  18. };
  19. struct LinkError {
  20. enum OtherErrors {
  21. InvalidImportedModule,
  22. };
  23. Vector<String> missing_imports;
  24. Vector<OtherErrors> other_errors;
  25. };
  26. TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, true, true, false, false, false, true, FunctionAddress);
  27. TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, true, true, false, false, false, true, ExternAddress);
  28. TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, true, true, false, false, false, true, TableAddress);
  29. TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, true, true, false, false, false, true, GlobalAddress);
  30. TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, true, true, false, false, false, true, ElementAddress);
  31. TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, true, true, false, false, false, true, MemoryAddress);
  32. // FIXME: These should probably be made generic/virtual if/when we decide to do something more
  33. // fancy than just a dumb interpreter.
  34. class Reference {
  35. public:
  36. struct Null {
  37. ValueType type;
  38. };
  39. struct Func {
  40. FunctionAddress address;
  41. };
  42. struct Extern {
  43. ExternAddress address;
  44. };
  45. using RefType = Variant<Null, Func, Extern>;
  46. explicit Reference(RefType ref)
  47. : m_ref(move(ref))
  48. {
  49. }
  50. auto& ref() const { return m_ref; }
  51. private:
  52. RefType m_ref;
  53. };
  54. class Value {
  55. public:
  56. Value()
  57. : m_value(0)
  58. , m_type(ValueType::I32)
  59. {
  60. }
  61. using AnyValueType = Variant<i32, i64, float, double, Reference>;
  62. explicit Value(AnyValueType value)
  63. : m_value(move(value))
  64. , m_type(ValueType::I32)
  65. {
  66. if (m_value.has<i32>())
  67. m_type = ValueType { ValueType::I32 };
  68. else if (m_value.has<i64>())
  69. m_type = ValueType { ValueType::I64 };
  70. else if (m_value.has<float>())
  71. m_type = ValueType { ValueType::F32 };
  72. else if (m_value.has<double>())
  73. m_type = ValueType { ValueType::F64 };
  74. else if (m_value.has<Reference>() && m_value.get<Reference>().ref().has<Reference::Func>())
  75. m_type = ValueType { ValueType::FunctionReference };
  76. else if (m_value.has<Reference>() && m_value.get<Reference>().ref().has<Reference::Extern>())
  77. m_type = ValueType { ValueType::ExternReference };
  78. else if (m_value.has<Reference>())
  79. m_type = m_value.get<Reference>().ref().get<Reference::Null>().type;
  80. else
  81. VERIFY_NOT_REACHED();
  82. }
  83. template<typename T>
  84. requires(sizeof(T) == sizeof(u64)) explicit Value(ValueType type, T raw_value)
  85. : m_value(0)
  86. , m_type(type)
  87. {
  88. switch (type.kind()) {
  89. case ValueType::Kind::ExternReference:
  90. m_value = Reference { Reference::Extern { { bit_cast<u64>(raw_value) } } };
  91. break;
  92. case ValueType::Kind::FunctionReference:
  93. m_value = Reference { Reference::Func { { bit_cast<u64>(raw_value) } } };
  94. break;
  95. case ValueType::Kind::I32:
  96. m_value = static_cast<i32>(bit_cast<i64>(raw_value));
  97. break;
  98. case ValueType::Kind::I64:
  99. m_value = static_cast<i64>(bit_cast<u64>(raw_value));
  100. break;
  101. case ValueType::Kind::F32:
  102. m_value = static_cast<float>(bit_cast<double>(raw_value));
  103. break;
  104. case ValueType::Kind::F64:
  105. m_value = bit_cast<double>(raw_value);
  106. break;
  107. case ValueType::Kind::NullFunctionReference:
  108. VERIFY(raw_value == 0);
  109. m_value = Reference { Reference::Null { ValueType(ValueType::Kind::FunctionReference) } };
  110. break;
  111. case ValueType::Kind::NullExternReference:
  112. VERIFY(raw_value == 0);
  113. m_value = Reference { Reference::Null { ValueType(ValueType::Kind::ExternReference) } };
  114. break;
  115. default:
  116. VERIFY_NOT_REACHED();
  117. }
  118. }
  119. Value(Value const& value)
  120. : m_value(AnyValueType { value.m_value })
  121. , m_type(value.m_type)
  122. {
  123. }
  124. Value(Value&& value)
  125. : m_value(move(value.m_value))
  126. , m_type(move(value.m_type))
  127. {
  128. }
  129. Value& operator=(Value&& value)
  130. {
  131. m_value = move(value.m_value);
  132. m_type = move(value.m_type);
  133. return *this;
  134. }
  135. Value& operator=(Value const& value)
  136. {
  137. m_value = value.m_value;
  138. m_type = value.m_type;
  139. return *this;
  140. }
  141. template<typename T>
  142. Optional<T> to()
  143. {
  144. Optional<T> result;
  145. m_value.visit(
  146. [&](auto value) {
  147. if constexpr (IsSame<T, decltype(value)>)
  148. result = value;
  149. else if constexpr (!IsFloatingPoint<T> && IsSame<decltype(value), MakeSigned<T>>)
  150. result = value;
  151. },
  152. [&](Reference const& value) {
  153. if constexpr (IsSame<T, Reference>) {
  154. result = value;
  155. } else if constexpr (IsSame<T, Reference::Func>) {
  156. if (auto ptr = value.ref().template get_pointer<Reference::Func>())
  157. result = *ptr;
  158. } else if constexpr (IsSame<T, Reference::Extern>) {
  159. if (auto ptr = value.ref().template get_pointer<Reference::Extern>())
  160. result = *ptr;
  161. } else if constexpr (IsSame<T, Reference::Null>) {
  162. if (auto ptr = value.ref().template get_pointer<Reference::Null>())
  163. result = *ptr;
  164. }
  165. });
  166. return result;
  167. }
  168. auto& type() const { return m_type; }
  169. auto& value() const { return m_value; }
  170. private:
  171. AnyValueType m_value;
  172. ValueType m_type;
  173. };
  174. struct Trap {
  175. String reason;
  176. };
  177. class Result {
  178. public:
  179. explicit Result(Vector<Value> values)
  180. : m_result(move(values))
  181. {
  182. }
  183. Result(Trap trap)
  184. : m_result(move(trap))
  185. {
  186. }
  187. auto is_trap() const { return m_result.has<Trap>(); }
  188. auto& values() const { return m_result.get<Vector<Value>>(); }
  189. auto& values() { return m_result.get<Vector<Value>>(); }
  190. auto& trap() const { return m_result.get<Trap>(); }
  191. auto& trap() { return m_result.get<Trap>(); }
  192. private:
  193. Variant<Vector<Value>, Trap> m_result;
  194. };
  195. using ExternValue = Variant<FunctionAddress, TableAddress, MemoryAddress, GlobalAddress>;
  196. class ExportInstance {
  197. public:
  198. explicit ExportInstance(String name, ExternValue value)
  199. : m_name(move(name))
  200. , m_value(move(value))
  201. {
  202. }
  203. auto& name() const { return m_name; }
  204. auto& value() const { return m_value; }
  205. private:
  206. String m_name;
  207. ExternValue m_value;
  208. };
  209. class ModuleInstance {
  210. public:
  211. explicit ModuleInstance(
  212. Vector<FunctionType> types, Vector<FunctionAddress> function_addresses, Vector<TableAddress> table_addresses,
  213. Vector<MemoryAddress> memory_addresses, Vector<GlobalAddress> global_addresses, Vector<ExportInstance> exports)
  214. : m_types(move(types))
  215. , m_functions(move(function_addresses))
  216. , m_tables(move(table_addresses))
  217. , m_memories(move(memory_addresses))
  218. , m_globals(move(global_addresses))
  219. , m_exports(move(exports))
  220. {
  221. }
  222. ModuleInstance() = default;
  223. auto& types() const { return m_types; }
  224. auto& functions() const { return m_functions; }
  225. auto& tables() const { return m_tables; }
  226. auto& memories() const { return m_memories; }
  227. auto& globals() const { return m_globals; }
  228. auto& elements() const { return m_elements; }
  229. auto& exports() const { return m_exports; }
  230. auto& types() { return m_types; }
  231. auto& functions() { return m_functions; }
  232. auto& tables() { return m_tables; }
  233. auto& memories() { return m_memories; }
  234. auto& globals() { return m_globals; }
  235. auto& elements() { return m_elements; }
  236. auto& exports() { return m_exports; }
  237. private:
  238. Vector<FunctionType> m_types;
  239. Vector<FunctionAddress> m_functions;
  240. Vector<TableAddress> m_tables;
  241. Vector<MemoryAddress> m_memories;
  242. Vector<GlobalAddress> m_globals;
  243. Vector<ElementAddress> m_elements;
  244. Vector<ExportInstance> m_exports;
  245. };
  246. class WasmFunction {
  247. public:
  248. explicit WasmFunction(FunctionType const& type, ModuleInstance const& module, Module::Function const& code)
  249. : m_type(type)
  250. , m_module(module)
  251. , m_code(code)
  252. {
  253. }
  254. auto& type() const { return m_type; }
  255. auto& module() const { return m_module; }
  256. auto& code() const { return m_code; }
  257. private:
  258. FunctionType m_type;
  259. ModuleInstance const& m_module;
  260. Module::Function const& m_code;
  261. };
  262. class HostFunction {
  263. public:
  264. explicit HostFunction(AK::Function<Result(Configuration&, Vector<Value>&)> function, FunctionType const& type)
  265. : m_function(move(function))
  266. , m_type(type)
  267. {
  268. }
  269. auto& function() { return m_function; }
  270. auto& type() const { return m_type; }
  271. private:
  272. AK::Function<Result(Configuration&, Vector<Value>&)> m_function;
  273. FunctionType m_type;
  274. };
  275. using FunctionInstance = Variant<WasmFunction, HostFunction>;
  276. class TableInstance {
  277. public:
  278. explicit TableInstance(TableType const& type, Vector<Optional<Reference>> elements)
  279. : m_elements(move(elements))
  280. , m_type(type)
  281. {
  282. }
  283. auto& elements() const { return m_elements; }
  284. auto& elements() { return m_elements; }
  285. auto& type() const { return m_type; }
  286. private:
  287. Vector<Optional<Reference>> m_elements;
  288. TableType const& m_type;
  289. };
  290. class MemoryInstance {
  291. public:
  292. explicit MemoryInstance(MemoryType const& type)
  293. : m_type(type)
  294. {
  295. grow(m_type.limits().min() * Constants::page_size);
  296. }
  297. auto& type() const { return m_type; }
  298. auto size() const { return m_size; }
  299. auto& data() const { return m_data; }
  300. auto& data() { return m_data; }
  301. bool grow(size_t size_to_grow)
  302. {
  303. if (size_to_grow == 0)
  304. return true;
  305. auto new_size = m_data.size() + size_to_grow;
  306. if (auto max = m_type.limits().max(); max.has_value()) {
  307. if (max.value() * Constants::page_size < new_size)
  308. return false;
  309. }
  310. auto previous_size = m_size;
  311. m_data.resize(new_size);
  312. m_size = new_size;
  313. // The spec requires that we zero out everything on grow
  314. __builtin_memset(m_data.offset_pointer(previous_size), 0, size_to_grow);
  315. return true;
  316. }
  317. private:
  318. MemoryType const& m_type;
  319. size_t m_size { 0 };
  320. ByteBuffer m_data;
  321. };
  322. class GlobalInstance {
  323. public:
  324. explicit GlobalInstance(Value value, bool is_mutable)
  325. : m_mutable(is_mutable)
  326. , m_value(move(value))
  327. {
  328. }
  329. auto is_mutable() const { return m_mutable; }
  330. auto& value() const { return m_value; }
  331. void set_value(Value value)
  332. {
  333. VERIFY(is_mutable());
  334. m_value = move(value);
  335. }
  336. private:
  337. bool m_mutable { false };
  338. Value m_value;
  339. };
  340. class ElementInstance {
  341. public:
  342. explicit ElementInstance(ValueType type, Vector<Reference> references)
  343. : m_type(move(type))
  344. , m_references(move(references))
  345. {
  346. }
  347. auto& type() const { return m_type; }
  348. auto& references() const { return m_references; }
  349. private:
  350. ValueType m_type;
  351. Vector<Reference> m_references;
  352. };
  353. class Store {
  354. public:
  355. Store() = default;
  356. Optional<FunctionAddress> allocate(ModuleInstance& module, Module::Function const& function);
  357. Optional<FunctionAddress> allocate(HostFunction&&);
  358. Optional<TableAddress> allocate(TableType const&);
  359. Optional<MemoryAddress> allocate(MemoryType const&);
  360. Optional<GlobalAddress> allocate(GlobalType const&, Value);
  361. Optional<ElementAddress> allocate(ValueType const&, Vector<Reference>);
  362. FunctionInstance* get(FunctionAddress);
  363. TableInstance* get(TableAddress);
  364. MemoryInstance* get(MemoryAddress);
  365. GlobalInstance* get(GlobalAddress);
  366. ElementInstance* get(ElementAddress);
  367. private:
  368. Vector<FunctionInstance> m_functions;
  369. Vector<TableInstance> m_tables;
  370. Vector<MemoryInstance> m_memories;
  371. Vector<GlobalInstance> m_globals;
  372. Vector<ElementInstance> m_elements;
  373. };
  374. class Label {
  375. public:
  376. explicit Label(size_t arity, InstructionPointer continuation)
  377. : m_arity(arity)
  378. , m_continuation(continuation)
  379. {
  380. }
  381. auto continuation() const { return m_continuation; }
  382. auto arity() const { return m_arity; }
  383. private:
  384. size_t m_arity { 0 };
  385. InstructionPointer m_continuation { 0 };
  386. };
  387. class Frame {
  388. public:
  389. explicit Frame(ModuleInstance const& module, Vector<Value> locals, Expression const& expression, size_t arity)
  390. : m_module(module)
  391. , m_locals(move(locals))
  392. , m_expression(expression)
  393. , m_arity(arity)
  394. {
  395. }
  396. auto& module() const { return m_module; }
  397. auto& locals() const { return m_locals; }
  398. auto& locals() { return m_locals; }
  399. auto& expression() const { return m_expression; }
  400. auto arity() const { return m_arity; }
  401. private:
  402. ModuleInstance const& m_module;
  403. Vector<Value> m_locals;
  404. Expression const& m_expression;
  405. size_t m_arity { 0 };
  406. };
  407. class Stack {
  408. public:
  409. using EntryType = Variant<Value, Label, Frame>;
  410. Stack() = default;
  411. [[nodiscard]] ALWAYS_INLINE bool is_empty() const { return m_data.is_empty(); }
  412. ALWAYS_INLINE void push(EntryType entry) { m_data.append(move(entry)); }
  413. ALWAYS_INLINE auto pop() { return m_data.take_last(); }
  414. ALWAYS_INLINE auto& peek() const { return m_data.last(); }
  415. ALWAYS_INLINE auto& peek() { return m_data.last(); }
  416. ALWAYS_INLINE auto size() const { return m_data.size(); }
  417. ALWAYS_INLINE auto& entries() const { return m_data; }
  418. ALWAYS_INLINE auto& entries() { return m_data; }
  419. private:
  420. Vector<EntryType, 1024> m_data;
  421. };
  422. using InstantiationResult = AK::Result<NonnullOwnPtr<ModuleInstance>, InstantiationError>;
  423. class AbstractMachine {
  424. public:
  425. explicit AbstractMachine() = default;
  426. // Load and instantiate a module, and link it into this interpreter.
  427. InstantiationResult instantiate(Module const&, Vector<ExternValue>);
  428. Result invoke(FunctionAddress, Vector<Value>);
  429. Result invoke(Interpreter&, FunctionAddress, Vector<Value>);
  430. auto& store() const { return m_store; }
  431. auto& store() { return m_store; }
  432. private:
  433. Optional<InstantiationError> allocate_all_initial_phase(Module const&, ModuleInstance&, Vector<ExternValue>&, Vector<Value>& global_values);
  434. Optional<InstantiationError> allocate_all_final_phase(Module const&, ModuleInstance&, Vector<Vector<Reference>>& elements);
  435. Store m_store;
  436. };
  437. class Linker {
  438. public:
  439. struct Name {
  440. String module;
  441. String name;
  442. ImportSection::Import::ImportDesc type;
  443. };
  444. explicit Linker(Module const& module)
  445. : m_module(module)
  446. {
  447. }
  448. // Link a module, the import 'module name' is ignored with this.
  449. void link(ModuleInstance const&);
  450. // Link a bunch of qualified values, also matches 'module name'.
  451. void link(HashMap<Name, ExternValue> const&);
  452. auto& unresolved_imports()
  453. {
  454. populate();
  455. return m_unresolved_imports;
  456. }
  457. AK::Result<Vector<ExternValue>, LinkError> finish();
  458. private:
  459. void populate();
  460. Module const& m_module;
  461. HashMap<Name, ExternValue> m_resolved_imports;
  462. HashTable<Name> m_unresolved_imports;
  463. Vector<Name> m_ordered_imports;
  464. Optional<LinkError> m_error;
  465. };
  466. }
  467. template<>
  468. struct AK::Traits<Wasm::Linker::Name> : public AK::GenericTraits<Wasm::Linker::Name> {
  469. static constexpr bool is_trivial() { return false; }
  470. static unsigned hash(Wasm::Linker::Name const& entry) { return pair_int_hash(entry.module.hash(), entry.name.hash()); }
  471. static bool equals(Wasm::Linker::Name const& a, Wasm::Linker::Name const& b) { return a.name == b.name && a.module == b.module; }
  472. };