AbstractMachine.cpp 23 KB

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