AbstractMachine.h 17 KB

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