AbstractMachine.cpp 21 KB

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