AbstractMachine.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. /*
  2. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Enumerate.h>
  7. #include <LibWasm/AbstractMachine/AbstractMachine.h>
  8. #include <LibWasm/AbstractMachine/BytecodeInterpreter.h>
  9. #include <LibWasm/AbstractMachine/Configuration.h>
  10. #include <LibWasm/AbstractMachine/Interpreter.h>
  11. #include <LibWasm/AbstractMachine/Validator.h>
  12. #include <LibWasm/Types.h>
  13. namespace Wasm {
  14. Optional<FunctionAddress> Store::allocate(ModuleInstance& module, CodeSection::Code const& code, TypeIndex type_index)
  15. {
  16. FunctionAddress address { m_functions.size() };
  17. if (type_index.value() > module.types().size())
  18. return {};
  19. auto& type = module.types()[type_index.value()];
  20. m_functions.empend(WasmFunction { type, module, code });
  21. return address;
  22. }
  23. Optional<FunctionAddress> Store::allocate(HostFunction&& function)
  24. {
  25. FunctionAddress address { m_functions.size() };
  26. m_functions.empend(HostFunction { move(function) });
  27. return address;
  28. }
  29. Optional<TableAddress> Store::allocate(TableType const& type)
  30. {
  31. TableAddress address { m_tables.size() };
  32. Vector<Reference> elements;
  33. elements.resize(type.limits().min());
  34. m_tables.empend(TableInstance { type, move(elements) });
  35. return address;
  36. }
  37. Optional<MemoryAddress> Store::allocate(MemoryType const& type)
  38. {
  39. MemoryAddress address { m_memories.size() };
  40. auto instance = MemoryInstance::create(type);
  41. if (instance.is_error())
  42. return {};
  43. m_memories.append(instance.release_value());
  44. return address;
  45. }
  46. Optional<GlobalAddress> Store::allocate(GlobalType const& type, Value value)
  47. {
  48. GlobalAddress address { m_globals.size() };
  49. m_globals.append(GlobalInstance { move(value), type.is_mutable() });
  50. return address;
  51. }
  52. Optional<DataAddress> Store::allocate_data(Vector<u8> initializer)
  53. {
  54. DataAddress address { m_datas.size() };
  55. m_datas.append(DataInstance { move(initializer) });
  56. return address;
  57. }
  58. Optional<ElementAddress> Store::allocate(ValueType const& type, Vector<Reference> references)
  59. {
  60. ElementAddress address { m_elements.size() };
  61. m_elements.append(ElementInstance { type, move(references) });
  62. return address;
  63. }
  64. FunctionInstance* Store::get(FunctionAddress address)
  65. {
  66. auto value = address.value();
  67. if (m_functions.size() <= value)
  68. return nullptr;
  69. return &m_functions[value];
  70. }
  71. TableInstance* Store::get(TableAddress address)
  72. {
  73. auto value = address.value();
  74. if (m_tables.size() <= value)
  75. return nullptr;
  76. return &m_tables[value];
  77. }
  78. MemoryInstance* Store::get(MemoryAddress address)
  79. {
  80. auto value = address.value();
  81. if (m_memories.size() <= value)
  82. return nullptr;
  83. return &m_memories[value];
  84. }
  85. GlobalInstance* Store::get(GlobalAddress address)
  86. {
  87. auto value = address.value();
  88. if (m_globals.size() <= value)
  89. return nullptr;
  90. return &m_globals[value];
  91. }
  92. ElementInstance* Store::get(ElementAddress address)
  93. {
  94. auto value = address.value();
  95. if (m_elements.size() <= value)
  96. return nullptr;
  97. return &m_elements[value];
  98. }
  99. DataInstance* Store::get(DataAddress address)
  100. {
  101. auto value = address.value();
  102. if (m_datas.size() <= value)
  103. return nullptr;
  104. return &m_datas[value];
  105. }
  106. ErrorOr<void, ValidationError> AbstractMachine::validate(Module& module)
  107. {
  108. if (module.validation_status() != Module::ValidationStatus::Unchecked) {
  109. if (module.validation_status() == Module::ValidationStatus::Valid)
  110. return {};
  111. return ValidationError { module.validation_error() };
  112. }
  113. auto result = Validator {}.validate(module);
  114. if (result.is_error()) {
  115. module.set_validation_error(result.error().error_string);
  116. return result.release_error();
  117. }
  118. return {};
  119. }
  120. InstantiationResult AbstractMachine::instantiate(Module const& module, Vector<ExternValue> externs)
  121. {
  122. if (auto result = validate(const_cast<Module&>(module)); result.is_error())
  123. return InstantiationError { ByteString::formatted("Validation failed: {}", result.error()) };
  124. auto main_module_instance_pointer = make<ModuleInstance>();
  125. auto& main_module_instance = *main_module_instance_pointer;
  126. main_module_instance.types() = module.type_section().types();
  127. Vector<Value> global_values;
  128. Vector<Vector<Reference>> elements;
  129. ModuleInstance auxiliary_instance;
  130. for (auto [i, import_] : enumerate(module.import_section().imports())) {
  131. auto extern_ = externs.at(i);
  132. auto invalid = import_.description().visit(
  133. [&](MemoryType const& mem_type) -> Optional<ByteString> {
  134. if (!extern_.has<MemoryAddress>())
  135. return "Expected memory import"sv;
  136. auto other_mem_type = m_store.get(extern_.get<MemoryAddress>())->type();
  137. if (other_mem_type.limits().is_subset_of(mem_type.limits()))
  138. return {};
  139. return ByteString::formatted("Memory import and extern do not match: {}-{} vs {}-{}", mem_type.limits().min(), mem_type.limits().max(), other_mem_type.limits().min(), other_mem_type.limits().max());
  140. },
  141. [&](TableType const& table_type) -> Optional<ByteString> {
  142. if (!extern_.has<TableAddress>())
  143. return "Expected table import"sv;
  144. auto other_table_type = m_store.get(extern_.get<TableAddress>())->type();
  145. if (table_type.element_type() == other_table_type.element_type()
  146. && other_table_type.limits().is_subset_of(table_type.limits()))
  147. return {};
  148. return ByteString::formatted("Table import and extern do not match: {}-{} vs {}-{}", table_type.limits().min(), table_type.limits().max(), other_table_type.limits().min(), other_table_type.limits().max());
  149. },
  150. [&](GlobalType const& global_type) -> Optional<ByteString> {
  151. if (!extern_.has<GlobalAddress>())
  152. return "Expected global import"sv;
  153. auto other_global_type = m_store.get(extern_.get<GlobalAddress>())->type();
  154. if (global_type.type() == other_global_type.type()
  155. && global_type.is_mutable() == other_global_type.is_mutable())
  156. return {};
  157. return "Global import and extern do not match"sv;
  158. },
  159. [&](FunctionType const& type) -> Optional<ByteString> {
  160. if (!extern_.has<FunctionAddress>())
  161. return "Expected function import"sv;
  162. auto other_type = m_store.get(extern_.get<FunctionAddress>())->visit([&](WasmFunction const& wasm_func) { return wasm_func.type(); }, [&](HostFunction const& host_func) { return host_func.type(); });
  163. if (type.results() != other_type.results())
  164. return ByteString::formatted("Function import and extern do not match, results: {} vs {}", type.results(), other_type.results());
  165. if (type.parameters() != other_type.parameters())
  166. return ByteString::formatted("Function import and extern do not match, parameters: {} vs {}", type.parameters(), other_type.parameters());
  167. return {};
  168. },
  169. [&](TypeIndex type_index) -> Optional<ByteString> {
  170. if (!extern_.has<FunctionAddress>())
  171. return "Expected function import"sv;
  172. auto other_type = m_store.get(extern_.get<FunctionAddress>())->visit([&](WasmFunction const& wasm_func) { return wasm_func.type(); }, [&](HostFunction const& host_func) { return host_func.type(); });
  173. auto& type = module.type_section().types()[type_index.value()];
  174. if (type.results() != other_type.results())
  175. return ByteString::formatted("Function import and extern do not match, results: {} vs {}", type.results(), other_type.results());
  176. if (type.parameters() != other_type.parameters())
  177. return ByteString::formatted("Function import and extern do not match, parameters: {} vs {}", type.parameters(), other_type.parameters());
  178. return {};
  179. });
  180. if (invalid.has_value())
  181. return InstantiationError { ByteString::formatted("{}::{}: {}", import_.module(), import_.name(), invalid.release_value()) };
  182. }
  183. for (auto& entry : externs) {
  184. if (auto* ptr = entry.get_pointer<GlobalAddress>())
  185. auxiliary_instance.globals().append(*ptr);
  186. else if (auto* ptr = entry.get_pointer<FunctionAddress>())
  187. auxiliary_instance.functions().append(*ptr);
  188. }
  189. Vector<FunctionAddress> module_functions;
  190. module_functions.ensure_capacity(module.function_section().types().size());
  191. size_t i = 0;
  192. for (auto& code : module.code_section().functions()) {
  193. auto type_index = module.function_section().types()[i];
  194. auto address = m_store.allocate(main_module_instance, code, type_index);
  195. VERIFY(address.has_value());
  196. auxiliary_instance.functions().append(*address);
  197. module_functions.append(*address);
  198. ++i;
  199. }
  200. BytecodeInterpreter interpreter(m_stack_info);
  201. for (auto& entry : module.global_section().entries()) {
  202. Configuration config { m_store };
  203. if (m_should_limit_instruction_count)
  204. config.enable_instruction_count_limit();
  205. config.set_frame(Frame {
  206. auxiliary_instance,
  207. Vector<Value> {},
  208. entry.expression(),
  209. 1,
  210. });
  211. auto result = config.execute(interpreter).assert_wasm_result();
  212. if (result.is_trap())
  213. return InstantiationError { ByteString::formatted("Global value construction trapped: {}", result.trap().reason) };
  214. global_values.append(result.values().first());
  215. }
  216. if (auto result = allocate_all_initial_phase(module, main_module_instance, externs, global_values, module_functions); result.has_value())
  217. return result.release_value();
  218. for (auto& segment : module.element_section().segments()) {
  219. Vector<Reference> references;
  220. for (auto& entry : segment.init) {
  221. Configuration config { m_store };
  222. if (m_should_limit_instruction_count)
  223. config.enable_instruction_count_limit();
  224. config.set_frame(Frame {
  225. auxiliary_instance,
  226. Vector<Value> {},
  227. entry,
  228. entry.instructions().size(),
  229. });
  230. auto result = config.execute(interpreter).assert_wasm_result();
  231. if (result.is_trap())
  232. return InstantiationError { ByteString::formatted("Element construction trapped: {}", result.trap().reason) };
  233. for (auto& value : result.values()) {
  234. auto reference = value.to<Reference>();
  235. references.append(reference.release_value());
  236. }
  237. }
  238. elements.append(move(references));
  239. }
  240. if (auto result = allocate_all_final_phase(module, main_module_instance, elements); result.has_value())
  241. return result.release_value();
  242. size_t index = 0;
  243. for (auto& segment : module.element_section().segments()) {
  244. auto current_index = index;
  245. ++index;
  246. auto active_ptr = segment.mode.get_pointer<ElementSection::Active>();
  247. auto elem_instance = m_store.get(main_module_instance.elements()[current_index]);
  248. if (!active_ptr) {
  249. if (segment.mode.has<ElementSection::Declarative>())
  250. *elem_instance = ElementInstance(elem_instance->type(), {});
  251. continue;
  252. }
  253. Configuration config { m_store };
  254. if (m_should_limit_instruction_count)
  255. config.enable_instruction_count_limit();
  256. config.set_frame(Frame {
  257. auxiliary_instance,
  258. Vector<Value> {},
  259. active_ptr->expression,
  260. 1,
  261. });
  262. auto result = config.execute(interpreter).assert_wasm_result();
  263. if (result.is_trap())
  264. return InstantiationError { ByteString::formatted("Element section initialisation trapped: {}", result.trap().reason) };
  265. auto d = result.values().first().to<i32>();
  266. if (!d.has_value())
  267. return InstantiationError { "Element section initialisation returned invalid table initial offset" };
  268. auto table_instance = m_store.get(main_module_instance.tables()[active_ptr->index.value()]);
  269. if (current_index >= main_module_instance.elements().size())
  270. return InstantiationError { "Invalid element referenced by active element segment" };
  271. if (!table_instance || !elem_instance)
  272. return InstantiationError { "Invalid element referenced by active element segment" };
  273. Checked<size_t> total_size = elem_instance->references().size();
  274. total_size.saturating_add(d.value());
  275. if (total_size.value() > table_instance->elements().size())
  276. return InstantiationError { "Table instantiation out of bounds" };
  277. size_t i = 0;
  278. for (auto it = elem_instance->references().begin(); it < elem_instance->references().end(); ++i, ++it)
  279. table_instance->elements()[i + d.value()] = *it;
  280. // Drop element
  281. *m_store.get(main_module_instance.elements()[current_index]) = ElementInstance(elem_instance->type(), {});
  282. }
  283. for (auto& segment : module.data_section().data()) {
  284. Optional<InstantiationError> result = segment.value().visit(
  285. [&](DataSection::Data::Active const& data) -> Optional<InstantiationError> {
  286. Configuration config { m_store };
  287. if (m_should_limit_instruction_count)
  288. config.enable_instruction_count_limit();
  289. config.set_frame(Frame {
  290. auxiliary_instance,
  291. Vector<Value> {},
  292. data.offset,
  293. 1,
  294. });
  295. auto result = config.execute(interpreter).assert_wasm_result();
  296. if (result.is_trap())
  297. return InstantiationError { ByteString::formatted("Data section initialisation trapped: {}", result.trap().reason) };
  298. size_t offset = TRY(result.values().first().value().visit(
  299. [&](auto const& value) { return ErrorOr<size_t, InstantiationError> { value }; },
  300. [&](u128 const&) { return ErrorOr<size_t, InstantiationError> { InstantiationError { "Data segment offset returned a vector type"sv } }; },
  301. [&](Reference const&) { return ErrorOr<size_t, InstantiationError> { InstantiationError { "Data segment offset returned a reference type"sv } }; }));
  302. if (main_module_instance.memories().size() <= data.index.value()) {
  303. return InstantiationError {
  304. ByteString::formatted("Data segment referenced out-of-bounds memory ({}) of max {} entries",
  305. data.index.value(), main_module_instance.memories().size())
  306. };
  307. }
  308. auto maybe_data_address = m_store.allocate_data(data.init);
  309. if (!maybe_data_address.has_value()) {
  310. return InstantiationError { "Failed to allocate a data instance for an active data segment"sv };
  311. }
  312. main_module_instance.datas().append(*maybe_data_address);
  313. auto address = main_module_instance.memories()[data.index.value()];
  314. auto instance = m_store.get(address);
  315. Checked<size_t> checked_offset = data.init.size();
  316. checked_offset += offset;
  317. if (checked_offset.has_overflow() || checked_offset > instance->size()) {
  318. return InstantiationError {
  319. ByteString::formatted("Data segment attempted to write to out-of-bounds memory ({}) in memory of size {}",
  320. offset, instance->size())
  321. };
  322. }
  323. if (!data.init.is_empty())
  324. instance->data().overwrite(offset, data.init.data(), data.init.size());
  325. return {};
  326. },
  327. [&](DataSection::Data::Passive const& passive) -> Optional<InstantiationError> {
  328. auto maybe_data_address = m_store.allocate_data(passive.init);
  329. if (!maybe_data_address.has_value()) {
  330. return InstantiationError { "Failed to allocate a data instance for a passive data segment"sv };
  331. }
  332. main_module_instance.datas().append(*maybe_data_address);
  333. return {};
  334. });
  335. if (result.has_value())
  336. return result.release_value();
  337. }
  338. if (module.start_section().function().has_value()) {
  339. auto& functions = main_module_instance.functions();
  340. auto index = module.start_section().function()->index();
  341. if (functions.size() <= index.value()) {
  342. return InstantiationError { ByteString::formatted("Start section function referenced invalid index {} of max {} entries", index.value(), functions.size()) };
  343. }
  344. auto result = invoke(functions[index.value()], {});
  345. if (result.is_trap())
  346. return InstantiationError { ByteString::formatted("Start function trapped: {}", result.trap().reason) };
  347. }
  348. return InstantiationResult { move(main_module_instance_pointer) };
  349. }
  350. Optional<InstantiationError> AbstractMachine::allocate_all_initial_phase(Module const& module, ModuleInstance& module_instance, Vector<ExternValue>& externs, Vector<Value>& global_values, Vector<FunctionAddress>& own_functions)
  351. {
  352. Optional<InstantiationError> result;
  353. for (auto& entry : externs) {
  354. entry.visit(
  355. [&](FunctionAddress const& address) { module_instance.functions().append(address); },
  356. [&](TableAddress const& address) { module_instance.tables().append(address); },
  357. [&](MemoryAddress const& address) { module_instance.memories().append(address); },
  358. [&](GlobalAddress const& address) { module_instance.globals().append(address); });
  359. }
  360. module_instance.functions().extend(own_functions);
  361. // FIXME: What if this fails?
  362. for (auto& table : module.table_section().tables()) {
  363. auto table_address = m_store.allocate(table.type());
  364. VERIFY(table_address.has_value());
  365. module_instance.tables().append(*table_address);
  366. }
  367. for (auto& memory : module.memory_section().memories()) {
  368. auto memory_address = m_store.allocate(memory.type());
  369. VERIFY(memory_address.has_value());
  370. module_instance.memories().append(*memory_address);
  371. }
  372. size_t index = 0;
  373. for (auto& entry : module.global_section().entries()) {
  374. auto address = m_store.allocate(entry.type(), move(global_values[index]));
  375. VERIFY(address.has_value());
  376. module_instance.globals().append(*address);
  377. index++;
  378. }
  379. for (auto& entry : module.export_section().entries()) {
  380. Variant<FunctionAddress, TableAddress, MemoryAddress, GlobalAddress, Empty> address {};
  381. entry.description().visit(
  382. [&](FunctionIndex const& index) {
  383. if (module_instance.functions().size() > index.value())
  384. address = FunctionAddress { module_instance.functions()[index.value()] };
  385. else
  386. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.functions().size());
  387. },
  388. [&](TableIndex const& index) {
  389. if (module_instance.tables().size() > index.value())
  390. address = TableAddress { module_instance.tables()[index.value()] };
  391. else
  392. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.tables().size());
  393. },
  394. [&](MemoryIndex const& index) {
  395. if (module_instance.memories().size() > index.value())
  396. address = MemoryAddress { module_instance.memories()[index.value()] };
  397. else
  398. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.memories().size());
  399. },
  400. [&](GlobalIndex const& index) {
  401. if (module_instance.globals().size() > index.value())
  402. address = GlobalAddress { module_instance.globals()[index.value()] };
  403. else
  404. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.globals().size());
  405. });
  406. if (address.has<Empty>()) {
  407. result = InstantiationError { "An export could not be resolved" };
  408. continue;
  409. }
  410. module_instance.exports().append(ExportInstance {
  411. entry.name(),
  412. move(address).downcast<FunctionAddress, TableAddress, MemoryAddress, GlobalAddress>(),
  413. });
  414. }
  415. return result;
  416. }
  417. Optional<InstantiationError> AbstractMachine::allocate_all_final_phase(Module const& module, ModuleInstance& module_instance, Vector<Vector<Reference>>& elements)
  418. {
  419. size_t index = 0;
  420. for (auto& segment : module.element_section().segments()) {
  421. auto address = m_store.allocate(segment.type, move(elements[index]));
  422. VERIFY(address.has_value());
  423. module_instance.elements().append(*address);
  424. index++;
  425. }
  426. return {};
  427. }
  428. Result AbstractMachine::invoke(FunctionAddress address, Vector<Value> arguments)
  429. {
  430. BytecodeInterpreter interpreter(m_stack_info);
  431. return invoke(interpreter, address, move(arguments));
  432. }
  433. Result AbstractMachine::invoke(Interpreter& interpreter, FunctionAddress address, Vector<Value> arguments)
  434. {
  435. Configuration configuration { m_store };
  436. if (m_should_limit_instruction_count)
  437. configuration.enable_instruction_count_limit();
  438. return configuration.call(interpreter, address, move(arguments));
  439. }
  440. void Linker::link(ModuleInstance const& instance)
  441. {
  442. populate();
  443. if (m_unresolved_imports.is_empty())
  444. return;
  445. HashTable<Name> resolved_imports;
  446. for (auto& import_ : m_unresolved_imports) {
  447. auto it = instance.exports().find_if([&](auto& export_) { return export_.name() == import_.name; });
  448. if (!it.is_end()) {
  449. resolved_imports.set(import_);
  450. m_resolved_imports.set(import_, it->value());
  451. }
  452. }
  453. for (auto& entry : resolved_imports)
  454. m_unresolved_imports.remove(entry);
  455. }
  456. void Linker::link(HashMap<Linker::Name, ExternValue> const& exports)
  457. {
  458. populate();
  459. if (m_unresolved_imports.is_empty())
  460. return;
  461. if (exports.is_empty())
  462. return;
  463. HashTable<Name> resolved_imports;
  464. for (auto& import_ : m_unresolved_imports) {
  465. auto export_ = exports.get(import_);
  466. if (export_.has_value()) {
  467. resolved_imports.set(import_);
  468. m_resolved_imports.set(import_, export_.value());
  469. }
  470. }
  471. for (auto& entry : resolved_imports)
  472. m_unresolved_imports.remove(entry);
  473. }
  474. AK::ErrorOr<Vector<ExternValue>, LinkError> Linker::finish()
  475. {
  476. populate();
  477. if (!m_unresolved_imports.is_empty()) {
  478. if (!m_error.has_value())
  479. m_error = LinkError {};
  480. for (auto& entry : m_unresolved_imports)
  481. m_error->missing_imports.append(entry.name);
  482. return *m_error;
  483. }
  484. if (m_error.has_value())
  485. return *m_error;
  486. // Result must be in the same order as the module imports
  487. Vector<ExternValue> exports;
  488. exports.ensure_capacity(m_ordered_imports.size());
  489. for (auto& import_ : m_ordered_imports)
  490. exports.unchecked_append(*m_resolved_imports.get(import_));
  491. return exports;
  492. }
  493. void Linker::populate()
  494. {
  495. if (!m_ordered_imports.is_empty())
  496. return;
  497. for (auto& import_ : m_module.import_section().imports()) {
  498. m_ordered_imports.append({ import_.module(), import_.name(), import_.description() });
  499. m_unresolved_imports.set(m_ordered_imports.last());
  500. }
  501. }
  502. }