AbstractMachine.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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 { value, type.is_mutable(), type.type() });
  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);
  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. auto table_instance = m_store.get(main_module_instance.tables()[active_ptr->index.value()]);
  267. if (current_index >= main_module_instance.elements().size())
  268. return InstantiationError { "Invalid element referenced by active element segment" };
  269. if (!table_instance || !elem_instance)
  270. return InstantiationError { "Invalid element referenced by active element segment" };
  271. Checked<size_t> total_size = elem_instance->references().size();
  272. total_size.saturating_add(d);
  273. if (total_size.value() > table_instance->elements().size())
  274. return InstantiationError { "Table instantiation out of bounds" };
  275. size_t i = 0;
  276. for (auto it = elem_instance->references().begin(); it < elem_instance->references().end(); ++i, ++it)
  277. table_instance->elements()[i + d] = *it;
  278. // Drop element
  279. *m_store.get(main_module_instance.elements()[current_index]) = ElementInstance(elem_instance->type(), {});
  280. }
  281. for (auto& segment : module.data_section().data()) {
  282. Optional<InstantiationError> result = segment.value().visit(
  283. [&](DataSection::Data::Active const& data) -> Optional<InstantiationError> {
  284. Configuration config { m_store };
  285. if (m_should_limit_instruction_count)
  286. config.enable_instruction_count_limit();
  287. config.set_frame(Frame {
  288. auxiliary_instance,
  289. Vector<Value> {},
  290. data.offset,
  291. 1,
  292. });
  293. auto result = config.execute(interpreter).assert_wasm_result();
  294. if (result.is_trap())
  295. return InstantiationError { ByteString::formatted("Data section initialisation trapped: {}", result.trap().reason) };
  296. size_t offset = result.values().first().to<u64>();
  297. if (main_module_instance.memories().size() <= data.index.value()) {
  298. return InstantiationError {
  299. ByteString::formatted("Data segment referenced out-of-bounds memory ({}) of max {} entries",
  300. data.index.value(), main_module_instance.memories().size())
  301. };
  302. }
  303. auto maybe_data_address = m_store.allocate_data(data.init);
  304. if (!maybe_data_address.has_value()) {
  305. return InstantiationError { "Failed to allocate a data instance for an active data segment"sv };
  306. }
  307. main_module_instance.datas().append(*maybe_data_address);
  308. auto address = main_module_instance.memories()[data.index.value()];
  309. auto instance = m_store.get(address);
  310. Checked<size_t> checked_offset = data.init.size();
  311. checked_offset += offset;
  312. if (checked_offset.has_overflow() || checked_offset > instance->size()) {
  313. return InstantiationError {
  314. ByteString::formatted("Data segment attempted to write to out-of-bounds memory ({}) in memory of size {}",
  315. offset, instance->size())
  316. };
  317. }
  318. if (!data.init.is_empty())
  319. instance->data().overwrite(offset, data.init.data(), data.init.size());
  320. return {};
  321. },
  322. [&](DataSection::Data::Passive const& passive) -> Optional<InstantiationError> {
  323. auto maybe_data_address = m_store.allocate_data(passive.init);
  324. if (!maybe_data_address.has_value()) {
  325. return InstantiationError { "Failed to allocate a data instance for a passive data segment"sv };
  326. }
  327. main_module_instance.datas().append(*maybe_data_address);
  328. return {};
  329. });
  330. if (result.has_value())
  331. return result.release_value();
  332. }
  333. if (module.start_section().function().has_value()) {
  334. auto& functions = main_module_instance.functions();
  335. auto index = module.start_section().function()->index();
  336. if (functions.size() <= index.value()) {
  337. return InstantiationError { ByteString::formatted("Start section function referenced invalid index {} of max {} entries", index.value(), functions.size()) };
  338. }
  339. auto result = invoke(functions[index.value()], {});
  340. if (result.is_trap())
  341. return InstantiationError { ByteString::formatted("Start function trapped: {}", result.trap().reason) };
  342. }
  343. return InstantiationResult { move(main_module_instance_pointer) };
  344. }
  345. Optional<InstantiationError> AbstractMachine::allocate_all_initial_phase(Module const& module, ModuleInstance& module_instance, Vector<ExternValue>& externs, Vector<Value>& global_values, Vector<FunctionAddress>& own_functions)
  346. {
  347. Optional<InstantiationError> result;
  348. for (auto& entry : externs) {
  349. entry.visit(
  350. [&](FunctionAddress const& address) { module_instance.functions().append(address); },
  351. [&](TableAddress const& address) { module_instance.tables().append(address); },
  352. [&](MemoryAddress const& address) { module_instance.memories().append(address); },
  353. [&](GlobalAddress const& address) { module_instance.globals().append(address); });
  354. }
  355. module_instance.functions().extend(own_functions);
  356. // FIXME: What if this fails?
  357. for (auto& table : module.table_section().tables()) {
  358. auto table_address = m_store.allocate(table.type());
  359. VERIFY(table_address.has_value());
  360. module_instance.tables().append(*table_address);
  361. }
  362. for (auto& memory : module.memory_section().memories()) {
  363. auto memory_address = m_store.allocate(memory.type());
  364. VERIFY(memory_address.has_value());
  365. module_instance.memories().append(*memory_address);
  366. }
  367. size_t index = 0;
  368. for (auto& entry : module.global_section().entries()) {
  369. auto address = m_store.allocate(entry.type(), move(global_values[index]));
  370. VERIFY(address.has_value());
  371. module_instance.globals().append(*address);
  372. index++;
  373. }
  374. for (auto& entry : module.export_section().entries()) {
  375. Variant<FunctionAddress, TableAddress, MemoryAddress, GlobalAddress, Empty> address {};
  376. entry.description().visit(
  377. [&](FunctionIndex const& index) {
  378. if (module_instance.functions().size() > index.value())
  379. address = FunctionAddress { module_instance.functions()[index.value()] };
  380. else
  381. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.functions().size());
  382. },
  383. [&](TableIndex const& index) {
  384. if (module_instance.tables().size() > index.value())
  385. address = TableAddress { module_instance.tables()[index.value()] };
  386. else
  387. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.tables().size());
  388. },
  389. [&](MemoryIndex const& index) {
  390. if (module_instance.memories().size() > index.value())
  391. address = MemoryAddress { module_instance.memories()[index.value()] };
  392. else
  393. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.memories().size());
  394. },
  395. [&](GlobalIndex const& index) {
  396. if (module_instance.globals().size() > index.value())
  397. address = GlobalAddress { module_instance.globals()[index.value()] };
  398. else
  399. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.globals().size());
  400. });
  401. if (address.has<Empty>()) {
  402. result = InstantiationError { "An export could not be resolved" };
  403. continue;
  404. }
  405. module_instance.exports().append(ExportInstance {
  406. entry.name(),
  407. move(address).downcast<FunctionAddress, TableAddress, MemoryAddress, GlobalAddress>(),
  408. });
  409. }
  410. return result;
  411. }
  412. Optional<InstantiationError> AbstractMachine::allocate_all_final_phase(Module const& module, ModuleInstance& module_instance, Vector<Vector<Reference>>& elements)
  413. {
  414. size_t index = 0;
  415. for (auto& segment : module.element_section().segments()) {
  416. auto address = m_store.allocate(segment.type, move(elements[index]));
  417. VERIFY(address.has_value());
  418. module_instance.elements().append(*address);
  419. index++;
  420. }
  421. return {};
  422. }
  423. Result AbstractMachine::invoke(FunctionAddress address, Vector<Value> arguments)
  424. {
  425. BytecodeInterpreter interpreter(m_stack_info);
  426. return invoke(interpreter, address, move(arguments));
  427. }
  428. Result AbstractMachine::invoke(Interpreter& interpreter, FunctionAddress address, Vector<Value> arguments)
  429. {
  430. Configuration configuration { m_store };
  431. if (m_should_limit_instruction_count)
  432. configuration.enable_instruction_count_limit();
  433. return configuration.call(interpreter, address, move(arguments));
  434. }
  435. void Linker::link(ModuleInstance const& instance)
  436. {
  437. populate();
  438. if (m_unresolved_imports.is_empty())
  439. return;
  440. HashTable<Name> resolved_imports;
  441. for (auto& import_ : m_unresolved_imports) {
  442. auto it = instance.exports().find_if([&](auto& export_) { return export_.name() == import_.name; });
  443. if (!it.is_end()) {
  444. resolved_imports.set(import_);
  445. m_resolved_imports.set(import_, it->value());
  446. }
  447. }
  448. for (auto& entry : resolved_imports)
  449. m_unresolved_imports.remove(entry);
  450. }
  451. void Linker::link(HashMap<Linker::Name, ExternValue> const& exports)
  452. {
  453. populate();
  454. if (m_unresolved_imports.is_empty())
  455. return;
  456. if (exports.is_empty())
  457. return;
  458. HashTable<Name> resolved_imports;
  459. for (auto& import_ : m_unresolved_imports) {
  460. auto export_ = exports.get(import_);
  461. if (export_.has_value()) {
  462. resolved_imports.set(import_);
  463. m_resolved_imports.set(import_, export_.value());
  464. }
  465. }
  466. for (auto& entry : resolved_imports)
  467. m_unresolved_imports.remove(entry);
  468. }
  469. AK::ErrorOr<Vector<ExternValue>, LinkError> Linker::finish()
  470. {
  471. populate();
  472. if (!m_unresolved_imports.is_empty()) {
  473. if (!m_error.has_value())
  474. m_error = LinkError {};
  475. for (auto& entry : m_unresolved_imports)
  476. m_error->missing_imports.append(entry.name);
  477. return *m_error;
  478. }
  479. if (m_error.has_value())
  480. return *m_error;
  481. // Result must be in the same order as the module imports
  482. Vector<ExternValue> exports;
  483. exports.ensure_capacity(m_ordered_imports.size());
  484. for (auto& import_ : m_ordered_imports)
  485. exports.unchecked_append(*m_resolved_imports.get(import_));
  486. return exports;
  487. }
  488. void Linker::populate()
  489. {
  490. if (!m_ordered_imports.is_empty())
  491. return;
  492. for (auto& import_ : m_module.import_section().imports()) {
  493. m_ordered_imports.append({ import_.module(), import_.name(), import_.description() });
  494. m_unresolved_imports.set(m_ordered_imports.last());
  495. }
  496. }
  497. }