AbstractMachine.cpp 24 KB

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