AbstractMachine.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. /*
  2. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Interpreter.h"
  7. #include <LibWasm/AbstractMachine/AbstractMachine.h>
  8. #include <LibWasm/AbstractMachine/Configuration.h>
  9. #include <LibWasm/Types.h>
  10. namespace Wasm {
  11. Optional<FunctionAddress> Store::allocate(ModuleInstance& module, const Module::Function& function)
  12. {
  13. FunctionAddress address { m_functions.size() };
  14. if (function.type().value() > module.types().size())
  15. return {};
  16. auto& type = module.types()[function.type().value()];
  17. m_functions.empend(WasmFunction { type, module, function });
  18. return address;
  19. }
  20. Optional<FunctionAddress> Store::allocate(HostFunction&& function)
  21. {
  22. FunctionAddress address { m_functions.size() };
  23. m_functions.empend(HostFunction { move(function) });
  24. return address;
  25. }
  26. Optional<TableAddress> Store::allocate(const TableType& type)
  27. {
  28. TableAddress address { m_tables.size() };
  29. Vector<Optional<Reference>> elements;
  30. elements.resize(type.limits().min());
  31. m_tables.empend(TableInstance { type, move(elements) });
  32. return address;
  33. }
  34. Optional<MemoryAddress> Store::allocate(const MemoryType& type)
  35. {
  36. MemoryAddress address { m_memories.size() };
  37. m_memories.empend(MemoryInstance { type });
  38. return address;
  39. }
  40. Optional<GlobalAddress> Store::allocate(const GlobalType& type, Value value)
  41. {
  42. GlobalAddress address { m_globals.size() };
  43. m_globals.append(GlobalInstance { move(value), type.is_mutable() });
  44. return address;
  45. }
  46. FunctionInstance* Store::get(FunctionAddress address)
  47. {
  48. auto value = address.value();
  49. if (m_functions.size() <= value)
  50. return nullptr;
  51. return &m_functions[value];
  52. }
  53. TableInstance* Store::get(TableAddress address)
  54. {
  55. auto value = address.value();
  56. if (m_tables.size() <= value)
  57. return nullptr;
  58. return &m_tables[value];
  59. }
  60. MemoryInstance* Store::get(MemoryAddress address)
  61. {
  62. auto value = address.value();
  63. if (m_memories.size() <= value)
  64. return nullptr;
  65. return &m_memories[value];
  66. }
  67. GlobalInstance* Store::get(GlobalAddress address)
  68. {
  69. auto value = address.value();
  70. if (m_globals.size() <= value)
  71. return nullptr;
  72. return &m_globals[value];
  73. }
  74. InstantiationResult AbstractMachine::instantiate(const Module& module, Vector<ExternValue> externs)
  75. {
  76. auto main_module_instance_pointer = make<ModuleInstance>();
  77. auto& main_module_instance = *main_module_instance_pointer;
  78. Optional<InstantiationResult> instantiation_result;
  79. module.for_each_section_of_type<TypeSection>([&](const TypeSection& section) {
  80. main_module_instance.types() = section.types();
  81. });
  82. // FIXME: Validate stuff
  83. Vector<Value> global_values;
  84. ModuleInstance auxiliary_instance;
  85. // FIXME: Check that imports/extern match
  86. for (auto& entry : externs) {
  87. if (auto* ptr = entry.get_pointer<GlobalAddress>())
  88. auxiliary_instance.globals().append(*ptr);
  89. }
  90. BytecodeInterpreter interpreter;
  91. module.for_each_section_of_type<GlobalSection>([&](auto& global_section) {
  92. for (auto& entry : global_section.entries()) {
  93. Configuration config { m_store };
  94. config.set_frame(Frame {
  95. auxiliary_instance,
  96. Vector<Value> {},
  97. entry.expression(),
  98. 1,
  99. });
  100. auto result = config.execute(interpreter);
  101. // What if this traps?
  102. if (result.is_trap())
  103. instantiation_result = InstantiationError { "Global value construction trapped" };
  104. else
  105. global_values.append(result.values().first());
  106. }
  107. });
  108. if (auto result = allocate_all(module, main_module_instance, externs, global_values); result.has_value()) {
  109. return result.release_value();
  110. }
  111. module.for_each_section_of_type<ElementSection>([&](const ElementSection&) {
  112. // FIXME: Implement me
  113. // https://webassembly.github.io/spec/core/bikeshed/#element-segments%E2%91%A0
  114. // https://webassembly.github.io/spec/core/bikeshed/#instantiation%E2%91%A1 step 9
  115. });
  116. module.for_each_section_of_type<DataSection>([&](const DataSection& data_section) {
  117. for (auto& segment : data_section.data()) {
  118. segment.value().visit(
  119. [&](const DataSection::Data::Active& data) {
  120. Configuration config { m_store };
  121. config.set_frame(Frame {
  122. main_module_instance,
  123. Vector<Value> {},
  124. data.offset,
  125. 1,
  126. });
  127. auto result = config.execute(interpreter);
  128. size_t offset = 0;
  129. result.values().first().value().visit(
  130. [&](const auto& value) { offset = value; },
  131. [&](const FunctionAddress&) { instantiation_result = InstantiationError { "Data segment offset returned an address" }; },
  132. [&](const ExternAddress&) { instantiation_result = InstantiationError { "Data segment offset returned an address" }; },
  133. [&](const Value::Null&) { instantiation_result = InstantiationError { "Data segment offset returned a null reference" }; });
  134. if (instantiation_result.has_value() && instantiation_result->is_error())
  135. return;
  136. if (main_module_instance.memories().size() <= data.index.value()) {
  137. instantiation_result = InstantiationError { String::formatted("Data segment referenced out-of-bounds memory ({}) of max {} entries", data.index.value(), main_module_instance.memories().size()) };
  138. return;
  139. }
  140. auto address = main_module_instance.memories()[data.index.value()];
  141. if (auto instance = m_store.get(address)) {
  142. if (instance->type().limits().max().value_or(data.init.size() + offset + 1) <= data.init.size() + offset) {
  143. instantiation_result = InstantiationError { String::formatted("Data segment attempted to write to out-of-bounds memory ({}) of max {} bytes", data.init.size() + offset, instance->type().limits().max().value()) };
  144. return;
  145. }
  146. if (instance->size() < data.init.size() + offset)
  147. instance->grow(data.init.size() + offset - instance->size());
  148. instance->data().overwrite(offset, data.init.data(), data.init.size());
  149. }
  150. },
  151. [&](const DataSection::Data::Passive&) {
  152. // FIXME: What do we do here?
  153. });
  154. }
  155. });
  156. module.for_each_section_of_type<StartSection>([&](const StartSection& section) {
  157. auto& functions = main_module_instance.functions();
  158. auto index = section.function().index();
  159. if (functions.size() <= index.value()) {
  160. instantiation_result = InstantiationError { String::formatted("Start section function referenced invalid index {} of max {} entries", index.value(), functions.size()) };
  161. return;
  162. }
  163. invoke(functions[index.value()], {});
  164. });
  165. if (instantiation_result.has_value())
  166. return instantiation_result.release_value();
  167. return InstantiationResult { move(main_module_instance_pointer) };
  168. }
  169. Optional<InstantiationError> AbstractMachine::allocate_all(const Module& module, ModuleInstance& module_instance, Vector<ExternValue>& externs, Vector<Value>& global_values)
  170. {
  171. Optional<InstantiationError> result;
  172. for (auto& entry : externs) {
  173. entry.visit(
  174. [&](const FunctionAddress& address) { module_instance.functions().append(address); },
  175. [&](const TableAddress& address) { module_instance.tables().append(address); },
  176. [&](const MemoryAddress& address) { module_instance.memories().append(address); },
  177. [&](const GlobalAddress& address) { module_instance.globals().append(address); });
  178. }
  179. // FIXME: What if this fails?
  180. for (auto& func : module.functions()) {
  181. auto address = m_store.allocate(module_instance, func);
  182. VERIFY(address.has_value());
  183. module_instance.functions().append(*address);
  184. }
  185. module.for_each_section_of_type<TableSection>([&](const TableSection& section) {
  186. for (auto& table : section.tables()) {
  187. auto table_address = m_store.allocate(table.type());
  188. VERIFY(table_address.has_value());
  189. module_instance.tables().append(*table_address);
  190. }
  191. });
  192. module.for_each_section_of_type<MemorySection>([&](const MemorySection& section) {
  193. for (auto& memory : section.memories()) {
  194. auto memory_address = m_store.allocate(memory.type());
  195. VERIFY(memory_address.has_value());
  196. module_instance.memories().append(*memory_address);
  197. }
  198. });
  199. module.for_each_section_of_type<GlobalSection>([&](const GlobalSection& section) {
  200. size_t index = 0;
  201. for (auto& entry : section.entries()) {
  202. auto address = m_store.allocate(entry.type(), global_values[index]);
  203. VERIFY(address.has_value());
  204. module_instance.globals().append(*address);
  205. index++;
  206. }
  207. });
  208. module.for_each_section_of_type<ExportSection>([&](const ExportSection& section) {
  209. for (auto& entry : section.entries()) {
  210. Variant<FunctionAddress, TableAddress, MemoryAddress, GlobalAddress, Empty> address { Empty {} };
  211. entry.description().visit(
  212. [&](const FunctionIndex& index) {
  213. if (module_instance.functions().size() > index.value())
  214. address = FunctionAddress { module_instance.functions()[index.value()] };
  215. else
  216. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.functions().size());
  217. },
  218. [&](const TableIndex& index) {
  219. if (module_instance.tables().size() > index.value())
  220. address = TableAddress { module_instance.tables()[index.value()] };
  221. else
  222. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.tables().size());
  223. },
  224. [&](const MemoryIndex& index) {
  225. if (module_instance.memories().size() > index.value())
  226. address = MemoryAddress { module_instance.memories()[index.value()] };
  227. else
  228. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.memories().size());
  229. },
  230. [&](const GlobalIndex& index) {
  231. if (module_instance.globals().size() > index.value())
  232. address = GlobalAddress { module_instance.globals()[index.value()] };
  233. else
  234. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.globals().size());
  235. });
  236. if (address.has<Empty>()) {
  237. result = InstantiationError { "An export could not be resolved" };
  238. continue;
  239. }
  240. module_instance.exports().append(ExportInstance {
  241. entry.name(),
  242. move(address).downcast<FunctionAddress, TableAddress, MemoryAddress, GlobalAddress>(),
  243. });
  244. }
  245. });
  246. return result;
  247. }
  248. Result AbstractMachine::invoke(FunctionAddress address, Vector<Value> arguments)
  249. {
  250. BytecodeInterpreter interpreter;
  251. return invoke(interpreter, address, move(arguments));
  252. }
  253. Result AbstractMachine::invoke(Interpreter& interpreter, FunctionAddress address, Vector<Value> arguments)
  254. {
  255. Configuration configuration { m_store };
  256. return configuration.call(interpreter, address, move(arguments));
  257. }
  258. void Linker::link(const ModuleInstance& instance)
  259. {
  260. populate();
  261. if (m_unresolved_imports.is_empty())
  262. return;
  263. HashTable<Name> resolved_imports;
  264. for (auto& import_ : m_unresolved_imports) {
  265. auto it = instance.exports().find_if([&](auto& export_) { return export_.name() == import_.name; });
  266. if (!it.is_end()) {
  267. resolved_imports.set(import_);
  268. m_resolved_imports.set(import_, it->value());
  269. }
  270. }
  271. for (auto& entry : resolved_imports)
  272. m_unresolved_imports.remove(entry);
  273. }
  274. void Linker::link(const HashMap<Linker::Name, ExternValue>& exports)
  275. {
  276. populate();
  277. if (m_unresolved_imports.is_empty())
  278. return;
  279. HashTable<Name> resolved_imports;
  280. for (auto& import_ : m_unresolved_imports) {
  281. auto export_ = exports.get(import_);
  282. if (export_.has_value()) {
  283. resolved_imports.set(import_);
  284. m_resolved_imports.set(import_, export_.value());
  285. }
  286. }
  287. for (auto& entry : resolved_imports)
  288. m_unresolved_imports.remove(entry);
  289. }
  290. AK::Result<Vector<ExternValue>, LinkError> Linker::finish()
  291. {
  292. populate();
  293. if (!m_unresolved_imports.is_empty()) {
  294. if (!m_error.has_value())
  295. m_error = LinkError {};
  296. for (auto& entry : m_unresolved_imports)
  297. m_error->missing_imports.append(entry.name);
  298. return *m_error;
  299. }
  300. if (m_error.has_value())
  301. return *m_error;
  302. // Result must be in the same order as the module imports
  303. Vector<ExternValue> exports;
  304. exports.ensure_capacity(m_ordered_imports.size());
  305. for (auto& import_ : m_ordered_imports)
  306. exports.unchecked_append(*m_resolved_imports.get(import_));
  307. return exports;
  308. }
  309. void Linker::populate()
  310. {
  311. if (!m_ordered_imports.is_empty())
  312. return;
  313. // There better be at most one import section!
  314. bool already_seen_an_import_section = false;
  315. m_module.for_each_section_of_type<ImportSection>([&](const ImportSection& section) {
  316. if (already_seen_an_import_section) {
  317. if (!m_error.has_value())
  318. m_error = LinkError {};
  319. m_error->other_errors.append(LinkError::InvalidImportedModule);
  320. return;
  321. }
  322. already_seen_an_import_section = true;
  323. for (auto& import_ : section.imports()) {
  324. m_ordered_imports.append({ import_.module(), import_.name(), import_.description() });
  325. m_unresolved_imports.set(m_ordered_imports.last());
  326. }
  327. });
  328. }
  329. }