AbstractMachine.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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. Optional<ElementAddress> Store::allocate(const ValueType& type, Vector<Reference> references)
  47. {
  48. ElementAddress address { m_elements.size() };
  49. m_elements.append(ElementInstance { type, move(references) });
  50. return address;
  51. }
  52. FunctionInstance* Store::get(FunctionAddress address)
  53. {
  54. auto value = address.value();
  55. if (m_functions.size() <= value)
  56. return nullptr;
  57. return &m_functions[value];
  58. }
  59. TableInstance* Store::get(TableAddress address)
  60. {
  61. auto value = address.value();
  62. if (m_tables.size() <= value)
  63. return nullptr;
  64. return &m_tables[value];
  65. }
  66. MemoryInstance* Store::get(MemoryAddress address)
  67. {
  68. auto value = address.value();
  69. if (m_memories.size() <= value)
  70. return nullptr;
  71. return &m_memories[value];
  72. }
  73. GlobalInstance* Store::get(GlobalAddress address)
  74. {
  75. auto value = address.value();
  76. if (m_globals.size() <= value)
  77. return nullptr;
  78. return &m_globals[value];
  79. }
  80. ElementInstance* Store::get(ElementAddress address)
  81. {
  82. auto value = address.value();
  83. if (m_elements.size() <= value)
  84. return nullptr;
  85. return &m_elements[value];
  86. }
  87. InstantiationResult AbstractMachine::instantiate(const Module& module, Vector<ExternValue> externs)
  88. {
  89. auto main_module_instance_pointer = make<ModuleInstance>();
  90. auto& main_module_instance = *main_module_instance_pointer;
  91. Optional<InstantiationResult> instantiation_result;
  92. module.for_each_section_of_type<TypeSection>([&](const TypeSection& section) {
  93. main_module_instance.types() = section.types();
  94. });
  95. // FIXME: Validate stuff
  96. Vector<Value> global_values;
  97. Vector<Vector<Reference>> elements;
  98. ModuleInstance auxiliary_instance;
  99. // FIXME: Check that imports/extern match
  100. for (auto& entry : externs) {
  101. if (auto* ptr = entry.get_pointer<GlobalAddress>())
  102. auxiliary_instance.globals().append(*ptr);
  103. }
  104. BytecodeInterpreter interpreter;
  105. module.for_each_section_of_type<GlobalSection>([&](auto& global_section) {
  106. for (auto& entry : global_section.entries()) {
  107. Configuration config { m_store };
  108. config.set_frame(Frame {
  109. auxiliary_instance,
  110. Vector<Value> {},
  111. entry.expression(),
  112. 1,
  113. });
  114. auto result = config.execute(interpreter);
  115. if (result.is_trap())
  116. instantiation_result = InstantiationError { "Global value construction trapped" };
  117. else
  118. global_values.append(result.values().first());
  119. }
  120. });
  121. if (instantiation_result.has_value())
  122. return instantiation_result.release_value();
  123. if (auto result = allocate_all_initial_phase(module, main_module_instance, externs, global_values); result.has_value())
  124. return result.release_value();
  125. module.for_each_section_of_type<ElementSection>([&](const ElementSection& section) {
  126. for (auto& segment : section.segments()) {
  127. Vector<Reference> references;
  128. for (auto& entry : segment.init) {
  129. Configuration config { m_store };
  130. config.set_frame(Frame {
  131. main_module_instance,
  132. Vector<Value> {},
  133. entry,
  134. entry.instructions().size(),
  135. });
  136. auto result = config.execute(interpreter);
  137. if (result.is_trap()) {
  138. instantiation_result = InstantiationError { "Element construction trapped" };
  139. return IterationDecision::Continue;
  140. }
  141. for (auto& value : result.values()) {
  142. if (!value.type().is_reference()) {
  143. instantiation_result = InstantiationError { "Evaluated element entry is not a reference" };
  144. return IterationDecision::Continue;
  145. }
  146. auto reference = value.to<Reference>();
  147. if (!reference.has_value()) {
  148. instantiation_result = InstantiationError { "Evaluated element entry does not contain a reference" };
  149. return IterationDecision::Continue;
  150. }
  151. // FIXME: type-check the reference.
  152. references.prepend(reference.release_value());
  153. }
  154. }
  155. elements.append(move(references));
  156. }
  157. return IterationDecision::Continue;
  158. });
  159. if (instantiation_result.has_value())
  160. return instantiation_result.release_value();
  161. if (auto result = allocate_all_final_phase(module, main_module_instance, elements); result.has_value())
  162. return result.release_value();
  163. module.for_each_section_of_type<ElementSection>([&](const ElementSection& section) {
  164. size_t index = 0;
  165. for (auto& segment : section.segments()) {
  166. auto current_index = index;
  167. ++index;
  168. auto active_ptr = segment.mode.get_pointer<ElementSection::Active>();
  169. if (!active_ptr)
  170. continue;
  171. if (active_ptr->index.value() != 0) {
  172. instantiation_result = InstantiationError { "Non-zero table referenced by active element segment" };
  173. return IterationDecision::Break;
  174. }
  175. Configuration config { m_store };
  176. config.set_frame(Frame {
  177. main_module_instance,
  178. Vector<Value> {},
  179. active_ptr->expression,
  180. 1,
  181. });
  182. auto result = config.execute(interpreter);
  183. if (result.is_trap()) {
  184. instantiation_result = InstantiationError { "Element section initialisation trapped" };
  185. return IterationDecision::Break;
  186. }
  187. auto d = result.values().first().to<i32>();
  188. if (!d.has_value()) {
  189. instantiation_result = InstantiationError { "Element section initialisation returned invalid table initial offset" };
  190. return IterationDecision::Break;
  191. }
  192. if (main_module_instance.tables().size() < 1) {
  193. instantiation_result = InstantiationError { "Element section initialisation references nonexistent table" };
  194. return IterationDecision::Break;
  195. }
  196. auto table_instance = m_store.get(main_module_instance.tables()[0]);
  197. if (current_index >= main_module_instance.elements().size()) {
  198. instantiation_result = InstantiationError { "Invalid element referenced by active element segment" };
  199. return IterationDecision::Break;
  200. }
  201. auto elem_instance = m_store.get(main_module_instance.elements()[current_index]);
  202. if (!table_instance || !elem_instance) {
  203. instantiation_result = InstantiationError { "Invalid element referenced by active element segment" };
  204. return IterationDecision::Break;
  205. }
  206. auto total_required_size = elem_instance->references().size() + d.value();
  207. if (table_instance->type().limits().max().value_or(total_required_size) < total_required_size) {
  208. instantiation_result = InstantiationError { "Table limit overflow in active element segment" };
  209. return IterationDecision::Break;
  210. }
  211. if (table_instance->elements().size() < total_required_size)
  212. table_instance->elements().resize(total_required_size);
  213. size_t i = 0;
  214. for (auto it = elem_instance->references().begin(); it < elem_instance->references().end(); ++i, ++it) {
  215. table_instance->elements()[i + d.value()] = *it;
  216. }
  217. }
  218. return IterationDecision::Continue;
  219. });
  220. if (instantiation_result.has_value())
  221. return instantiation_result.release_value();
  222. module.for_each_section_of_type<DataSection>([&](const DataSection& data_section) {
  223. for (auto& segment : data_section.data()) {
  224. segment.value().visit(
  225. [&](const DataSection::Data::Active& data) {
  226. Configuration config { m_store };
  227. config.set_frame(Frame {
  228. main_module_instance,
  229. Vector<Value> {},
  230. data.offset,
  231. 1,
  232. });
  233. auto result = config.execute(interpreter);
  234. if (result.is_trap()) {
  235. instantiation_result = InstantiationError { "Data section initialisation trapped" };
  236. return;
  237. }
  238. size_t offset = 0;
  239. result.values().first().value().visit(
  240. [&](const auto& value) { offset = value; },
  241. [&](const Reference&) { instantiation_result = InstantiationError { "Data segment offset returned a reference" }; });
  242. if (instantiation_result.has_value() && instantiation_result->is_error())
  243. return;
  244. if (main_module_instance.memories().size() <= data.index.value()) {
  245. instantiation_result = InstantiationError { String::formatted("Data segment referenced out-of-bounds memory ({}) of max {} entries", data.index.value(), main_module_instance.memories().size()) };
  246. return;
  247. }
  248. auto address = main_module_instance.memories()[data.index.value()];
  249. if (auto instance = m_store.get(address)) {
  250. if (instance->type().limits().max().value_or(data.init.size() + offset + 1) <= data.init.size() + offset) {
  251. 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()) };
  252. return;
  253. }
  254. if (instance->size() < data.init.size() + offset)
  255. instance->grow(data.init.size() + offset - instance->size());
  256. instance->data().overwrite(offset, data.init.data(), data.init.size());
  257. }
  258. },
  259. [&](const DataSection::Data::Passive&) {
  260. // FIXME: What do we do here?
  261. });
  262. }
  263. });
  264. module.for_each_section_of_type<StartSection>([&](const StartSection& section) {
  265. auto& functions = main_module_instance.functions();
  266. auto index = section.function().index();
  267. if (functions.size() <= index.value()) {
  268. instantiation_result = InstantiationError { String::formatted("Start section function referenced invalid index {} of max {} entries", index.value(), functions.size()) };
  269. return;
  270. }
  271. invoke(functions[index.value()], {});
  272. });
  273. if (instantiation_result.has_value())
  274. return instantiation_result.release_value();
  275. return InstantiationResult { move(main_module_instance_pointer) };
  276. }
  277. Optional<InstantiationError> AbstractMachine::allocate_all_initial_phase(const Module& module, ModuleInstance& module_instance, Vector<ExternValue>& externs, Vector<Value>& global_values)
  278. {
  279. Optional<InstantiationError> result;
  280. for (auto& entry : externs) {
  281. entry.visit(
  282. [&](const FunctionAddress& address) { module_instance.functions().append(address); },
  283. [&](const TableAddress& address) { module_instance.tables().append(address); },
  284. [&](const MemoryAddress& address) { module_instance.memories().append(address); },
  285. [&](const GlobalAddress& address) { module_instance.globals().append(address); });
  286. }
  287. // FIXME: What if this fails?
  288. for (auto& func : module.functions()) {
  289. auto address = m_store.allocate(module_instance, func);
  290. VERIFY(address.has_value());
  291. module_instance.functions().append(*address);
  292. }
  293. module.for_each_section_of_type<TableSection>([&](const TableSection& section) {
  294. for (auto& table : section.tables()) {
  295. auto table_address = m_store.allocate(table.type());
  296. VERIFY(table_address.has_value());
  297. module_instance.tables().append(*table_address);
  298. }
  299. });
  300. module.for_each_section_of_type<MemorySection>([&](const MemorySection& section) {
  301. for (auto& memory : section.memories()) {
  302. auto memory_address = m_store.allocate(memory.type());
  303. VERIFY(memory_address.has_value());
  304. module_instance.memories().append(*memory_address);
  305. }
  306. });
  307. module.for_each_section_of_type<GlobalSection>([&](const GlobalSection& section) {
  308. size_t index = 0;
  309. for (auto& entry : section.entries()) {
  310. auto address = m_store.allocate(entry.type(), move(global_values[index]));
  311. VERIFY(address.has_value());
  312. module_instance.globals().append(*address);
  313. index++;
  314. }
  315. });
  316. module.for_each_section_of_type<ExportSection>([&](const ExportSection& section) {
  317. for (auto& entry : section.entries()) {
  318. Variant<FunctionAddress, TableAddress, MemoryAddress, GlobalAddress, Empty> address { Empty {} };
  319. entry.description().visit(
  320. [&](const FunctionIndex& index) {
  321. if (module_instance.functions().size() > index.value())
  322. address = FunctionAddress { module_instance.functions()[index.value()] };
  323. else
  324. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.functions().size());
  325. },
  326. [&](const TableIndex& index) {
  327. if (module_instance.tables().size() > index.value())
  328. address = TableAddress { module_instance.tables()[index.value()] };
  329. else
  330. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.tables().size());
  331. },
  332. [&](const MemoryIndex& index) {
  333. if (module_instance.memories().size() > index.value())
  334. address = MemoryAddress { module_instance.memories()[index.value()] };
  335. else
  336. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.memories().size());
  337. },
  338. [&](const GlobalIndex& index) {
  339. if (module_instance.globals().size() > index.value())
  340. address = GlobalAddress { module_instance.globals()[index.value()] };
  341. else
  342. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.globals().size());
  343. });
  344. if (address.has<Empty>()) {
  345. result = InstantiationError { "An export could not be resolved" };
  346. continue;
  347. }
  348. module_instance.exports().append(ExportInstance {
  349. entry.name(),
  350. move(address).downcast<FunctionAddress, TableAddress, MemoryAddress, GlobalAddress>(),
  351. });
  352. }
  353. });
  354. return result;
  355. }
  356. Optional<InstantiationError> AbstractMachine::allocate_all_final_phase(const Module& module, ModuleInstance& module_instance, Vector<Vector<Reference>>& elements)
  357. {
  358. module.for_each_section_of_type<ElementSection>([&](const ElementSection& section) {
  359. size_t index = 0;
  360. for (auto& segment : section.segments()) {
  361. auto address = m_store.allocate(segment.type, move(elements[index]));
  362. VERIFY(address.has_value());
  363. module_instance.elements().append(*address);
  364. index++;
  365. }
  366. });
  367. return {};
  368. }
  369. Result AbstractMachine::invoke(FunctionAddress address, Vector<Value> arguments)
  370. {
  371. BytecodeInterpreter interpreter;
  372. return invoke(interpreter, address, move(arguments));
  373. }
  374. Result AbstractMachine::invoke(Interpreter& interpreter, FunctionAddress address, Vector<Value> arguments)
  375. {
  376. Configuration configuration { m_store };
  377. return configuration.call(interpreter, address, move(arguments));
  378. }
  379. void Linker::link(const ModuleInstance& instance)
  380. {
  381. populate();
  382. if (m_unresolved_imports.is_empty())
  383. return;
  384. HashTable<Name> resolved_imports;
  385. for (auto& import_ : m_unresolved_imports) {
  386. auto it = instance.exports().find_if([&](auto& export_) { return export_.name() == import_.name; });
  387. if (!it.is_end()) {
  388. resolved_imports.set(import_);
  389. m_resolved_imports.set(import_, it->value());
  390. }
  391. }
  392. for (auto& entry : resolved_imports)
  393. m_unresolved_imports.remove(entry);
  394. }
  395. void Linker::link(const HashMap<Linker::Name, ExternValue>& exports)
  396. {
  397. populate();
  398. if (m_unresolved_imports.is_empty())
  399. return;
  400. HashTable<Name> resolved_imports;
  401. for (auto& import_ : m_unresolved_imports) {
  402. auto export_ = exports.get(import_);
  403. if (export_.has_value()) {
  404. resolved_imports.set(import_);
  405. m_resolved_imports.set(import_, export_.value());
  406. }
  407. }
  408. for (auto& entry : resolved_imports)
  409. m_unresolved_imports.remove(entry);
  410. }
  411. AK::Result<Vector<ExternValue>, LinkError> Linker::finish()
  412. {
  413. populate();
  414. if (!m_unresolved_imports.is_empty()) {
  415. if (!m_error.has_value())
  416. m_error = LinkError {};
  417. for (auto& entry : m_unresolved_imports)
  418. m_error->missing_imports.append(entry.name);
  419. return *m_error;
  420. }
  421. if (m_error.has_value())
  422. return *m_error;
  423. // Result must be in the same order as the module imports
  424. Vector<ExternValue> exports;
  425. exports.ensure_capacity(m_ordered_imports.size());
  426. for (auto& import_ : m_ordered_imports)
  427. exports.unchecked_append(*m_resolved_imports.get(import_));
  428. return exports;
  429. }
  430. void Linker::populate()
  431. {
  432. if (!m_ordered_imports.is_empty())
  433. return;
  434. // There better be at most one import section!
  435. bool already_seen_an_import_section = false;
  436. m_module.for_each_section_of_type<ImportSection>([&](const ImportSection& section) {
  437. if (already_seen_an_import_section) {
  438. if (!m_error.has_value())
  439. m_error = LinkError {};
  440. m_error->other_errors.append(LinkError::InvalidImportedModule);
  441. return;
  442. }
  443. already_seen_an_import_section = true;
  444. for (auto& import_ : section.imports()) {
  445. m_ordered_imports.append({ import_.module(), import_.name(), import_.description() });
  446. m_unresolved_imports.set(m_ordered_imports.last());
  447. }
  448. });
  449. }
  450. }