AbstractMachine.cpp 26 KB

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