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
use super::Module;
use crate::{
    Result,
    arch::NativeArch,
    custom_error,
    elf::SymbolLookup,
    input::ModuleSourceId,
    memory::VmAddr,
    relocation::RelocationArch,
    runtime::DomainId,
    sync::{Arc, AtomicU8, AtomicUsize, Ordering, Weak, arc_unsize},
    tls::TlsResolver,
};
use alloc::vec::Vec;
use core::{fmt, ops::Deref};
use spin::{Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard};

const UNINITIALIZED: u8 = 0;
const INITIALIZING: u8 = 1;
const INITIALIZED: u8 = 2;
const FAILED: u8 = 3;
const FINALIZED: u8 = 4;

static NEXT_INSTANCE: AtomicUsize = AtomicUsize::new(1);

#[inline]
fn next_instance() -> usize {
    NEXT_INSTANCE
        .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
            value.checked_add(1)
        })
        .expect("module instance identity space is exhausted")
}

struct InitializationGuard<'a>(&'a AtomicU8);

impl Drop for InitializationGuard<'_> {
    fn drop(&mut self) {
        // A panic must not leave the module permanently stuck in INITIALIZING.
        self.0.store(FAILED, Ordering::Release);
    }
}

#[inline]
pub(super) fn lookup_symbol<Arch, Tls>(
    module: &dyn Module<Arch, Tls>,
    lookup: &mut SymbolLookup<'_>,
) -> Result<Option<VmAddr>>
where
    Arch: RelocationArch,
    Tls: TlsResolver<Arch>,
{
    let Some(symbol) = module.exports().lookup(lookup) else {
        return Ok(None);
    };
    if !symbol.is_exported() {
        return Ok(None);
    }
    module.resolve_symbol(symbol).map(Some)
}

/// Identity and runtime state shared by every view of one logical module.
///
/// Module implementations store this value and return it from
/// [`Module::state`]. It owns the canonical instance identity and runtime domain,
/// and coordinates initialization, finalization, and runtime bindings without
/// duplicating the ownership count already maintained by [`Arc`].
pub struct ModuleState {
    id: ModuleInstanceId,
    domain: DomainId,
    phase: AtomicU8,
    // Relocation facts follow this concrete module across context imports.
    // Context-specific pin counts remain owned by LinkContext.
    effects: Mutex<ModuleEffects>,
}

#[derive(Default)]
struct ModuleEffects {
    bindings: Vec<ModuleInstanceId>,
    pins: Vec<ModuleInstanceId>,
}

/// Non-owning identity of one loaded module instance.
///
/// Unlike [`ModuleSourceId`], this value changes when the same source is
/// unloaded and loaded again.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ModuleInstanceId {
    source: ModuleSourceId,
    instance: usize,
}

impl ModuleInstanceId {
    #[inline]
    fn new(source: ModuleSourceId) -> Self {
        Self {
            source,
            instance: next_instance(),
        }
    }

    /// Returns the stable identity of the source backing this instance.
    #[inline]
    pub const fn source_id(self) -> ModuleSourceId {
        self.source
    }
}

impl ModuleState {
    /// Creates state for a module whose initializer has not run.
    #[inline]
    pub fn new(source: ModuleSourceId, domain: DomainId) -> Self {
        Self {
            id: ModuleInstanceId::new(source),
            domain,
            phase: AtomicU8::new(UNINITIALIZED),
            effects: Mutex::new(ModuleEffects::default()),
        }
    }

    /// Creates state for a module that is already initialized.
    #[inline]
    pub fn initialized(source: ModuleSourceId, domain: DomainId) -> Self {
        Self {
            id: ModuleInstanceId::new(source),
            domain,
            phase: AtomicU8::new(INITIALIZED),
            effects: Mutex::new(ModuleEffects::default()),
        }
    }

    /// Returns the identity of this particular loaded module instance.
    #[inline]
    pub const fn instance_id(&self) -> ModuleInstanceId {
        self.id
    }

    /// Returns the runtime domain in which this module's addresses are meaningful.
    #[inline]
    pub const fn domain_id(&self) -> DomainId {
        self.domain
    }

    #[inline]
    pub(super) fn set_domain(&mut self, domain: DomainId) {
        self.domain = domain;
    }

    #[inline]
    pub(crate) fn with_effects<T>(
        &self,
        f: impl FnOnce(&[ModuleInstanceId], &[ModuleInstanceId]) -> T,
    ) -> T {
        let effects = self.effects.lock();
        f(&effects.bindings, &effects.pins)
    }

    pub(crate) fn install_effects(
        &self,
        bindings: impl IntoIterator<Item = ModuleInstanceId>,
        pins: impl IntoIterator<Item = ModuleInstanceId>,
    ) {
        let mut effects = self.effects.lock();
        for binding in bindings {
            if binding != self.id && !effects.bindings.contains(&binding) {
                effects.bindings.push(binding);
            }
        }
        for pin in pins {
            if !effects.pins.contains(&pin) {
                effects.pins.push(pin);
            }
        }
    }

    /// Returns whether the module is currently initialized.
    #[inline]
    pub fn is_initialized(&self) -> bool {
        self.phase.load(Ordering::Acquire) == INITIALIZED
    }

    /// Runs the module initializer at most once.
    ///
    /// Recursive callers observe an initialization in progress as already
    /// claimed and do not run the initializer again. If the callback returns
    /// an error or unwinds, the state becomes permanently failed.
    pub fn initialize(&self, initialize: impl FnOnce() -> Result<()>) -> Result<()> {
        let mut phase = self.phase.load(Ordering::Acquire);
        loop {
            match phase {
                INITIALIZING | INITIALIZED => return Ok(()),
                FAILED => return Err(custom_error("cannot initialize a failed module")),
                FINALIZED => return Err(custom_error("cannot initialize a finalized module")),
                _ => {}
            }
            match self.phase.compare_exchange_weak(
                phase,
                INITIALIZING,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => {
                    // The guard covers unwinding; the explicit store below
                    // records the callback's normal return value.
                    let guard = InitializationGuard(&self.phase);
                    let result = initialize();
                    self.phase.store(
                        if result.is_ok() { INITIALIZED } else { FAILED },
                        Ordering::Release,
                    );
                    core::mem::forget(guard);
                    return result;
                }
                Err(current) => phase = current,
            }
        }
    }

    /// Runs the module finalizer at most once after initialization was attempted.
    ///
    /// A module with finalization work should call this from its owning
    /// allocation's [`Drop`] implementation. For core-backed ELF modules,
    /// `ElfModule` already provides that integration. Calls made before
    /// initialization or after another finalizer claimed the module are no-ops.
    pub fn finalize(&self, finalize: impl FnOnce() -> Result<()>) -> Result<()> {
        let mut phase = self.phase.load(Ordering::Acquire);
        loop {
            match phase {
                INITIALIZED | FAILED => {}
                _ => return Ok(()),
            }
            match self.phase.compare_exchange_weak(
                phase,
                FINALIZED,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => return finalize(),
                Err(current) => phase = current,
            }
        }
    }
}

impl Default for ModuleState {
    #[inline]
    fn default() -> Self {
        Self::new(ModuleSourceId::fresh(), DomainId::PROCESS)
    }
}

/// One shared ownership reference to a module.
///
/// Finalization follows the lifetime of the underlying module allocation, not
/// an individual handle. Cloning or dropping a handle only changes the [`Arc`]
/// ownership count.
pub struct ModuleHandle<Arch: RelocationArch = NativeArch, Tls: TlsResolver<Arch> = ()> {
    module: Arc<dyn Module<Arch, Tls>>,
}

impl<Arch: RelocationArch, Tls: TlsResolver<Arch>> Clone for ModuleHandle<Arch, Tls> {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            module: Arc::clone(&self.module),
        }
    }
}

impl<Arch: RelocationArch, Tls: TlsResolver<Arch> + 'static> ModuleHandle<Arch, Tls> {
    /// Creates the canonical shared handle for a module.
    ///
    /// Clone this handle when the same logical module is used in another scope
    /// or link context.
    #[inline]
    pub fn new<M>(module: M) -> Self
    where
        M: Module<Arch, Tls> + 'static,
    {
        Self::from_shared(arc_unsize!(Arc::new(module) => dyn Module<Arch, Tls>))
    }

    /// Wraps a shared module while preserving the state owned by that module.
    #[inline]
    pub fn from_shared(module: Arc<dyn Module<Arch, Tls>>) -> Self {
        Self { module }
    }

    #[inline]
    pub(crate) fn downgrade(&self) -> Weak<dyn Module<Arch, Tls>> {
        Arc::downgrade(&self.module)
    }

    /// Returns the stable identity of the source backing this module.
    #[inline]
    pub fn source_id(&self) -> ModuleSourceId {
        self.module.state().instance_id().source_id()
    }

    /// Returns the runtime domain in which this module's addresses are meaningful.
    #[inline]
    pub fn domain_id(&self) -> DomainId {
        self.module.state().domain_id()
    }

    /// Runs this module's initialization hook at most once.
    #[inline]
    pub fn initialize(&self) -> Result<()> {
        let module = &*self.module;
        module.state().initialize(|| module.initialize())
    }
}

impl<Arch: RelocationArch, Tls: TlsResolver<Arch> + 'static> Deref for ModuleHandle<Arch, Tls> {
    type Target = dyn Module<Arch, Tls>;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &*self.module
    }
}

impl<Arch: RelocationArch, Tls: TlsResolver<Arch> + 'static> AsRef<dyn Module<Arch, Tls>>
    for ModuleHandle<Arch, Tls>
{
    #[inline]
    fn as_ref(&self) -> &(dyn Module<Arch, Tls> + 'static) {
        &*self.module
    }
}

/// Copy-on-write ordered modules used for symbol lookup and dependency retention.
///
/// Modules are searched in order and held alive by relocated outputs that keep
/// this scope. Clones remain stable when another clone is modified. The scope
/// dereferences to its ordered module slice for read-only access.
pub struct ModuleScope<Arch: RelocationArch = NativeArch, Tls: TlsResolver<Arch> = ()> {
    modules: Arc<Vec<ModuleHandle<Arch, Tls>>>,
    domain: DomainId,
}

/// Eager and deferred local scopes used while relocating one module.
///
/// The eager scope is used for ordinary relocation. The lazy scope is always
/// present and is retained by standalone loaded images. Linker-managed images
/// normally use their dependency closure as the lazy scope.
pub struct LocalScope<Arch: RelocationArch = NativeArch, Tls: TlsResolver<Arch> = ()> {
    groups: Arc<[ModuleScope<Arch, Tls>]>,
    lazy: ModuleScope<Arch, Tls>,
}

/// Weak references used by deferred lookup to recover local and global scopes.
///
/// Linker-managed images use their retained dependency closure instead of the
/// wider eager-relocation load group. This deliberately gives lazy binding the
/// conservative `retained + global` lookup semantics documented by the linker.
pub(crate) struct WeakLocalScope<Arch: RelocationArch = NativeArch, Tls: TlsResolver<Arch> = ()> {
    local: Weak<Vec<ModuleHandle<Arch, Tls>>>,
    global: Option<Weak<GlobalScopeInner<Arch, Tls>>>,
    domain: DomainId,
}

/// Shared live global lookup order owned by a [`LinkContext`](crate::LinkContext).
///
/// Clones refer to the same global scope. Use
/// [`LinkContext::promote_global`](crate::LinkContext::promote_global) or
/// [`LinkContext::extend_global`](crate::LinkContext::extend_global) to change
/// its contents without bypassing the context's lifetime bookkeeping.
pub struct GlobalScope<Arch: RelocationArch = NativeArch, Tls: TlsResolver<Arch> = ()> {
    inner: Arc<GlobalScopeInner<Arch, Tls>>,
}

struct GlobalScopeInner<Arch: RelocationArch, Tls: TlsResolver<Arch>> {
    modules: RwLock<ModuleScope<Arch, Tls>>,
    domain: DomainId,
}

impl<Arch: RelocationArch, Tls: TlsResolver<Arch>> Clone for ModuleScope<Arch, Tls> {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            modules: Arc::clone(&self.modules),
            domain: self.domain,
        }
    }
}

impl<Arch, Tls> fmt::Debug for ModuleScope<Arch, Tls>
where
    Arch: RelocationArch,
    Tls: TlsResolver<Arch>,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list()
            .entries(self.modules.iter().map(|module| module.name()))
            .finish()
    }
}

impl<Arch: RelocationArch, Tls: TlsResolver<Arch>> Deref for ModuleScope<Arch, Tls> {
    type Target = [ModuleHandle<Arch, Tls>];

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.modules
    }
}

impl<Arch: RelocationArch, Tls: TlsResolver<Arch>> ModuleScope<Arch, Tls> {
    /// Creates an empty module scope for `domain`.
    #[inline]
    pub fn new(domain: DomainId) -> Self {
        Self {
            modules: Arc::new(Vec::new()),
            domain,
        }
    }

    /// Returns the runtime domain shared by this module group.
    #[inline]
    pub const fn domain_id(&self) -> DomainId {
        self.domain
    }

    /// Checks that this scope and all its modules belong to `expected`.
    pub fn check_domain(&self, expected: DomainId) -> Result<()> {
        expected.ensure(self.domain)?;
        for module in self.modules.iter() {
            expected.ensure(module.domain_id())?;
        }
        Ok(())
    }

    /// Appends a module without modifying existing snapshots.
    pub fn push(&mut self, module: ModuleHandle<Arch, Tls>) {
        Arc::make_mut(&mut self.modules).push(module);
    }

    /// Replaces this scope's modules without modifying existing snapshots.
    pub fn replace<I, R>(&mut self, modules: I)
    where
        I: IntoIterator<Item = R>,
        R: Into<ModuleHandle<Arch, Tls>>,
    {
        if let Some(current) = Arc::get_mut(&mut self.modules) {
            current.clear();
            current.extend(modules.into_iter().map(Into::into));
        } else {
            self.modules = Arc::new(modules.into_iter().map(Into::into).collect());
        }
    }

    /// Appends modules without modifying existing snapshots.
    pub fn extend<I, R>(&mut self, modules: I)
    where
        I: IntoIterator<Item = R>,
        R: Into<ModuleHandle<Arch, Tls>>,
    {
        Arc::make_mut(&mut self.modules).extend(modules.into_iter().map(Into::into));
    }

    /// Retains only modules accepted by `keep` without modifying existing snapshots.
    pub fn retain(&mut self, keep: impl FnMut(&ModuleHandle<Arch, Tls>) -> bool) {
        Arc::make_mut(&mut self.modules).retain(keep);
    }
}

impl<Arch: RelocationArch, Tls: TlsResolver<Arch>> Clone for LocalScope<Arch, Tls> {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            groups: Arc::clone(&self.groups),
            lazy: self.lazy.clone(),
        }
    }
}

impl<Arch: RelocationArch, Tls: TlsResolver<Arch>> Clone for GlobalScope<Arch, Tls> {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
        }
    }
}

impl<Arch, Tls> fmt::Debug for LocalScope<Arch, Tls>
where
    Arch: RelocationArch,
    Tls: TlsResolver<Arch>,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("LocalScope")
            .field("groups", &self.groups)
            .field("lazy", &self.lazy)
            .finish()
    }
}

impl<Arch: RelocationArch, Tls: TlsResolver<Arch>> LocalScope<Arch, Tls> {
    /// Creates an empty local scope for `domain`.
    #[inline]
    pub fn empty(domain: DomainId) -> Self {
        Self::new([], ModuleScope::new(domain))
    }

    /// Creates a local scope with explicit eager groups and deferred scope.
    pub fn new<I>(groups: I, lazy: ModuleScope<Arch, Tls>) -> Self
    where
        I: IntoIterator<Item = ModuleScope<Arch, Tls>>,
    {
        let groups = groups.into_iter().collect::<Vec<_>>();
        debug_assert!(
            groups
                .iter()
                .all(|group| group.domain_id() == lazy.domain_id())
        );
        Self {
            groups: Arc::from(groups),
            lazy,
        }
    }

    /// Returns the runtime domain shared by this lookup scope.
    #[inline]
    pub const fn domain_id(&self) -> DomainId {
        self.lazy.domain_id()
    }

    /// Checks that the eager and deferred scopes belong to `expected`.
    #[inline]
    pub fn check_domain(&self, expected: DomainId) -> Result<()> {
        for group in self.groups.iter() {
            group.check_domain(expected)?;
        }
        self.lazy.check_domain(expected)
    }

    #[inline]
    pub(crate) fn downgrade(
        &self,
        global: Option<&GlobalScope<Arch, Tls>>,
    ) -> WeakLocalScope<Arch, Tls> {
        let domain = self.domain_id();
        debug_assert!(global.is_none_or(|global| global.domain_id() == domain));
        WeakLocalScope {
            local: Arc::downgrade(&self.lazy.modules),
            global: global.map(GlobalScope::downgrade),
            domain,
        }
    }

    /// Returns the eager module groups in lookup order.
    #[inline]
    pub fn groups(&self) -> &[ModuleScope<Arch, Tls>] {
        &self.groups
    }

    /// Returns the local scope retained for deferred PLT lookup.
    #[inline]
    pub const fn lazy_scope(&self) -> &ModuleScope<Arch, Tls> {
        &self.lazy
    }

    /// Appends an eager lookup group without changing deferred lookup.
    pub fn push(&mut self, group: ModuleScope<Arch, Tls>) {
        debug_assert_eq!(group.domain_id(), self.domain_id());
        let mut groups = Vec::with_capacity(self.groups.len() + 1);
        groups.extend(self.groups.iter().cloned());
        groups.push(group);
        self.groups = Arc::from(groups);
    }

    /// Appends eager lookup groups without changing deferred lookup.
    pub fn extend<I>(&mut self, groups: I)
    where
        I: IntoIterator<Item = ModuleScope<Arch, Tls>>,
    {
        let mut groups = groups.into_iter().peekable();
        if groups.peek().is_none() {
            return;
        }
        let (lower, _) = groups.size_hint();
        let mut current = Vec::with_capacity(self.groups.len() + lower);
        current.extend(self.groups.iter().cloned());
        for group in groups {
            debug_assert_eq!(group.domain_id(), self.domain_id());
            current.push(group);
        }
        self.groups = Arc::from(current);
    }

    /// Iterates over eager lookup modules in order.
    #[inline]
    pub fn iter(&self) -> impl Iterator<Item = &ModuleHandle<Arch, Tls>> {
        self.groups.iter().flat_map(|group| group.iter())
    }

    /// Returns the number of eager lookup entries.
    #[inline]
    pub fn len(&self) -> usize {
        self.groups.iter().map(|group| group.len()).sum()
    }

    /// Returns whether the eager lookup scope is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.groups.iter().all(|group| group.is_empty())
    }

    /// Replaces the local scope retained for deferred PLT lookup.
    #[inline]
    pub fn set_lazy_scope(&mut self, scope: ModuleScope<Arch, Tls>) {
        debug_assert_eq!(scope.domain_id(), self.domain_id());
        self.lazy = scope;
    }
}

impl<Arch: RelocationArch, Tls: TlsResolver<Arch>> WeakLocalScope<Arch, Tls> {
    #[inline]
    pub(crate) fn upgrade_local(&self) -> Option<LocalScope<Arch, Tls>> {
        let scope = ModuleScope {
            modules: self.local.upgrade()?,
            domain: self.domain,
        };
        Some(LocalScope::new([scope.clone()], scope))
    }

    #[inline]
    pub(crate) fn upgrade_global(&self) -> Option<GlobalScope<Arch, Tls>> {
        self.global
            .as_ref()
            .and_then(Weak::upgrade)
            .map(|inner| GlobalScope { inner })
    }
}

impl<Arch: RelocationArch, Tls: TlsResolver<Arch>> GlobalScope<Arch, Tls> {
    #[inline]
    pub(crate) fn new(domain: DomainId) -> Self {
        Self {
            inner: Arc::new(GlobalScopeInner {
                modules: RwLock::new(ModuleScope::new(domain)),
                domain,
            }),
        }
    }

    #[inline]
    /// Returns the runtime domain shared by modules in this scope.
    pub fn domain_id(&self) -> DomainId {
        self.inner.domain
    }

    #[inline]
    fn downgrade(&self) -> Weak<GlobalScopeInner<Arch, Tls>> {
        Arc::downgrade(&self.inner)
    }

    #[inline]
    /// Captures the current global lookup order.
    ///
    /// The returned copy-on-write scope remains stable if the context later
    /// promotes or unloads modules.
    pub fn modules(&self) -> ModuleScope<Arch, Tls> {
        self.read().clone()
    }

    #[inline]
    pub(crate) fn read(&self) -> RwLockReadGuard<'_, ModuleScope<Arch, Tls>> {
        self.inner.modules.read()
    }

    #[inline]
    pub(crate) fn write(&self) -> RwLockWriteGuard<'_, ModuleScope<Arch, Tls>> {
        self.inner.modules.write()
    }
}

#[cfg(test)]
mod tests {
    extern crate std;

    use super::*;
    use crate::image::SyntheticModule;

    #[test]
    fn shared_module_preserves_identity() {
        let module = Arc::new(SyntheticModule::<NativeArch>::empty("shared"));
        let first: ModuleHandle = ModuleHandle::new(module.clone());
        let second: ModuleHandle = ModuleHandle::new(module);

        assert!(first.as_ref().ptr_eq(second.as_ref()));
    }

    #[test]
    fn module_scope_mutation_preserves_snapshots() {
        let first: ModuleHandle = ModuleHandle::new(SyntheticModule::<NativeArch>::empty("first"));
        let second: ModuleHandle =
            ModuleHandle::new(SyntheticModule::<NativeArch>::empty("second"));
        let mut scope: ModuleScope = ModuleScope::new(DomainId::PROCESS);
        scope.push(first);
        let snapshot = scope.clone();

        scope.push(second);
        assert_eq!(snapshot.len(), 1);
        assert_eq!(scope.len(), 2);

        scope.retain(|module| module.name() == "second");
        assert_eq!(snapshot.iter().next().unwrap().name(), "first");
        assert_eq!(scope.iter().next().unwrap().name(), "second");
    }

    #[test]
    fn local_scope_retains_modules_and_tracks_live_global() {
        let first: ModuleHandle = ModuleHandle::new(SyntheticModule::<NativeArch>::empty("first"));
        let second: ModuleHandle =
            ModuleHandle::new(SyntheticModule::<NativeArch>::empty("second"));
        let local: ModuleHandle = ModuleHandle::new(SyntheticModule::<NativeArch>::empty("local"));
        let global = GlobalScope::new(DomainId::PROCESS);
        global.write().push(first);
        let prepared = global.modules();

        let mut local_scope = ModuleScope::new(DomainId::PROCESS);
        local_scope.push(local);
        let scope = LocalScope::new([local_scope.clone()], local_scope);
        let weak = scope.downgrade(Some(&global));

        global.write().replace([second]);
        assert_eq!(
            prepared
                .iter()
                .map(|module| module.name())
                .collect::<Vec<_>>(),
            ["first"]
        );
        assert_eq!(
            weak.upgrade_local()
                .unwrap()
                .iter()
                .map(|module| module.name())
                .collect::<Vec<_>>(),
            ["local"]
        );

        let deferred = weak.upgrade_local().unwrap();
        let live = weak.upgrade_global().unwrap();
        assert_eq!(
            live.modules()
                .iter()
                .map(|module| module.name())
                .collect::<Vec<_>>(),
            ["second"]
        );
        assert_eq!(
            deferred
                .iter()
                .map(|module| module.name())
                .collect::<Vec<_>>(),
            ["local"]
        );

        drop(live);
        drop(global);
        let deferred = weak.upgrade_local().unwrap();
        assert!(weak.upgrade_global().is_none());
        assert_eq!(
            deferred
                .iter()
                .map(|module| module.name())
                .collect::<Vec<_>>(),
            ["local"]
        );
        assert_eq!(
            scope.iter().map(|module| module.name()).collect::<Vec<_>>(),
            ["local"]
        );
    }

    #[test]
    fn deferred_scope_uses_retained_dependencies() {
        let root: ModuleHandle = ModuleHandle::new(SyntheticModule::<NativeArch>::empty("root"));
        let dependency: ModuleHandle =
            ModuleHandle::new(SyntheticModule::<NativeArch>::empty("dependency"));
        let unrelated: ModuleHandle =
            ModuleHandle::new(SyntheticModule::<NativeArch>::empty("unrelated"));
        let mut group = ModuleScope::new(DomainId::PROCESS);
        group.extend([root, dependency.clone()]);
        let mut retained = ModuleScope::new(DomainId::PROCESS);
        retained.push(dependency);
        let owner = retained.clone();
        let mut scope = LocalScope::new([group], retained);
        let mut extra = ModuleScope::new(DomainId::PROCESS);
        extra.push(unrelated);
        scope.push(extra);
        let weak = scope.downgrade(None);

        assert_eq!(
            scope.iter().map(|module| module.name()).collect::<Vec<_>>(),
            ["root", "dependency", "unrelated"]
        );
        assert_eq!(
            scope
                .lazy_scope()
                .iter()
                .map(|module| module.name())
                .collect::<Vec<_>>(),
            ["dependency"]
        );
        assert_eq!(
            weak.upgrade_local()
                .unwrap()
                .iter()
                .map(|module| module.name())
                .collect::<Vec<_>>(),
            ["dependency"]
        );

        drop(scope);
        drop(owner);
        assert!(weak.upgrade_local().is_none());
    }

    #[test]
    fn initializer_panic_marks_module_failed() {
        let state = ModuleState::new(ModuleSourceId::fresh(), DomainId::PROCESS);
        let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _ = state.initialize(|| -> crate::Result<()> { panic!("initializer panic") });
        }));

        assert!(panic.is_err());
        assert!(!state.is_initialized());
        assert!(state.initialize(|| Ok(())).is_err());
    }

    #[test]
    fn module_state_ignores_self_binding() {
        let module = SyntheticModule::<NativeArch>::empty("module");
        let state = <SyntheticModule<NativeArch> as Module<NativeArch>>::state(&module);
        let binding = state.instance_id();

        state.install_effects([binding], []);

        assert!(state.with_effects(|bindings, _| bindings.is_empty()));
    }

    #[test]
    fn binding_distinguishes_reloaded_source() {
        let source = ModuleSourceId::fresh();
        let old = ModuleState::new(source, DomainId::PROCESS);
        let binding = old.instance_id();
        let replacement = ModuleState::new(source, DomainId::PROCESS);

        assert_eq!(binding, old.instance_id());
        assert_ne!(binding, replacement.instance_id());
    }
}