AbstractMachine.cpp 28 KB

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