AbstractMachine.cpp 24 KB

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