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
use super::{
    context::LinkContext,
    storage::{ModuleId, ModuleKey, ModuleLease, ModuleSlot, StoredEntry},
};
use crate::{
    LinkContextError, LinkerError, Result,
    arch::NativeArch,
    entity::{EntitySet, SecondaryMap},
    image::{ModuleHandle, ModuleInstanceId, ModuleScope},
    input::ModuleSourceId,
    relocation::RelocationArch,
    tls::TlsResolver,
};
use alloc::{
    boxed::Box,
    collections::{BTreeMap, BTreeSet},
    vec::Vec,
};

struct PreparedModule<Meta, Arch: RelocationArch, Tls: TlsResolver<Arch>> {
    key: ModuleKey,
    existing: Option<ModuleSlot>,
    instance: ModuleInstanceId,
    module: ModuleHandle<Arch, Tls>,
    deps: Box<[ModuleInstanceId]>,
    meta: Meta,
}

/// One module and its direct edges in a graph imported into a [`LinkContext`].
///
/// Dependencies use concrete module instance identities rather than source ids
/// or names. This preserves bindings across unload/reload cycles and remains
/// unambiguous when several modules share a key. Use [`LinkContext::add_alias`]
/// separately for additional names.
pub struct GraphModule<Meta = (), Arch: RelocationArch = NativeArch, Tls: TlsResolver<Arch> = ()> {
    key: ModuleKey,
    module: ModuleHandle<Arch, Tls>,
    deps: Box<[ModuleInstanceId]>,
    meta: Meta,
}

impl<Arch, Tls> GraphModule<(), Arch, Tls>
where
    Arch: RelocationArch,
    Tls: TlsResolver<Arch>,
{
    /// Creates a graph node without context-specific metadata.
    #[inline]
    pub fn new(key: impl Into<ModuleKey>, module: impl Into<ModuleHandle<Arch, Tls>>) -> Self {
        Self::with_meta(key, module, ())
    }
}

impl<Meta, Arch, Tls> GraphModule<Meta, Arch, Tls>
where
    Arch: RelocationArch,
    Tls: TlsResolver<Arch>,
{
    /// Creates a graph node with context-specific metadata.
    #[inline]
    pub fn with_meta(
        key: impl Into<ModuleKey>,
        module: impl Into<ModuleHandle<Arch, Tls>>,
        meta: Meta,
    ) -> Self {
        Self {
            key: key.into(),
            module: module.into(),
            deps: Box::new([]),
            meta,
        }
    }

    /// Sets the direct dependency instances of this node.
    #[inline]
    pub fn dependencies(mut self, deps: impl IntoIterator<Item = ModuleInstanceId>) -> Self {
        self.deps = deps.into_iter().collect();
        self
    }
}

fn collect_modules<Arch, Tls, TargetMeta, SourceMeta>(
    target: &LinkContext<TargetMeta, Arch, Tls>,
    source: &LinkContext<SourceMeta, Arch, Tls>,
    slot: ModuleSlot,
    visited: &mut EntitySet<ModuleSlot>,
    mapped: &mut SecondaryMap<ModuleSlot, ModuleSlot>,
    modules: &mut Vec<ModuleSlot>,
    bindings: &mut Vec<(ModuleKey, ModuleSlot)>,
) -> Result<()>
where
    Arch: RelocationArch,
    Tls: TlsResolver<Arch>,
{
    if !visited.insert(slot) {
        return Ok(());
    }

    let module = source
        .committed
        .module(slot)
        .expect("import traversal must only contain committed modules");
    let key = module.entry_key();

    if let Some(target_slot) = target
        .committed
        .module_for_source(module.handle().source_id())
    {
        let target_module = target
            .committed
            .module(target_slot)
            .expect("source index must refer to a committed module");
        if target_module.handle().state().instance_id() != module.handle().state().instance_id() {
            return Err(LinkerError::context(LinkContextError::SourceOccupied {
                source: module.handle().source_id(),
            })
            .into());
        }
        bindings.push((key.clone(), target_slot));
        mapped.insert(slot, target_slot);
        return Ok(());
    }

    for dep in module.direct_deps().iter().copied() {
        collect_modules(target, source, dep, visited, mapped, modules, bindings)?;
    }
    let providers = module.handle().state().with_effects(|bindings, pins| {
        bindings
            .iter()
            .chain(pins)
            .map(|binding| {
                source
                    .committed
                    .module_for_binding(*binding)
                    .expect("bound module must remain committed with its dependent")
            })
            .collect::<Vec<_>>()
    });
    for dep in providers {
        collect_modules(target, source, dep, visited, mapped, modules, bindings)?;
    }
    modules.push(slot);
    Ok(())
}

fn copy_modules<Arch, Tls, TargetMeta, SourceMeta>(
    target: &mut LinkContext<TargetMeta, Arch, Tls>,
    source: &LinkContext<SourceMeta, Arch, Tls>,
    modules: &[ModuleSlot],
    mapped: &SecondaryMap<ModuleSlot, ModuleSlot>,
) where
    Arch: RelocationArch,
    Tls: TlsResolver<Arch>,
    TargetMeta: Default,
{
    let mut lifecycle = Vec::with_capacity(modules.len());
    let mut pins = Vec::new();
    for &slot in modules {
        let module = source
            .committed
            .module(slot)
            .expect("collected imports must only contain committed modules");
        let deps = module
            .direct_deps()
            .iter()
            .map(|dep| {
                *mapped
                    .get(*dep)
                    .expect("dependency closure must contain every bound module")
            })
            .collect::<Vec<_>>()
            .into_boxed_slice();
        let target_slot = *mapped
            .get(slot)
            .expect("collected module must have a target slot");
        target.committed.insert(
            target_slot,
            StoredEntry::new(
                module.entry_key().clone(),
                module.handle().clone(),
                deps,
                module.retained().clone(),
                0,
                TargetMeta::default(),
            ),
        );
        module.handle().state().with_effects(|_, requested| {
            for provider in requested {
                let source_slot = source
                    .committed
                    .module_for_binding(*provider)
                    .expect("pinned provider must remain committed with its dependent");
                let target_slot = *mapped
                    .get(source_slot)
                    .expect("import closure must contain every pinned provider");
                if !pins.contains(&target_slot) {
                    pins.push(target_slot);
                }
            }
        });
        lifecycle.push(target_slot);
    }
    target.committed.extend_lifecycle(&lifecycle);
    for slot in pins {
        target
            .committed
            .module_mut(slot)
            .expect("imported pin must refer to a committed module")
            .pin();
    }
}

fn copy_closure<Arch, Tls, TargetMeta, SourceMeta>(
    target: &mut LinkContext<TargetMeta, Arch, Tls>,
    source: &LinkContext<SourceMeta, Arch, Tls>,
    roots: &[ModuleSlot],
) -> Result<SecondaryMap<ModuleSlot, ModuleSlot>>
where
    Arch: RelocationArch,
    Tls: TlsResolver<Arch>,
    TargetMeta: Default,
{
    let mut mapped = SecondaryMap::default();
    let mut visited = EntitySet::default();
    let mut modules = Vec::new();
    let mut bindings = Vec::new();
    for &root in roots {
        collect_modules(
            target,
            source,
            root,
            &mut visited,
            &mut mapped,
            &mut modules,
            &mut bindings,
        )?;
    }
    for &slot in &modules {
        let module = source
            .committed
            .module(slot)
            .expect("collected imports must only contain committed modules");
        let module_key = module.entry_key().clone();
        let target_slot = target.committed.alloc_module();
        bindings.push((module_key, target_slot));
        mapped.insert(slot, target_slot);
    }
    copy_modules(target, source, &modules, &mapped);
    for (key, module) in bindings {
        target.committed.bind_key(key, module);
    }
    Ok(mapped)
}

fn reusable_root<Arch, Tls, TargetMeta, SourceMeta>(
    target: &LinkContext<TargetMeta, Arch, Tls>,
    source: &LinkContext<SourceMeta, Arch, Tls>,
    slot: ModuleSlot,
) -> Option<(ModuleSlot, ModuleKey)>
where
    Arch: RelocationArch,
    Tls: TlsResolver<Arch>,
{
    let module = source
        .committed
        .module(slot)
        .expect("import roots must refer to committed modules");
    target
        .committed
        .module_for_source(module.handle().source_id())
        .map(|target| (target, module.entry_key().clone()))
}

impl<Meta, Arch, Tls> LinkContext<Meta, Arch, Tls>
where
    Arch: RelocationArch,
    Tls: TlsResolver<Arch>,
{
    /// Inserts one retained graph node.
    ///
    /// This is the single-node form of [`insert_batch`](Self::insert_batch).
    #[inline]
    pub fn insert(&mut self, module: GraphModule<Meta, Arch, Tls>) -> Result<ModuleLease> {
        Ok(self
            .insert_batch([module])?
            .into_vec()
            .pop()
            .expect("single-node batch must return one lease"))
    }

    /// Inserts a module graph as one validated batch.
    ///
    /// Dependencies may refer to committed modules or other nodes in the batch,
    /// including cycles. Each input node adds one direct acquisition and returns
    /// one lease in input order. Modules sharing a key become ordered lookup
    /// candidates. An exact instance already in this context is reused and its
    /// new key is bound to the existing module; the supplied metadata and
    /// dependency list are then ignored. A different instance of an occupied
    /// source is rejected.
    pub fn insert_batch(
        &mut self,
        modules: impl IntoIterator<Item = GraphModule<Meta, Arch, Tls>>,
    ) -> Result<Box<[ModuleLease]>> {
        let modules = modules.into_iter().collect::<Vec<_>>();
        for node in &modules {
            self.committed.ensure_domain(node.module.domain_id())?;
        }

        let mut sources = BTreeSet::<ModuleSourceId>::new();
        let mut instances = BTreeSet::<ModuleInstanceId>::new();
        let mut planned = Vec::with_capacity(modules.len());

        for GraphModule {
            key: module_key,
            module,
            deps,
            meta,
        } in modules
        {
            let instance = module.state().instance_id();
            let source = instance.source_id();
            if !sources.insert(source) {
                return Err(
                    LinkerError::context(LinkContextError::SourceOccupied { source }).into(),
                );
            }

            let existing = match self.committed.module_for_source(source) {
                Some(slot) => {
                    let committed = self
                        .committed
                        .module(slot)
                        .expect("source index must refer to a committed module");
                    if committed.handle().state().instance_id() != instance {
                        return Err(LinkerError::context(LinkContextError::SourceOccupied {
                            source,
                        })
                        .into());
                    }
                    Some(slot)
                }
                None => None,
            };
            instances.insert(instance);
            planned.push(PreparedModule {
                key: module_key,
                existing,
                instance,
                module,
                deps,
                meta,
            });
        }

        for node in &planned {
            if node.existing.is_some() {
                continue;
            }
            let validate = |id| -> Result<()> {
                (instances.contains(&id) || self.committed.module_for_binding(id).is_some())
                    .then_some(())
                    .ok_or_else(|| {
                        LinkerError::context(LinkContextError::DependencyMissing { id }).into()
                    })
            };
            node.deps.iter().copied().try_for_each(&validate)?;
            node.module.state().with_effects(|bindings, pins| {
                bindings.iter().chain(pins).copied().try_for_each(validate)
            })?;
        }

        let mut slots = BTreeMap::<ModuleInstanceId, ModuleSlot>::new();
        for node in &planned {
            let slot = match node.existing {
                Some(slot) => slot,
                None => self.committed.alloc_module(),
            };
            slots.insert(node.instance, slot);
        }
        let resolved = planned
            .iter()
            .map(|node| {
                if node.existing.is_some() {
                    return Vec::new().into_boxed_slice();
                }
                node.deps
                    .iter()
                    .copied()
                    .map(|id| {
                        slots
                            .get(&id)
                            .copied()
                            .or_else(|| self.committed.module_for_binding(id))
                            .expect("validated dependency must have a module slot")
                    })
                    .collect::<Vec<_>>()
                    .into_boxed_slice()
            })
            .collect::<Vec<_>>();

        let mut pins = Vec::new();
        for node in &planned {
            if node.existing.is_some() {
                continue;
            }
            node.module.state().with_effects(|_, requested| {
                for provider in requested {
                    let slot = slots
                        .get(provider)
                        .copied()
                        .or_else(|| self.committed.module_for_binding(*provider))
                        .expect("validated pin must have a module slot");
                    if !pins.contains(&slot) {
                        pins.push(slot);
                    }
                }
            });
        }

        let mut lifecycle = Vec::with_capacity(planned.len());
        let mut leases = Vec::with_capacity(planned.len());
        for (node, deps) in planned.into_iter().zip(resolved) {
            let slot = slots[&node.instance];
            if node.existing.is_none() {
                let retained = ModuleScope::new(node.module.domain_id());
                self.committed.insert(
                    slot,
                    StoredEntry::new(node.key.clone(), node.module, deps, retained, 1, node.meta),
                );
                lifecycle.push(slot);
            } else {
                self.committed
                    .module_mut(slot)
                    .expect("reused module must remain committed")
                    .acquire_root();
            }
            self.committed.bind_key(node.key, slot);
            leases.push(ModuleLease::new(self.committed.make_module_id(slot)));
        }
        self.committed.extend_lifecycle(&lifecycle);
        for slot in pins {
            self.committed
                .module_mut(slot)
                .expect("inserted pin must refer to a committed module")
                .pin();
        }
        Ok(leases.into_boxed_slice())
    }

    /// Imports one module and its bound dependency closure from another context.
    ///
    /// The imported modules share their underlying [`ModuleHandle`] allocations
    /// with `source`, but receive ids in this context. The selected module gains
    /// one direct acquisition; imported dependencies do not become roots.
    /// A root whose source is already present reuses the target context's
    /// instance. Within a copied dependency closure, only exact module instances
    /// are reused because the relocated parent may already contain addresses
    /// from that incarnation. Modules sharing an entry key retain insertion
    /// order. Source aliases are not imported.
    pub fn import<SourceMeta>(
        &mut self,
        source: &LinkContext<SourceMeta, Arch, Tls>,
        id: ModuleId,
    ) -> Result<ModuleLease>
    where
        Meta: Default,
    {
        self.committed.ensure_domain(source.committed.domain())?;
        let source_root = source.committed.module_slot(id)?;
        if let Some((root, key)) = reusable_root(self, source, source_root) {
            self.committed.bind_key(key, root);
            let id = self.committed.make_module_id(root);
            self.committed
                .module_mut(root)
                .expect("reused import root must remain committed")
                .acquire_root();
            return Ok(ModuleLease::new(id));
        }

        let mapped = copy_closure(self, source, &[source_root])?;
        let root = *mapped
            .get(source_root)
            .expect("imported root must have a target slot");
        let id = self.committed.make_module_id(root);
        self.committed
            .module_mut(root)
            .expect("copied import root must be committed")
            .acquire_root();
        Ok(ModuleLease::new(id))
    }

    /// Imports every acquired or pinned root from another context.
    ///
    /// Each source root receives one acquisition in this context, regardless of
    /// its acquisition count in `source`. Shared dependencies are copied once
    /// and remain dependency-only. Each returned lease represents one direct
    /// acquisition in this context. Roots already present by source are reused;
    /// copied dependency closures still require exact instances. Source aliases
    /// are not imported because they belong to the source namespace.
    pub fn import_roots<SourceMeta>(
        &mut self,
        source: &LinkContext<SourceMeta, Arch, Tls>,
    ) -> Result<Box<[ModuleLease]>>
    where
        Meta: Default,
    {
        self.committed.ensure_domain(source.committed.domain())?;
        let roots = source
            .committed
            .lifecycle()
            .filter(|slot| {
                source
                    .committed
                    .module(*slot)
                    .is_some_and(|module| module.is_root())
            })
            .collect::<Vec<_>>();
        let mut reused = Vec::new();
        let mut copied = Vec::new();
        for &root in &roots {
            if let Some((target, key)) = reusable_root(self, source, root) {
                reused.push((root, target, key));
            } else {
                copied.push(root);
            }
        }
        let mut mapped = copy_closure(self, source, &copied)?;
        for (source, target, key) in reused {
            self.committed.bind_key(key, target);
            mapped.insert(source, target);
        }
        let mut imported = Vec::with_capacity(roots.len());
        for root in roots {
            let root = *mapped
                .get(root)
                .expect("imported root must have a target slot");
            let id = self.committed.make_module_id(root);
            self.committed
                .module_mut(root)
                .expect("imported root must be committed")
                .acquire_root();
            imported.push(ModuleLease::new(id));
        }
        Ok(imported.into_boxed_slice())
    }
}

#[cfg(test)]
mod tests {
    use super::{GraphModule, LinkContext};
    use crate::{
        Error, LinkContextError, LinkerError,
        arch::NativeArch,
        image::{ModuleHandle, SyntheticModule},
        runtime::DomainId,
    };
    use alloc::vec::Vec;

    fn module(name: &str) -> ModuleHandle<NativeArch> {
        ModuleHandle::new(SyntheticModule::empty(name))
    }

    #[test]
    fn inserts_cycle() {
        let first = module("first");
        let second = module("second");
        let first_instance = first.state().instance_id();
        let second_instance = second.state().instance_id();
        let mut context = LinkContext::<()>::new(DomainId::PROCESS);

        let leases = context
            .insert_batch([
                GraphModule::new("first", first).dependencies([second_instance]),
                GraphModule::new("second", second).dependencies([first_instance]),
            ])
            .unwrap();
        let mut leases = leases.into_vec().into_iter();
        let first = leases.next().unwrap();
        let second = leases.next().unwrap();

        assert_eq!(
            context.direct_deps(first.id()).unwrap().collect::<Vec<_>>(),
            [second.id()]
        );
        assert_eq!(
            context
                .direct_deps(second.id())
                .unwrap()
                .collect::<Vec<_>>(),
            [first.id()]
        );
        assert!(context.release(first).unwrap().is_empty());
        assert_eq!(context.release(second).unwrap().len(), 2);
        assert!(context.is_empty());
    }

    #[test]
    fn duplicate_keys_keep_order() {
        let mut context = LinkContext::<()>::new(DomainId::PROCESS);
        let leases = context
            .insert_batch([
                GraphModule::new("shared", module("first")),
                GraphModule::new("shared", module("second")),
            ])
            .unwrap();
        let mut leases = leases.into_vec().into_iter();
        let first = leases.next().unwrap();
        let second = leases.next().unwrap();

        assert_eq!(context.module_id("shared"), Some(first.id()));
        assert_eq!(context.release(first).unwrap().len(), 1);
        assert_eq!(context.module_id("shared"), Some(second.id()));
        assert_eq!(context.release(second).unwrap().len(), 1);
    }

    #[test]
    fn uses_committed_dependency() {
        let dependency = module("dependency");
        let dependency_instance = dependency.state().instance_id();
        let mut context = LinkContext::<()>::new(DomainId::PROCESS);
        let dependency = context
            .insert(GraphModule::new("dependency", dependency))
            .unwrap();

        let root = context
            .insert_batch([
                GraphModule::new("root", module("root")).dependencies([dependency_instance])
            ])
            .unwrap()
            .into_vec()
            .pop()
            .unwrap();

        assert_eq!(
            context.direct_deps(root.id()).unwrap().collect::<Vec<_>>(),
            [dependency.id()]
        );
        assert!(context.release(dependency).unwrap().is_empty());
        assert_eq!(context.release(root).unwrap().len(), 2);
    }

    #[test]
    fn missing_dependency_does_not_publish() {
        let missing = module("missing").state().instance_id();
        let mut context = LinkContext::<()>::new(DomainId::PROCESS);
        let error = match context
            .insert_batch([GraphModule::new("root", module("root")).dependencies([missing])])
        {
            Ok(_) => panic!("missing dependency should fail"),
            Err(error) => error,
        };

        let Error::Linker(LinkerError::Context { reason }) = error else {
            panic!("unexpected graph error: {error}");
        };
        assert!(matches!(
            *reason,
            LinkContextError::DependencyMissing { id } if id == missing
        ));
        assert!(context.is_empty());
        assert_eq!(context.module_id("root"), None);
    }

    #[test]
    fn reuses_exact_instance() {
        let module = module("shared");
        let mut context = LinkContext::<()>::new(DomainId::PROCESS);
        let first = context
            .insert(GraphModule::new("first", module.clone()))
            .unwrap();
        let second = context
            .insert_batch([GraphModule::new("second", module)])
            .unwrap()
            .into_vec()
            .pop()
            .unwrap();

        assert_eq!(first.id(), second.id());
        assert_eq!(context.module_id("second"), Some(first.id()));
        assert!(context.release(first).unwrap().is_empty());
        assert_eq!(context.release(second).unwrap().len(), 1);
    }
}