AbstractMachine.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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. auto total_required_size = elem_instance->references().size() + d.value();
  246. if (table_instance->type().limits().max().value_or(total_required_size) < total_required_size) {
  247. instantiation_result = InstantiationError { "Table limit overflow in active element segment" };
  248. return IterationDecision::Break;
  249. }
  250. if (table_instance->elements().size() < total_required_size)
  251. table_instance->elements().resize(total_required_size);
  252. size_t i = 0;
  253. for (auto it = elem_instance->references().begin(); it < elem_instance->references().end(); ++i, ++it) {
  254. table_instance->elements()[i + d.value()] = *it;
  255. }
  256. }
  257. return IterationDecision::Continue;
  258. });
  259. if (instantiation_result.has_value())
  260. return instantiation_result.release_value();
  261. module.for_each_section_of_type<DataSection>([&](DataSection const& data_section) {
  262. for (auto& segment : data_section.data()) {
  263. segment.value().visit(
  264. [&](DataSection::Data::Active const& data) {
  265. Configuration config { m_store };
  266. if (m_should_limit_instruction_count)
  267. config.enable_instruction_count_limit();
  268. config.set_frame(Frame {
  269. main_module_instance,
  270. Vector<Value> {},
  271. data.offset,
  272. 1,
  273. });
  274. auto result = config.execute(interpreter).assert_wasm_result();
  275. if (result.is_trap()) {
  276. instantiation_result = InstantiationError { ByteString::formatted("Data section initialisation trapped: {}", result.trap().reason) };
  277. return;
  278. }
  279. size_t offset = 0;
  280. result.values().first().value().visit(
  281. [&](auto const& value) { offset = value; },
  282. [&](u128 const&) { instantiation_result = InstantiationError { "Data segment offset returned a vector type"sv }; },
  283. [&](Reference const&) { instantiation_result = InstantiationError { "Data segment offset returned a reference"sv }; });
  284. if (instantiation_result.has_value() && instantiation_result->is_error())
  285. return;
  286. if (main_module_instance.memories().size() <= data.index.value()) {
  287. instantiation_result = InstantiationError {
  288. ByteString::formatted("Data segment referenced out-of-bounds memory ({}) of max {} entries",
  289. data.index.value(), main_module_instance.memories().size())
  290. };
  291. return;
  292. }
  293. auto maybe_data_address = m_store.allocate_data(data.init);
  294. if (!maybe_data_address.has_value()) {
  295. instantiation_result = InstantiationError { "Failed to allocate a data instance for an active data segment"sv };
  296. return;
  297. }
  298. main_module_instance.datas().append(*maybe_data_address);
  299. if (data.init.is_empty())
  300. return;
  301. auto address = main_module_instance.memories()[data.index.value()];
  302. if (auto instance = m_store.get(address)) {
  303. if (auto max = instance->type().limits().max(); max.has_value()) {
  304. if (*max * Constants::page_size < data.init.size() + offset) {
  305. instantiation_result = InstantiationError {
  306. ByteString::formatted("Data segment attempted to write to out-of-bounds memory ({}) of max {} bytes",
  307. data.init.size() + offset, instance->type().limits().max().value())
  308. };
  309. return;
  310. }
  311. }
  312. if (instance->size() < data.init.size() + offset)
  313. instance->grow(data.init.size() + offset - instance->size());
  314. instance->data().overwrite(offset, data.init.data(), data.init.size());
  315. }
  316. },
  317. [&](DataSection::Data::Passive const& passive) {
  318. auto maybe_data_address = m_store.allocate_data(passive.init);
  319. if (!maybe_data_address.has_value()) {
  320. instantiation_result = InstantiationError { "Failed to allocate a data instance for a passive data segment"sv };
  321. return;
  322. }
  323. main_module_instance.datas().append(*maybe_data_address);
  324. });
  325. }
  326. });
  327. module.for_each_section_of_type<StartSection>([&](StartSection const& section) {
  328. auto& functions = main_module_instance.functions();
  329. auto index = section.function().index();
  330. if (functions.size() <= index.value()) {
  331. instantiation_result = InstantiationError { ByteString::formatted("Start section function referenced invalid index {} of max {} entries", index.value(), functions.size()) };
  332. return;
  333. }
  334. invoke(functions[index.value()], {});
  335. });
  336. if (instantiation_result.has_value())
  337. return instantiation_result.release_value();
  338. return InstantiationResult { move(main_module_instance_pointer) };
  339. }
  340. Optional<InstantiationError> AbstractMachine::allocate_all_initial_phase(Module const& module, ModuleInstance& module_instance, Vector<ExternValue>& externs, Vector<Value>& global_values, Vector<FunctionAddress>& own_functions)
  341. {
  342. Optional<InstantiationError> result;
  343. for (auto& entry : externs) {
  344. entry.visit(
  345. [&](FunctionAddress const& address) { module_instance.functions().append(address); },
  346. [&](TableAddress const& address) { module_instance.tables().append(address); },
  347. [&](MemoryAddress const& address) { module_instance.memories().append(address); },
  348. [&](GlobalAddress const& address) { module_instance.globals().append(address); });
  349. }
  350. module_instance.functions().extend(own_functions);
  351. // FIXME: What if this fails?
  352. module.for_each_section_of_type<TableSection>([&](TableSection const& section) {
  353. for (auto& table : section.tables()) {
  354. auto table_address = m_store.allocate(table.type());
  355. VERIFY(table_address.has_value());
  356. module_instance.tables().append(*table_address);
  357. }
  358. });
  359. module.for_each_section_of_type<MemorySection>([&](MemorySection const& section) {
  360. for (auto& memory : section.memories()) {
  361. auto memory_address = m_store.allocate(memory.type());
  362. VERIFY(memory_address.has_value());
  363. module_instance.memories().append(*memory_address);
  364. }
  365. });
  366. module.for_each_section_of_type<GlobalSection>([&](GlobalSection const& section) {
  367. size_t index = 0;
  368. for (auto& entry : 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. });
  375. module.for_each_section_of_type<ExportSection>([&](ExportSection const& section) {
  376. for (auto& entry : section.entries()) {
  377. Variant<FunctionAddress, TableAddress, MemoryAddress, GlobalAddress, Empty> address {};
  378. entry.description().visit(
  379. [&](FunctionIndex const& index) {
  380. if (module_instance.functions().size() > index.value())
  381. address = FunctionAddress { module_instance.functions()[index.value()] };
  382. else
  383. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.functions().size());
  384. },
  385. [&](TableIndex const& index) {
  386. if (module_instance.tables().size() > index.value())
  387. address = TableAddress { module_instance.tables()[index.value()] };
  388. else
  389. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.tables().size());
  390. },
  391. [&](MemoryIndex const& index) {
  392. if (module_instance.memories().size() > index.value())
  393. address = MemoryAddress { module_instance.memories()[index.value()] };
  394. else
  395. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.memories().size());
  396. },
  397. [&](GlobalIndex const& index) {
  398. if (module_instance.globals().size() > index.value())
  399. address = GlobalAddress { module_instance.globals()[index.value()] };
  400. else
  401. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.globals().size());
  402. });
  403. if (address.has<Empty>()) {
  404. result = InstantiationError { "An export could not be resolved" };
  405. continue;
  406. }
  407. module_instance.exports().append(ExportInstance {
  408. entry.name(),
  409. move(address).downcast<FunctionAddress, TableAddress, MemoryAddress, GlobalAddress>(),
  410. });
  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. module.for_each_section_of_type<ElementSection>([&](ElementSection const& section) {
  418. size_t index = 0;
  419. for (auto& segment : section.segments()) {
  420. auto address = m_store.allocate(segment.type, move(elements[index]));
  421. VERIFY(address.has_value());
  422. module_instance.elements().append(*address);
  423. index++;
  424. }
  425. });
  426. return {};
  427. }
  428. Result AbstractMachine::invoke(FunctionAddress address, Vector<Value> arguments)
  429. {
  430. BytecodeInterpreter interpreter(m_stack_info);
  431. return invoke(interpreter, address, move(arguments));
  432. }
  433. Result AbstractMachine::invoke(Interpreter& interpreter, FunctionAddress address, Vector<Value> arguments)
  434. {
  435. Configuration configuration { m_store };
  436. if (m_should_limit_instruction_count)
  437. configuration.enable_instruction_count_limit();
  438. return configuration.call(interpreter, address, move(arguments));
  439. }
  440. void Linker::link(ModuleInstance const& instance)
  441. {
  442. populate();
  443. if (m_unresolved_imports.is_empty())
  444. return;
  445. HashTable<Name> resolved_imports;
  446. for (auto& import_ : m_unresolved_imports) {
  447. auto it = instance.exports().find_if([&](auto& export_) { return export_.name() == import_.name; });
  448. if (!it.is_end()) {
  449. resolved_imports.set(import_);
  450. m_resolved_imports.set(import_, it->value());
  451. }
  452. }
  453. for (auto& entry : resolved_imports)
  454. m_unresolved_imports.remove(entry);
  455. }
  456. void Linker::link(HashMap<Linker::Name, ExternValue> const& exports)
  457. {
  458. populate();
  459. if (m_unresolved_imports.is_empty())
  460. return;
  461. if (exports.is_empty())
  462. return;
  463. HashTable<Name> resolved_imports;
  464. for (auto& import_ : m_unresolved_imports) {
  465. auto export_ = exports.get(import_);
  466. if (export_.has_value()) {
  467. resolved_imports.set(import_);
  468. m_resolved_imports.set(import_, export_.value());
  469. }
  470. }
  471. for (auto& entry : resolved_imports)
  472. m_unresolved_imports.remove(entry);
  473. }
  474. AK::ErrorOr<Vector<ExternValue>, LinkError> Linker::finish()
  475. {
  476. populate();
  477. if (!m_unresolved_imports.is_empty()) {
  478. if (!m_error.has_value())
  479. m_error = LinkError {};
  480. for (auto& entry : m_unresolved_imports)
  481. m_error->missing_imports.append(entry.name);
  482. return *m_error;
  483. }
  484. if (m_error.has_value())
  485. return *m_error;
  486. // Result must be in the same order as the module imports
  487. Vector<ExternValue> exports;
  488. exports.ensure_capacity(m_ordered_imports.size());
  489. for (auto& import_ : m_ordered_imports)
  490. exports.unchecked_append(*m_resolved_imports.get(import_));
  491. return exports;
  492. }
  493. void Linker::populate()
  494. {
  495. if (!m_ordered_imports.is_empty())
  496. return;
  497. // There better be at most one import section!
  498. bool already_seen_an_import_section = false;
  499. m_module.for_each_section_of_type<ImportSection>([&](ImportSection const& section) {
  500. if (already_seen_an_import_section) {
  501. if (!m_error.has_value())
  502. m_error = LinkError {};
  503. m_error->other_errors.append(LinkError::InvalidImportedModule);
  504. return;
  505. }
  506. already_seen_an_import_section = true;
  507. for (auto& import_ : section.imports()) {
  508. m_ordered_imports.append({ import_.module(), import_.name(), import_.description() });
  509. m_unresolved_imports.set(m_ordered_imports.last());
  510. }
  511. });
  512. }
  513. }