elf_loader 0.17.0

A no_std-friendly ELF loader and runtime linker for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
use super::{Module, ModuleHandle, ModuleState, SymbolExports, SymbolLookup};
use crate::{
    Result,
    arch::NativeArch,
    custom_error,
    elf::{ElfLayout, ElfSectionIndex, ElfSymbol, ElfSymbolBind, ElfSymbolType},
    input::ModuleSourceId,
    memory::{ImageMemory, VmAddr, VmOffset},
    relocation::RelocationArch,
    runtime::DomainId,
    sync::{Arc, arc_unsize},
    tls::{ModuleTls, TlsResolver},
};
use alloc::{collections::BTreeMap, string::String, vec::Vec};
use core::ptr::NonNull;

/// One synthetic symbol exported by a [`SyntheticModule`].
///
/// Synthetic symbols are useful for host callbacks, native bridge wrappers,
/// and virtual replacement libraries where a symbol should resolve to a known
/// runtime address without loading another ELF image.
#[derive(Clone, Debug)]
pub struct SyntheticSymbol {
    name: String,
    version: Option<SymbolVersion>,
    value: usize,
    size: usize,
    bind: ElfSymbolBind,
    symbol_type: ElfSymbolType,
    other: u8,
    section_index: ElfSectionIndex,
}

/// GNU symbol-version metadata for a [`SyntheticSymbol`].
#[derive(Clone, Debug)]
pub struct SymbolVersion {
    name: String,
    default: bool,
}

impl SymbolVersion {
    /// Creates symbol-version metadata.
    ///
    /// A default version corresponds to GNU `name@@version`; a non-default
    /// version corresponds to `name@version`.
    #[inline]
    pub fn new(name: impl Into<String>, default: bool) -> Self {
        Self {
            name: name.into(),
            default,
        }
    }

    /// Returns the version name.
    #[inline]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns whether this version satisfies an unversioned lookup.
    #[inline]
    pub const fn is_default(&self) -> bool {
        self.default
    }
}

impl SyntheticSymbol {
    /// Creates a function symbol backed by an absolute runtime address.
    #[inline]
    pub fn function(name: impl Into<String>, value: *const ()) -> Self {
        Self::from_fields(
            name,
            value as usize,
            0,
            ElfSymbolBind::GLOBAL,
            ElfSymbolType::FUNC,
            0,
            ElfSectionIndex::ABS,
            None,
        )
    }

    /// Creates an object symbol backed by an absolute runtime address.
    #[inline]
    pub fn object(name: impl Into<String>, value: *const (), size: usize) -> Self {
        Self::from_fields(
            name,
            value as usize,
            size,
            ElfSymbolBind::GLOBAL,
            ElfSymbolType::OBJECT,
            0,
            ElfSectionIndex::ABS,
            None,
        )
    }

    /// Creates a TLS symbol whose value is an offset in this module's TLS block.
    #[inline]
    pub fn tls(name: impl Into<String>, offset: usize, size: usize) -> Self {
        Self::from_fields(
            name,
            offset,
            size,
            ElfSymbolBind::GLOBAL,
            ElfSymbolType::TLS,
            0,
            ElfSectionIndex::new(1),
            None,
        )
    }

    /// Creates a synthetic symbol with explicit ELF symbol fields.
    ///
    /// The synthetic module fills `st_name` when the symbol is inserted, so the
    /// caller controls every field except the internal name-table slot. Pass
    /// [`SymbolVersion`] to attach GNU symbol-version metadata.
    #[inline]
    pub fn from_fields(
        name: impl Into<String>,
        value: usize,
        size: usize,
        bind: ElfSymbolBind,
        symbol_type: ElfSymbolType,
        other: u8,
        section_index: ElfSectionIndex,
        version: Option<SymbolVersion>,
    ) -> Self {
        Self {
            name: name.into(),
            version,
            value,
            size,
            bind,
            symbol_type,
            other,
            section_index,
        }
    }

    /// Creates a synthetic symbol from an ELF symbol-table entry.
    ///
    /// `name` must be supplied separately because [`ElfSymbol::st_name`] is an
    /// index into the source image's string table. GNU version metadata likewise
    /// lives outside the ELF symbol-table entry.
    #[inline]
    pub fn from_elf<L: ElfLayout>(
        name: impl Into<String>,
        symbol: &ElfSymbol<L>,
        version: Option<SymbolVersion>,
    ) -> Self {
        Self::from_fields(
            name,
            symbol.st_value(),
            symbol.st_size(),
            symbol.bind(),
            symbol.symbol_type(),
            symbol.st_other(),
            symbol.st_shndx(),
            version,
        )
    }

    /// Exports this symbol with `version`.
    ///
    /// A default definition corresponds to GNU `name@@version` and may satisfy
    /// an unversioned lookup. A non-default definition corresponds to
    /// `name@version` and is available only to an exact versioned lookup.
    #[inline]
    pub fn with_version(mut self, version: impl Into<String>, default: bool) -> Self {
        self.version = Some(SymbolVersion::new(version, default));
        self
    }

    /// Sets the ELF symbol binding used by the synthetic symbol.
    #[inline]
    pub fn with_bind(mut self, bind: ElfSymbolBind) -> Self {
        self.bind = bind;
        self
    }

    /// Sets the ELF symbol size.
    #[inline]
    pub fn with_size(mut self, size: usize) -> Self {
        self.size = size;
        self
    }

    /// Sets the ELF `st_other` value.
    #[inline]
    pub fn with_other(mut self, other: u8) -> Self {
        self.other = other;
        self
    }

    /// Sets the ELF section index used by the synthetic symbol.
    ///
    /// Function and object symbols default to [`ElfSectionIndex::ABS`] because
    /// they normally carry an already-resolved runtime address. TLS and
    /// module-relative symbols can override this with their real section index.
    #[inline]
    pub fn with_section(mut self, section_index: ElfSectionIndex) -> Self {
        self.section_index = section_index;
        self
    }
}

#[derive(Clone, Copy)]
struct UnmappedImageMemory {
    base: VmAddr,
}

impl Default for UnmappedImageMemory {
    #[inline]
    fn default() -> Self {
        Self {
            base: VmAddr::null(),
        }
    }
}

impl ImageMemory for UnmappedImageMemory {
    #[inline]
    fn base(&self) -> VmAddr {
        self.base
    }

    #[inline]
    fn range_at(&self, _addr: VmAddr) -> Option<core::ops::Range<VmAddr>> {
        None
    }

    #[inline]
    fn host_ptr(&self, _addr: VmAddr) -> Option<NonNull<u8>> {
        None
    }

    #[inline]
    fn host_ptr_range(&self, _addr: VmAddr, _len: usize) -> Option<NonNull<u8>> {
        None
    }

    #[inline]
    fn read_bytes(&self, _addr: VmAddr, dst: &mut [u8]) -> Result<()> {
        if dst.is_empty() {
            return Ok(());
        }

        Err(custom_error(
            "synthetic modules do not expose readable image bytes",
        ))
    }

    #[inline]
    fn write_bytes(&self, _addr: VmAddr, src: &[u8]) -> Result<()> {
        if src.is_empty() {
            return Ok(());
        }

        Err(custom_error(
            "synthetic modules do not expose writable image bytes",
        ))
    }
}

/// A [`Module`] backed by a synthetic table of absolute symbols.
///
/// The module owns stable synthetic ELF symbols, so it can be retained in a
/// [`ModuleScope`](crate::image::ModuleScope) without borrowing callback-owned
/// symbol metadata.
pub struct SyntheticModule<Arch: RelocationArch = NativeArch, D = (), R = ()> {
    state: ModuleState,
    name: String,
    memory: Arc<dyn ImageMemory>,
    tls: Option<ModuleTls>,
    resolve_hook: R,
    user_data: D,
    names: Vec<String>,
    symbols: Vec<ElfSymbol<Arch::Layout>>,
    index: BTreeMap<String, SymbolIndex>,
}

/// Runtime callback invoked when a synthetic symbol is resolved.
pub trait ResolveHook<Arch: RelocationArch>: Send + Sync {
    /// Prepares runtime state associated with `symbol` and its stable address.
    fn resolve(&self, symbol: &ElfSymbol<Arch::Layout>, address: VmAddr) -> Result<()>;
}

impl<Arch: RelocationArch> ResolveHook<Arch> for () {
    #[inline]
    fn resolve(&self, _symbol: &ElfSymbol<Arch::Layout>, _address: VmAddr) -> Result<()> {
        Ok(())
    }
}

impl<Arch, F> ResolveHook<Arch> for F
where
    Arch: RelocationArch,
    F: Fn(&ElfSymbol<Arch::Layout>, VmAddr) -> Result<()> + Send + Sync,
{
    #[inline]
    fn resolve(&self, symbol: &ElfSymbol<Arch::Layout>, address: VmAddr) -> Result<()> {
        self(symbol, address)
    }
}

#[derive(Clone, Default)]
struct SymbolIndex {
    default: Option<usize>,
    versions: Vec<(SymbolVersion, usize)>,
}

impl<Arch: RelocationArch, D: Clone, R: Clone> Clone for SyntheticModule<Arch, D, R> {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            state: ModuleState::new(ModuleSourceId::fresh(), self.state.domain_id()),
            name: self.name.clone(),
            memory: self.memory.clone(),
            tls: self.tls,
            resolve_hook: self.resolve_hook.clone(),
            user_data: self.user_data.clone(),
            names: self.names.clone(),
            symbols: self.symbols.clone(),
            index: self.index.clone(),
        }
    }
}

impl<Arch: RelocationArch> SyntheticModule<Arch> {
    /// Creates a module from an ordered list of synthetic symbols.
    pub fn new<I>(name: impl Into<String>, symbols: I) -> Self
    where
        I: IntoIterator<Item = SyntheticSymbol>,
    {
        let mut module = Self::empty(name);
        for symbol in symbols {
            let _ = module.insert(symbol);
        }
        module
    }

    /// Creates an empty synthetic module.
    pub fn empty(name: impl Into<String>) -> Self {
        Self {
            state: ModuleState::new(ModuleSourceId::fresh(), DomainId::PROCESS),
            name: name.into(),
            memory: arc_unsize!(
                Arc::new(UnmappedImageMemory::default()) => dyn ImageMemory
            ),
            tls: None,
            resolve_hook: (),
            user_data: (),
            names: Vec::new(),
            symbols: Vec::new(),
            index: BTreeMap::new(),
        }
    }
}

impl<Arch: RelocationArch, D, R> SyntheticModule<Arch, D, R> {
    /// Replaces the user data associated with this synthetic module.
    #[inline]
    pub fn with_user_data<NewD>(self, user_data: NewD) -> SyntheticModule<Arch, NewD, R> {
        SyntheticModule {
            state: self.state,
            name: self.name,
            memory: self.memory,
            tls: self.tls,
            resolve_hook: self.resolve_hook,
            user_data,
            names: self.names,
            symbols: self.symbols,
            index: self.index,
        }
    }

    /// Returns immutable user data for this synthetic module.
    #[inline]
    pub const fn user_data(&self) -> &D {
        &self.user_data
    }

    /// Returns mutable user data for this synthetic module.
    #[inline]
    pub fn user_data_mut(&mut self) -> &mut D {
        &mut self.user_data
    }

    /// Uses a real image-memory backend for this synthetic module.
    ///
    /// This is required when synthetic symbols may be used as byte sources, such
    /// as for COPY relocations against synthetic object symbols.
    #[inline]
    pub fn with_memory<M>(mut self, memory: M) -> Self
    where
        M: ImageMemory + 'static,
    {
        self.memory = arc_unsize!(Arc::new(memory) => dyn ImageMemory);
        self
    }

    /// Sets TLS metadata exposed by this synthetic module.
    #[inline]
    pub fn with_tls(mut self, tls: ModuleTls) -> Self {
        self.tls = Some(tls);
        self
    }

    /// Runs a callback when a synthetic symbol is resolved.
    ///
    /// The callback receives the symbol's stable address and may prepare lazy
    /// runtime state before that address is returned.
    #[inline]
    pub fn with_resolve_hook<F>(self, hook: F) -> SyntheticModule<Arch, D, F>
    where
        F: Fn(&ElfSymbol<Arch::Layout>, VmAddr) -> Result<()> + Send + Sync,
    {
        SyntheticModule {
            state: self.state,
            name: self.name,
            memory: self.memory,
            tls: self.tls,
            resolve_hook: hook,
            user_data: self.user_data,
            names: self.names,
            symbols: self.symbols,
            index: self.index,
        }
    }

    /// Binds this synthetic module to one runtime domain.
    #[inline]
    pub fn with_domain(mut self, domain: DomainId) -> Self {
        self.state.set_domain(domain);
        self
    }

    /// Inserts one symbol, returning the definition it replaced.
    pub fn insert(&mut self, symbol: SyntheticSymbol) -> Option<SyntheticSymbol> {
        let name = symbol.name;
        let version = symbol.version;
        let entry = self.index.entry(name.clone()).or_default();
        let existing = match version.as_ref() {
            Some(version) => entry.versions.iter().find_map(|(entry, index)| {
                (entry.name == version.name).then(|| (*index, Some(entry.clone())))
            }),
            None => entry.default.map(|index| {
                let version = entry.versions.iter().find_map(|(version, version_index)| {
                    (*version_index == index && version.default).then(|| version.clone())
                });
                (index, version)
            }),
        };

        let (idx, previous) = if let Some((idx, previous_version)) = existing {
            let elf_symbol = ElfSymbol::synthetic(
                idx,
                symbol.value,
                symbol.size,
                symbol.bind,
                symbol.symbol_type,
                symbol.other,
                symbol.section_index,
            );
            let previous_name = core::mem::replace(&mut self.names[idx], name);
            let previous_symbol = core::mem::replace(&mut self.symbols[idx], elf_symbol);
            let previous =
                SyntheticSymbol::from_elf(previous_name, &previous_symbol, previous_version);
            (idx, Some(previous))
        } else {
            let idx = self.symbols.len();
            let elf_symbol = ElfSymbol::synthetic(
                idx,
                symbol.value,
                symbol.size,
                symbol.bind,
                symbol.symbol_type,
                symbol.other,
                symbol.section_index,
            );
            self.names.push(name);
            self.symbols.push(elf_symbol);
            (idx, None)
        };

        match version {
            Some(version) => {
                let was_default = entry
                    .versions
                    .iter()
                    .position(|(entry, _)| entry.name == version.name)
                    .map(|position| entry.versions.remove(position).0.default)
                    .unwrap_or(false);
                if version.default {
                    for (entry, _) in &mut entry.versions {
                        entry.default = false;
                    }
                    entry.default = Some(idx);
                } else if was_default && entry.default == Some(idx) {
                    entry.default = None;
                }
                entry.versions.push((version, idx));
            }
            None => {
                if let Some(position) = entry
                    .versions
                    .iter()
                    .position(|(version, version_index)| *version_index == idx && version.default)
                {
                    entry.versions.remove(position);
                }
                entry.default = Some(idx);
            }
        }

        previous
    }

    /// Returns whether this module exports a synthetic symbol with `name`.
    #[inline]
    pub fn contains(&self, name: &str) -> bool {
        self.index.contains_key(name)
    }

    /// Returns the number of synthetic symbols.
    #[inline]
    pub fn len(&self) -> usize {
        self.symbols.len()
    }

    /// Returns whether this module contains no symbols.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.symbols.is_empty()
    }
}

impl<Arch, D, R, Tls> From<SyntheticModule<Arch, D, R>> for ModuleHandle<Arch, Tls>
where
    Arch: RelocationArch,
    D: Send + Sync + 'static,
    R: ResolveHook<Arch> + 'static,
    Tls: TlsResolver<Arch> + 'static,
{
    #[inline]
    fn from(module: SyntheticModule<Arch, D, R>) -> Self {
        Self::new(module)
    }
}

impl<Arch, D, R, Tls> Module<Arch, Tls> for SyntheticModule<Arch, D, R>
where
    Arch: RelocationArch,
    D: Send + Sync + 'static,
    R: ResolveHook<Arch> + 'static,
    Tls: TlsResolver<Arch> + 'static,
{
    #[inline]
    fn name(&self) -> &str {
        &self.name
    }

    #[inline]
    fn exports(&self) -> &dyn SymbolExports<Arch::Layout> {
        self
    }

    #[inline]
    fn memory(&self) -> &dyn ImageMemory {
        &*self.memory
    }

    fn resolve_symbol(&self, symbol: &ElfSymbol<Arch::Layout>) -> Result<VmAddr> {
        match symbol.symbol_type() {
            ElfSymbolType::TLS => {
                return Err(custom_error(
                    "synthetic module cannot resolve TLS symbol addresses",
                ));
            }
            ElfSymbolType::GNU_IFUNC => {
                return Err(custom_error(
                    "synthetic module cannot execute IFUNC resolvers",
                ));
            }
            _ => {}
        }

        let address = if symbol.st_shndx().is_abs() {
            VmAddr::new(symbol.st_value())
        } else {
            self.memory.base() + VmOffset::new(symbol.st_value())
        };
        self.resolve_hook.resolve(symbol, address)?;
        Ok(address)
    }

    #[inline]
    fn tls(&self) -> Option<ModuleTls> {
        self.tls
    }

    #[inline]
    fn state(&self) -> &ModuleState {
        &self.state
    }
}

impl<Arch, D, R> SymbolExports<Arch::Layout> for SyntheticModule<Arch, D, R>
where
    Arch: RelocationArch,
    D: Send + Sync,
    R: Send + Sync,
{
    #[inline]
    fn for_each(&self, visitor: &mut dyn FnMut(&ElfSymbol<Arch::Layout>)) {
        self.symbols.iter().for_each(visitor);
    }

    #[inline]
    fn symbol_name<'exports>(
        &'exports self,
        symbol: &ElfSymbol<Arch::Layout>,
    ) -> Option<&'exports str> {
        self.names.get(symbol.st_name()).map(String::as_str)
    }

    #[inline]
    fn lookup<'exports>(
        &'exports self,
        lookup: &mut SymbolLookup<'_>,
    ) -> Option<&'exports ElfSymbol<Arch::Layout>> {
        let entry = self.index.get(lookup.name())?;
        let idx = match lookup.version_name() {
            Some(version) => entry
                .versions
                .iter()
                .find_map(|(entry, index)| (entry.name == version).then_some(*index))?,
            None => entry.default?,
        };
        Some(&self.symbols[idx])
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        elf::ElfSymbolVisibility,
        image::ModuleScope,
        memory::{MappedRegion, VmOffset},
        segment::ElfSegments,
        tls::{TlsModuleId, TlsTpOffset},
    };
    use core::sync::atomic::{AtomicUsize, Ordering};

    #[test]
    fn synthetic_module_resolves_absolute_symbols_from_scope() {
        let module = SyntheticModule::<NativeArch>::new(
            "__bridge",
            [SyntheticSymbol::function(
                "host_double",
                0x1234usize as *const (),
            )],
        );
        assert_eq!(
            <SyntheticModule<NativeArch> as Module<NativeArch, ()>>::memory(&module).base(),
            VmAddr::null()
        );

        let mut scope = ModuleScope::<NativeArch>::new(DomainId::PROCESS);
        scope.extend([module]);
        let mut lookup = SymbolLookup::new("host_double");

        let module = scope
            .iter()
            .find(|module| module.name() == "__bridge")
            .expect("synthetic module should be retained in scope");
        assert_eq!(module.memory().base(), VmAddr::null());
        let symbol = module
            .exports()
            .lookup(&mut lookup)
            .expect("synthetic symbol should resolve");

        assert_eq!(symbol.st_value(), 0x1234);
        assert_eq!(symbol.st_size(), 0);
        assert_eq!(symbol.bind(), ElfSymbolBind::GLOBAL);
        assert_eq!(symbol.symbol_type(), ElfSymbolType::FUNC);
        assert!(symbol.st_shndx().is_abs());
        assert_eq!(module.exports().symbol_name(symbol), Some("host_double"));
    }

    #[test]
    fn resolve_hook_observes_address_and_propagates_errors() {
        let observed = Arc::new(AtomicUsize::new(0));
        let hook_observed = Arc::clone(&observed);
        let module = SyntheticModule::<NativeArch>::new(
            "__hook",
            [SyntheticSymbol::function("entry", 0x1234usize as *const ())],
        )
        .with_resolve_hook(move |symbol: &ElfSymbol<_>, address| {
            assert_eq!(symbol.st_value(), 0x1234);
            hook_observed.store(address.get(), Ordering::Relaxed);
            Ok(())
        });
        let mut lookup = SymbolLookup::new("entry");
        let symbol = module.lookup(&mut lookup).unwrap();

        let address = Module::<NativeArch, ()>::resolve_symbol(&module, symbol).unwrap();
        assert_eq!(address, VmAddr::new(0x1234));
        assert_eq!(observed.load(Ordering::Relaxed), 0x1234);

        let failing = SyntheticModule::<NativeArch>::new(
            "__failing_hook",
            [SyntheticSymbol::function("entry", 0x1234usize as *const ())],
        )
        .with_resolve_hook(|_: &ElfSymbol<_>, _| Err(crate::custom_error("hook failed")));
        let symbol = failing.lookup(&mut lookup).unwrap();
        assert!(Module::<NativeArch, ()>::resolve_symbol(&failing, symbol).is_err());
    }

    #[cfg(feature = "version")]
    #[test]
    fn synthetic_module_uses_one_default_symbol() {
        let mut module = SyntheticModule::<NativeArch>::new(
            "__versions",
            [SyntheticSymbol::function("entry", 0x1000usize as *const ())],
        );
        assert!(
            module
                .insert(SyntheticSymbol::from_fields(
                    "entry",
                    0x2000,
                    0,
                    ElfSymbolBind::GLOBAL,
                    ElfSymbolType::FUNC,
                    0,
                    ElfSectionIndex::ABS,
                    Some(SymbolVersion::new("VER_1", false)),
                ))
                .is_none()
        );

        let mut lookup = SymbolLookup::new("entry");
        assert_eq!(module.lookup(&mut lookup).unwrap().st_value(), 0x1000);

        let mut lookup = SymbolLookup::with_version("entry", "VER_1");
        assert_eq!(module.lookup(&mut lookup).unwrap().st_value(), 0x2000);

        assert!(
            module
                .insert(
                    SyntheticSymbol::function("entry", 0x3000usize as *const ())
                        .with_version("VER_2", true),
                )
                .is_none()
        );

        let mut lookup = SymbolLookup::new("entry");
        assert_eq!(module.lookup(&mut lookup).unwrap().st_value(), 0x3000);

        let mut lookup = SymbolLookup::with_version("entry", "VER_2");
        assert_eq!(module.lookup(&mut lookup).unwrap().st_value(), 0x3000);

        let previous = module
            .insert(
                SyntheticSymbol::function("entry", 0x4000usize as *const ())
                    .with_version("VER_2", true),
            )
            .unwrap();
        assert_eq!(previous.value, 0x3000);
        assert_eq!(previous.version.unwrap().name(), "VER_2");

        let previous = module
            .insert(SyntheticSymbol::function("entry", 0x5000usize as *const ()))
            .unwrap();
        assert_eq!(previous.value, 0x4000);
        assert_eq!(previous.version.unwrap().name(), "VER_2");

        let mut lookup = SymbolLookup::new("entry");
        assert_eq!(module.lookup(&mut lookup).unwrap().st_value(), 0x5000);

        let mut lookup = SymbolLookup::with_version("entry", "VER_2");
        assert!(module.lookup(&mut lookup).is_none());
    }

    #[test]
    fn synthetic_symbol_can_use_non_absolute_section() {
        let module = SyntheticModule::<NativeArch>::new(
            "__tls",
            [SyntheticSymbol::from_fields(
                "tls_slot",
                0x20,
                8,
                ElfSymbolBind::WEAK,
                ElfSymbolType::TLS,
                3,
                ElfSectionIndex::new(1),
                None,
            )],
        );
        let mut scope = ModuleScope::<NativeArch>::new(DomainId::PROCESS);
        scope.extend([module]);
        let mut lookup = SymbolLookup::new("tls_slot");

        let module = scope
            .iter()
            .find(|module| module.name() == "__tls")
            .expect("synthetic module should be retained in scope");
        let symbol = module
            .exports()
            .lookup(&mut lookup)
            .expect("synthetic TLS symbol should resolve");

        assert_eq!(symbol.st_value(), 0x20);
        assert_eq!(symbol.st_size(), 8);
        assert_eq!(symbol.bind(), ElfSymbolBind::WEAK);
        assert_eq!(symbol.symbol_type(), ElfSymbolType::TLS);
        assert_eq!(symbol.st_other(), 3);
        assert_eq!(symbol.visibility(), ElfSymbolVisibility::PROTECTED);
        assert_eq!(symbol.st_shndx(), ElfSectionIndex::new(1));
    }

    #[test]
    fn synthetic_module_carries_metadata() {
        #[derive(Clone, Debug, PartialEq, Eq)]
        struct SyntheticData {
            tag: usize,
        }

        let tls = ModuleTls::Static {
            mod_id: TlsModuleId::new(7),
            tp_offset: TlsTpOffset::new(-0x80),
        };
        let mut module = SyntheticModule::<NativeArch>::empty("__tls")
            .with_tls(tls)
            .with_user_data(SyntheticData { tag: 7 });

        assert_eq!(
            <SyntheticModule<NativeArch, SyntheticData> as Module<NativeArch, ()>>::tls(&module),
            Some(tls)
        );
        assert_eq!(module.user_data().tag, 7);
        module.user_data_mut().tag = 11;
        assert_eq!(module.user_data(), &SyntheticData { tag: 11 });
    }

    #[test]
    fn synthetic_module_can_delegate_image_memory() {
        let bytes = alloc::boxed::Box::leak(alloc::boxed::Box::new([1u8, 2, 3, 4]));
        let region = unsafe {
            MappedRegion::local_alias_no_unmap(bytes.as_ptr().cast_mut().cast(), bytes.len())
        };
        let base = VmAddr::from_ptr(bytes.as_ptr());
        let memory = ElfSegments::new(region, base, VmOffset::new(0));
        let module = SyntheticModule::<NativeArch>::empty("__data").with_memory(memory);
        let memory = <SyntheticModule<NativeArch> as Module<NativeArch, ()>>::memory(&module);
        let mut out = [0u8; 2];

        memory
            .read_bytes(base + VmOffset::new(1), &mut out)
            .expect("synthetic module should delegate readable image memory");

        assert_eq!(memory.base(), base);
        assert_eq!(out, [2, 3]);
    }
}