AbstractMachine.cpp 23 KB

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