AbstractMachine.cpp 23 KB

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