AbstractMachine.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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<Optional<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 { DeprecatedString::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. for (auto& func : module.functions()) {
  138. auto address = m_store.allocate(main_module_instance, func);
  139. VERIFY(address.has_value());
  140. auxiliary_instance.functions().append(*address);
  141. main_module_instance.functions().append(*address);
  142. }
  143. BytecodeInterpreter interpreter(m_stack_info);
  144. module.for_each_section_of_type<GlobalSection>([&](auto& global_section) {
  145. for (auto& entry : global_section.entries()) {
  146. Configuration config { m_store };
  147. if (m_should_limit_instruction_count)
  148. config.enable_instruction_count_limit();
  149. config.set_frame(Frame {
  150. auxiliary_instance,
  151. Vector<Value> {},
  152. entry.expression(),
  153. 1,
  154. });
  155. auto result = config.execute(interpreter).assert_wasm_result();
  156. if (result.is_trap())
  157. instantiation_result = InstantiationError { DeprecatedString::formatted("Global value construction trapped: {}", result.trap().reason) };
  158. else
  159. global_values.append(result.values().first());
  160. }
  161. });
  162. if (instantiation_result.has_value())
  163. return instantiation_result.release_value();
  164. if (auto result = allocate_all_initial_phase(module, main_module_instance, externs, global_values); result.has_value())
  165. return result.release_value();
  166. module.for_each_section_of_type<ElementSection>([&](ElementSection const& section) {
  167. for (auto& segment : section.segments()) {
  168. Vector<Reference> references;
  169. for (auto& entry : segment.init) {
  170. Configuration config { m_store };
  171. if (m_should_limit_instruction_count)
  172. config.enable_instruction_count_limit();
  173. config.set_frame(Frame {
  174. main_module_instance,
  175. Vector<Value> {},
  176. entry,
  177. entry.instructions().size(),
  178. });
  179. auto result = config.execute(interpreter).assert_wasm_result();
  180. if (result.is_trap()) {
  181. instantiation_result = InstantiationError { DeprecatedString::formatted("Element construction trapped: {}", result.trap().reason) };
  182. return IterationDecision::Continue;
  183. }
  184. for (auto& value : result.values()) {
  185. if (!value.type().is_reference()) {
  186. instantiation_result = InstantiationError { "Evaluated element entry is not a reference" };
  187. return IterationDecision::Continue;
  188. }
  189. auto reference = value.to<Reference>();
  190. if (!reference.has_value()) {
  191. instantiation_result = InstantiationError { "Evaluated element entry does not contain a reference" };
  192. return IterationDecision::Continue;
  193. }
  194. // FIXME: type-check the reference.
  195. references.prepend(reference.release_value());
  196. }
  197. }
  198. elements.append(move(references));
  199. }
  200. return IterationDecision::Continue;
  201. });
  202. if (instantiation_result.has_value())
  203. return instantiation_result.release_value();
  204. if (auto result = allocate_all_final_phase(module, main_module_instance, elements); result.has_value())
  205. return result.release_value();
  206. module.for_each_section_of_type<ElementSection>([&](ElementSection const& section) {
  207. size_t index = 0;
  208. for (auto& segment : section.segments()) {
  209. auto current_index = index;
  210. ++index;
  211. auto active_ptr = segment.mode.get_pointer<ElementSection::Active>();
  212. if (!active_ptr)
  213. continue;
  214. if (active_ptr->index.value() != 0) {
  215. instantiation_result = InstantiationError { "Non-zero table referenced by active element segment" };
  216. return IterationDecision::Break;
  217. }
  218. Configuration config { m_store };
  219. if (m_should_limit_instruction_count)
  220. config.enable_instruction_count_limit();
  221. config.set_frame(Frame {
  222. main_module_instance,
  223. Vector<Value> {},
  224. active_ptr->expression,
  225. 1,
  226. });
  227. auto result = config.execute(interpreter).assert_wasm_result();
  228. if (result.is_trap()) {
  229. instantiation_result = InstantiationError { DeprecatedString::formatted("Element section initialisation trapped: {}", result.trap().reason) };
  230. return IterationDecision::Break;
  231. }
  232. auto d = result.values().first().to<i32>();
  233. if (!d.has_value()) {
  234. instantiation_result = InstantiationError { "Element section initialisation returned invalid table initial offset" };
  235. return IterationDecision::Break;
  236. }
  237. if (main_module_instance.tables().size() < 1) {
  238. instantiation_result = InstantiationError { "Element section initialisation references nonexistent table" };
  239. return IterationDecision::Break;
  240. }
  241. auto table_instance = m_store.get(main_module_instance.tables()[0]);
  242. if (current_index >= main_module_instance.elements().size()) {
  243. instantiation_result = InstantiationError { "Invalid element referenced by active element segment" };
  244. return IterationDecision::Break;
  245. }
  246. auto elem_instance = m_store.get(main_module_instance.elements()[current_index]);
  247. if (!table_instance || !elem_instance) {
  248. instantiation_result = InstantiationError { "Invalid element referenced by active element segment" };
  249. return IterationDecision::Break;
  250. }
  251. auto total_required_size = elem_instance->references().size() + d.value();
  252. if (table_instance->type().limits().max().value_or(total_required_size) < total_required_size) {
  253. instantiation_result = InstantiationError { "Table limit overflow in active element segment" };
  254. return IterationDecision::Break;
  255. }
  256. if (table_instance->elements().size() < total_required_size)
  257. table_instance->elements().resize(total_required_size);
  258. size_t i = 0;
  259. for (auto it = elem_instance->references().begin(); it < elem_instance->references().end(); ++i, ++it) {
  260. table_instance->elements()[i + d.value()] = *it;
  261. }
  262. }
  263. return IterationDecision::Continue;
  264. });
  265. if (instantiation_result.has_value())
  266. return instantiation_result.release_value();
  267. module.for_each_section_of_type<DataSection>([&](DataSection const& data_section) {
  268. for (auto& segment : data_section.data()) {
  269. segment.value().visit(
  270. [&](DataSection::Data::Active const& data) {
  271. Configuration config { m_store };
  272. if (m_should_limit_instruction_count)
  273. config.enable_instruction_count_limit();
  274. config.set_frame(Frame {
  275. main_module_instance,
  276. Vector<Value> {},
  277. data.offset,
  278. 1,
  279. });
  280. auto result = config.execute(interpreter).assert_wasm_result();
  281. if (result.is_trap()) {
  282. instantiation_result = InstantiationError { DeprecatedString::formatted("Data section initialisation trapped: {}", result.trap().reason) };
  283. return;
  284. }
  285. size_t offset = 0;
  286. result.values().first().value().visit(
  287. [&](auto const& value) { offset = value; },
  288. [&](Reference const&) { instantiation_result = InstantiationError { "Data segment offset returned a reference"sv }; });
  289. if (instantiation_result.has_value() && instantiation_result->is_error())
  290. return;
  291. if (main_module_instance.memories().size() <= data.index.value()) {
  292. instantiation_result = InstantiationError {
  293. DeprecatedString::formatted("Data segment referenced out-of-bounds memory ({}) of max {} entries",
  294. data.index.value(), main_module_instance.memories().size())
  295. };
  296. return;
  297. }
  298. auto maybe_data_address = m_store.allocate_data(data.init);
  299. if (!maybe_data_address.has_value()) {
  300. instantiation_result = InstantiationError { "Failed to allocate a data instance for an active data segment"sv };
  301. return;
  302. }
  303. main_module_instance.datas().append(*maybe_data_address);
  304. if (data.init.is_empty())
  305. return;
  306. auto address = main_module_instance.memories()[data.index.value()];
  307. if (auto instance = m_store.get(address)) {
  308. if (auto max = instance->type().limits().max(); max.has_value()) {
  309. if (*max * Constants::page_size < data.init.size() + offset) {
  310. instantiation_result = InstantiationError {
  311. DeprecatedString::formatted("Data segment attempted to write to out-of-bounds memory ({}) of max {} bytes",
  312. data.init.size() + offset, instance->type().limits().max().value())
  313. };
  314. return;
  315. }
  316. }
  317. if (instance->size() < data.init.size() + offset)
  318. instance->grow(data.init.size() + offset - instance->size());
  319. instance->data().overwrite(offset, data.init.data(), data.init.size());
  320. }
  321. },
  322. [&](DataSection::Data::Passive const& passive) {
  323. auto maybe_data_address = m_store.allocate_data(passive.init);
  324. if (!maybe_data_address.has_value()) {
  325. instantiation_result = InstantiationError { "Failed to allocate a data instance for a passive data segment"sv };
  326. return;
  327. }
  328. main_module_instance.datas().append(*maybe_data_address);
  329. });
  330. }
  331. });
  332. module.for_each_section_of_type<StartSection>([&](StartSection const& section) {
  333. auto& functions = main_module_instance.functions();
  334. auto index = section.function().index();
  335. if (functions.size() <= index.value()) {
  336. instantiation_result = InstantiationError { DeprecatedString::formatted("Start section function referenced invalid index {} of max {} entries", index.value(), functions.size()) };
  337. return;
  338. }
  339. invoke(functions[index.value()], {});
  340. });
  341. if (instantiation_result.has_value())
  342. return instantiation_result.release_value();
  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)
  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. // FIXME: What if this fails?
  356. module.for_each_section_of_type<TableSection>([&](TableSection const& section) {
  357. for (auto& 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. });
  363. module.for_each_section_of_type<MemorySection>([&](MemorySection const& section) {
  364. for (auto& memory : section.memories()) {
  365. auto memory_address = m_store.allocate(memory.type());
  366. VERIFY(memory_address.has_value());
  367. module_instance.memories().append(*memory_address);
  368. }
  369. });
  370. module.for_each_section_of_type<GlobalSection>([&](GlobalSection const& section) {
  371. size_t index = 0;
  372. for (auto& entry : section.entries()) {
  373. auto address = m_store.allocate(entry.type(), move(global_values[index]));
  374. VERIFY(address.has_value());
  375. module_instance.globals().append(*address);
  376. index++;
  377. }
  378. });
  379. module.for_each_section_of_type<ExportSection>([&](ExportSection const& section) {
  380. for (auto& entry : section.entries()) {
  381. Variant<FunctionAddress, TableAddress, MemoryAddress, GlobalAddress, Empty> address {};
  382. entry.description().visit(
  383. [&](FunctionIndex const& index) {
  384. if (module_instance.functions().size() > index.value())
  385. address = FunctionAddress { module_instance.functions()[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.functions().size());
  388. },
  389. [&](TableIndex const& index) {
  390. if (module_instance.tables().size() > index.value())
  391. address = TableAddress { module_instance.tables()[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.tables().size());
  394. },
  395. [&](MemoryIndex const& index) {
  396. if (module_instance.memories().size() > index.value())
  397. address = MemoryAddress { module_instance.memories()[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.memories().size());
  400. },
  401. [&](GlobalIndex const& index) {
  402. if (module_instance.globals().size() > index.value())
  403. address = GlobalAddress { module_instance.globals()[index.value()] };
  404. else
  405. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.globals().size());
  406. });
  407. if (address.has<Empty>()) {
  408. result = InstantiationError { "An export could not be resolved" };
  409. continue;
  410. }
  411. module_instance.exports().append(ExportInstance {
  412. entry.name(),
  413. move(address).downcast<FunctionAddress, TableAddress, MemoryAddress, GlobalAddress>(),
  414. });
  415. }
  416. });
  417. return result;
  418. }
  419. Optional<InstantiationError> AbstractMachine::allocate_all_final_phase(Module const& module, ModuleInstance& module_instance, Vector<Vector<Reference>>& elements)
  420. {
  421. module.for_each_section_of_type<ElementSection>([&](ElementSection const& section) {
  422. size_t index = 0;
  423. for (auto& segment : section.segments()) {
  424. auto address = m_store.allocate(segment.type, move(elements[index]));
  425. VERIFY(address.has_value());
  426. module_instance.elements().append(*address);
  427. index++;
  428. }
  429. });
  430. return {};
  431. }
  432. Result AbstractMachine::invoke(FunctionAddress address, Vector<Value> arguments)
  433. {
  434. BytecodeInterpreter interpreter(m_stack_info);
  435. return invoke(interpreter, address, move(arguments));
  436. }
  437. Result AbstractMachine::invoke(Interpreter& interpreter, FunctionAddress address, Vector<Value> arguments)
  438. {
  439. Configuration configuration { m_store };
  440. if (m_should_limit_instruction_count)
  441. configuration.enable_instruction_count_limit();
  442. return configuration.call(interpreter, address, move(arguments));
  443. }
  444. void Linker::link(ModuleInstance const& instance)
  445. {
  446. populate();
  447. if (m_unresolved_imports.is_empty())
  448. return;
  449. HashTable<Name> resolved_imports;
  450. for (auto& import_ : m_unresolved_imports) {
  451. auto it = instance.exports().find_if([&](auto& export_) { return export_.name() == import_.name; });
  452. if (!it.is_end()) {
  453. resolved_imports.set(import_);
  454. m_resolved_imports.set(import_, it->value());
  455. }
  456. }
  457. for (auto& entry : resolved_imports)
  458. m_unresolved_imports.remove(entry);
  459. }
  460. void Linker::link(HashMap<Linker::Name, ExternValue> const& exports)
  461. {
  462. populate();
  463. if (m_unresolved_imports.is_empty())
  464. return;
  465. if (exports.is_empty())
  466. return;
  467. HashTable<Name> resolved_imports;
  468. for (auto& import_ : m_unresolved_imports) {
  469. auto export_ = exports.get(import_);
  470. if (export_.has_value()) {
  471. resolved_imports.set(import_);
  472. m_resolved_imports.set(import_, export_.value());
  473. }
  474. }
  475. for (auto& entry : resolved_imports)
  476. m_unresolved_imports.remove(entry);
  477. }
  478. AK::Result<Vector<ExternValue>, LinkError> Linker::finish()
  479. {
  480. populate();
  481. if (!m_unresolved_imports.is_empty()) {
  482. if (!m_error.has_value())
  483. m_error = LinkError {};
  484. for (auto& entry : m_unresolved_imports)
  485. m_error->missing_imports.append(entry.name);
  486. return *m_error;
  487. }
  488. if (m_error.has_value())
  489. return *m_error;
  490. // Result must be in the same order as the module imports
  491. Vector<ExternValue> exports;
  492. exports.ensure_capacity(m_ordered_imports.size());
  493. for (auto& import_ : m_ordered_imports)
  494. exports.unchecked_append(*m_resolved_imports.get(import_));
  495. return exports;
  496. }
  497. void Linker::populate()
  498. {
  499. if (!m_ordered_imports.is_empty())
  500. return;
  501. // There better be at most one import section!
  502. bool already_seen_an_import_section = false;
  503. m_module.for_each_section_of_type<ImportSection>([&](ImportSection const& section) {
  504. if (already_seen_an_import_section) {
  505. if (!m_error.has_value())
  506. m_error = LinkError {};
  507. m_error->other_errors.append(LinkError::InvalidImportedModule);
  508. return;
  509. }
  510. already_seen_an_import_section = true;
  511. for (auto& import_ : section.imports()) {
  512. m_ordered_imports.append({ import_.module(), import_.name(), import_.description() });
  513. m_unresolved_imports.set(m_ordered_imports.last());
  514. }
  515. });
  516. }
  517. }