AbstractMachine.cpp 15 KB

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