elf_loader 0.16.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
use super::storage::{
    CommittedStorage, ContextId, DepEdge, EntryState, KeyId, ModuleId, ModuleSlot,
};
use crate::{
    LinkContextError, LinkerError, Result, arch::NativeArch, image::ModuleHandle,
    relocation::RelocationArch, tls::TlsResolver,
};
use alloc::{
    boxed::Box,
    collections::{BTreeSet, VecDeque},
    vec::Vec,
};
use core::borrow::Borrow;

#[inline]
fn require_module<T>(id: ModuleId, state: EntryState<T>) -> Result<T> {
    state
        .present()
        .ok_or_else(|| LinkerError::context(LinkContextError::ModuleNotCommitted { id }).into())
}

#[inline]
fn dep_ids(context: ContextId, edge: DepEdge) -> (KeyId, ModuleId) {
    (
        KeyId::from_slot(context, edge.key()),
        ModuleId::from_slot(context, edge.module()),
    )
}

/// Owned direct dependency edges removed from a link context.
pub struct DirectDeps {
    context: ContextId,
    edges: Box<[DepEdge]>,
}

impl DirectDeps {
    #[inline]
    fn new(context: ContextId, edges: Box<[DepEdge]>) -> Self {
        Self { context, edges }
    }

    /// Returns true when no direct dependency edges were removed.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.edges.is_empty()
    }

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

    /// Iterates over removed dependency key/module pairs.
    #[inline]
    pub fn iter(&self) -> impl Iterator<Item = (KeyId, ModuleId)> + '_ {
        let context = self.context;
        self.edges
            .iter()
            .copied()
            .map(move |edge| dep_ids(context, edge))
    }

    /// Consumes the collection and yields removed dependency key/module pairs.
    #[inline]
    pub fn into_iter(self) -> impl Iterator<Item = (KeyId, ModuleId)> {
        let context = self.context;
        self.edges
            .into_vec()
            .into_iter()
            .map(move |edge| dep_ids(context, edge))
    }
}

fn copy_committed_module<K, D, M, Arch, Tls>(
    target: &mut LinkContext<K, D, M, Arch, Tls>,
    source: &LinkContext<K, D, M, Arch, Tls>,
    slot: ModuleSlot,
    copied: &mut BTreeSet<ModuleSlot>,
) -> Result<()>
where
    K: Clone + Ord,
    D: 'static,
    M: Clone,
    Arch: RelocationArch,
    Tls: TlsResolver<Arch>,
{
    if !copied.insert(slot) {
        return Ok(());
    }

    let id = source.committed.make_module_id(slot);
    let module = require_module(id, source.committed.module(slot))?;
    for dep in module.direct_deps().iter().copied() {
        copy_committed_module(target, source, dep.module(), copied)?;
    }

    let entry_key = source.committed.key(module.entry_key());
    if target.committed.contains_key(entry_key) {
        return Ok(());
    }

    let direct_deps = module
        .direct_deps()
        .iter()
        .map(|dep| {
            let dep_key = target
                .committed
                .intern_key(source.committed.key(dep.key()).clone());
            let source_dep_id = source.committed.make_module_id(dep.module());
            let source_dep = require_module(source_dep_id, source.committed.module(dep.module()))?;
            let source_dep_key = source.committed.key(source_dep.entry_key());
            let module = target
                .committed
                .key_slot_for(source_dep_key)
                .and_then(|slot| target.committed.module_for_key(slot))
                .expect("copied dependency module must resolve in target context");
            Ok(DepEdge::new(dep_key, module))
        })
        .collect::<Result<Vec<_>>>()?
        .into_boxed_slice();
    let entry_slot = target.committed.intern_key(entry_key.clone());
    target.committed.insert(
        entry_slot,
        module.handle().clone(),
        direct_deps,
        module.meta().clone(),
    );
    Ok(())
}

/// Local repository of committed modules and their dependency graph.
///
/// `LinkContext` is the mutable state paired with [`Linker`](crate::Linker).
/// It owns module ids, loaded module handles, aliases, and direct dependency
/// edges produced by successful linker loads.
///
/// Keep one context per target runtime/address space. Module ids and key ids are
/// branded with a context identity so ids from different contexts cannot be
/// mixed accidentally.
pub struct LinkContext<
    K,
    D: 'static,
    M = (),
    Arch: RelocationArch = NativeArch,
    Tls: TlsResolver<Arch> = (),
> {
    pub(super) committed: CommittedStorage<K, D, M, Arch, Tls>,
}

impl<K, D: 'static, M, Arch, Tls> Default for LinkContext<K, D, M, Arch, Tls>
where
    Arch: RelocationArch,
    Tls: TlsResolver<Arch>,
{
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl<K, D: 'static, M, Arch, Tls> LinkContext<K, D, M, Arch, Tls>
where
    Arch: RelocationArch,
    Tls: TlsResolver<Arch>,
{
    /// Creates an empty link context.
    #[inline]
    pub fn new() -> Self {
        Self {
            committed: CommittedStorage::new(ContextId::fresh()),
        }
    }

    /// Returns this context's runtime identity.
    #[inline]
    pub fn context_id(&self) -> ContextId {
        self.committed.context()
    }
}

impl<K, D: 'static, M, Arch, Tls> LinkContext<K, D, M, Arch, Tls>
where
    K: Clone + Ord,
    Arch: RelocationArch,
    Tls: TlsResolver<Arch>,
{
    /// Returns whether no modules have been committed.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.committed.is_empty()
    }

    /// Returns whether the context contains a module with `key`.
    #[inline]
    pub fn contains_key<Q>(&self, key: &Q) -> bool
    where
        K: Borrow<Q>,
        Q: Ord + ?Sized,
    {
        self.committed.contains_key(key)
    }

    /// Returns whether the context contains the committed module `id`.
    #[inline]
    pub fn contains_module(&self, id: ModuleId) -> Result<bool> {
        Ok(self
            .committed
            .contains_module(self.committed.module_slot(id)?))
    }

    /// Returns the interned id for a known key.
    #[inline]
    pub fn key_id<Q>(&self, key: &Q) -> Option<KeyId>
    where
        K: Borrow<Q>,
        Q: Ord + ?Sized,
    {
        self.committed
            .key_slot_for(key)
            .map(|slot| self.committed.make_key_id(slot))
    }

    /// Returns the key associated with an interned id.
    #[inline]
    pub fn key(&self, id: KeyId) -> Result<&K> {
        let slot = self.committed.key_slot(id)?;
        Ok(self.committed.key(slot))
    }

    /// Returns the committed module id that `id` resolves to.
    #[inline]
    pub fn module_id(&self, id: KeyId) -> Result<Option<ModuleId>> {
        let slot = self.committed.key_slot(id)?;
        Ok(self
            .committed
            .module_for_key(slot)
            .map(|slot| self.committed.make_module_id(slot)))
    }

    /// Returns the representative key associated with a committed module id.
    #[inline]
    pub fn module_key(&self, id: ModuleId) -> Result<&K> {
        let module_slot = self.committed.module_slot(id)?;
        let module = require_module(id, self.committed.module(module_slot))?;
        Ok(self.committed.key(module.entry_key()))
    }

    /// Returns the retained module handle associated with a committed module id.
    #[inline]
    pub fn get(&self, id: ModuleId) -> Result<&ModuleHandle<Arch, Tls>> {
        let slot = self.committed.module_slot(id)?;
        Ok(require_module(id, self.committed.module(slot))?.handle())
    }

    /// Returns direct dependency keys and bound modules for a committed module.
    #[inline]
    pub fn direct_deps(
        &self,
        id: ModuleId,
    ) -> Result<impl Iterator<Item = (KeyId, ModuleId)> + '_> {
        let slot = self.committed.module_slot(id)?;
        let context = self.committed.context();
        Ok(require_module(id, self.committed.module(slot))?
            .direct_deps()
            .iter()
            .copied()
            .map(move |edge| dep_ids(context, edge)))
    }

    /// Iterates committed modules in load order.
    #[inline]
    pub fn load_order(&self) -> impl Iterator<Item = ModuleId> + '_ {
        self.committed
            .load_order()
            .map(|slot| self.committed.make_module_id(slot))
    }

    /// Returns immutable user metadata for a committed module.
    #[inline]
    pub fn meta(&self, id: ModuleId) -> Result<&M> {
        let slot = self.committed.module_slot(id)?;
        Ok(require_module(id, self.committed.module(slot))?.meta())
    }

    /// Returns mutable user metadata for a committed module.
    #[inline]
    pub fn meta_mut(&mut self, id: ModuleId) -> Result<&mut M> {
        let slot = self.committed.module_slot(id)?;
        Ok(require_module(id, self.committed.module_mut(slot))?.meta_mut())
    }

    /// Inserts an already retained module with default metadata.
    pub fn insert<R>(&mut self, key: K, module: R, direct_deps: Box<[K]>) -> Result<ModuleId>
    where
        M: Default,
        R: Into<ModuleHandle<Arch, Tls>>,
    {
        self.insert_with_meta(key, module, direct_deps, M::default())
    }

    /// Inserts or replaces an already retained module with explicit metadata.
    pub fn insert_with_meta<R>(
        &mut self,
        key: K,
        module: R,
        direct_deps: Box<[K]>,
        meta: M,
    ) -> Result<ModuleId>
    where
        R: Into<ModuleHandle<Arch, Tls>>,
    {
        let slot = self.committed.intern_key(key);
        let direct_deps = direct_deps
            .into_vec()
            .into_iter()
            .map(|key| self.committed.intern_key(key))
            .collect::<Vec<_>>()
            .into_boxed_slice();
        let direct_deps = self.committed.resolve_dep_edges(direct_deps)?;
        Ok(self
            .committed
            .insert(slot, module.into(), direct_deps, meta))
    }

    /// Adds or replaces an alternate key for an already committed module.
    ///
    /// Returns the previous committed module id when `alias` used to resolve to
    /// a different module.
    pub fn add_alias(&mut self, module_id: ModuleId, alias: K) -> Result<Option<ModuleId>> {
        let module_slot = self.committed.module_slot(module_id)?;
        if !self.committed.contains_module(module_slot) {
            return Err(LinkerError::context(LinkContextError::ModuleNotCommitted {
                id: module_id,
            })
            .into());
        }

        Ok(self
            .committed
            .add_alias(module_slot, alias)
            .map(|slot| self.committed.make_module_id(slot)))
    }

    /// Removes a committed module and returns its handle, dependencies, and metadata.
    #[inline]
    pub fn remove(&mut self, id: ModuleId) -> Result<(ModuleHandle<Arch, Tls>, DirectDeps, M)> {
        let slot = self.committed.module_slot(id)?;
        let (module, direct_deps, meta) = require_module(id, self.committed.remove(slot))?;
        Ok((
            module,
            DirectDeps::new(self.committed.context(), direct_deps),
            meta,
        ))
    }

    /// Returns the breadth-first dependency scope rooted at `root`.
    pub fn dependency_scope(&self, root: ModuleId) -> Result<Vec<ModuleId>> {
        let root_slot = self.committed.module_slot(root)?;
        if !self.committed.contains_module(root_slot) {
            return Err(
                LinkerError::context(LinkContextError::ModuleNotCommitted { id: root }).into(),
            );
        }

        let mut scope = Vec::new();
        let mut visited = BTreeSet::new();
        let mut queue = VecDeque::new();
        visited.insert(root_slot);
        queue.push_back(root_slot);

        while let Some(slot) = queue.pop_front() {
            let id = self.committed.make_module_id(slot);
            let module = require_module(id, self.committed.module(slot))?;

            scope.push(id);
            for dep in module.direct_deps().iter().copied() {
                let dep = dep.module();
                let dep_id = self.committed.make_module_id(dep);
                require_module(dep_id, self.committed.module(dep))?;
                if visited.insert(dep) {
                    queue.push_back(dep);
                }
            }
        }

        Ok(scope)
    }

    /// Extends this context with modules from another context.
    pub fn extend(&mut self, other: &LinkContext<K, D, M, Arch, Tls>) -> Result<()>
    where
        M: Clone,
    {
        let mut copied = BTreeSet::new();
        for slot in other.committed.load_order() {
            copy_committed_module(self, other, slot, &mut copied)?;
        }

        for (alias_slot, target_slot) in other.committed.aliases() {
            let alias = other.committed.key(alias_slot);
            let target_id = other.committed.make_module_id(target_slot);
            let canonical_slot =
                require_module(target_id, other.committed.module(target_slot))?.entry_key();
            let canonical = other.committed.key(canonical_slot);
            if self.committed.contains_key(alias) {
                continue;
            }
            let canonical_slot = self
                .committed
                .key_slot_for(canonical)
                .and_then(|slot| self.committed.module_for_key(slot))
                .expect("copied alias target must resolve to a committed module");
            let _ = self.committed.add_alias(canonical_slot, alias.clone());
        }
        Ok(())
    }

    /// Creates a detached clone of the committed context state.
    pub fn snapshot(&self) -> Self
    where
        M: Clone,
    {
        Self {
            committed: self.committed.clone(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::LinkContext;
    use crate::{
        arch::NativeArch,
        image::SyntheticModule,
        linker::{KeyId, ModuleId},
    };
    use alloc::{boxed::Box, string::String, vec::Vec};

    fn direct_deps<K: Clone + Ord>(
        context: &LinkContext<K, (), usize, NativeArch>,
        id: ModuleId,
    ) -> Vec<(KeyId, ModuleId)> {
        context
            .direct_deps(id)
            .expect("direct deps should resolve")
            .collect()
    }

    #[test]
    fn ids_do_not_cross_contexts() {
        let mut first = LinkContext::<&'static str, (), usize, NativeArch>::new();
        let first_root = first
            .insert_with_meta("root", SyntheticModule::empty("first"), Box::new([]), 1)
            .expect("failed to insert first module");
        let first_key = first.key_id(&"root").expect("root key should be interned");

        let mut second = LinkContext::<&'static str, (), usize, NativeArch>::new();
        let second_root = second
            .insert_with_meta("root", SyntheticModule::empty("second"), Box::new([]), 2)
            .expect("failed to insert second module");
        let second_key = second.key_id(&"root").expect("root key should be interned");

        assert_ne!(first.context_id(), second.context_id());
        assert_ne!(first_root, second_root);
        assert_ne!(first_key, second_key);
        assert!(second.contains_module(first_root).is_err());
        assert!(second.get(first_root).is_err());
        assert!(second.key(first_key).is_err());
        assert!(second.module_id(first_key).is_err());
        assert!(second.dependency_scope(first_root).is_err());
        assert!(second.contains_module(second_root).unwrap());
    }

    #[test]
    fn snapshot_clones_committed_state_without_rebuilding() {
        let mut context = LinkContext::<&'static str, (), usize, NativeArch>::new();
        let dep_module = context
            .insert_with_meta("dep", SyntheticModule::empty("dep"), Box::new([]), 3)
            .expect("failed to insert dependency module");
        let dep = context
            .key_id(&"dep")
            .expect("dependency key should be interned");
        let root = context
            .insert_with_meta("root", SyntheticModule::empty("root"), Box::new(["dep"]), 7)
            .expect("failed to insert root module");

        let snapshot = context.snapshot();
        assert_eq!(context.context_id(), snapshot.context_id());
        context.remove(root).unwrap();

        assert!(!context.contains_module(root).unwrap());
        assert!(context.get(root).is_err());
        assert!(snapshot.contains_module(root).unwrap());
        assert_eq!(snapshot.module_id(dep).unwrap(), Some(dep_module));
        assert_eq!(snapshot.module_key(root).unwrap(), &"root");
        assert_eq!(snapshot.key(dep).unwrap(), &"dep");
        assert_eq!(direct_deps(&snapshot, root), [(dep, dep_module)]);
        assert_eq!(snapshot.meta(root).unwrap(), &7);
    }

    #[test]
    fn dependency_edges_keep_their_bound_module_when_alias_changes() {
        let mut context = LinkContext::<String, (), usize, NativeArch>::new();
        let canonical = context
            .insert_with_meta(
                String::from("canonical"),
                SyntheticModule::empty("canonical"),
                Box::new([]),
                2,
            )
            .expect("failed to insert canonical module");
        context
            .add_alias(canonical, String::from("alias"))
            .expect("failed to add alias");
        let alias_id = context
            .key_id("alias")
            .expect("dependency key should be interned before root insertion");
        let root = context
            .insert_with_meta(
                String::from("root"),
                SyntheticModule::empty("root"),
                Box::new([String::from("alias")]),
                1,
            )
            .expect("failed to insert root module");
        let replacement = context
            .insert_with_meta(
                String::from("replacement"),
                SyntheticModule::empty("replacement"),
                Box::new([]),
                3,
            )
            .expect("failed to insert replacement module");
        context
            .add_alias(replacement, String::from("alias"))
            .expect("failed to replace alias");

        assert!(context.module_id(alias_id).unwrap().is_some());
        assert_eq!(context.key_id("alias"), Some(alias_id));
        assert_eq!(context.module_id(alias_id).unwrap(), Some(replacement));
        assert_eq!(direct_deps(&context, root), [(alias_id, canonical)]);
        assert_eq!(
            context
                .dependency_scope(root)
                .expect("dependency scope should resolve")
                .as_slice(),
            &[root, canonical]
        );
    }

    #[test]
    fn add_alias_replaces_existing_target() {
        let mut context = LinkContext::<&'static str, (), usize, NativeArch>::new();
        let first = context
            .insert_with_meta("first", SyntheticModule::empty("first"), Box::new([]), 1)
            .expect("failed to insert first module");
        let second = context
            .insert_with_meta("second", SyntheticModule::empty("second"), Box::new([]), 2)
            .expect("failed to insert second module");

        assert_eq!(
            context
                .add_alias(first, "alias")
                .expect("failed to add alias"),
            None
        );
        let alias = context.key_id(&"alias").expect("alias key should exist");
        assert_eq!(context.module_id(alias).unwrap(), Some(first));
        assert_eq!(
            context
                .add_alias(second, "alias")
                .expect("failed to replace alias"),
            Some(first)
        );
        assert_eq!(context.module_id(alias).unwrap(), Some(second));
        assert_eq!(
            context
                .add_alias(second, "alias")
                .expect("failed to keep alias"),
            None
        );
    }

    #[test]
    fn insert_with_meta_replaces_existing_key_in_place() {
        let mut context = LinkContext::<&'static str, (), usize, NativeArch>::new();
        context
            .insert_with_meta("old", SyntheticModule::empty("old"), Box::new([]), 0)
            .expect("failed to insert old dependency");
        let root = context
            .insert_with_meta(
                "root",
                SyntheticModule::empty("old-root"),
                Box::new(["old"]),
                1,
            )
            .expect("failed to insert root module");
        let root_key = context.key_id(&"root").expect("root key should exist");
        let new_dep_module = context
            .insert_with_meta("new", SyntheticModule::empty("new"), Box::new([]), 0)
            .expect("failed to insert new dependency");

        let replaced = context
            .insert_with_meta(
                "root",
                SyntheticModule::empty("new-root"),
                Box::new(["new"]),
                2,
            )
            .expect("failed to replace root module");
        let new_dep = context
            .key_id(&"new")
            .expect("new dependency should be interned");

        assert_eq!(replaced, root);
        assert_eq!(context.key_id(&"root"), Some(root_key));
        assert_eq!(context.module_id(root_key).unwrap(), Some(root));
        assert_eq!(context.module_key(root).unwrap(), &"root");
        assert_eq!(context.meta(root).unwrap(), &2);
        assert_eq!(direct_deps(&context, root), [(new_dep, new_dep_module)]);
    }

    #[test]
    fn insert_with_meta_replaces_alias_target_in_place() {
        let mut context = LinkContext::<&'static str, (), usize, NativeArch>::new();
        let root = context
            .insert_with_meta("root", SyntheticModule::empty("root"), Box::new([]), 1)
            .expect("failed to insert root module");
        context
            .add_alias(root, "alias")
            .expect("failed to add alias");
        let alias = context.key_id(&"alias").expect("alias key should exist");
        let dep_module = context
            .insert_with_meta("dep", SyntheticModule::empty("dep"), Box::new([]), 0)
            .expect("failed to insert dependency");

        let replaced = context
            .insert_with_meta(
                "alias",
                SyntheticModule::empty("alias"),
                Box::new(["dep"]),
                2,
            )
            .expect("failed to replace alias target");
        let dep = context
            .key_id(&"dep")
            .expect("dependency should be interned");

        assert_eq!(replaced, root);
        assert_eq!(context.module_id(alias).unwrap(), Some(root));
        assert_eq!(context.module_key(root).unwrap(), &"root");
        assert_eq!(context.meta(root).unwrap(), &2);
        assert_eq!(direct_deps(&context, root), [(dep, dep_module)]);
    }

    #[test]
    fn extend_preserves_bound_dependency_modules() {
        let mut source = LinkContext::<&'static str, (), usize, NativeArch>::new();
        let canonical = source
            .insert_with_meta(
                "canonical",
                SyntheticModule::empty("canonical"),
                Box::new([]),
                2,
            )
            .expect("failed to insert canonical module");
        source
            .add_alias(canonical, "alias")
            .expect("failed to add alias");
        let alias = source
            .key_id(&"alias")
            .expect("dependency key should be interned before root insertion");
        let root = source
            .insert_with_meta(
                "root",
                SyntheticModule::empty("root"),
                Box::new(["alias"]),
                1,
            )
            .expect("failed to insert root module");
        let replacement = source
            .insert_with_meta(
                "replacement",
                SyntheticModule::empty("replacement"),
                Box::new([]),
                3,
            )
            .expect("failed to insert replacement module");
        source
            .add_alias(replacement, "alias")
            .expect("failed to replace alias");

        let mut target = LinkContext::<&'static str, (), usize, NativeArch>::new();
        target.extend(&source).expect("failed to extend context");
        let target_root = target
            .key_id(&"root")
            .and_then(|id| target.module_id(id).unwrap())
            .expect("root module should be copied");
        let target_alias = target.key_id(&"alias").expect("alias key should be copied");
        let target_canonical = target
            .key_id(&"canonical")
            .and_then(|id| target.module_id(id).unwrap())
            .expect("canonical key should be copied");
        let target_replacement = target
            .key_id(&"replacement")
            .and_then(|id| target.module_id(id).unwrap())
            .expect("replacement key should be copied");

        assert_eq!(direct_deps(&source, root), [(alias, canonical)]);
        assert_eq!(
            source
                .dependency_scope(root)
                .expect("source scope should resolve")
                .as_slice(),
            &[root, canonical]
        );
        assert_eq!(
            direct_deps(&target, target_root),
            [(target_alias, target_canonical)]
        );
        assert_eq!(
            target.module_id(target_alias).unwrap(),
            Some(target_replacement)
        );
        assert_eq!(
            target
                .dependency_scope(target_root)
                .expect("target scope should resolve")
                .as_slice(),
            &[target_root, target_canonical]
        );
    }
}