AbstractMachine.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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. auto address = main_module_instance.memories()[data.index.value()];
  253. if (auto instance = m_store.get(address)) {
  254. if (auto max = instance->type().limits().max(); max.has_value()) {
  255. if (*max < data.init.size() + offset) {
  256. instantiation_result = InstantiationError {
  257. String::formatted("Data segment attempted to write to out-of-bounds memory ({}) of max {} bytes",
  258. data.init.size() + offset, instance->type().limits().max().value())
  259. };
  260. return;
  261. }
  262. }
  263. if (instance->size() < data.init.size() + offset)
  264. instance->grow(data.init.size() + offset - instance->size());
  265. instance->data().overwrite(offset, data.init.data(), data.init.size());
  266. }
  267. },
  268. [&](DataSection::Data::Passive const&) {
  269. // FIXME: What do we do here?
  270. });
  271. }
  272. });
  273. module.for_each_section_of_type<StartSection>([&](StartSection const& section) {
  274. auto& functions = main_module_instance.functions();
  275. auto index = section.function().index();
  276. if (functions.size() <= index.value()) {
  277. instantiation_result = InstantiationError { String::formatted("Start section function referenced invalid index {} of max {} entries", index.value(), functions.size()) };
  278. return;
  279. }
  280. invoke(functions[index.value()], {});
  281. });
  282. if (instantiation_result.has_value())
  283. return instantiation_result.release_value();
  284. return InstantiationResult { move(main_module_instance_pointer) };
  285. }
  286. Optional<InstantiationError> AbstractMachine::allocate_all_initial_phase(Module const& module, ModuleInstance& module_instance, Vector<ExternValue>& externs, Vector<Value>& global_values)
  287. {
  288. Optional<InstantiationError> result;
  289. for (auto& entry : externs) {
  290. entry.visit(
  291. [&](FunctionAddress const& address) { module_instance.functions().append(address); },
  292. [&](TableAddress const& address) { module_instance.tables().append(address); },
  293. [&](MemoryAddress const& address) { module_instance.memories().append(address); },
  294. [&](GlobalAddress const& address) { module_instance.globals().append(address); });
  295. }
  296. // FIXME: What if this fails?
  297. for (auto& func : module.functions()) {
  298. auto address = m_store.allocate(module_instance, func);
  299. VERIFY(address.has_value());
  300. module_instance.functions().append(*address);
  301. }
  302. module.for_each_section_of_type<TableSection>([&](TableSection const& section) {
  303. for (auto& table : section.tables()) {
  304. auto table_address = m_store.allocate(table.type());
  305. VERIFY(table_address.has_value());
  306. module_instance.tables().append(*table_address);
  307. }
  308. });
  309. module.for_each_section_of_type<MemorySection>([&](MemorySection const& section) {
  310. for (auto& memory : section.memories()) {
  311. auto memory_address = m_store.allocate(memory.type());
  312. VERIFY(memory_address.has_value());
  313. module_instance.memories().append(*memory_address);
  314. }
  315. });
  316. module.for_each_section_of_type<GlobalSection>([&](GlobalSection const& section) {
  317. size_t index = 0;
  318. for (auto& entry : section.entries()) {
  319. auto address = m_store.allocate(entry.type(), move(global_values[index]));
  320. VERIFY(address.has_value());
  321. module_instance.globals().append(*address);
  322. index++;
  323. }
  324. });
  325. module.for_each_section_of_type<ExportSection>([&](ExportSection const& section) {
  326. for (auto& entry : section.entries()) {
  327. Variant<FunctionAddress, TableAddress, MemoryAddress, GlobalAddress, Empty> address { Empty {} };
  328. entry.description().visit(
  329. [&](FunctionIndex const& index) {
  330. if (module_instance.functions().size() > index.value())
  331. address = FunctionAddress { module_instance.functions()[index.value()] };
  332. else
  333. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.functions().size());
  334. },
  335. [&](TableIndex const& index) {
  336. if (module_instance.tables().size() > index.value())
  337. address = TableAddress { module_instance.tables()[index.value()] };
  338. else
  339. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.tables().size());
  340. },
  341. [&](MemoryIndex const& index) {
  342. if (module_instance.memories().size() > index.value())
  343. address = MemoryAddress { module_instance.memories()[index.value()] };
  344. else
  345. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.memories().size());
  346. },
  347. [&](GlobalIndex const& index) {
  348. if (module_instance.globals().size() > index.value())
  349. address = GlobalAddress { module_instance.globals()[index.value()] };
  350. else
  351. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.globals().size());
  352. });
  353. if (address.has<Empty>()) {
  354. result = InstantiationError { "An export could not be resolved" };
  355. continue;
  356. }
  357. module_instance.exports().append(ExportInstance {
  358. entry.name(),
  359. move(address).downcast<FunctionAddress, TableAddress, MemoryAddress, GlobalAddress>(),
  360. });
  361. }
  362. });
  363. return result;
  364. }
  365. Optional<InstantiationError> AbstractMachine::allocate_all_final_phase(Module const& module, ModuleInstance& module_instance, Vector<Vector<Reference>>& elements)
  366. {
  367. module.for_each_section_of_type<ElementSection>([&](ElementSection const& section) {
  368. size_t index = 0;
  369. for (auto& segment : section.segments()) {
  370. auto address = m_store.allocate(segment.type, move(elements[index]));
  371. VERIFY(address.has_value());
  372. module_instance.elements().append(*address);
  373. index++;
  374. }
  375. });
  376. return {};
  377. }
  378. Result AbstractMachine::invoke(FunctionAddress address, Vector<Value> arguments)
  379. {
  380. BytecodeInterpreter interpreter;
  381. return invoke(interpreter, address, move(arguments));
  382. }
  383. Result AbstractMachine::invoke(Interpreter& interpreter, FunctionAddress address, Vector<Value> arguments)
  384. {
  385. Configuration configuration { m_store };
  386. return configuration.call(interpreter, address, move(arguments));
  387. }
  388. void Linker::link(ModuleInstance const& instance)
  389. {
  390. populate();
  391. if (m_unresolved_imports.is_empty())
  392. return;
  393. HashTable<Name> resolved_imports;
  394. for (auto& import_ : m_unresolved_imports) {
  395. auto it = instance.exports().find_if([&](auto& export_) { return export_.name() == import_.name; });
  396. if (!it.is_end()) {
  397. resolved_imports.set(import_);
  398. m_resolved_imports.set(import_, it->value());
  399. }
  400. }
  401. for (auto& entry : resolved_imports)
  402. m_unresolved_imports.remove(entry);
  403. }
  404. void Linker::link(HashMap<Linker::Name, ExternValue> const& exports)
  405. {
  406. populate();
  407. if (m_unresolved_imports.is_empty())
  408. return;
  409. if (exports.is_empty())
  410. return;
  411. HashTable<Name> resolved_imports;
  412. for (auto& import_ : m_unresolved_imports) {
  413. auto export_ = exports.get(import_);
  414. if (export_.has_value()) {
  415. resolved_imports.set(import_);
  416. m_resolved_imports.set(import_, export_.value());
  417. }
  418. }
  419. for (auto& entry : resolved_imports)
  420. m_unresolved_imports.remove(entry);
  421. }
  422. AK::Result<Vector<ExternValue>, LinkError> Linker::finish()
  423. {
  424. populate();
  425. if (!m_unresolved_imports.is_empty()) {
  426. if (!m_error.has_value())
  427. m_error = LinkError {};
  428. for (auto& entry : m_unresolved_imports)
  429. m_error->missing_imports.append(entry.name);
  430. return *m_error;
  431. }
  432. if (m_error.has_value())
  433. return *m_error;
  434. // Result must be in the same order as the module imports
  435. Vector<ExternValue> exports;
  436. exports.ensure_capacity(m_ordered_imports.size());
  437. for (auto& import_ : m_ordered_imports)
  438. exports.unchecked_append(*m_resolved_imports.get(import_));
  439. return exports;
  440. }
  441. void Linker::populate()
  442. {
  443. if (!m_ordered_imports.is_empty())
  444. return;
  445. // There better be at most one import section!
  446. bool already_seen_an_import_section = false;
  447. m_module.for_each_section_of_type<ImportSection>([&](ImportSection const& section) {
  448. if (already_seen_an_import_section) {
  449. if (!m_error.has_value())
  450. m_error = LinkError {};
  451. m_error->other_errors.append(LinkError::InvalidImportedModule);
  452. return;
  453. }
  454. already_seen_an_import_section = true;
  455. for (auto& import_ : section.imports()) {
  456. m_ordered_imports.append({ import_.module(), import_.name(), import_.description() });
  457. m_unresolved_imports.set(m_ordered_imports.last());
  458. }
  459. });
  460. }
  461. }