AbstractMachine.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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. ALWAYS_INLINE Value(Value const& value)
  120. : m_value(AnyValueType { value.m_value })
  121. , m_type(value.m_type)
  122. {
  123. }
  124. ALWAYS_INLINE Value(Value&& value)
  125. : m_value(move(value.m_value))
  126. , m_type(move(value.m_type))
  127. {
  128. }
  129. ALWAYS_INLINE Value& operator=(Value&& value)
  130. {
  131. m_value = move(value.m_value);
  132. m_type = move(value.m_type);
  133. return *this;
  134. }
  135. ALWAYS_INLINE 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. ALWAYS_INLINE 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. // Can't grow past 2^16 pages.
  307. if (new_size >= Constants::page_size * 65536)
  308. return false;
  309. if (auto max = m_type.limits().max(); max.has_value()) {
  310. if (max.value() * Constants::page_size < new_size)
  311. return false;
  312. }
  313. auto previous_size = m_size;
  314. m_data.resize(new_size);
  315. m_size = new_size;
  316. // The spec requires that we zero out everything on grow
  317. __builtin_memset(m_data.offset_pointer(previous_size), 0, size_to_grow);
  318. return true;
  319. }
  320. private:
  321. MemoryType const& m_type;
  322. size_t m_size { 0 };
  323. ByteBuffer m_data;
  324. };
  325. class GlobalInstance {
  326. public:
  327. explicit GlobalInstance(Value value, bool is_mutable)
  328. : m_mutable(is_mutable)
  329. , m_value(move(value))
  330. {
  331. }
  332. auto is_mutable() const { return m_mutable; }
  333. auto& value() const { return m_value; }
  334. void set_value(Value value)
  335. {
  336. VERIFY(is_mutable());
  337. m_value = move(value);
  338. }
  339. private:
  340. bool m_mutable { false };
  341. Value m_value;
  342. };
  343. class ElementInstance {
  344. public:
  345. explicit ElementInstance(ValueType type, Vector<Reference> references)
  346. : m_type(move(type))
  347. , m_references(move(references))
  348. {
  349. }
  350. auto& type() const { return m_type; }
  351. auto& references() const { return m_references; }
  352. private:
  353. ValueType m_type;
  354. Vector<Reference> m_references;
  355. };
  356. class Store {
  357. public:
  358. Store() = default;
  359. Optional<FunctionAddress> allocate(ModuleInstance& module, Module::Function const& function);
  360. Optional<FunctionAddress> allocate(HostFunction&&);
  361. Optional<TableAddress> allocate(TableType const&);
  362. Optional<MemoryAddress> allocate(MemoryType const&);
  363. Optional<GlobalAddress> allocate(GlobalType const&, Value);
  364. Optional<ElementAddress> allocate(ValueType const&, Vector<Reference>);
  365. FunctionInstance* get(FunctionAddress);
  366. TableInstance* get(TableAddress);
  367. MemoryInstance* get(MemoryAddress);
  368. GlobalInstance* get(GlobalAddress);
  369. ElementInstance* get(ElementAddress);
  370. private:
  371. Vector<FunctionInstance> m_functions;
  372. Vector<TableInstance> m_tables;
  373. Vector<MemoryInstance> m_memories;
  374. Vector<GlobalInstance> m_globals;
  375. Vector<ElementInstance> m_elements;
  376. };
  377. class Label {
  378. public:
  379. explicit Label(size_t arity, InstructionPointer continuation)
  380. : m_arity(arity)
  381. , m_continuation(continuation)
  382. {
  383. }
  384. auto continuation() const { return m_continuation; }
  385. auto arity() const { return m_arity; }
  386. private:
  387. size_t m_arity { 0 };
  388. InstructionPointer m_continuation { 0 };
  389. };
  390. class Frame {
  391. public:
  392. explicit Frame(ModuleInstance const& module, Vector<Value> locals, Expression const& expression, size_t arity)
  393. : m_module(module)
  394. , m_locals(move(locals))
  395. , m_expression(expression)
  396. , m_arity(arity)
  397. {
  398. }
  399. auto& module() const { return m_module; }
  400. auto& locals() const { return m_locals; }
  401. auto& locals() { return m_locals; }
  402. auto& expression() const { return m_expression; }
  403. auto arity() const { return m_arity; }
  404. private:
  405. ModuleInstance const& m_module;
  406. Vector<Value> m_locals;
  407. Expression const& m_expression;
  408. size_t m_arity { 0 };
  409. };
  410. class Stack {
  411. public:
  412. using EntryType = Variant<Value, Label, Frame>;
  413. Stack() = default;
  414. [[nodiscard]] ALWAYS_INLINE bool is_empty() const { return m_data.is_empty(); }
  415. ALWAYS_INLINE void push(EntryType entry) { m_data.append(move(entry)); }
  416. ALWAYS_INLINE auto pop() { return m_data.take_last(); }
  417. ALWAYS_INLINE auto& peek() const { return m_data.last(); }
  418. ALWAYS_INLINE auto& peek() { return m_data.last(); }
  419. ALWAYS_INLINE auto size() const { return m_data.size(); }
  420. ALWAYS_INLINE auto& entries() const { return m_data; }
  421. ALWAYS_INLINE auto& entries() { return m_data; }
  422. private:
  423. Vector<EntryType, 1024> m_data;
  424. };
  425. using InstantiationResult = AK::Result<NonnullOwnPtr<ModuleInstance>, InstantiationError>;
  426. class AbstractMachine {
  427. public:
  428. explicit AbstractMachine() = default;
  429. // Load and instantiate a module, and link it into this interpreter.
  430. InstantiationResult instantiate(Module const&, Vector<ExternValue>);
  431. Result invoke(FunctionAddress, Vector<Value>);
  432. Result invoke(Interpreter&, FunctionAddress, Vector<Value>);
  433. auto& store() const { return m_store; }
  434. auto& store() { return m_store; }
  435. void enable_instruction_count_limit() { m_should_limit_instruction_count = true; }
  436. private:
  437. Optional<InstantiationError> allocate_all_initial_phase(Module const&, ModuleInstance&, Vector<ExternValue>&, Vector<Value>& global_values);
  438. Optional<InstantiationError> allocate_all_final_phase(Module const&, ModuleInstance&, Vector<Vector<Reference>>& elements);
  439. Store m_store;
  440. bool m_should_limit_instruction_count { false };
  441. };
  442. class Linker {
  443. public:
  444. struct Name {
  445. String module;
  446. String name;
  447. ImportSection::Import::ImportDesc type;
  448. };
  449. explicit Linker(Module const& module)
  450. : m_module(module)
  451. {
  452. }
  453. // Link a module, the import 'module name' is ignored with this.
  454. void link(ModuleInstance const&);
  455. // Link a bunch of qualified values, also matches 'module name'.
  456. void link(HashMap<Name, ExternValue> const&);
  457. auto& unresolved_imports()
  458. {
  459. populate();
  460. return m_unresolved_imports;
  461. }
  462. AK::Result<Vector<ExternValue>, LinkError> finish();
  463. private:
  464. void populate();
  465. Module const& m_module;
  466. HashMap<Name, ExternValue> m_resolved_imports;
  467. HashTable<Name> m_unresolved_imports;
  468. Vector<Name> m_ordered_imports;
  469. Optional<LinkError> m_error;
  470. };
  471. }
  472. template<>
  473. struct AK::Traits<Wasm::Linker::Name> : public AK::GenericTraits<Wasm::Linker::Name> {
  474. static constexpr bool is_trivial() { return false; }
  475. static unsigned hash(Wasm::Linker::Name const& entry) { return pair_int_hash(entry.module.hash(), entry.name.hash()); }
  476. static bool equals(Wasm::Linker::Name const& a, Wasm::Linker::Name const& b) { return a.name == b.name && a.module == b.module; }
  477. };