AbstractMachine.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. /*
  2. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Enumerate.h>
  7. #include <LibWasm/AbstractMachine/AbstractMachine.h>
  8. #include <LibWasm/AbstractMachine/BytecodeInterpreter.h>
  9. #include <LibWasm/AbstractMachine/Configuration.h>
  10. #include <LibWasm/AbstractMachine/Interpreter.h>
  11. #include <LibWasm/AbstractMachine/Validator.h>
  12. #include <LibWasm/Types.h>
  13. namespace Wasm {
  14. Optional<FunctionAddress> Store::allocate(ModuleInstance& module, CodeSection::Code const& code, TypeIndex type_index)
  15. {
  16. FunctionAddress address { m_functions.size() };
  17. if (type_index.value() > module.types().size())
  18. return {};
  19. auto& type = module.types()[type_index.value()];
  20. m_functions.empend(WasmFunction { type, module, code });
  21. return address;
  22. }
  23. Optional<FunctionAddress> Store::allocate(HostFunction&& function)
  24. {
  25. FunctionAddress address { m_functions.size() };
  26. m_functions.empend(HostFunction { move(function) });
  27. return address;
  28. }
  29. Optional<TableAddress> Store::allocate(TableType const& type)
  30. {
  31. TableAddress address { m_tables.size() };
  32. Vector<Reference> elements;
  33. elements.resize(type.limits().min());
  34. m_tables.empend(TableInstance { type, move(elements) });
  35. return address;
  36. }
  37. Optional<MemoryAddress> Store::allocate(MemoryType const& type)
  38. {
  39. MemoryAddress address { m_memories.size() };
  40. auto instance = MemoryInstance::create(type);
  41. if (instance.is_error())
  42. return {};
  43. m_memories.append(instance.release_value());
  44. return address;
  45. }
  46. Optional<GlobalAddress> Store::allocate(GlobalType const& type, Value value)
  47. {
  48. GlobalAddress address { m_globals.size() };
  49. m_globals.append(GlobalInstance { move(value), type.is_mutable() });
  50. return address;
  51. }
  52. Optional<DataAddress> Store::allocate_data(Vector<u8> initializer)
  53. {
  54. DataAddress address { m_datas.size() };
  55. m_datas.append(DataInstance { move(initializer) });
  56. return address;
  57. }
  58. Optional<ElementAddress> Store::allocate(ValueType const& type, Vector<Reference> references)
  59. {
  60. ElementAddress address { m_elements.size() };
  61. m_elements.append(ElementInstance { type, move(references) });
  62. return address;
  63. }
  64. FunctionInstance* Store::get(FunctionAddress address)
  65. {
  66. auto value = address.value();
  67. if (m_functions.size() <= value)
  68. return nullptr;
  69. return &m_functions[value];
  70. }
  71. TableInstance* Store::get(TableAddress address)
  72. {
  73. auto value = address.value();
  74. if (m_tables.size() <= value)
  75. return nullptr;
  76. return &m_tables[value];
  77. }
  78. MemoryInstance* Store::get(MemoryAddress address)
  79. {
  80. auto value = address.value();
  81. if (m_memories.size() <= value)
  82. return nullptr;
  83. return &m_memories[value];
  84. }
  85. GlobalInstance* Store::get(GlobalAddress address)
  86. {
  87. auto value = address.value();
  88. if (m_globals.size() <= value)
  89. return nullptr;
  90. return &m_globals[value];
  91. }
  92. ElementInstance* Store::get(ElementAddress address)
  93. {
  94. auto value = address.value();
  95. if (m_elements.size() <= value)
  96. return nullptr;
  97. return &m_elements[value];
  98. }
  99. DataInstance* Store::get(DataAddress address)
  100. {
  101. auto value = address.value();
  102. if (m_datas.size() <= value)
  103. return nullptr;
  104. return &m_datas[value];
  105. }
  106. ErrorOr<void, ValidationError> AbstractMachine::validate(Module& module)
  107. {
  108. if (module.validation_status() != Module::ValidationStatus::Unchecked) {
  109. if (module.validation_status() == Module::ValidationStatus::Valid)
  110. return {};
  111. return ValidationError { module.validation_error() };
  112. }
  113. auto result = Validator {}.validate(module);
  114. if (result.is_error()) {
  115. module.set_validation_error(result.error().error_string);
  116. return result.release_error();
  117. }
  118. return {};
  119. }
  120. InstantiationResult AbstractMachine::instantiate(Module const& module, Vector<ExternValue> externs)
  121. {
  122. if (auto result = validate(const_cast<Module&>(module)); result.is_error())
  123. return InstantiationError { ByteString::formatted("Validation failed: {}", result.error()) };
  124. auto main_module_instance_pointer = make<ModuleInstance>();
  125. auto& main_module_instance = *main_module_instance_pointer;
  126. Optional<InstantiationResult> instantiation_result;
  127. module.for_each_section_of_type<TypeSection>([&](TypeSection const& section) {
  128. main_module_instance.types() = section.types();
  129. });
  130. Vector<Value> global_values;
  131. Vector<Vector<Reference>> elements;
  132. ModuleInstance auxiliary_instance;
  133. module.for_each_section_of_type<ImportSection>([&](ImportSection const& section) {
  134. for (auto [i, import_] : enumerate(section.imports())) {
  135. auto extern_ = externs.at(i);
  136. auto invalid = import_.description().visit(
  137. [&](MemoryType const& mem_type) -> Optional<ByteString> {
  138. if (!extern_.has<MemoryAddress>())
  139. return "Expected memory import"sv;
  140. auto other_mem_type = m_store.get(extern_.get<MemoryAddress>())->type();
  141. if (other_mem_type.limits().is_subset_of(mem_type.limits()))
  142. return {};
  143. return ByteString::formatted("Memory import and extern do not match: {}-{} vs {}-{}", mem_type.limits().min(), mem_type.limits().max(), other_mem_type.limits().min(), other_mem_type.limits().max());
  144. },
  145. [&](TableType const& table_type) -> Optional<ByteString> {
  146. if (!extern_.has<TableAddress>())
  147. return "Expected table import"sv;
  148. auto other_table_type = m_store.get(extern_.get<TableAddress>())->type();
  149. if (table_type.element_type() == other_table_type.element_type()
  150. && other_table_type.limits().is_subset_of(table_type.limits()))
  151. return {};
  152. return ByteString::formatted("Table import and extern do not match: {}-{} vs {}-{}", table_type.limits().min(), table_type.limits().max(), other_table_type.limits().min(), other_table_type.limits().max());
  153. },
  154. [&](GlobalType const& global_type) -> Optional<ByteString> {
  155. if (!extern_.has<GlobalAddress>())
  156. return "Expected global import"sv;
  157. auto other_global_type = m_store.get(extern_.get<GlobalAddress>())->type();
  158. if (global_type.type() == other_global_type.type()
  159. && global_type.is_mutable() == other_global_type.is_mutable())
  160. return {};
  161. return "Global import and extern do not match"sv;
  162. },
  163. [&](FunctionType const& type) -> Optional<ByteString> {
  164. if (!extern_.has<FunctionAddress>())
  165. return "Expected function import"sv;
  166. auto other_type = m_store.get(extern_.get<FunctionAddress>())->visit([&](WasmFunction const& wasm_func) { return wasm_func.type(); }, [&](HostFunction const& host_func) { return host_func.type(); });
  167. if (type.results() != other_type.results())
  168. return ByteString::formatted("Function import and extern do not match, results: {} vs {}", type.results(), other_type.results());
  169. if (type.parameters() != other_type.parameters())
  170. return ByteString::formatted("Function import and extern do not match, parameters: {} vs {}", type.parameters(), other_type.parameters());
  171. return {};
  172. },
  173. [&](TypeIndex type_index) -> Optional<ByteString> {
  174. if (!extern_.has<FunctionAddress>())
  175. return "Expected function import"sv;
  176. auto other_type = m_store.get(extern_.get<FunctionAddress>())->visit([&](WasmFunction const& wasm_func) { return wasm_func.type(); }, [&](HostFunction const& host_func) { return host_func.type(); });
  177. auto& type = module.type(type_index);
  178. if (type.results() != other_type.results())
  179. return ByteString::formatted("Function import and extern do not match, results: {} vs {}", type.results(), other_type.results());
  180. if (type.parameters() != other_type.parameters())
  181. return ByteString::formatted("Function import and extern do not match, parameters: {} vs {}", type.parameters(), other_type.parameters());
  182. return {};
  183. });
  184. if (invalid.has_value())
  185. instantiation_result = InstantiationError { ByteString::formatted("{}::{}: {}", import_.module(), import_.name(), invalid.release_value()) };
  186. }
  187. });
  188. if (instantiation_result.has_value())
  189. return instantiation_result.release_value();
  190. for (auto& entry : externs) {
  191. if (auto* ptr = entry.get_pointer<GlobalAddress>())
  192. auxiliary_instance.globals().append(*ptr);
  193. else if (auto* ptr = entry.get_pointer<FunctionAddress>())
  194. auxiliary_instance.functions().append(*ptr);
  195. }
  196. FunctionSection const* function_section { nullptr };
  197. module.for_each_section_of_type<FunctionSection>([&](FunctionSection const& section) { function_section = &section; });
  198. Vector<FunctionAddress> module_functions;
  199. if (function_section)
  200. module_functions.ensure_capacity(function_section->types().size());
  201. module.for_each_section_of_type<CodeSection>([&](auto& code_section) {
  202. size_t i = 0;
  203. for (auto& code : code_section.functions()) {
  204. auto type_index = function_section->types()[i];
  205. auto address = m_store.allocate(main_module_instance, code, type_index);
  206. VERIFY(address.has_value());
  207. auxiliary_instance.functions().append(*address);
  208. module_functions.append(*address);
  209. ++i;
  210. }
  211. });
  212. BytecodeInterpreter interpreter(m_stack_info);
  213. module.for_each_section_of_type<GlobalSection>([&](auto& global_section) {
  214. for (auto& entry : global_section.entries()) {
  215. Configuration config { m_store };
  216. if (m_should_limit_instruction_count)
  217. config.enable_instruction_count_limit();
  218. config.set_frame(Frame {
  219. auxiliary_instance,
  220. Vector<Value> {},
  221. entry.expression(),
  222. 1,
  223. });
  224. auto result = config.execute(interpreter).assert_wasm_result();
  225. if (result.is_trap())
  226. instantiation_result = InstantiationError { ByteString::formatted("Global value construction trapped: {}", result.trap().reason) };
  227. else
  228. global_values.append(result.values().first());
  229. }
  230. });
  231. if (instantiation_result.has_value())
  232. return instantiation_result.release_value();
  233. if (auto result = allocate_all_initial_phase(module, main_module_instance, externs, global_values, module_functions); result.has_value())
  234. return result.release_value();
  235. module.for_each_section_of_type<ElementSection>([&](ElementSection const& section) {
  236. for (auto& segment : section.segments()) {
  237. Vector<Reference> references;
  238. for (auto& entry : segment.init) {
  239. Configuration config { m_store };
  240. if (m_should_limit_instruction_count)
  241. config.enable_instruction_count_limit();
  242. config.set_frame(Frame {
  243. auxiliary_instance,
  244. Vector<Value> {},
  245. entry,
  246. entry.instructions().size(),
  247. });
  248. auto result = config.execute(interpreter).assert_wasm_result();
  249. if (result.is_trap()) {
  250. instantiation_result = InstantiationError { ByteString::formatted("Element construction trapped: {}", result.trap().reason) };
  251. return IterationDecision::Continue;
  252. }
  253. for (auto& value : result.values()) {
  254. if (!value.type().is_reference()) {
  255. instantiation_result = InstantiationError { "Evaluated element entry is not a reference" };
  256. return IterationDecision::Continue;
  257. }
  258. auto reference = value.to<Reference>();
  259. if (!reference.has_value()) {
  260. instantiation_result = InstantiationError { "Evaluated element entry does not contain a reference" };
  261. return IterationDecision::Continue;
  262. }
  263. // FIXME: type-check the reference.
  264. references.append(reference.release_value());
  265. }
  266. }
  267. elements.append(move(references));
  268. }
  269. return IterationDecision::Continue;
  270. });
  271. if (instantiation_result.has_value())
  272. return instantiation_result.release_value();
  273. if (auto result = allocate_all_final_phase(module, main_module_instance, elements); result.has_value())
  274. return result.release_value();
  275. module.for_each_section_of_type<ElementSection>([&](ElementSection const& section) {
  276. size_t index = 0;
  277. for (auto& segment : section.segments()) {
  278. auto current_index = index;
  279. ++index;
  280. auto active_ptr = segment.mode.get_pointer<ElementSection::Active>();
  281. auto elem_instance = m_store.get(main_module_instance.elements()[current_index]);
  282. if (!active_ptr) {
  283. if (segment.mode.has<ElementSection::Declarative>())
  284. *elem_instance = ElementInstance(elem_instance->type(), {});
  285. continue;
  286. }
  287. Configuration config { m_store };
  288. if (m_should_limit_instruction_count)
  289. config.enable_instruction_count_limit();
  290. config.set_frame(Frame {
  291. auxiliary_instance,
  292. Vector<Value> {},
  293. active_ptr->expression,
  294. 1,
  295. });
  296. auto result = config.execute(interpreter).assert_wasm_result();
  297. if (result.is_trap()) {
  298. instantiation_result = InstantiationError { ByteString::formatted("Element section initialisation trapped: {}", result.trap().reason) };
  299. return IterationDecision::Break;
  300. }
  301. auto d = result.values().first().to<i32>();
  302. if (!d.has_value()) {
  303. instantiation_result = InstantiationError { "Element section initialisation returned invalid table initial offset" };
  304. return IterationDecision::Break;
  305. }
  306. auto table_instance = m_store.get(main_module_instance.tables()[active_ptr->index.value()]);
  307. if (current_index >= main_module_instance.elements().size()) {
  308. instantiation_result = InstantiationError { "Invalid element referenced by active element segment" };
  309. return IterationDecision::Break;
  310. }
  311. if (!table_instance || !elem_instance) {
  312. instantiation_result = InstantiationError { "Invalid element referenced by active element segment" };
  313. return IterationDecision::Break;
  314. }
  315. Checked<size_t> total_size = elem_instance->references().size();
  316. total_size.saturating_add(d.value());
  317. if (total_size.value() > table_instance->elements().size()) {
  318. instantiation_result = InstantiationError { "Table instantiation out of bounds" };
  319. return IterationDecision::Break;
  320. }
  321. size_t i = 0;
  322. for (auto it = elem_instance->references().begin(); it < elem_instance->references().end(); ++i, ++it) {
  323. table_instance->elements()[i + d.value()] = *it;
  324. }
  325. // Drop element
  326. *m_store.get(main_module_instance.elements()[current_index]) = ElementInstance(elem_instance->type(), {});
  327. }
  328. return IterationDecision::Continue;
  329. });
  330. if (instantiation_result.has_value())
  331. return instantiation_result.release_value();
  332. module.for_each_section_of_type<DataSection>([&](DataSection const& data_section) {
  333. for (auto& segment : data_section.data()) {
  334. segment.value().visit(
  335. [&](DataSection::Data::Active const& data) {
  336. Configuration config { m_store };
  337. if (m_should_limit_instruction_count)
  338. config.enable_instruction_count_limit();
  339. config.set_frame(Frame {
  340. auxiliary_instance,
  341. Vector<Value> {},
  342. data.offset,
  343. 1,
  344. });
  345. auto result = config.execute(interpreter).assert_wasm_result();
  346. if (result.is_trap()) {
  347. instantiation_result = InstantiationError { ByteString::formatted("Data section initialisation trapped: {}", result.trap().reason) };
  348. return;
  349. }
  350. size_t offset = 0;
  351. result.values().first().value().visit(
  352. [&](auto const& value) { offset = value; },
  353. [&](u128 const&) { instantiation_result = InstantiationError { "Data segment offset returned a vector type"sv }; },
  354. [&](Reference const&) { instantiation_result = InstantiationError { "Data segment offset returned a reference"sv }; });
  355. if (instantiation_result.has_value() && instantiation_result->is_error())
  356. return;
  357. if (main_module_instance.memories().size() <= data.index.value()) {
  358. instantiation_result = InstantiationError {
  359. ByteString::formatted("Data segment referenced out-of-bounds memory ({}) of max {} entries",
  360. data.index.value(), main_module_instance.memories().size())
  361. };
  362. return;
  363. }
  364. auto maybe_data_address = m_store.allocate_data(data.init);
  365. if (!maybe_data_address.has_value()) {
  366. instantiation_result = InstantiationError { "Failed to allocate a data instance for an active data segment"sv };
  367. return;
  368. }
  369. main_module_instance.datas().append(*maybe_data_address);
  370. auto address = main_module_instance.memories()[data.index.value()];
  371. auto instance = m_store.get(address);
  372. Checked<size_t> checked_offset = data.init.size();
  373. checked_offset += offset;
  374. if (checked_offset.has_overflow() || checked_offset > instance->size()) {
  375. instantiation_result = InstantiationError {
  376. ByteString::formatted("Data segment attempted to write to out-of-bounds memory ({}) in memory of size {}",
  377. offset, instance->size())
  378. };
  379. return;
  380. }
  381. if (data.init.is_empty())
  382. return;
  383. instance->data().overwrite(offset, data.init.data(), data.init.size());
  384. },
  385. [&](DataSection::Data::Passive const& passive) {
  386. auto maybe_data_address = m_store.allocate_data(passive.init);
  387. if (!maybe_data_address.has_value()) {
  388. instantiation_result = InstantiationError { "Failed to allocate a data instance for a passive data segment"sv };
  389. return;
  390. }
  391. main_module_instance.datas().append(*maybe_data_address);
  392. });
  393. }
  394. });
  395. module.for_each_section_of_type<StartSection>([&](StartSection const& section) {
  396. auto& functions = main_module_instance.functions();
  397. auto index = section.function().index();
  398. if (functions.size() <= index.value()) {
  399. instantiation_result = InstantiationError { ByteString::formatted("Start section function referenced invalid index {} of max {} entries", index.value(), functions.size()) };
  400. return;
  401. }
  402. auto result = invoke(functions[index.value()], {});
  403. if (result.is_trap())
  404. instantiation_result = InstantiationError { ByteString::formatted("Start function trapped: {}", result.trap().reason) };
  405. });
  406. if (instantiation_result.has_value())
  407. return instantiation_result.release_value();
  408. return InstantiationResult { move(main_module_instance_pointer) };
  409. }
  410. Optional<InstantiationError> AbstractMachine::allocate_all_initial_phase(Module const& module, ModuleInstance& module_instance, Vector<ExternValue>& externs, Vector<Value>& global_values, Vector<FunctionAddress>& own_functions)
  411. {
  412. Optional<InstantiationError> result;
  413. for (auto& entry : externs) {
  414. entry.visit(
  415. [&](FunctionAddress const& address) { module_instance.functions().append(address); },
  416. [&](TableAddress const& address) { module_instance.tables().append(address); },
  417. [&](MemoryAddress const& address) { module_instance.memories().append(address); },
  418. [&](GlobalAddress const& address) { module_instance.globals().append(address); });
  419. }
  420. module_instance.functions().extend(own_functions);
  421. // FIXME: What if this fails?
  422. module.for_each_section_of_type<TableSection>([&](TableSection const& section) {
  423. for (auto& table : section.tables()) {
  424. auto table_address = m_store.allocate(table.type());
  425. VERIFY(table_address.has_value());
  426. module_instance.tables().append(*table_address);
  427. }
  428. });
  429. module.for_each_section_of_type<MemorySection>([&](MemorySection const& section) {
  430. for (auto& memory : section.memories()) {
  431. auto memory_address = m_store.allocate(memory.type());
  432. VERIFY(memory_address.has_value());
  433. module_instance.memories().append(*memory_address);
  434. }
  435. });
  436. module.for_each_section_of_type<GlobalSection>([&](GlobalSection const& section) {
  437. size_t index = 0;
  438. for (auto& entry : section.entries()) {
  439. auto address = m_store.allocate(entry.type(), move(global_values[index]));
  440. VERIFY(address.has_value());
  441. module_instance.globals().append(*address);
  442. index++;
  443. }
  444. });
  445. module.for_each_section_of_type<ExportSection>([&](ExportSection const& section) {
  446. for (auto& entry : section.entries()) {
  447. Variant<FunctionAddress, TableAddress, MemoryAddress, GlobalAddress, Empty> address {};
  448. entry.description().visit(
  449. [&](FunctionIndex const& index) {
  450. if (module_instance.functions().size() > index.value())
  451. address = FunctionAddress { module_instance.functions()[index.value()] };
  452. else
  453. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.functions().size());
  454. },
  455. [&](TableIndex const& index) {
  456. if (module_instance.tables().size() > index.value())
  457. address = TableAddress { module_instance.tables()[index.value()] };
  458. else
  459. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.tables().size());
  460. },
  461. [&](MemoryIndex const& index) {
  462. if (module_instance.memories().size() > index.value())
  463. address = MemoryAddress { module_instance.memories()[index.value()] };
  464. else
  465. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.memories().size());
  466. },
  467. [&](GlobalIndex const& index) {
  468. if (module_instance.globals().size() > index.value())
  469. address = GlobalAddress { module_instance.globals()[index.value()] };
  470. else
  471. dbgln("Failed to export '{}', the exported address ({}) was out of bounds (min: 0, max: {})", entry.name(), index.value(), module_instance.globals().size());
  472. });
  473. if (address.has<Empty>()) {
  474. result = InstantiationError { "An export could not be resolved" };
  475. continue;
  476. }
  477. module_instance.exports().append(ExportInstance {
  478. entry.name(),
  479. move(address).downcast<FunctionAddress, TableAddress, MemoryAddress, GlobalAddress>(),
  480. });
  481. }
  482. });
  483. return result;
  484. }
  485. Optional<InstantiationError> AbstractMachine::allocate_all_final_phase(Module const& module, ModuleInstance& module_instance, Vector<Vector<Reference>>& elements)
  486. {
  487. module.for_each_section_of_type<ElementSection>([&](ElementSection const& section) {
  488. size_t index = 0;
  489. for (auto& segment : section.segments()) {
  490. auto address = m_store.allocate(segment.type, move(elements[index]));
  491. VERIFY(address.has_value());
  492. module_instance.elements().append(*address);
  493. index++;
  494. }
  495. });
  496. return {};
  497. }
  498. Result AbstractMachine::invoke(FunctionAddress address, Vector<Value> arguments)
  499. {
  500. BytecodeInterpreter interpreter(m_stack_info);
  501. return invoke(interpreter, address, move(arguments));
  502. }
  503. Result AbstractMachine::invoke(Interpreter& interpreter, FunctionAddress address, Vector<Value> arguments)
  504. {
  505. Configuration configuration { m_store };
  506. if (m_should_limit_instruction_count)
  507. configuration.enable_instruction_count_limit();
  508. return configuration.call(interpreter, address, move(arguments));
  509. }
  510. void Linker::link(ModuleInstance const& instance)
  511. {
  512. populate();
  513. if (m_unresolved_imports.is_empty())
  514. return;
  515. HashTable<Name> resolved_imports;
  516. for (auto& import_ : m_unresolved_imports) {
  517. auto it = instance.exports().find_if([&](auto& export_) { return export_.name() == import_.name; });
  518. if (!it.is_end()) {
  519. resolved_imports.set(import_);
  520. m_resolved_imports.set(import_, it->value());
  521. }
  522. }
  523. for (auto& entry : resolved_imports)
  524. m_unresolved_imports.remove(entry);
  525. }
  526. void Linker::link(HashMap<Linker::Name, ExternValue> const& exports)
  527. {
  528. populate();
  529. if (m_unresolved_imports.is_empty())
  530. return;
  531. if (exports.is_empty())
  532. return;
  533. HashTable<Name> resolved_imports;
  534. for (auto& import_ : m_unresolved_imports) {
  535. auto export_ = exports.get(import_);
  536. if (export_.has_value()) {
  537. resolved_imports.set(import_);
  538. m_resolved_imports.set(import_, export_.value());
  539. }
  540. }
  541. for (auto& entry : resolved_imports)
  542. m_unresolved_imports.remove(entry);
  543. }
  544. AK::ErrorOr<Vector<ExternValue>, LinkError> Linker::finish()
  545. {
  546. populate();
  547. if (!m_unresolved_imports.is_empty()) {
  548. if (!m_error.has_value())
  549. m_error = LinkError {};
  550. for (auto& entry : m_unresolved_imports)
  551. m_error->missing_imports.append(entry.name);
  552. return *m_error;
  553. }
  554. if (m_error.has_value())
  555. return *m_error;
  556. // Result must be in the same order as the module imports
  557. Vector<ExternValue> exports;
  558. exports.ensure_capacity(m_ordered_imports.size());
  559. for (auto& import_ : m_ordered_imports)
  560. exports.unchecked_append(*m_resolved_imports.get(import_));
  561. return exports;
  562. }
  563. void Linker::populate()
  564. {
  565. if (!m_ordered_imports.is_empty())
  566. return;
  567. // There better be at most one import section!
  568. bool already_seen_an_import_section = false;
  569. m_module.for_each_section_of_type<ImportSection>([&](ImportSection const& section) {
  570. if (already_seen_an_import_section) {
  571. if (!m_error.has_value())
  572. m_error = LinkError {};
  573. m_error->other_errors.append(LinkError::InvalidImportedModule);
  574. return;
  575. }
  576. already_seen_an_import_section = true;
  577. for (auto& import_ : section.imports()) {
  578. m_ordered_imports.append({ import_.module(), import_.name(), import_.description() });
  579. m_unresolved_imports.set(m_ordered_imports.last());
  580. }
  581. });
  582. }
  583. }