Coverage Report

Created: 2026-11-23 07:59

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wasm-tools/crates/wit-component/src/linking.rs
Line
Count
Source
1
//! Support for "pseudo-dynamic", shared-everything linking of Wasm modules into a component.
2
//!
3
//! This implements [shared-everything
4
//! linking](https://github.com/WebAssembly/component-model/blob/main/design/mvp/examples/SharedEverythingDynamicLinking.md),
5
//! taking as input one or more [dynamic
6
//! library](https://github.com/WebAssembly/tool-conventions/blob/main/DynamicLinking.md) modules and producing a
7
//! component whose type is the union of any `component-type*` custom sections found in the input modules.
8
//!
9
//! The entry point into this process is `Linker::encode`, which analyzes and topologically sorts the input
10
//! modules, then synthesizes two additional modules:
11
//!
12
//! - `main` AKA `env`: hosts the component's single memory and function table and exports any functions needed to
13
//! break dependency cycles discovered in the input modules. Those functions use `call.indirect` to invoke the real
14
//! functions, references to which are placed in the table by the `init` module.
15
//!
16
//! - `init`: populates the function table as described above, initializes global variables per the dynamic linking
17
//! tool convention, and calls any static constructors and/or link-time fixup functions
18
//!
19
//! `Linker` also supports synthesizing `dlopen`/`dlsym` lookup tables which allow symbols to be resolved at
20
//! runtime.  Note that this is not true dynamic linking, since all the code is baked into the component ahead of
21
//! time -- we simply allow runtime resolution of already-resident definitions.  This is sufficient to support
22
//! dynamic language FFI features such as Python native extensions, provided the required libraries are linked
23
//! ahead-of-time.
24
25
use {
26
    crate::encoding::fixup::{AddressDest, FixupModule, ImportedInstance, StartAction},
27
    crate::encoding::{ComponentEncoder, Instance, Item, LibraryInfo, MainOrAdapter},
28
    crate::gc::PtrInstructions,
29
    crate::validation::IndexType,
30
    anyhow::{Context, Result, anyhow, bail},
31
    indexmap::{IndexMap, IndexSet, map::Entry},
32
    metadata::{Export, ExportKey, FunctionType, GlobalType, Metadata, Type, ValueType},
33
    std::{
34
        borrow::Cow,
35
        collections::{BTreeMap, HashMap, HashSet},
36
        fmt::Debug,
37
        hash::Hash,
38
    },
39
    wasm_encoder::{
40
        CodeSection, Elements, EntityType, ExportKind, ExportSection, Function, FunctionSection,
41
        GlobalSection, ImportSection, MemArg, MemorySection, MemoryType, Module, RawCustomSection,
42
        RefType, TableSection, TableType, TypeSection, ValType,
43
    },
44
    wasmparser::SymbolFlags,
45
};
46
47
pub(crate) mod metadata;
48
49
const PAGE_SIZE_BYTES: u32 = 65536;
50
// This matches the default stack size LLVM produces:
51
pub const DEFAULT_STACK_SIZE_BYTES: u32 = 16 * PAGE_SIZE_BYTES;
52
const HEAP_ALIGNMENT_BYTES: u32 = 16;
53
const STUB_LIBRARY_NAME: &str = "wit-component:stubs";
54
const CABI_REALLOC: &str = "cabi_realloc";
55
56
/// Symbols to re-export from the `env` module regardless of whether any
57
/// libraries import them, since
58
/// `EncodingState::create_export_task_initialization_wrappers` needs to be able
59
/// to call them.
60
static ENV_REEXPORTS: &[(&str, &[ValueType], &[ValueType])] =
61
    &[(metadata::TASK_HOOK, &[ValueType::I32], &[])];
62
63
enum Address<'a> {
64
    Function(u32),
65
    Global(&'a str),
66
}
67
68
/// Represents a `dlopen`/`dlsym` lookup table enabling runtime symbol resolution
69
///
70
/// The top level of this table is a sorted list of library names and offsets, each pointing to a sorted list of
71
/// symbol names and offsets.  See ../dl/src/lib.rs for how this is used at runtime.
72
struct DlOpenables<'a> {
73
    /// Offset into the main module's table where function references will be stored
74
    table_base: u32,
75
76
    /// Offset into the main module's memory where the lookup table will be stored
77
    memory_base: u32,
78
79
    /// The lookup table itself
80
    buffer: Vec<u8>,
81
82
    /// Linear memory addresses where global variable addresses will live
83
    ///
84
    /// The init module will fill in the correct values at instantiation time.
85
    global_addresses: Vec<(&'a str, &'a str, u32)>,
86
87
    /// Number of function references to be stored in the main module's table
88
    function_count: u32,
89
90
    /// Linear memory address where the root of the lookup table will reside
91
    ///
92
    /// This can be different from `memory_base` depending on how the tree of libraries and symbols is laid out in
93
    /// memory.
94
    libraries_address: u32,
95
}
96
97
impl<'a> DlOpenables<'a> {
98
    /// Construct a lookup table containing all "dlopen-able" libraries and their symbols using the specified table
99
    /// and memory offsets.
100
    ///
101
    /// The layout of the table matches the `#[repr(C)]` structures in
102
    /// ../dl/src/lib.rs compiled for a target whose pointers are described by
103
    /// `index_type`.
104
0
    fn new(
105
0
        table_base: u32,
106
0
        memory_base: u32,
107
0
        metadata: &'a [Metadata<'a>],
108
0
        index_type: IndexType,
109
0
    ) -> Self {
110
0
        let mut function_count = 0;
111
0
        let mut data = StaticData::new(memory_base, index_type);
112
0
        let mut global_addresses = Vec::new();
113
0
        let mut libraries = metadata
114
0
            .iter()
115
0
            .filter(|metadata| metadata.dl_openable)
116
0
            .map(|metadata| {
117
0
                let name_address = data.bytes(metadata.name.as_bytes());
118
119
0
                let mut symbols = metadata
120
0
                    .exports
121
0
                    .iter()
122
0
                    .filter_map(|export| {
123
0
                        let address = match &export.key.ty {
124
0
                            Type::Function(_) => Address::Function(
125
0
                                table_base + get_and_increment(&mut function_count),
126
0
                            ),
127
0
                            Type::Global(_) => Address::Global(export.key.name),
128
0
                            Type::Tag(_) => return None,
129
                        };
130
0
                        let name_address = data.bytes(export.key.name.as_bytes());
131
132
0
                        Some((export.key.name, name_address, address))
133
0
                    })
134
0
                    .collect::<Vec<_>>();
135
136
0
                symbols.sort_by_key(|(name, ..)| *name);
137
138
                // struct Symbol symbols[];
139
0
                let symbols_address = data.start_struct();
140
0
                for (name, name_address, address) in symbols {
141
0
                    data.start_struct();
142
0
                    data.u32(u32::try_from(name.len()).unwrap());
143
0
                    data.ptr(name_address);
144
0
                    match address {
145
0
                        Address::Function(address) => {
146
0
                            data.ptr(address);
147
0
                        }
148
0
                        Address::Global(name) => {
149
0
                            let address = data.ptr(0);
150
0
                            global_addresses.push((metadata.name, name, address));
151
0
                        }
152
                    }
153
                }
154
155
0
                (
156
0
                    metadata.name,
157
0
                    name_address,
158
0
                    metadata.exports.len(),
159
0
                    symbols_address,
160
0
                )
161
0
            })
162
0
            .collect::<Vec<_>>();
163
164
0
        libraries.sort_by_key(|(name, ..)| *name);
165
166
        // struct Library libraries[];
167
0
        let libraries_array_address = data.start_struct();
168
0
        for (name, name_address, count, symbols) in &libraries {
169
0
            data.start_struct();
170
0
            data.u32(u32::try_from(name.len()).unwrap());
171
0
            data.ptr(*name_address);
172
0
            data.u32(u32::try_from(*count).unwrap());
173
0
            data.ptr(*symbols);
174
0
        }
175
176
        // struct Libraries libraries;
177
0
        let libraries_address = data.start_struct();
178
0
        data.u32(u32::try_from(libraries.len()).unwrap());
179
0
        data.ptr(libraries_array_address);
180
181
0
        Self {
182
0
            table_base,
183
0
            memory_base,
184
0
            buffer: data.finish(),
185
0
            global_addresses,
186
0
            function_count,
187
0
            libraries_address,
188
0
        }
189
0
    }
190
}
191
192
/// The layout of the whole program's thread-local storage bookkeeping.
193
///
194
/// This generates a C structure that matches this layout:
195
///
196
/// ```c
197
/// struct {
198
///     size_t num_libraries;
199
///     void **library_info;
200
///     void **main_thread_tls_base;
201
/// } __wasm_program_tls_info;
202
/// ```
203
///
204
/// where the `main_thread_tls_base` array is placed first, then the
205
/// `library_info` array, then this structure itself.
206
#[derive(Default)]
207
struct TlsLayout {
208
    /// Address of the `main_thread_tls_base` array.
209
    ///
210
    /// This is left zero-initialized; no data segment covers it.
211
    main_thread_tls_base: u32,
212
213
    /// Address of the `library_info` array.
214
    library_info: u32,
215
216
    /// Address of the `__wasm_program_tls_info` struct itself.
217
    program_info: u32,
218
219
    /// For each library, the slot it uses in the array of TLS base pointers, or
220
    /// `None` if it has no thread-local storage of its own.
221
    slots: Vec<Option<u32>>,
222
223
    /// Static contents of the `__wasm_program_tls_info`.
224
    buffer: Vec<u8>,
225
}
226
227
impl TlsLayout {
228
    /// Reserve linear memory space for the layout described above, advancing
229
    /// `memory_offset` past what's used.
230
    ///
231
    /// Nothing is reserved for a program which doesn't use thread-local storage
232
    /// at all, and the `__wasm_program_tls_info` half is skipped unless some
233
    /// library actually asks for it, which is only the case when the program
234
    /// might spawn a thread.
235
0
    fn new(metadata: &[Metadata], memory_offset: &mut u32, index_type: IndexType) -> Self {
236
0
        let needs_tls_base = metadata
237
0
            .iter()
238
0
            .any(|m| m.needs_get_tls_base || m.needs_set_tls_base);
239
0
        let needs_program_info = metadata.iter().any(|m| m.needs_program_tls_info);
240
0
        if !needs_tls_base && !needs_program_info {
241
0
            return Self::default();
242
0
        }
243
244
        // Filter out libraries that don't have TLS.
245
0
        let libraries = metadata
246
0
            .iter()
247
0
            .enumerate()
248
0
            .filter(|(_, metadata)| metadata.has_library_tls_info)
249
0
            .map(|(index, _)| index)
250
0
            .collect::<Vec<_>>();
251
252
0
        let mut slots = vec![None; metadata.len()];
253
0
        for (slot, index) in libraries.iter().enumerate() {
254
0
            slots[*index] = Some(u32::try_from(slot).unwrap());
255
0
        }
256
0
        let count = u32::try_from(libraries.len()).unwrap();
257
258
0
        let ptr_size = index_type.ptr_size();
259
260
        // Allocate space for `main_thread_tls_base`
261
0
        *memory_offset = align(*memory_offset, ptr_size);
262
0
        let main_thread_tls_base = *memory_offset;
263
0
        *memory_offset += count * ptr_size;
264
265
0
        let mut library_info = 0;
266
0
        let mut program_info = 0;
267
0
        let mut buffer = Vec::new();
268
0
        if needs_program_info {
269
0
            library_info = *memory_offset;
270
0
            *memory_offset += count * ptr_size;
271
0
272
0
            let mut data = StaticData::new(*memory_offset, index_type);
273
0
            program_info = data.start_struct();
274
0
            data.ptr(count);
275
0
            data.ptr(library_info);
276
0
            data.ptr(main_thread_tls_base);
277
0
            *memory_offset = data.end();
278
0
            buffer = data.finish();
279
0
        }
280
281
0
        Self {
282
0
            main_thread_tls_base,
283
0
            library_info,
284
0
            program_info,
285
0
            slots,
286
0
            buffer,
287
0
        }
288
0
    }
289
290
    /// The slot library `index` uses in the array of TLS base pointers.
291
0
    fn slot(&self, index: usize) -> Option<u32> {
292
0
        self.slots.get(index).copied().flatten()
293
0
    }
294
}
295
296
/// Builder for a blob of data which will be placed at the fixed address
297
/// `base` in linear memory, laid out the same way that C would lay out
298
/// structures for a target whose pointers are described by `index_type`.
299
///
300
/// All methods which write data return the address in linear memory, not the
301
/// offset in the buffer, at which the data was written, after any padding
302
/// needed for alignment.
303
struct StaticData {
304
    base: u32,
305
    buffer: Vec<u8>,
306
    index_type: IndexType,
307
}
308
309
impl StaticData {
310
0
    fn new(base: u32, index_type: IndexType) -> Self {
311
        // Alignment within `buffer` only translates to alignment in linear
312
        // memory if `base` is itself sufficiently aligned.
313
0
        assert_eq!(
314
0
            base % index_type.ptr_size(),
315
            0,
316
            "static data must be pointer-aligned"
317
        );
318
0
        Self {
319
0
            base,
320
0
            buffer: Vec::new(),
321
0
            index_type,
322
0
        }
323
0
    }
324
325
    /// Returns the address in linear memory just past the end of the data
326
    /// written so far.
327
0
    fn end(&self) -> u32 {
328
0
        self.base + u32::try_from(self.buffer.len()).unwrap()
329
0
    }
330
331
    /// Pads with zeros to `alignment`, returning the now-aligned address.
332
0
    fn align(&mut self, alignment: u32) -> u32 {
333
0
        let end = self.end();
334
0
        let aligned = align(end, alignment);
335
0
        self.buffer.resize(
336
0
            self.buffer.len() + usize::try_from(aligned - end).unwrap(),
337
            0,
338
        );
339
0
        aligned
340
0
    }
341
342
    /// Aligns for the start of a structure or an element of an array of
343
    /// structures, returning its address.
344
    ///
345
    /// Every structure written here contains a pointer, so its alignment is
346
    /// that of a pointer.
347
0
    fn start_struct(&mut self) -> u32 {
348
0
        self.align(self.index_type.ptr_size())
349
0
    }
350
351
    /// Writes unaligned raw bytes, such as a string.
352
0
    fn bytes(&mut self, bytes: &[u8]) -> u32 {
353
0
        let address = self.end();
354
0
        self.buffer.extend_from_slice(bytes);
355
0
        address
356
0
    }
357
358
0
    fn u32(&mut self, value: u32) -> u32 {
359
0
        let address = self.align(4);
360
0
        self.buffer.extend(value.to_le_bytes());
361
0
        address
362
0
    }
363
364
    /// Writes a pointer-sized `value`, such as a pointer or a `size_t`.
365
0
    fn ptr(&mut self, value: u32) -> u32 {
366
0
        let address = self.align(self.index_type.ptr_size());
367
0
        match self.index_type {
368
0
            IndexType::I32 => self.buffer.extend(value.to_le_bytes()),
369
0
            IndexType::I64 => self.buffer.extend(u64::from(value).to_le_bytes()),
370
        }
371
0
        address
372
0
    }
373
374
0
    fn finish(self) -> Vec<u8> {
375
0
        self.buffer
376
0
    }
377
}
378
379
0
fn align(a: u32, b: u32) -> u32 {
380
0
    assert!(b.is_power_of_two());
381
0
    (a + (b - 1)) & !(b - 1)
382
0
}
383
384
0
fn get_and_increment(n: &mut u32) -> u32 {
385
0
    let v = *n;
386
0
    *n += 1;
387
0
    v
388
0
}
389
390
/// Helper trait for determining the size of a set or map
391
trait Length {
392
    fn len(&self) -> usize;
393
}
394
395
impl<T> Length for HashSet<T> {
396
0
    fn len(&self) -> usize {
397
0
        HashSet::len(self)
398
0
    }
Unexecuted instantiation: <std::collections::hash::set::HashSet<alloc::string::String> as wit_component::linking::Length>::len
Unexecuted instantiation: <std::collections::hash::set::HashSet<&str> as wit_component::linking::Length>::len
399
}
400
401
impl<K, V> Length for HashMap<K, V> {
402
0
    fn len(&self) -> usize {
403
0
        HashMap::len(self)
404
0
    }
Unexecuted instantiation: <std::collections::hash::map::HashMap<&str, (&wit_component::linking::metadata::FunctionType, (&str, &wit_component::linking::metadata::Export))> as wit_component::linking::Length>::len
Unexecuted instantiation: <std::collections::hash::map::HashMap<&str, (u32, bool)> as wit_component::linking::Length>::len
Unexecuted instantiation: <std::collections::hash::map::HashMap<&str, usize> as wit_component::linking::Length>::len
405
}
406
407
impl<T> Length for IndexSet<T> {
408
0
    fn len(&self) -> usize {
409
0
        IndexSet::len(self)
410
0
    }
411
}
412
413
impl<K, V> Length for IndexMap<K, V> {
414
0
    fn len(&self) -> usize {
415
0
        IndexMap::len(self)
416
0
    }
Unexecuted instantiation: <indexmap::map::IndexMap<&str, (&&wit_component::linking::metadata::ExportKey, &alloc::vec::Vec<(&str, &wit_component::linking::metadata::Export)>)> as wit_component::linking::Length>::len
Unexecuted instantiation: <indexmap::map::IndexMap<usize, indexmap::set::IndexSet<usize>> as wit_component::linking::Length>::len
417
}
418
419
/// Extension trait for collecting into a set or map and asserting that there were no duplicate entries in the
420
/// source iterator.
421
trait CollectUnique: Iterator + Sized {
422
0
    fn collect_unique<T: FromIterator<Self::Item> + Length>(self) -> T {
423
0
        let tmp = self.collect::<Vec<_>>();
424
0
        let len = tmp.len();
425
0
        let result = tmp.into_iter().collect::<T>();
426
0
        assert!(
427
0
            result.len() == len,
428
            "one or more duplicate items detected when collecting into set or map"
429
        );
430
0
        result
431
0
    }
Unexecuted instantiation: <core::iter::adapters::filter_map::FilterMap<core::iter::adapters::enumerate::Enumerate<core::slice::iter::Iter<wit_component::linking::metadata::Metadata>>, wit_component::linking::find_reachable::{closure#0}> as wit_component::linking::CollectUnique>::collect_unique::<indexmap::set::IndexSet<usize>>
Unexecuted instantiation: <core::iter::adapters::filter_map::FilterMap<core::slice::iter::Iter<(alloc::string::String, alloc::vec::Vec<u8>, bool)>, <wit_component::linking::Linker>::encode::{closure#7}> as wit_component::linking::CollectUnique>::collect_unique::<std::collections::hash::set::HashSet<alloc::string::String>>
Unexecuted instantiation: <core::iter::adapters::filter_map::FilterMap<indexmap::map::iter::Iter<&wit_component::linking::metadata::ExportKey, alloc::vec::Vec<(&str, &wit_component::linking::metadata::Export)>>, wit_component::linking::resolve_symbols::{closure#0}> as wit_component::linking::CollectUnique>::collect_unique::<indexmap::map::IndexMap<&str, (&&wit_component::linking::metadata::ExportKey, &alloc::vec::Vec<(&str, &wit_component::linking::metadata::Export)>)>>
Unexecuted instantiation: <core::iter::adapters::filter_map::FilterMap<indexmap::map::iter::Iter<&wit_component::linking::metadata::ExportKey, (&str, &wit_component::linking::metadata::Export)>, wit_component::linking::env_exports::{closure#0}> as wit_component::linking::CollectUnique>::collect_unique::<std::collections::hash::map::HashMap<&str, (&wit_component::linking::metadata::FunctionType, (&str, &wit_component::linking::metadata::Export))>>
Unexecuted instantiation: <core::iter::adapters::map::Map<core::iter::adapters::enumerate::Enumerate<core::slice::iter::Iter<wit_component::linking::EnvExport>>, wit_component::linking::make_env_module::{closure#10}> as wit_component::linking::CollectUnique>::collect_unique::<std::collections::hash::map::HashMap<&str, (u32, bool)>>
Unexecuted instantiation: <core::iter::adapters::map::Map<core::iter::adapters::enumerate::Enumerate<core::slice::iter::Iter<wit_component::linking::metadata::Metadata>>, wit_component::linking::env_exports::{closure#1}> as wit_component::linking::CollectUnique>::collect_unique::<std::collections::hash::map::HashMap<&str, usize>>
Unexecuted instantiation: <core::iter::adapters::map::Map<core::slice::iter::Iter<(alloc::string::String, alloc::vec::Vec<u8>, bool)>, <wit_component::linking::Linker>::encode::{closure#2}> as wit_component::linking::CollectUnique>::collect_unique::<std::collections::hash::set::HashSet<&str>>
Unexecuted instantiation: <core::iter::adapters::map::Map<indexmap::map::iter::IntoIter<&str, indexmap::set::IndexSet<&str>>, wit_component::linking::find_dependencies::{closure#0}> as wit_component::linking::CollectUnique>::collect_unique::<indexmap::map::IndexMap<usize, indexmap::set::IndexSet<usize>>>
Unexecuted instantiation: <core::iter::adapters::map::Map<indexmap::set::iter::IntoIter<&str>, wit_component::linking::find_dependencies::{closure#0}::{closure#0}> as wit_component::linking::CollectUnique>::collect_unique::<indexmap::set::IndexSet<usize>>
432
}
433
434
impl<T: Iterator> CollectUnique for T {}
435
436
/// Extension trait for inserting into a map and asserting that an entry did not already exist for the key
437
trait InsertUnique {
438
    type Key;
439
    type Value;
440
441
    fn insert_unique(&mut self, k: Self::Key, v: Self::Value);
442
}
443
444
impl<K: Hash + Eq + PartialEq + Debug, V: Debug> InsertUnique for HashMap<K, V> {
445
    type Key = K;
446
    type Value = V;
447
448
0
    fn insert_unique(&mut self, k: Self::Key, v: Self::Value) {
449
0
        if let Some(old_v) = self.get(&k) {
450
0
            panic!(
451
                "duplicate item inserted into map for key {k:?} (old value: {old_v:?}; new value: {v:?})"
452
            );
453
0
        }
454
0
        self.insert(k, v);
455
0
    }
Unexecuted instantiation: <std::collections::hash::map::HashMap<&str, usize> as wit_component::linking::InsertUnique>::insert_unique
Unexecuted instantiation: <std::collections::hash::map::HashMap<usize, &str> as wit_component::linking::InsertUnique>::insert_unique
456
}
457
458
/// Synthesize the "main" module for the component, responsible for exporting functions which break cyclic
459
/// dependencies, as well as hosting the memory and function table.
460
0
fn make_env_module<'a>(
461
0
    metadata: &'a [Metadata<'a>],
462
0
    env_exports: &[EnvExport<'_>],
463
0
    cabi_realloc_exporter: Option<&str>,
464
0
    stack_size_bytes: u32,
465
0
    index_type: IndexType,
466
0
) -> (Vec<u8>, DlOpenables<'a>, TlsLayout, u32) {
467
0
    let ptr = index_type.encoder_ptr();
468
    // TODO: deduplicate types
469
0
    let mut types = TypeSection::new();
470
0
    let mut imports = ImportSection::new();
471
0
    let mut import_map = IndexMap::new();
472
0
    let mut function_count = 0;
473
0
    let mut global_offset = 0;
474
0
    let mut wasi_start = None;
475
476
0
    for metadata in metadata {
477
0
        for import in &metadata.imports {
478
0
            if let Entry::Vacant(entry) = import_map.entry(import) {
479
0
                imports.import(
480
0
                    import.module,
481
0
                    import.name,
482
0
                    match &import.ty {
483
0
                        Type::Function(ty) => {
484
0
                            let index = get_and_increment(&mut function_count);
485
0
                            entry.insert(index);
486
0
                            types.ty().function(
487
0
                                ty.parameters.iter().copied().map(ValType::from),
488
0
                                ty.results.iter().copied().map(ValType::from),
489
                            );
490
0
                            EntityType::Function(index)
491
                        }
492
0
                        Type::Global(ty) => {
493
0
                            entry.insert(get_and_increment(&mut global_offset));
494
0
                            EntityType::Global(wasm_encoder::GlobalType {
495
0
                                val_type: ty.ty.into(),
496
0
                                mutable: ty.mutable,
497
0
                                shared: ty.shared,
498
0
                            })
499
                        }
500
0
                        Type::Tag(_) => continue,
501
                    },
502
                );
503
0
            }
504
        }
505
506
0
        if metadata.has_wasi_start {
507
0
            if wasi_start.is_some() {
508
0
                panic!("multiple libraries export {}", metadata::START);
509
0
            }
510
0
            let index = get_and_increment(&mut function_count);
511
512
0
            types.ty().function(vec![], vec![]);
513
0
            imports.import(metadata.name, metadata::START, EntityType::Function(index));
514
515
0
            wasi_start = Some(index);
516
0
        }
517
    }
518
519
0
    let mut memory_offset = stack_size_bytes;
520
521
    // Table offset 0 is reserved for the null function pointer.
522
    // This convention follows wasm-ld's table layout:
523
    // https://github.com/llvm/llvm-project/blob/913622d012f72edb5ac3a501cef8639d0ebe471b/lld/wasm/Driver.cpp#L581-L584
524
0
    let mut table_offset = 1;
525
0
    let mut globals = GlobalSection::new();
526
0
    let mut exports = ExportSection::new();
527
528
0
    if let Some(exporter) = cabi_realloc_exporter {
529
0
        let index = get_and_increment(&mut function_count);
530
0
        types.ty().function([ptr; 4], [ptr]);
531
0
        imports.import(exporter, CABI_REALLOC, EntityType::Function(index));
532
0
        exports.export(CABI_REALLOC, ExportKind::Func, index);
533
0
    }
534
535
    // If tls base shims are being generated, and something might spawn a
536
    // thread, then the shims generated will need access to `context.get 1`.
537
0
    let indirect_tls_base = metadata
538
0
        .iter()
539
0
        .any(|m| m.needs_get_tls_base || m.needs_set_tls_base)
540
0
        && metadata.iter().any(|m| m.uses_thread_new_indirect);
541
0
    let tls_context_get = if indirect_tls_base {
542
0
        let index = get_and_increment(&mut function_count);
543
0
        types.ty().function([], [ptr]);
544
0
        imports.import(
545
0
            metadata::ROOT,
546
0
            metadata::CONTEXT_GET_1,
547
0
            EntityType::Function(index),
548
        );
549
0
        Some(index)
550
    } else {
551
0
        None
552
    };
553
554
    // Note that most globals here are pointers, and thus have the type of
555
    // `index_type`, but `__asyncify_state` is always `i32`.
556
0
    let mut add_global_export = |name: &str, ty: IndexType, value, mutable| {
557
0
        let index = globals.len();
558
0
        globals.global(
559
0
            wasm_encoder::GlobalType {
560
0
                val_type: ty.encoder_ptr(),
561
0
                mutable,
562
0
                shared: false,
563
0
            },
564
0
            &ty.const_expr(value),
565
        );
566
0
        exports.export(name, ExportKind::Global, index);
567
0
    };
568
569
0
    memory_offset = align(memory_offset, index_type.ptr_size());
570
0
    let dl_openables = DlOpenables::new(table_offset, memory_offset, metadata, index_type);
571
572
0
    if metadata.iter().any(|m| m.needs_libdl_libraries) {
573
0
        add_global_export(
574
0
            metadata::LIBDL_LIBRARIES,
575
0
            index_type,
576
0
            dl_openables.libraries_address,
577
0
            true,
578
0
        );
579
0
    }
580
581
0
    table_offset += dl_openables.function_count;
582
0
    memory_offset += u32::try_from(dl_openables.buffer.len()).unwrap();
583
584
0
    let tls = TlsLayout::new(metadata, &mut memory_offset, index_type);
585
586
0
    if metadata.iter().any(|m| m.needs_program_tls_info) {
587
0
        add_global_export(
588
0
            metadata::PROGRAM_TLS_INFO,
589
0
            index_type,
590
0
            tls.program_info,
591
0
            true,
592
0
        );
593
0
    }
594
595
0
    let memory_size = {
596
0
        if metadata.iter().any(|m| m.needs_stack_pointer) {
597
0
            add_global_export(metadata::STACK_POINTER, index_type, stack_size_bytes, true);
598
0
        }
599
0
        if metadata.iter().any(|m| m.needs_init_stack_pointer) {
600
0
            add_global_export(
601
0
                metadata::INIT_STACK_POINTER,
602
0
                index_type,
603
0
                stack_size_bytes,
604
0
                false,
605
0
            );
606
0
        }
607
608
        // Binaryen's Asyncify transform for shared everything linking requires these globals
609
        // to be provided from env module
610
0
        let has_asyncified_module = metadata.iter().any(|m| m.is_asyncified);
611
0
        if has_asyncified_module {
612
0
            add_global_export(metadata::ASYNCIFY_STATE, IndexType::I32, 0, true);
613
0
            add_global_export(metadata::ASYNCIFY_DATA, index_type, 0, true);
614
0
        }
615
616
        // The libc.so in WASI-SDK 28+ requires these:
617
0
        if metadata.iter().any(|m| m.needs_stack_high) {
618
0
            add_global_export(metadata::STACK_HIGH, index_type, stack_size_bytes, true);
619
0
        }
620
0
        if metadata.iter().any(|m| m.needs_stack_low) {
621
0
            add_global_export(metadata::STACK_LOW, index_type, 0, true);
622
0
        }
623
624
0
        for metadata in metadata {
625
0
            memory_offset = align(memory_offset, 1 << metadata.mem_info.memory_alignment);
626
0
            table_offset = align(table_offset, 1 << metadata.mem_info.table_alignment);
627
628
0
            add_global_export(
629
0
                &format!("{}:memory_base", metadata.name),
630
0
                index_type,
631
0
                memory_offset,
632
0
                false,
633
0
            );
634
0
            add_global_export(
635
0
                &format!("{}:table_base", metadata.name),
636
0
                index_type,
637
0
                table_offset,
638
0
                false,
639
0
            );
640
641
0
            memory_offset += metadata.mem_info.memory_size;
642
0
            table_offset += metadata.mem_info.table_size;
643
644
0
            for import in &metadata.memory_address_imports {
645
0
                // Note that we initialize this to zero and let the init module compute the real value at
646
0
                // instantiation time.
647
0
                add_global_export(&format!("{}:{import}", metadata.name), index_type, 0, true);
648
0
            }
649
        }
650
651
        {
652
0
            let offsets = env_exports
653
0
                .iter()
654
0
                .enumerate()
655
0
                .map(|(offset, EnvExport { name, exporter, .. })| {
656
0
                    (
657
0
                        *name,
658
0
                        (
659
0
                            table_offset + u32::try_from(offset).unwrap(),
660
0
                            metadata[*exporter].name == STUB_LIBRARY_NAME,
661
0
                        ),
662
0
                    )
663
0
                })
664
0
                .collect_unique::<HashMap<_, _>>();
665
666
0
            for metadata in metadata {
667
0
                for import in &metadata.table_address_imports {
668
0
                    let &(offset, is_stub) = offsets.get(import).unwrap();
669
0
                    if is_stub
670
0
                        && metadata
671
0
                            .env_imports
672
0
                            .iter()
673
0
                            .any(|e| e.0 == *import && e.1.1.contains(SymbolFlags::BINDING_WEAK))
674
0
                    {
675
0
                        add_global_export(
676
0
                            &format!("{}:{import}", metadata.name),
677
0
                            index_type,
678
0
                            0,
679
0
                            true,
680
0
                        );
681
0
                    } else {
682
0
                        add_global_export(
683
0
                            &format!("{}:{import}", metadata.name),
684
0
                            index_type,
685
0
                            offset,
686
0
                            true,
687
0
                        );
688
0
                    }
689
                }
690
            }
691
        }
692
693
0
        memory_offset = align(memory_offset, HEAP_ALIGNMENT_BYTES);
694
0
        if metadata.iter().any(|m| m.needs_heap_base) {
695
0
            add_global_export(metadata::HEAP_BASE, index_type, memory_offset, true);
696
0
        }
697
698
0
        let heap_end = align(memory_offset, PAGE_SIZE_BYTES);
699
0
        if metadata.iter().any(|m| m.needs_heap_end) {
700
0
            add_global_export(metadata::HEAP_END, index_type, heap_end, true);
701
0
        }
702
0
        heap_end / PAGE_SIZE_BYTES
703
    };
704
705
0
    let indirection_table_base = table_offset;
706
707
0
    let mut functions = FunctionSection::new();
708
0
    let mut code = CodeSection::new();
709
0
    for export in env_exports {
710
0
        let index = get_and_increment(&mut function_count);
711
0
        types.ty().function(
712
0
            export.ty.parameters.iter().copied().map(ValType::from),
713
0
            export.ty.results.iter().copied().map(ValType::from),
714
        );
715
0
        functions.function(u32::try_from(index).unwrap());
716
0
        let mut function = Function::new([]);
717
0
        for local in 0..export.ty.parameters.len() {
718
0
            function
719
0
                .instructions()
720
0
                .local_get(u32::try_from(local).unwrap());
721
0
        }
722
0
        function
723
0
            .instructions()
724
0
            .ptr_uconst(index_type, table_offset)
725
0
            .call_indirect(0, u32::try_from(index).unwrap())
726
0
            .end();
727
0
        code.function(&function);
728
0
        exports.export(export.name, ExportKind::Func, index);
729
730
0
        table_offset += 1;
731
    }
732
733
    // Define a distinct `__wasm_{get,set}_tls_base` pair for each library that
734
    // needs one. Each pair reads and writes that library's slot of the array of
735
    // pointers described by `TlsLayout`.
736
0
    for (index, metadata) in metadata.iter().enumerate() {
737
        // A library with no thread-local storage of its own has no slot in the
738
        // array. If it still imports these then synthesize functions that trap
739
        // since they shouldn't ever be called.
740
0
        let Some(slot) = tls.slot(index) else {
741
0
            for (needed, name, params, results) in [
742
0
                (
743
0
                    metadata.needs_get_tls_base,
744
0
                    metadata::GET_TLS_BASE,
745
0
                    &[][..],
746
0
                    &[ptr][..],
747
0
                ),
748
0
                (
749
0
                    metadata.needs_set_tls_base,
750
0
                    metadata::SET_TLS_BASE,
751
0
                    &[ptr][..],
752
0
                    &[][..],
753
0
                ),
754
0
            ] {
755
0
                if !needed {
756
0
                    continue;
757
0
                }
758
0
                let func = get_and_increment(&mut function_count);
759
0
                types
760
0
                    .ty()
761
0
                    .function(params.iter().copied(), results.iter().copied());
762
0
                functions.function(func);
763
0
                let mut function = Function::new([]);
764
0
                function.instructions().unreachable().end();
765
0
                code.function(&function);
766
0
                exports.export(&format!("{}:{name}", metadata.name), ExportKind::Func, func);
767
            }
768
0
            continue;
769
        };
770
771
0
        let mem_arg = MemArg {
772
0
            offset: u64::from(slot * index_type.ptr_size()),
773
0
            align: index_type.ptr_align_log2(),
774
0
            target: Default::default(),
775
0
            ordering: None,
776
0
        };
777
778
0
        if metadata.needs_get_tls_base {
779
0
            let func = get_and_increment(&mut function_count);
780
0
            types.ty().function([], [ptr]);
781
0
            functions.function(func);
782
0
            let mut function = Function::new([]);
783
            // With coop threads the base pointer is in `context.get 1`. Without
784
            // coop threads the base pointer is `main_thread_tls_base` itself.
785
0
            match tls_context_get {
786
0
                Some(get) => {
787
0
                    function.instructions().call(get);
788
0
                }
789
0
                None => {
790
0
                    function
791
0
                        .instructions()
792
0
                        .ptr_uconst(index_type, tls.main_thread_tls_base);
793
0
                }
794
            }
795
0
            function.instructions().ptr_load(index_type, mem_arg).end();
796
0
            code.function(&function);
797
0
            exports.export(
798
0
                &format!("{}:{}", metadata.name, metadata::GET_TLS_BASE),
799
0
                ExportKind::Func,
800
0
                func,
801
            );
802
0
        }
803
804
0
        if metadata.needs_set_tls_base {
805
0
            let func = get_and_increment(&mut function_count);
806
0
            types.ty().function([ptr], []);
807
0
            functions.function(func);
808
0
            let mut function = Function::new_with_locals_types(if tls_context_get.is_some() {
809
0
                vec![ptr]
810
            } else {
811
0
                vec![]
812
            });
813
            // With coop threads this intrinsic conditionally initializes
814
            // `main_thread_tls_base` based on `context.get 1`. Otherwise it
815
            // writes through to it if it's set.
816
            //
817
            // Without coop threads this is updating `main_thread_tls_base`.
818
0
            match tls_context_get {
819
0
                Some(get) => {
820
0
                    function
821
0
                        .instructions()
822
0
                        .call(get)
823
0
                        .local_tee(1)
824
0
                        .ptr_eqz(index_type)
825
0
                        .if_(wasm_encoder::BlockType::Empty)
826
0
                        .ptr_uconst(index_type, tls.main_thread_tls_base)
827
0
                        .local_get(0)
828
0
                        .ptr_store(index_type, mem_arg)
829
0
                        .else_()
830
0
                        .local_get(1)
831
0
                        .local_get(0)
832
0
                        .ptr_store(index_type, mem_arg)
833
0
                        .end()
834
0
                        .end();
835
0
                }
836
0
                None => {
837
0
                    function
838
0
                        .instructions()
839
0
                        .ptr_uconst(index_type, tls.main_thread_tls_base)
840
0
                        .local_get(0)
841
0
                        .ptr_store(index_type, mem_arg)
842
0
                        .end();
843
0
                }
844
            }
845
0
            code.function(&function);
846
0
            exports.export(
847
0
                &format!("{}:{}", metadata.name, metadata::SET_TLS_BASE),
848
0
                ExportKind::Func,
849
0
                func,
850
            );
851
0
        }
852
    }
853
854
0
    for (import, offset) in import_map {
855
0
        exports.export(
856
0
            &format!("{}:{}", import.module, import.name),
857
0
            ExportKind::from(&import.ty),
858
0
            offset,
859
0
        );
860
0
    }
861
0
    if let Some(index) = wasi_start {
862
0
        exports.export(metadata::START, ExportKind::Func, index);
863
0
    }
864
865
0
    let mut module = Module::new();
866
867
0
    module.section(&types);
868
0
    module.section(&imports);
869
0
    module.section(&functions);
870
871
0
    {
872
0
        let mut tables = TableSection::new();
873
0
        tables.table(TableType {
874
0
            element_type: RefType::FUNCREF,
875
0
            minimum: table_offset.into(),
876
0
            maximum: None,
877
0
            table64: index_type == IndexType::I64,
878
0
            shared: false,
879
0
        });
880
0
        exports.export(metadata::INDIRECT_FUNCTION_TABLE, ExportKind::Table, 0);
881
0
        module.section(&tables);
882
0
    }
883
884
0
    {
885
0
        let mut memories = MemorySection::new();
886
0
        memories.memory(MemoryType {
887
0
            minimum: u64::from(memory_size),
888
0
            maximum: None,
889
0
            memory64: index_type == IndexType::I64,
890
0
            shared: false,
891
0
            page_size_log2: None,
892
0
        });
893
0
        exports.export(metadata::MEMORY, ExportKind::Memory, 0);
894
0
        module.section(&memories);
895
0
    }
896
897
0
    module.section(&globals);
898
0
    module.section(&exports);
899
0
    module.section(&code);
900
0
    module.section(&RawCustomSection(
901
0
        &crate::base_producers().raw_custom_section(),
902
0
    ));
903
904
0
    let module = module.finish();
905
0
    wasmparser::validate(&module).unwrap();
906
907
0
    (module, dl_openables, tls, indirection_table_base)
908
0
}
909
910
/// Synthesize the "init" module, responsible for initializing global variables per the dynamic linking tool
911
/// convention and calling any static constructors and/or link-time fixup functions.
912
///
913
/// This module also contains the data segment for the `dlopen`/`dlsym` lookup table.
914
0
fn make_init_module(
915
0
    fixups: &mut FixupModule,
916
0
    metadata: &[Metadata],
917
0
    exporters: &IndexMap<&ExportKey, (&str, &Export)>,
918
0
    env_exports: &[EnvExport<'_>],
919
0
    dl_openables: &DlOpenables,
920
0
    tls: &TlsLayout,
921
0
    indirection_table_base: u32,
922
0
    index_type: IndexType,
923
0
) -> Result<()> {
924
0
    let thunk_ty = fixups.type_thunk();
925
0
    let memory = fixups.import(
926
0
        &ImportedInstance::Main,
927
0
        metadata::MEMORY,
928
0
        MemoryType {
929
0
            minimum: 0,
930
0
            maximum: None,
931
0
            memory64: index_type == IndexType::I64,
932
0
            shared: false,
933
0
            page_size_log2: None,
934
0
        }
935
0
        .into(),
936
0
    )?;
937
0
    let table = fixups.import(
938
0
        &ImportedInstance::Main,
939
0
        metadata::INDIRECT_FUNCTION_TABLE,
940
0
        TableType {
941
0
            element_type: RefType::FUNCREF,
942
0
            minimum: 0,
943
0
            maximum: None,
944
0
            table64: index_type == IndexType::I64,
945
0
            shared: false,
946
0
        }
947
0
        .into(),
948
0
    )?;
949
950
0
    let module_name_to_instance = |module: &str| match module {
951
0
        metadata::ENV => ImportedInstance::Main,
952
0
        other => ImportedInstance::Adapter(other.to_string()),
953
0
    };
954
955
0
    let mut global_map = HashMap::new();
956
0
    let mut add_global_import = |fixups: &mut FixupModule, module: &str, name: &str, mutable| {
957
0
        *global_map
958
0
            .entry((module.to_owned(), name.to_owned()))
959
0
            .or_insert_with(|| {
960
0
                fixups
961
0
                    .import_global(
962
0
                        &module_name_to_instance(module),
963
0
                        name,
964
0
                        wasm_encoder::GlobalType {
965
0
                            val_type: index_type.encoder_ptr(),
966
0
                            mutable,
967
0
                            shared: false,
968
0
                        },
969
                    )
970
0
                    .unwrap()
971
0
            })
972
0
    };
973
974
0
    let mut function_map = HashMap::new();
975
0
    let mut add_function_import = |fixups: &mut FixupModule, module: &str, name: &str, ty| {
976
0
        *function_map
977
0
            .entry((module.to_owned(), name.to_owned()))
978
0
            .or_insert_with(|| {
979
0
                fixups
980
0
                    .import_func(&module_name_to_instance(module), name, ty)
981
0
                    .unwrap()
982
0
            })
983
0
    };
984
985
0
    let mut names = HashMap::new();
986
0
    for (index, metadata) in metadata.iter().enumerate() {
987
0
        names.insert_unique(index, metadata.name);
988
0
    }
989
990
0
    for (exporter, export, address) in dl_openables.global_addresses.iter() {
991
0
        let memory_base = add_global_import(
992
0
            fixups,
993
0
            metadata::ENV,
994
0
            &format!("{exporter}:memory_base"),
995
0
            false,
996
0
        );
997
0
        let export = add_global_import(fixups, exporter, export, false);
998
0
999
0
        fixups.add_start_abi_detail(StartAction::InitializeAddress {
1000
0
            memory_base,
1001
0
            export,
1002
0
            dest: AddressDest::LinearMemory {
1003
0
                address: *address,
1004
0
                memory,
1005
0
            },
1006
0
        });
1007
0
    }
1008
1009
0
    for metadata in metadata {
1010
0
        for import in &metadata.memory_address_imports {
1011
0
            let (exporter, _) = find_offset_exporter(import, exporters, index_type)?;
1012
1013
0
            let memory_base = add_global_import(
1014
0
                fixups,
1015
0
                metadata::ENV,
1016
0
                &format!("{exporter}:memory_base"),
1017
0
                false,
1018
0
            );
1019
0
            let offset = add_global_import(fixups, exporter, import, false);
1020
0
            let address = add_global_import(
1021
0
                fixups,
1022
0
                metadata::ENV,
1023
0
                &format!("{}:{import}", metadata.name),
1024
0
                true,
1025
0
            );
1026
0
            fixups.add_start_abi_detail(StartAction::InitializeAddress {
1027
0
                memory_base,
1028
0
                export: offset,
1029
0
                dest: AddressDest::Global(address),
1030
0
            });
1031
        }
1032
    }
1033
1034
0
    for metadata in metadata {
1035
0
        if metadata.has_data_relocs {
1036
0
            let func =
1037
0
                add_function_import(fixups, metadata.name, metadata::APPLY_DATA_RELOCS, thunk_ty);
1038
0
            fixups.add_start_abi_detail(StartAction::Call(func));
1039
0
        }
1040
    }
1041
1042
0
    for metadata in metadata {
1043
0
        if metadata.has_ctors && metadata.has_initialize {
1044
0
            bail!(
1045
                "library {} exports both `{}` and `{}`; \
1046
                 expected at most one of the two",
1047
                metadata.name,
1048
                metadata::CALL_CTORS,
1049
                metadata::INITIALIZE
1050
            );
1051
0
        }
1052
1053
0
        if metadata.has_ctors {
1054
0
            let func = add_function_import(fixups, metadata.name, metadata::CALL_CTORS, thunk_ty);
1055
0
            fixups.add_start_user_func(StartAction::Call(func));
1056
0
        }
1057
1058
0
        if metadata.has_initialize {
1059
0
            let func = add_function_import(fixups, metadata.name, metadata::INITIALIZE, thunk_ty);
1060
0
            fixups.add_start_user_func(StartAction::Call(func));
1061
0
        }
1062
    }
1063
1064
0
    let intern_type = |fixups: &mut FixupModule, ty: &FunctionType| {
1065
0
        fixups.type_intern(
1066
0
            ty.parameters.iter().copied().map(|t| t.into()).collect(),
1067
0
            ty.results.iter().copied().map(|t| t.into()).collect(),
1068
        )
1069
0
    };
1070
1071
0
    let mut dl_openable_functions = Vec::new();
1072
0
    for metadata in metadata {
1073
0
        if metadata.dl_openable {
1074
0
            for export in &metadata.exports {
1075
0
                if let Type::Function(fty) = &export.key.ty {
1076
0
                    let ty = intern_type(fixups, fty);
1077
0
                    dl_openable_functions.push(add_function_import(
1078
0
                        fixups,
1079
0
                        metadata.name,
1080
0
                        export.key.name,
1081
0
                        ty,
1082
0
                    ));
1083
0
                }
1084
            }
1085
0
        }
1086
    }
1087
1088
0
    let indirections = env_exports
1089
0
        .iter()
1090
0
        .map(|EnvExport { name, exporter, ty }| {
1091
0
            let ty = intern_type(fixups, ty);
1092
0
            add_function_import(fixups, names[exporter], name, ty)
1093
0
        })
1094
0
        .collect::<Vec<_>>();
1095
1096
    // For all libraries that export TLS information the initialization function
1097
    // here will setup the in-memory `__wasm_program_tls_info` structure by
1098
    // storing the pointers to each `__wasm_library_tls_info` structure in a
1099
    // sequence.
1100
0
    if tls.library_info != 0 {
1101
0
        for (lib_index, tls_index) in tls
1102
0
            .slots
1103
0
            .iter()
1104
0
            .enumerate()
1105
0
            .filter_map(|(i, slot)| slot.map(|j| (i, j)))
1106
0
        {
1107
0
            let metadata = &metadata[lib_index];
1108
0
            let memory_base = add_global_import(
1109
0
                fixups,
1110
0
                metadata::ENV,
1111
0
                &format!("{}:memory_base", metadata.name),
1112
0
                false,
1113
0
            );
1114
0
            let i = add_global_import(fixups, metadata.name, metadata::LIBRARY_TLS_INFO, false);
1115
0
1116
0
            fixups.add_start_abi_detail(StartAction::InitializeAddress {
1117
0
                memory_base,
1118
0
                export: i,
1119
0
                dest: AddressDest::LinearMemory {
1120
0
                    address: tls.library_info + tls_index * index_type.ptr_size(),
1121
0
                    memory,
1122
0
                },
1123
0
            });
1124
0
        }
1125
0
    }
1126
1127
0
    fixups.elements().active(
1128
0
        if table == 0 { None } else { Some(table) },
1129
0
        &index_type.const_expr(dl_openables.table_base),
1130
0
        Elements::Functions(dl_openable_functions.into()),
1131
    );
1132
0
    fixups.elements().active(
1133
0
        if table == 0 { None } else { Some(table) },
1134
0
        &index_type.const_expr(indirection_table_base),
1135
0
        Elements::Functions(indirections.into()),
1136
    );
1137
1138
0
    let data = fixups.data();
1139
0
    data.active(
1140
0
        memory,
1141
0
        &index_type.const_expr(dl_openables.memory_base),
1142
0
        dl_openables.buffer.clone(),
1143
    );
1144
0
    if !tls.buffer.is_empty() {
1145
0
        data.active(
1146
0
            memory,
1147
0
            &index_type.const_expr(tls.program_info),
1148
0
            tls.buffer.clone(),
1149
0
        );
1150
0
    }
1151
1152
0
    Ok(())
1153
0
}
1154
1155
/// Find the library which exports the specified function or global address.
1156
0
fn find_offset_exporter<'a>(
1157
0
    name: &str,
1158
0
    exporters: &IndexMap<&ExportKey, (&'a str, &'a Export<'a>)>,
1159
0
    index_type: IndexType,
1160
0
) -> Result<(&'a str, &'a Export<'a>)> {
1161
0
    let export = ExportKey {
1162
0
        name,
1163
0
        ty: Type::Global(GlobalType {
1164
0
            ty: index_type.into(),
1165
0
            mutable: false,
1166
0
            shared: false,
1167
0
        }),
1168
0
    };
1169
1170
0
    exporters
1171
0
        .get(&export)
1172
0
        .copied()
1173
0
        .ok_or_else(|| anyhow!("unable to find {export:?} in any library"))
1174
0
}
1175
1176
/// Find the library which exports the specified function.
1177
0
fn find_function_exporter<'a>(
1178
0
    name: &str,
1179
0
    ty: &FunctionType,
1180
0
    exporters: &IndexMap<&ExportKey, (&'a str, &'a Export<'a>)>,
1181
0
) -> Result<(&'a str, &'a Export<'a>)> {
1182
0
    let export = ExportKey {
1183
0
        name,
1184
0
        ty: Type::Function(ty.clone()),
1185
0
    };
1186
1187
0
    exporters
1188
0
        .get(&export)
1189
0
        .copied()
1190
0
        .ok_or_else(|| anyhow!("unable to find {export:?} in any library"))
1191
0
}
1192
1193
/// Find the library which exports the specified tag.
1194
0
fn find_tag_exporter<'a>(
1195
0
    name: &str,
1196
0
    ty: &FunctionType,
1197
0
    exporters: &IndexMap<&ExportKey, (&'a str, &'a Export<'a>)>,
1198
0
) -> Result<(&'a str, &'a Export<'a>)> {
1199
0
    let export = ExportKey {
1200
0
        name,
1201
0
        ty: Type::Tag(ty.clone()),
1202
0
    };
1203
1204
0
    exporters
1205
0
        .get(&export)
1206
0
        .copied()
1207
0
        .ok_or_else(|| anyhow!("unable to find {export:?} in any library"))
1208
0
}
1209
1210
/// Analyze the specified library metadata, producing a symbol-to-library-name map of exports.
1211
0
fn resolve_exporters<'a>(
1212
0
    metadata: &'a [Metadata<'a>],
1213
0
) -> Result<IndexMap<&'a ExportKey<'a>, Vec<(&'a str, &'a Export<'a>)>>> {
1214
0
    let mut exporters = IndexMap::<_, Vec<_>>::new();
1215
0
    for metadata in metadata {
1216
0
        for export in &metadata.exports {
1217
0
            exporters
1218
0
                .entry(&export.key)
1219
0
                .or_default()
1220
0
                .push((metadata.name, export));
1221
0
        }
1222
    }
1223
0
    Ok(exporters)
1224
0
}
1225
1226
/// Match up all imported symbols to their corresponding exports, reporting any missing or duplicate symbols.
1227
0
fn resolve_symbols<'a>(
1228
0
    metadata: &'a [Metadata<'a>],
1229
0
    exporters: &'a IndexMap<&'a ExportKey<'a>, Vec<(&'a str, &'a Export<'a>)>>,
1230
0
    index_type: IndexType,
1231
0
) -> (
1232
0
    IndexMap<&'a ExportKey<'a>, (&'a str, &'a Export<'a>)>,
1233
0
    Vec<(&'a str, Export<'a>)>,
1234
0
    Vec<(&'a str, &'a ExportKey<'a>, &'a [(&'a str, &'a Export<'a>)])>,
1235
0
) {
1236
0
    let function_exporters = exporters
1237
0
        .iter()
1238
0
        .filter_map(|(export, exporters)| match &export.ty {
1239
0
            Type::Function(_) => Some((export.name, (export, exporters))),
1240
0
            Type::Global(_) | Type::Tag(_) => None,
1241
0
        })
1242
0
        .collect_unique::<IndexMap<_, _>>();
1243
1244
0
    let mut resolved = IndexMap::new();
1245
0
    let mut missing = Vec::new();
1246
0
    let mut duplicates = Vec::new();
1247
1248
0
    let mut triage = |metadata: &'a Metadata, export: Export<'a>| {
1249
0
        if let Some((key, value)) = exporters.get_key_value(&export.key) {
1250
            // Note that we do not use `insert_unique` here since multiple libraries may import the same
1251
            // symbol, in which case we may redundantly insert the same value.
1252
0
            match value.as_slice() {
1253
0
                [] => unreachable!(),
1254
0
                [exporter] => {
1255
0
                    resolved.insert(*key, *exporter);
1256
0
                }
1257
0
                [exporter, ..] => {
1258
0
                    resolved.insert(*key, *exporter);
1259
0
                    duplicates.push((metadata.name, *key, value.as_slice()));
1260
0
                }
1261
            }
1262
0
        } else {
1263
0
            missing.push((metadata.name, export));
1264
0
        }
1265
0
    };
1266
1267
0
    for metadata in metadata {
1268
0
        for (name, (ty, flags)) in &metadata.env_imports {
1269
0
            triage(
1270
0
                metadata,
1271
0
                Export {
1272
0
                    key: ExportKey {
1273
0
                        name,
1274
0
                        ty: Type::Function(ty.clone()),
1275
0
                    },
1276
0
                    flags: *flags,
1277
0
                },
1278
0
            );
1279
0
        }
1280
1281
0
        for name in &metadata.memory_address_imports {
1282
0
            triage(
1283
0
                metadata,
1284
0
                Export {
1285
0
                    key: ExportKey {
1286
0
                        name,
1287
0
                        ty: Type::Global(GlobalType {
1288
0
                            ty: index_type.into(),
1289
0
                            mutable: false,
1290
0
                            shared: false,
1291
0
                        }),
1292
0
                    },
1293
0
                    flags: SymbolFlags::empty(),
1294
0
                },
1295
0
            );
1296
0
        }
1297
1298
0
        for (name, ty) in &metadata.tag_imports {
1299
0
            triage(
1300
0
                metadata,
1301
0
                Export {
1302
0
                    key: ExportKey {
1303
0
                        name,
1304
0
                        ty: Type::Tag(ty.clone()),
1305
0
                    },
1306
0
                    flags: SymbolFlags::empty(),
1307
0
                },
1308
0
            );
1309
0
        }
1310
    }
1311
1312
0
    for metadata in metadata {
1313
0
        for name in &metadata.table_address_imports {
1314
0
            if let Some((key, value)) = function_exporters.get(name) {
1315
                // Note that we do not use `insert_unique` here since multiple libraries may import the same
1316
                // symbol, in which case we may redundantly insert the same value.
1317
0
                match value.as_slice() {
1318
0
                    [] => unreachable!(),
1319
0
                    [exporter] => {
1320
0
                        resolved.insert(key, *exporter);
1321
0
                    }
1322
0
                    [exporter, ..] => {
1323
0
                        resolved.insert(key, *exporter);
1324
0
                        duplicates.push((metadata.name, *key, value.as_slice()));
1325
0
                    }
1326
                }
1327
0
            } else if metadata.env_imports.iter().any(|(n, _)| n == name) {
1328
0
                // GOT entry for a function which is imported from the env module, but not exported by any library,
1329
0
                // already handled above.
1330
0
            } else {
1331
0
                missing.push((
1332
0
                    metadata.name,
1333
0
                    Export {
1334
0
                        key: ExportKey {
1335
0
                            name,
1336
0
                            ty: Type::Function(FunctionType {
1337
0
                                parameters: Vec::new(),
1338
0
                                results: Vec::new(),
1339
0
                            }),
1340
0
                        },
1341
0
                        flags: SymbolFlags::empty(),
1342
0
                    },
1343
0
                ));
1344
0
            }
1345
        }
1346
    }
1347
1348
    // Even if no library imports these symbols, we re-export them from the
1349
    // `env` module so that
1350
    // `EncodingState::create_export_task_initialization_wrappers` can find
1351
    // and use them:
1352
0
    for (name, params, results) in ENV_REEXPORTS {
1353
0
        let export = Export {
1354
0
            key: ExportKey {
1355
0
                name,
1356
0
                ty: Type::Function(FunctionType {
1357
0
                    parameters: params.to_vec(),
1358
0
                    results: results.to_vec(),
1359
0
                }),
1360
0
            },
1361
0
            flags: SymbolFlags::empty(),
1362
0
        };
1363
1364
0
        if let Some((key, value)) = exporters.get_key_value(&export.key) {
1365
            // Note that we do not use `insert_unique` here since multiple
1366
            // libraries may import the same symbol, in which case we may
1367
            // redundantly insert the same value.
1368
0
            match value.as_slice() {
1369
0
                [] => unreachable!(),
1370
0
                [exporter] | [exporter, ..] => {
1371
0
                    resolved.insert(*key, *exporter);
1372
0
                }
1373
            }
1374
0
        }
1375
    }
1376
1377
0
    (resolved, missing, duplicates)
1378
0
}
1379
1380
/// Recursively add a library (represented by its offset) and its dependency to the specified set, maintaining
1381
/// topological order (modulo cycles).
1382
0
fn topo_add(
1383
0
    sorted: &mut IndexSet<usize>,
1384
0
    dependencies: &IndexMap<usize, IndexSet<usize>>,
1385
0
    element: usize,
1386
0
) {
1387
0
    let empty = &IndexSet::new();
1388
0
    let deps = dependencies.get(&element).unwrap_or(empty);
1389
1390
    // First, add any dependencies which do not depend on `element`
1391
0
    for &dep in deps {
1392
0
        if !(sorted.contains(&dep) || dependencies.get(&dep).unwrap_or(empty).contains(&element)) {
1393
0
            topo_add(sorted, dependencies, dep);
1394
0
        }
1395
    }
1396
1397
    // Next, add the element
1398
0
    sorted.insert(element);
1399
1400
    // Finally, add any dependencies which depend on `element`
1401
0
    for &dep in deps {
1402
0
        if !sorted.contains(&dep) && dependencies.get(&dep).unwrap_or(empty).contains(&element) {
1403
0
            topo_add(sorted, dependencies, dep);
1404
0
        }
1405
    }
1406
0
}
1407
1408
/// Topologically sort a set of libraries (represented by their offsets) according to their dependencies, modulo
1409
/// cycles.
1410
0
fn topo_sort(count: usize, dependencies: &IndexMap<usize, IndexSet<usize>>) -> Result<Vec<usize>> {
1411
0
    let mut sorted = IndexSet::new();
1412
0
    for index in 0..count {
1413
0
        topo_add(&mut sorted, &dependencies, index);
1414
0
    }
1415
1416
0
    Ok(sorted.into_iter().collect())
1417
0
}
1418
1419
/// Analyze the specified library metadata, producing a map of transitive dependencies, where each library is
1420
/// represented by its offset in the original metadata slice.
1421
0
fn find_dependencies(
1422
0
    metadata: &[Metadata],
1423
0
    exporters: &IndexMap<&ExportKey, (&str, &Export)>,
1424
0
) -> Result<IndexMap<usize, IndexSet<usize>>> {
1425
    // First, generate a map of direct dependencies (i.e. depender to dependees)
1426
0
    let mut dependencies = IndexMap::<_, IndexSet<_>>::new();
1427
0
    let mut indexes = HashMap::new();
1428
0
    for (index, metadata) in metadata.iter().enumerate() {
1429
0
        indexes.insert_unique(metadata.name, index);
1430
0
        for &needed in &metadata.needed_libs {
1431
0
            dependencies
1432
0
                .entry(metadata.name)
1433
0
                .or_default()
1434
0
                .insert(needed);
1435
0
        }
1436
0
        for (import_name, (ty, _)) in &metadata.env_imports {
1437
0
            dependencies
1438
0
                .entry(metadata.name)
1439
0
                .or_default()
1440
0
                .insert(find_function_exporter(import_name, ty, exporters)?.0);
1441
        }
1442
    }
1443
1444
    // Next, convert the map from names to offsets
1445
0
    let mut dependencies = dependencies
1446
0
        .into_iter()
1447
0
        .map(|(k, v)| {
1448
            (
1449
0
                indexes[k],
1450
0
                v.into_iter()
1451
0
                    .map(|v| indexes[v])
1452
0
                    .collect_unique::<IndexSet<_>>(),
1453
            )
1454
0
        })
1455
0
        .collect_unique::<IndexMap<_, _>>();
1456
1457
    // Finally, add all transitive dependencies to the map in a fixpoint loop, exiting when no new dependencies are
1458
    // discovered.
1459
0
    let empty = &IndexSet::new();
1460
1461
    loop {
1462
0
        let mut new = IndexMap::<_, IndexSet<_>>::new();
1463
0
        for (index, exporters) in &dependencies {
1464
0
            for exporter in exporters {
1465
0
                for exporter in dependencies.get(exporter).unwrap_or(empty) {
1466
0
                    if !exporters.contains(exporter) {
1467
0
                        new.entry(*index).or_default().insert(*exporter);
1468
0
                    }
1469
                }
1470
            }
1471
        }
1472
1473
0
        if new.is_empty() {
1474
0
            break Ok(dependencies);
1475
        } else {
1476
0
            for (index, exporters) in new {
1477
0
                dependencies.entry(index).or_default().extend(exporters);
1478
0
            }
1479
        }
1480
    }
1481
0
}
1482
1483
struct EnvExports<'a> {
1484
    exports: Vec<EnvExport<'a>>,
1485
    reexport_cabi_realloc: bool,
1486
}
1487
1488
struct EnvExport<'a> {
1489
    name: &'a str,
1490
    ty: Cow<'a, FunctionType>,
1491
    exporter: usize,
1492
}
1493
1494
/// Analyze the specified metadata and generate what needs to be exported from
1495
/// the main (aka "env") module.
1496
///
1497
/// This includes a list of functions which should be re-exported as a
1498
/// `call.indirect`-based function including the offset of the library
1499
/// containing the original export.
1500
///
1501
/// Additionally this includes any tags necessary that are shared amongst
1502
/// modules.
1503
0
fn env_exports<'a>(
1504
0
    metadata: &'a [Metadata<'a>],
1505
0
    exporters: &'a IndexMap<&'a ExportKey, (&'a str, &Export)>,
1506
0
    topo_sorted: &[usize],
1507
0
) -> Result<EnvExports<'a>> {
1508
0
    let function_exporters = exporters
1509
0
        .iter()
1510
0
        .filter_map(|(export, exporter)| {
1511
0
            if let Type::Function(ty) = &export.ty {
1512
0
                Some((export.name, (ty, *exporter)))
1513
            } else {
1514
0
                None
1515
            }
1516
0
        })
1517
0
        .collect_unique::<HashMap<_, _>>();
1518
1519
0
    let indexes = metadata
1520
0
        .iter()
1521
0
        .enumerate()
1522
0
        .map(|(index, metadata)| (metadata.name, index))
1523
0
        .collect_unique::<HashMap<_, _>>();
1524
1525
0
    let mut result = Vec::new();
1526
0
    let mut exported = HashSet::new();
1527
0
    let mut seen = HashSet::new();
1528
1529
0
    for &index in topo_sorted {
1530
0
        let metadata = &metadata[index];
1531
1532
0
        for name in &metadata.table_address_imports {
1533
0
            if !exported.contains(name) {
1534
0
                let (ty, (exporter, _)) = function_exporters
1535
0
                    .get(name)
1536
0
                    .ok_or_else(|| anyhow!("unable to find {name:?} in any library"))?;
1537
1538
0
                result.push(EnvExport {
1539
0
                    name: *name,
1540
0
                    ty: Cow::Borrowed(*ty),
1541
0
                    exporter: indexes[exporter],
1542
0
                });
1543
0
                exported.insert(*name);
1544
0
            }
1545
        }
1546
1547
0
        for (import_name, (ty, _)) in &metadata.env_imports {
1548
0
            if !exported.contains(import_name) {
1549
0
                let exporter = indexes[find_function_exporter(import_name, ty, exporters)
1550
0
                    .unwrap()
1551
0
                    .0];
1552
0
                if !seen.contains(&exporter) {
1553
0
                    result.push(EnvExport {
1554
0
                        name: *import_name,
1555
0
                        ty: Cow::Borrowed(ty),
1556
0
                        exporter,
1557
0
                    });
1558
0
                    exported.insert(*import_name);
1559
0
                }
1560
0
            }
1561
        }
1562
1563
0
        seen.insert(index);
1564
    }
1565
1566
    // Even if no library imports these symbols, we re-export them from the
1567
    // `env` module so that
1568
    // `EncodingState::create_export_task_initialization_wrappers` can find
1569
    // and use them:
1570
0
    for (name, params, results) in ENV_REEXPORTS {
1571
0
        if !exported.contains(name) {
1572
0
            let ty = FunctionType {
1573
0
                parameters: params.to_vec(),
1574
0
                results: results.to_vec(),
1575
0
            };
1576
0
            if let Some(exporter) = exporters.get(&ExportKey {
1577
0
                name,
1578
0
                ty: Type::Function(ty.clone()),
1579
0
            }) {
1580
0
                result.push(EnvExport {
1581
0
                    name,
1582
0
                    ty: Cow::Owned(ty),
1583
0
                    exporter: indexes[exporter.0],
1584
0
                });
1585
0
                exported.insert(name);
1586
0
            }
1587
0
        }
1588
    }
1589
1590
0
    let reexport_cabi_realloc = exported.contains(CABI_REALLOC);
1591
1592
0
    Ok(EnvExports {
1593
0
        exports: result,
1594
0
        reexport_cabi_realloc,
1595
0
    })
1596
0
}
1597
1598
/// Synthesize a module which contains trapping stub exports for the specified functions.
1599
0
fn make_stubs_module(missing: &[(&str, Export)]) -> Vec<u8> {
1600
0
    let mut types = TypeSection::new();
1601
0
    let mut exports = ExportSection::new();
1602
0
    let mut functions = FunctionSection::new();
1603
0
    let mut code = CodeSection::new();
1604
0
    for (offset, (_, export)) in missing.iter().enumerate() {
1605
0
        let offset = u32::try_from(offset).unwrap();
1606
1607
        let Export {
1608
            key:
1609
                ExportKey {
1610
0
                    name,
1611
0
                    ty: Type::Function(ty),
1612
                },
1613
            ..
1614
0
        } = export
1615
        else {
1616
0
            unreachable!();
1617
        };
1618
1619
0
        types.ty().function(
1620
0
            ty.parameters.iter().copied().map(ValType::from),
1621
0
            ty.results.iter().copied().map(ValType::from),
1622
        );
1623
0
        functions.function(offset);
1624
0
        let mut function = Function::new([]);
1625
0
        function.instructions().unreachable().end();
1626
0
        code.function(&function);
1627
0
        exports.export(name, ExportKind::Func, offset);
1628
    }
1629
1630
0
    let mut module = Module::new();
1631
1632
0
    module.section(&types);
1633
0
    module.section(&functions);
1634
0
    module.section(&exports);
1635
0
    module.section(&code);
1636
0
    module.section(&RawCustomSection(
1637
0
        &crate::base_producers().raw_custom_section(),
1638
0
    ));
1639
1640
0
    let module = module.finish();
1641
0
    wasmparser::validate(&module).unwrap();
1642
1643
0
    module
1644
0
}
1645
1646
/// Determine which of the specified libraries are transitively reachable at runtime, i.e. reachable from a
1647
/// component export or via `dlopen`.
1648
0
fn find_reachable<'a>(
1649
0
    metadata: &'a [Metadata<'a>],
1650
0
    dependencies: &IndexMap<usize, IndexSet<usize>>,
1651
0
) -> IndexSet<&'a str> {
1652
0
    let reachable = metadata
1653
0
        .iter()
1654
0
        .enumerate()
1655
0
        .filter_map(|(index, metadata)| {
1656
0
            if metadata.has_component_exports || metadata.dl_openable || metadata.has_wasi_start {
1657
0
                Some(index)
1658
            } else {
1659
0
                None
1660
            }
1661
0
        })
1662
0
        .collect_unique::<IndexSet<_>>();
1663
1664
0
    let empty = &IndexSet::new();
1665
1666
0
    reachable
1667
0
        .iter()
1668
0
        .chain(
1669
0
            reachable
1670
0
                .iter()
1671
0
                .flat_map(|index| dependencies.get(index).unwrap_or(empty)),
1672
        )
1673
0
        .map(|&index| metadata[index].name)
1674
0
        .collect()
1675
0
}
1676
1677
/// Determines the index type of the linear memory shared by all libraries in
1678
/// `metadata`, returning an error if they disagree.
1679
///
1680
/// Libraries which don't say either way are compatible with any index type,
1681
/// and if no library says either way then 32-bit memory is used.
1682
0
fn linked_index_type(metadata: &[Metadata]) -> Result<IndexType> {
1683
0
    let mut found: Option<(&str, IndexType)> = None;
1684
0
    for metadata in metadata {
1685
0
        let Some(ty) = metadata.index_type else {
1686
0
            continue;
1687
        };
1688
0
        match found {
1689
0
            None => found = Some((metadata.name, ty)),
1690
0
            Some((_, prev)) if prev == ty => {}
1691
0
            Some((prev_name, prev)) => bail!(
1692
                "library `{}` uses a linear memory index type of `{ty}` but \
1693
                 library `{prev_name}` uses `{prev}`; all libraries must use the same index type",
1694
                metadata.name,
1695
            ),
1696
        }
1697
    }
1698
0
    Ok(found.map(|(_, ty)| ty).unwrap_or_default())
1699
0
}
1700
1701
/// Builder type for composing dynamic library modules into a component
1702
#[derive(Default)]
1703
pub struct Linker {
1704
    /// The `(name, module, dl_openable)` triple representing the libraries to be composed
1705
    ///
1706
    /// The order of this list determines priority in cases where more than one library exports the same symbol.
1707
    libraries: Vec<(String, Vec<u8>, bool)>,
1708
1709
    /// Whether to generate trapping stubs for any unresolved imports
1710
    stub_missing_functions: bool,
1711
1712
    /// Whether to use a built-in implementation of `dlopen`/`dlsym`.
1713
    use_built_in_libdl: bool,
1714
1715
    /// Size of stack (in bytes) to allocate in the synthesized main module
1716
    ///
1717
    /// If `None`, use `DEFAULT_STACK_SIZE_BYTES`.
1718
    stack_size: Option<u32>,
1719
1720
    encoder: ComponentEncoder,
1721
}
1722
1723
impl Linker {
1724
    /// Add a dynamic library module to this linker.
1725
    ///
1726
    /// If `dl_openable` is true, all of the library's exports will be added to the `dlopen`/`dlsym` lookup table
1727
    /// for runtime resolution.
1728
0
    pub fn library(&mut self, name: &str, module: &[u8], dl_openable: bool) -> Result<&mut Self> {
1729
0
        self.libraries
1730
0
            .push((name.to_owned(), module.to_vec(), dl_openable));
1731
1732
0
        Ok(self)
1733
0
    }
1734
1735
    /// Specify size of stack to allocate in the synthesized main module
1736
0
    pub fn stack_size(&mut self, stack_size: u32) -> &mut Self {
1737
0
        self.stack_size = Some(stack_size);
1738
0
        self
1739
0
    }
1740
1741
    /// Specify whether to generate trapping stubs for any unresolved imports
1742
0
    pub fn stub_missing_functions(&mut self, stub_missing_functions: bool) -> &mut Self {
1743
0
        self.stub_missing_functions = stub_missing_functions;
1744
0
        self
1745
0
    }
1746
1747
    /// Specify whether to use a built-in implementation of `dlopen`/`dlsym`.
1748
0
    pub fn use_built_in_libdl(&mut self, use_built_in_libdl: bool) -> &mut Self {
1749
0
        self.use_built_in_libdl = use_built_in_libdl;
1750
0
        self
1751
0
    }
1752
1753
    /// Returns a reference to the internal [`ComponentEncoder`] that can be
1754
    /// configured.
1755
0
    pub fn encoder(&mut self) -> &mut ComponentEncoder {
1756
0
        &mut self.encoder
1757
0
    }
1758
1759
    /// Encode the component and return the bytes
1760
0
    pub fn encode(mut self) -> Result<Vec<u8>> {
1761
0
        let adapter_names = self
1762
0
            .encoder
1763
0
            .adapters
1764
0
            .keys()
1765
0
            .map(|name| name.as_str())
1766
0
            .collect::<HashSet<_>>();
1767
1768
0
        let metadata = self
1769
0
            .libraries
1770
0
            .iter()
1771
0
            .map(|(name, module, dl_openable)| {
1772
0
                Metadata::try_new(name, *dl_openable, module, &adapter_names)
1773
0
                    .with_context(|| format!("failed to extract linking metadata from {name}"))
1774
0
            })
1775
0
            .collect::<Result<Vec<_>>>()?;
1776
1777
0
        let index_type = linked_index_type(&metadata)?;
1778
1779
0
        if self.use_built_in_libdl {
1780
0
            self.use_built_in_libdl = false;
1781
0
            let libdl: &[u8] = match index_type {
1782
0
                IndexType::I32 => include_bytes!("../libdl32.so"),
1783
0
                IndexType::I64 => include_bytes!("../libdl64.so"),
1784
            };
1785
0
            self.library("libdl.so", libdl, false)?;
1786
0
            return self.encode();
1787
0
        }
1788
1789
        {
1790
0
            let names = self
1791
0
                .libraries
1792
0
                .iter()
1793
0
                .map(|(name, ..)| name.as_str())
1794
0
                .collect_unique::<HashSet<_>>();
1795
1796
0
            let missing = metadata
1797
0
                .iter()
1798
0
                .filter_map(|metadata| {
1799
0
                    let missing = metadata
1800
0
                        .needed_libs
1801
0
                        .iter()
1802
0
                        .copied()
1803
0
                        .filter(|name| !names.contains(*name))
1804
0
                        .collect::<Vec<_>>();
1805
1806
0
                    if missing.is_empty() {
1807
0
                        None
1808
                    } else {
1809
0
                        Some((metadata.name, missing))
1810
                    }
1811
0
                })
1812
0
                .collect::<Vec<_>>();
1813
1814
0
            if !missing.is_empty() {
1815
0
                bail!(
1816
                    "missing libraries:\n{}",
1817
0
                    missing
1818
0
                        .iter()
1819
0
                        .map(|(needed_by, missing)| format!(
1820
                            "\t{needed_by} needs {}",
1821
0
                            missing.join(", ")
1822
                        ))
1823
0
                        .collect::<Vec<_>>()
1824
0
                        .join("\n")
1825
                );
1826
0
            }
1827
        }
1828
1829
0
        let exporters = resolve_exporters(&metadata)?;
1830
1831
0
        let cabi_realloc_exporter = exporters
1832
0
            .get(&ExportKey {
1833
0
                name: "cabi_realloc",
1834
0
                ty: Type::Function(FunctionType {
1835
0
                    parameters: vec![index_type.into(); 4],
1836
0
                    results: vec![index_type.into()],
1837
0
                }),
1838
0
            })
1839
0
            .map(|exporters| exporters.first().unwrap().0);
1840
1841
0
        let (exporters, missing, _) = resolve_symbols(&metadata, &exporters, index_type);
1842
1843
0
        if !missing.is_empty() {
1844
0
            if missing
1845
0
                .iter()
1846
0
                .all(|(_, export)| matches!(&export.key.ty, Type::Function(_)))
1847
0
                && (self.stub_missing_functions
1848
0
                    || missing
1849
0
                        .iter()
1850
0
                        .all(|(_, export)| export.flags.contains(SymbolFlags::BINDING_WEAK)))
1851
            {
1852
0
                self.stub_missing_functions = false;
1853
0
                self.libraries
1854
0
                    .push((STUB_LIBRARY_NAME.into(), make_stubs_module(&missing), false));
1855
0
                return self.encode();
1856
            } else {
1857
0
                bail!(
1858
                    "unresolved symbol(s):\n{}",
1859
0
                    missing
1860
0
                        .iter()
1861
0
                        .filter(|(_, export)| !export.flags.contains(SymbolFlags::BINDING_WEAK))
1862
0
                        .map(|(importer, export)| { format!("\t{importer} needs {}", export.key) })
1863
0
                        .collect::<Vec<_>>()
1864
0
                        .join("\n")
1865
                );
1866
            }
1867
0
        }
1868
1869
0
        let dependencies = find_dependencies(&metadata, &exporters)?;
1870
1871
        {
1872
0
            let reachable = find_reachable(&metadata, &dependencies);
1873
0
            let unreachable = self
1874
0
                .libraries
1875
0
                .iter()
1876
0
                .filter_map(|(name, ..)| (!reachable.contains(name.as_str())).then(|| name.clone()))
1877
0
                .collect_unique::<HashSet<_>>();
1878
1879
0
            if !unreachable.is_empty() {
1880
0
                self.libraries
1881
0
                    .retain(|(name, ..)| !unreachable.contains(name));
1882
0
                return self.encode();
1883
0
            }
1884
        }
1885
1886
0
        let topo_sorted = topo_sort(metadata.len(), &dependencies)?;
1887
1888
        let EnvExports {
1889
0
            exports: env_exports,
1890
0
            reexport_cabi_realloc,
1891
0
        } = env_exports(&metadata, &exporters, &topo_sorted)?;
1892
1893
0
        let (env_module, dl_openables, tls, table_base) = make_env_module(
1894
0
            &metadata,
1895
0
            &env_exports,
1896
0
            if reexport_cabi_realloc {
1897
                // If "env" module already reexports "cabi_realloc", we don't need to
1898
                // reexport it again.
1899
0
                None
1900
            } else {
1901
0
                cabi_realloc_exporter
1902
            },
1903
0
            self.stack_size.unwrap_or(DEFAULT_STACK_SIZE_BYTES),
1904
0
            index_type,
1905
        );
1906
1907
0
        self.encoder.module(&env_module)?;
1908
1909
0
        let default_env_items = [
1910
0
            Item {
1911
0
                alias: metadata::MEMORY.into(),
1912
0
                kind: ExportKind::Memory,
1913
0
                which: MainOrAdapter::Main,
1914
0
                name: metadata::MEMORY.into(),
1915
0
            },
1916
0
            Item {
1917
0
                alias: metadata::INDIRECT_FUNCTION_TABLE.into(),
1918
0
                kind: ExportKind::Table,
1919
0
                which: MainOrAdapter::Main,
1920
0
                name: metadata::INDIRECT_FUNCTION_TABLE.into(),
1921
0
            },
1922
0
            Item {
1923
0
                alias: metadata::STACK_POINTER.into(),
1924
0
                kind: ExportKind::Global,
1925
0
                which: MainOrAdapter::Main,
1926
0
                name: metadata::STACK_POINTER.into(),
1927
0
            },
1928
0
            Item {
1929
0
                alias: metadata::INIT_STACK_POINTER.into(),
1930
0
                kind: ExportKind::Global,
1931
0
                which: MainOrAdapter::Main,
1932
0
                name: metadata::INIT_STACK_POINTER.into(),
1933
0
            },
1934
0
        ];
1935
1936
0
        let mut seen = HashSet::new();
1937
0
        for index in topo_sorted {
1938
0
            let (name, module, _) = &self.libraries[index];
1939
0
            let metadata = &metadata[index];
1940
1941
0
            let env_items = default_env_items
1942
0
                .iter()
1943
0
                .cloned()
1944
0
                .chain([
1945
0
                    Item {
1946
0
                        alias: metadata::MEMORY_BASE.into(),
1947
0
                        kind: ExportKind::Global,
1948
0
                        which: MainOrAdapter::Main,
1949
0
                        name: format!("{name}:memory_base"),
1950
0
                    },
1951
0
                    Item {
1952
0
                        alias: metadata::TABLE_BASE.into(),
1953
0
                        kind: ExportKind::Global,
1954
0
                        which: MainOrAdapter::Main,
1955
0
                        name: format!("{name}:table_base"),
1956
0
                    },
1957
0
                ])
1958
0
                .chain(
1959
0
                    [
1960
0
                        (metadata.needs_get_tls_base, metadata::GET_TLS_BASE),
1961
0
                        (metadata.needs_set_tls_base, metadata::SET_TLS_BASE),
1962
0
                    ]
1963
0
                    .into_iter()
1964
0
                    .filter(|(needed, _)| *needed)
1965
0
                    .map(|(_, intrinsic)| Item {
1966
0
                        alias: intrinsic.into(),
1967
0
                        kind: ExportKind::Func,
1968
0
                        which: MainOrAdapter::Main,
1969
0
                        name: format!("{name}:{intrinsic}"),
1970
0
                    }),
1971
                )
1972
0
                .chain(metadata.env_imports.iter().map(|(name, (ty, _))| {
1973
0
                    let (exporter, _) = find_function_exporter(name, ty, &exporters).unwrap();
1974
1975
                    Item {
1976
0
                        alias: (*name).into(),
1977
0
                        kind: ExportKind::Func,
1978
0
                        which: if seen.contains(exporter) {
1979
0
                            MainOrAdapter::Adapter(exporter.to_owned())
1980
                        } else {
1981
0
                            MainOrAdapter::Main
1982
                        },
1983
0
                        name: (*name).into(),
1984
                    }
1985
0
                }))
1986
0
                .chain(
1987
0
                    metadata
1988
0
                        .tag_imports
1989
0
                        .iter()
1990
0
                        .map(|(name, ty)| {
1991
0
                            let (exporter, _) = find_tag_exporter(name, ty, &exporters).unwrap();
1992
1993
                            Ok(Item {
1994
0
                                alias: (*name).into(),
1995
0
                                kind: ExportKind::Tag,
1996
0
                                which: if seen.contains(exporter) {
1997
0
                                    MainOrAdapter::Adapter(exporter.to_owned())
1998
                                } else {
1999
                                    // As of this writing, LLVM-produced shared
2000
                                    // libraries which use C++ exceptions import
2001
                                    // a `cpp_exception` tag which is defined in
2002
                                    // `libunwind.so`.  Presumably
2003
                                    // `libunwind.so` will not import anything
2004
                                    // circularly from such shared libraries, so
2005
                                    // this case shouldn't be hit in practice
2006
                                    // unless we're dealing with some other,
2007
                                    // non-LLVM toolchain that does weird
2008
                                    // circular things with imports and
2009
                                    // exception tags.
2010
0
                                    bail!(
2011
                                        "circular dependency prevents direct tag import from `{}`",
2012
0
                                        exporter.to_owned()
2013
                                    )
2014
                                },
2015
0
                                name: (*name).into(),
2016
                            })
2017
0
                        })
2018
0
                        .collect::<Result<Vec<_>>>()?,
2019
                )
2020
0
                .chain(if metadata.is_asyncified {
2021
0
                    vec![
2022
0
                        Item {
2023
0
                            alias: metadata::ASYNCIFY_STATE.into(),
2024
0
                            kind: ExportKind::Global,
2025
0
                            which: MainOrAdapter::Main,
2026
0
                            name: metadata::ASYNCIFY_STATE.into(),
2027
0
                        },
2028
0
                        Item {
2029
0
                            alias: metadata::ASYNCIFY_DATA.into(),
2030
0
                            kind: ExportKind::Global,
2031
0
                            which: MainOrAdapter::Main,
2032
0
                            name: metadata::ASYNCIFY_DATA.into(),
2033
0
                        },
2034
                    ]
2035
                } else {
2036
0
                    vec![]
2037
                })
2038
0
                .collect();
2039
2040
0
            let global_item = |address_name: &str| Item {
2041
0
                alias: address_name.into(),
2042
0
                kind: ExportKind::Global,
2043
0
                which: MainOrAdapter::Main,
2044
0
                name: format!("{name}:{address_name}"),
2045
0
            };
2046
2047
0
            let mem_items = metadata
2048
0
                .memory_address_imports
2049
0
                .iter()
2050
0
                .copied()
2051
0
                .map(global_item)
2052
0
                .chain(
2053
0
                    [
2054
0
                        metadata::HEAP_BASE,
2055
0
                        metadata::HEAP_END,
2056
0
                        metadata::STACK_HIGH,
2057
0
                        metadata::STACK_LOW,
2058
0
                        metadata::LIBDL_LIBRARIES,
2059
0
                        metadata::PROGRAM_TLS_INFO,
2060
0
                    ]
2061
0
                    .into_iter()
2062
0
                    .map(|name| Item {
2063
0
                        alias: name.into(),
2064
0
                        kind: ExportKind::Global,
2065
0
                        which: MainOrAdapter::Main,
2066
0
                        name: name.into(),
2067
0
                    }),
2068
                )
2069
0
                .collect();
2070
2071
0
            let func_items = metadata
2072
0
                .table_address_imports
2073
0
                .iter()
2074
0
                .copied()
2075
0
                .map(global_item)
2076
0
                .collect();
2077
2078
0
            let mut import_items = BTreeMap::<_, Vec<_>>::new();
2079
0
            for import in &metadata.imports {
2080
0
                import_items.entry(import.module).or_default().push(Item {
2081
0
                    alias: import.name.into(),
2082
0
                    kind: ExportKind::from(&import.ty),
2083
0
                    which: MainOrAdapter::Main,
2084
0
                    name: format!("{}:{}", import.module, import.name),
2085
0
                });
2086
0
            }
2087
2088
0
            self.encoder.library(
2089
0
                name,
2090
0
                module,
2091
                LibraryInfo {
2092
0
                    arguments: [
2093
0
                        (metadata::GOT_MEM.into(), Instance::Items(mem_items)),
2094
0
                        (metadata::GOT_FUNC.into(), Instance::Items(func_items)),
2095
0
                        (metadata::ENV.into(), Instance::Items(env_items)),
2096
0
                    ]
2097
0
                    .into_iter()
2098
0
                    .chain(
2099
0
                        import_items
2100
0
                            .into_iter()
2101
0
                            .map(|(k, v)| (k.into(), Instance::Items(v))),
2102
                    )
2103
0
                    .collect(),
2104
                },
2105
0
            )?;
2106
2107
0
            seen.insert(name.as_str());
2108
        }
2109
2110
0
        self.encoder.encode_with_fixups(Some(&mut |fixups| {
2111
0
            make_init_module(
2112
0
                fixups,
2113
0
                &metadata,
2114
0
                &exporters,
2115
0
                &env_exports,
2116
0
                &dl_openables,
2117
0
                &tls,
2118
0
                table_base,
2119
0
                index_type,
2120
            )
2121
0
        }))
2122
0
    }
2123
}