AbstractMachine.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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(const HostFunction& function)
  20. {
  21. FunctionAddress address { m_functions.size() };
  22. m_functions.empend(HostFunction { 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. Optional<InstantiationResult> instantiation_result;
  76. module.for_each_section_of_type<TypeSection>([&](const TypeSection& section) {
  77. m_module_instance.types() = section.types();
  78. });
  79. // FIXME: Validate stuff
  80. Vector<Value> global_values;
  81. ModuleInstance auxiliary_instance;
  82. // FIXME: Check that imports/extern match
  83. for (auto& entry : externs) {
  84. if (auto* ptr = entry.get_pointer<GlobalAddress>())
  85. auxiliary_instance.globals().append(*ptr);
  86. }
  87. module.for_each_section_of_type<GlobalSection>([&](auto& global_section) {
  88. for (auto& entry : global_section.entries()) {
  89. auto frame = make<Frame>(
  90. auxiliary_instance,
  91. Vector<Value> {},
  92. entry.expression(),
  93. 1);
  94. Configuration config { m_store };
  95. config.set_frame(move(frame));
  96. auto result = config.execute();
  97. // What if this traps?
  98. if (result.is_trap())
  99. instantiation_result = InstantiationError { "Global value construction trapped" };
  100. else
  101. global_values.append(result.values().first());
  102. }
  103. });
  104. if (auto result = allocate_all(module, externs, global_values); result.is_error()) {
  105. return result.error();
  106. }
  107. module.for_each_section_of_type<ElementSection>([&](const ElementSection&) {
  108. // FIXME: Implement me
  109. // https://webassembly.github.io/spec/core/bikeshed/#element-segments%E2%91%A0
  110. // https://webassembly.github.io/spec/core/bikeshed/#instantiation%E2%91%A1 step 9
  111. });
  112. module.for_each_section_of_type<DataSection>([&](const DataSection& data_section) {
  113. for (auto& segment : data_section.data()) {
  114. segment.value().visit(
  115. [&](const DataSection::Data::Active& data) {
  116. auto frame = make<Frame>(
  117. m_module_instance,
  118. Vector<Value> {},
  119. data.offset,
  120. 1);
  121. Configuration config { m_store };
  122. config.set_frame(move(frame));
  123. auto result = config.execute();
  124. size_t offset = 0;
  125. result.values().first().value().visit(
  126. [&](const auto& value) { offset = value; },
  127. [&](const FunctionAddress&) { instantiation_result = InstantiationError { "Data segment offset returned an address" }; },
  128. [&](const ExternAddress&) { instantiation_result = InstantiationError { "Data segment offset returned an address" }; });
  129. if (instantiation_result.has_value() && instantiation_result->is_error())
  130. return;
  131. if (m_module_instance.memories().size() <= data.index.value()) {
  132. instantiation_result = InstantiationError { String::formatted("Data segment referenced out-of-bounds memory ({}) of max {} entries", data.index.value(), m_module_instance.memories().size()) };
  133. return;
  134. }
  135. auto address = m_module_instance.memories()[data.index.value()];
  136. if (auto instance = m_store.get(address)) {
  137. if (instance->type().limits().max().value_or(data.init.size() + offset + 1) <= data.init.size() + offset) {
  138. 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()) };
  139. return;
  140. }
  141. instance->grow(data.init.size() + offset - instance->size());
  142. instance->data().overwrite(offset, data.init.data(), data.init.size());
  143. }
  144. },
  145. [&](const DataSection::Data::Passive&) {
  146. // FIXME: What do we do here?
  147. });
  148. }
  149. });
  150. module.for_each_section_of_type<StartSection>([&](const StartSection& section) {
  151. auto& functions = m_module_instance.functions();
  152. auto index = section.function().index();
  153. if (functions.size() <= index.value()) {
  154. instantiation_result = InstantiationError { String::formatted("Start section function referenced invalid index {} of max {} entries", index.value(), functions.size()) };
  155. return;
  156. }
  157. invoke(functions[index.value()], {});
  158. });
  159. return instantiation_result.value_or({});
  160. }
  161. InstantiationResult AbstractMachine::allocate_all(const Module& module, Vector<ExternValue>& externs, Vector<Value>& global_values)
  162. {
  163. Optional<InstantiationResult> result;
  164. for (auto& entry : externs) {
  165. entry.visit(
  166. [&](const FunctionAddress& address) { m_module_instance.functions().append(address); },
  167. [&](const TableAddress& address) { m_module_instance.tables().append(address); },
  168. [&](const MemoryAddress& address) { m_module_instance.memories().append(address); },
  169. [&](const GlobalAddress& address) { m_module_instance.globals().append(address); });
  170. }
  171. // FIXME: What if this fails?
  172. for (auto& func : module.functions()) {
  173. auto address = m_store.allocate(m_module_instance, func);
  174. VERIFY(address.has_value());
  175. m_module_instance.functions().append(*address);
  176. }
  177. module.for_each_section_of_type<TableSection>([&](const TableSection& section) {
  178. for (auto& table : section.tables()) {
  179. auto table_address = m_store.allocate(table.type());
  180. VERIFY(table_address.has_value());
  181. m_module_instance.tables().append(*table_address);
  182. }
  183. });
  184. module.for_each_section_of_type<MemorySection>([&](const MemorySection& section) {
  185. for (auto& memory : section.memories()) {
  186. auto memory_address = m_store.allocate(memory.type());
  187. VERIFY(memory_address.has_value());
  188. m_module_instance.memories().append(*memory_address);
  189. }
  190. });
  191. module.for_each_section_of_type<GlobalSection>([&](const GlobalSection& section) {
  192. size_t index = 0;
  193. for (auto& entry : section.entries()) {
  194. auto address = m_store.allocate(entry.type(), global_values[index]);
  195. VERIFY(address.has_value());
  196. m_module_instance.globals().append(*address);
  197. index++;
  198. }
  199. });
  200. module.for_each_section_of_type<ExportSection>([&](const ExportSection& section) {
  201. for (auto& entry : section.entries()) {
  202. Variant<FunctionAddress, TableAddress, MemoryAddress, GlobalAddress, Empty> address { Empty {} };
  203. entry.description().visit(
  204. [&](const FunctionIndex& index) {
  205. if (m_module_instance.functions().size() > index.value())
  206. address = FunctionAddress { m_module_instance.functions()[index.value()] };
  207. else
  208. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), m_module_instance.functions().size());
  209. },
  210. [&](const TableIndex& index) {
  211. if (m_module_instance.tables().size() > index.value())
  212. address = TableAddress { m_module_instance.tables()[index.value()] };
  213. else
  214. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), m_module_instance.tables().size());
  215. },
  216. [&](const MemoryIndex& index) {
  217. if (m_module_instance.memories().size() > index.value())
  218. address = MemoryAddress { m_module_instance.memories()[index.value()] };
  219. else
  220. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), m_module_instance.memories().size());
  221. },
  222. [&](const GlobalIndex& index) {
  223. if (m_module_instance.globals().size() > index.value())
  224. address = GlobalAddress { m_module_instance.globals()[index.value()] };
  225. else
  226. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), m_module_instance.globals().size());
  227. });
  228. if (address.has<Empty>()) {
  229. result = InstantiationError { "An export could not be resolved" };
  230. continue;
  231. }
  232. m_module_instance.exports().append(ExportInstance {
  233. entry.name(),
  234. move(address).downcast<FunctionAddress, TableAddress, MemoryAddress, GlobalAddress>(),
  235. });
  236. }
  237. });
  238. return result.value_or({});
  239. }
  240. Result AbstractMachine::invoke(FunctionAddress address, Vector<Value> arguments)
  241. {
  242. return Configuration { m_store }.call(address, move(arguments));
  243. }
  244. }