AbstractMachine.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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. m_memories.empend(MemoryInstance { type });
  40. return address;
  41. }
  42. Optional<GlobalAddress> Store::allocate(GlobalType const& type, Value value)
  43. {
  44. GlobalAddress address { m_globals.size() };
  45. m_globals.append(GlobalInstance { move(value), type.is_mutable() });
  46. return address;
  47. }
  48. Optional<DataAddress> Store::allocate_data(Vector<u8> initializer)
  49. {
  50. DataAddress address { m_datas.size() };
  51. m_datas.append(DataInstance { move(initializer) });
  52. return address;
  53. }
  54. Optional<ElementAddress> Store::allocate(ValueType const& type, Vector<Reference> references)
  55. {
  56. ElementAddress address { m_elements.size() };
  57. m_elements.append(ElementInstance { type, move(references) });
  58. return address;
  59. }
  60. FunctionInstance* Store::get(FunctionAddress address)
  61. {
  62. auto value = address.value();
  63. if (m_functions.size() <= value)
  64. return nullptr;
  65. return &m_functions[value];
  66. }
  67. TableInstance* Store::get(TableAddress address)
  68. {
  69. auto value = address.value();
  70. if (m_tables.size() <= value)
  71. return nullptr;
  72. return &m_tables[value];
  73. }
  74. MemoryInstance* Store::get(MemoryAddress address)
  75. {
  76. auto value = address.value();
  77. if (m_memories.size() <= value)
  78. return nullptr;
  79. return &m_memories[value];
  80. }
  81. GlobalInstance* Store::get(GlobalAddress address)
  82. {
  83. auto value = address.value();
  84. if (m_globals.size() <= value)
  85. return nullptr;
  86. return &m_globals[value];
  87. }
  88. ElementInstance* Store::get(ElementAddress address)
  89. {
  90. auto value = address.value();
  91. if (m_elements.size() <= value)
  92. return nullptr;
  93. return &m_elements[value];
  94. }
  95. DataInstance* Store::get(DataAddress address)
  96. {
  97. auto value = address.value();
  98. if (m_datas.size() <= value)
  99. return nullptr;
  100. return &m_datas[value];
  101. }
  102. ErrorOr<void, ValidationError> AbstractMachine::validate(Module& module)
  103. {
  104. if (module.validation_status() != Module::ValidationStatus::Unchecked) {
  105. if (module.validation_status() == Module::ValidationStatus::Valid)
  106. return {};
  107. return ValidationError { module.validation_error() };
  108. }
  109. auto result = Validator {}.validate(module);
  110. if (result.is_error()) {
  111. module.set_validation_error(result.error().error_string);
  112. return result.release_error();
  113. }
  114. return {};
  115. }
  116. InstantiationResult AbstractMachine::instantiate(Module const& module, Vector<ExternValue> externs)
  117. {
  118. if (auto result = validate(const_cast<Module&>(module)); result.is_error())
  119. return InstantiationError { String::formatted("Validation failed: {}", result.error()) };
  120. auto main_module_instance_pointer = make<ModuleInstance>();
  121. auto& main_module_instance = *main_module_instance_pointer;
  122. Optional<InstantiationResult> instantiation_result;
  123. module.for_each_section_of_type<TypeSection>([&](TypeSection const& section) {
  124. main_module_instance.types() = section.types();
  125. });
  126. Vector<Value> global_values;
  127. Vector<Vector<Reference>> elements;
  128. ModuleInstance auxiliary_instance;
  129. // FIXME: Check that imports/extern match
  130. for (auto& entry : externs) {
  131. if (auto* ptr = entry.get_pointer<GlobalAddress>())
  132. auxiliary_instance.globals().append(*ptr);
  133. }
  134. BytecodeInterpreter interpreter;
  135. module.for_each_section_of_type<GlobalSection>([&](auto& global_section) {
  136. for (auto& entry : global_section.entries()) {
  137. Configuration config { m_store };
  138. if (m_should_limit_instruction_count)
  139. config.enable_instruction_count_limit();
  140. config.set_frame(Frame {
  141. auxiliary_instance,
  142. Vector<Value> {},
  143. entry.expression(),
  144. 1,
  145. });
  146. auto result = config.execute(interpreter);
  147. if (result.is_trap())
  148. instantiation_result = InstantiationError { String::formatted("Global value construction trapped: {}", result.trap().reason) };
  149. else
  150. global_values.append(result.values().first());
  151. }
  152. });
  153. if (instantiation_result.has_value())
  154. return instantiation_result.release_value();
  155. if (auto result = allocate_all_initial_phase(module, main_module_instance, externs, global_values); result.has_value())
  156. return result.release_value();
  157. module.for_each_section_of_type<ElementSection>([&](ElementSection const& section) {
  158. for (auto& segment : section.segments()) {
  159. Vector<Reference> references;
  160. for (auto& entry : segment.init) {
  161. Configuration config { m_store };
  162. if (m_should_limit_instruction_count)
  163. config.enable_instruction_count_limit();
  164. config.set_frame(Frame {
  165. main_module_instance,
  166. Vector<Value> {},
  167. entry,
  168. entry.instructions().size(),
  169. });
  170. auto result = config.execute(interpreter);
  171. if (result.is_trap()) {
  172. instantiation_result = InstantiationError { String::formatted("Element construction trapped: {}", result.trap().reason) };
  173. return IterationDecision::Continue;
  174. }
  175. for (auto& value : result.values()) {
  176. if (!value.type().is_reference()) {
  177. instantiation_result = InstantiationError { "Evaluated element entry is not a reference" };
  178. return IterationDecision::Continue;
  179. }
  180. auto reference = value.to<Reference>();
  181. if (!reference.has_value()) {
  182. instantiation_result = InstantiationError { "Evaluated element entry does not contain a reference" };
  183. return IterationDecision::Continue;
  184. }
  185. // FIXME: type-check the reference.
  186. references.prepend(reference.release_value());
  187. }
  188. }
  189. elements.append(move(references));
  190. }
  191. return IterationDecision::Continue;
  192. });
  193. if (instantiation_result.has_value())
  194. return instantiation_result.release_value();
  195. if (auto result = allocate_all_final_phase(module, main_module_instance, elements); result.has_value())
  196. return result.release_value();
  197. module.for_each_section_of_type<ElementSection>([&](ElementSection const& section) {
  198. size_t index = 0;
  199. for (auto& segment : section.segments()) {
  200. auto current_index = index;
  201. ++index;
  202. auto active_ptr = segment.mode.get_pointer<ElementSection::Active>();
  203. if (!active_ptr)
  204. continue;
  205. if (active_ptr->index.value() != 0) {
  206. instantiation_result = InstantiationError { "Non-zero table referenced by active element segment" };
  207. return IterationDecision::Break;
  208. }
  209. Configuration config { m_store };
  210. if (m_should_limit_instruction_count)
  211. config.enable_instruction_count_limit();
  212. config.set_frame(Frame {
  213. main_module_instance,
  214. Vector<Value> {},
  215. active_ptr->expression,
  216. 1,
  217. });
  218. auto result = config.execute(interpreter);
  219. if (result.is_trap()) {
  220. instantiation_result = InstantiationError { String::formatted("Element section initialisation trapped: {}", result.trap().reason) };
  221. return IterationDecision::Break;
  222. }
  223. auto d = result.values().first().to<i32>();
  224. if (!d.has_value()) {
  225. instantiation_result = InstantiationError { "Element section initialisation returned invalid table initial offset" };
  226. return IterationDecision::Break;
  227. }
  228. if (main_module_instance.tables().size() < 1) {
  229. instantiation_result = InstantiationError { "Element section initialisation references nonexistent table" };
  230. return IterationDecision::Break;
  231. }
  232. auto table_instance = m_store.get(main_module_instance.tables()[0]);
  233. if (current_index >= main_module_instance.elements().size()) {
  234. instantiation_result = InstantiationError { "Invalid element referenced by active element segment" };
  235. return IterationDecision::Break;
  236. }
  237. auto elem_instance = m_store.get(main_module_instance.elements()[current_index]);
  238. if (!table_instance || !elem_instance) {
  239. instantiation_result = InstantiationError { "Invalid element referenced by active element segment" };
  240. return IterationDecision::Break;
  241. }
  242. auto total_required_size = elem_instance->references().size() + d.value();
  243. if (table_instance->type().limits().max().value_or(total_required_size) < total_required_size) {
  244. instantiation_result = InstantiationError { "Table limit overflow in active element segment" };
  245. return IterationDecision::Break;
  246. }
  247. if (table_instance->elements().size() < total_required_size)
  248. table_instance->elements().resize(total_required_size);
  249. size_t i = 0;
  250. for (auto it = elem_instance->references().begin(); it < elem_instance->references().end(); ++i, ++it) {
  251. table_instance->elements()[i + d.value()] = *it;
  252. }
  253. }
  254. return IterationDecision::Continue;
  255. });
  256. if (instantiation_result.has_value())
  257. return instantiation_result.release_value();
  258. module.for_each_section_of_type<DataSection>([&](DataSection const& data_section) {
  259. for (auto& segment : data_section.data()) {
  260. segment.value().visit(
  261. [&](DataSection::Data::Active const& data) {
  262. Configuration config { m_store };
  263. if (m_should_limit_instruction_count)
  264. config.enable_instruction_count_limit();
  265. config.set_frame(Frame {
  266. main_module_instance,
  267. Vector<Value> {},
  268. data.offset,
  269. 1,
  270. });
  271. auto result = config.execute(interpreter);
  272. if (result.is_trap()) {
  273. instantiation_result = InstantiationError { String::formatted("Data section initialisation trapped: {}", result.trap().reason) };
  274. return;
  275. }
  276. size_t offset = 0;
  277. result.values().first().value().visit(
  278. [&](auto const& value) { offset = value; },
  279. [&](Reference const&) { instantiation_result = InstantiationError { "Data segment offset returned a reference"sv }; });
  280. if (instantiation_result.has_value() && instantiation_result->is_error())
  281. return;
  282. if (main_module_instance.memories().size() <= data.index.value()) {
  283. instantiation_result = InstantiationError {
  284. String::formatted("Data segment referenced out-of-bounds memory ({}) of max {} entries",
  285. data.index.value(), main_module_instance.memories().size())
  286. };
  287. return;
  288. }
  289. auto maybe_data_address = m_store.allocate_data(data.init);
  290. if (!maybe_data_address.has_value()) {
  291. instantiation_result = InstantiationError { "Failed to allocate a data instance for an active data segment"sv };
  292. return;
  293. }
  294. main_module_instance.datas().append(*maybe_data_address);
  295. if (data.init.is_empty())
  296. return;
  297. auto address = main_module_instance.memories()[data.index.value()];
  298. if (auto instance = m_store.get(address)) {
  299. if (auto max = instance->type().limits().max(); max.has_value()) {
  300. if (*max < data.init.size() + offset) {
  301. instantiation_result = InstantiationError {
  302. String::formatted("Data segment attempted to write to out-of-bounds memory ({}) of max {} bytes",
  303. data.init.size() + offset, instance->type().limits().max().value())
  304. };
  305. return;
  306. }
  307. }
  308. if (instance->size() < data.init.size() + offset)
  309. instance->grow(data.init.size() + offset - instance->size());
  310. instance->data().overwrite(offset, data.init.data(), data.init.size());
  311. }
  312. },
  313. [&](DataSection::Data::Passive const& passive) {
  314. auto maybe_data_address = m_store.allocate_data(passive.init);
  315. if (!maybe_data_address.has_value()) {
  316. instantiation_result = InstantiationError { "Failed to allocate a data instance for a passive data segment"sv };
  317. return;
  318. }
  319. main_module_instance.datas().append(*maybe_data_address);
  320. });
  321. }
  322. });
  323. module.for_each_section_of_type<StartSection>([&](StartSection const& section) {
  324. auto& functions = main_module_instance.functions();
  325. auto index = section.function().index();
  326. if (functions.size() <= index.value()) {
  327. instantiation_result = InstantiationError { String::formatted("Start section function referenced invalid index {} of max {} entries", index.value(), functions.size()) };
  328. return;
  329. }
  330. invoke(functions[index.value()], {});
  331. });
  332. if (instantiation_result.has_value())
  333. return instantiation_result.release_value();
  334. return InstantiationResult { move(main_module_instance_pointer) };
  335. }
  336. Optional<InstantiationError> AbstractMachine::allocate_all_initial_phase(Module const& module, ModuleInstance& module_instance, Vector<ExternValue>& externs, Vector<Value>& global_values)
  337. {
  338. Optional<InstantiationError> result;
  339. for (auto& entry : externs) {
  340. entry.visit(
  341. [&](FunctionAddress const& address) { module_instance.functions().append(address); },
  342. [&](TableAddress const& address) { module_instance.tables().append(address); },
  343. [&](MemoryAddress const& address) { module_instance.memories().append(address); },
  344. [&](GlobalAddress const& address) { module_instance.globals().append(address); });
  345. }
  346. // FIXME: What if this fails?
  347. for (auto& func : module.functions()) {
  348. auto address = m_store.allocate(module_instance, func);
  349. VERIFY(address.has_value());
  350. module_instance.functions().append(*address);
  351. }
  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;
  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::Result<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. }