Skip to main content
← PSoXide SDK guides and examples · SDK 80d1c329e977 · All Cargo features enabled; check feature gates before use.

psx_residency/
arena.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2//! Borrowed code/data arenas with generation-bound execution admission.
3//!
4//! Transport completes in caller-owned staging bytes before `install`. No
5//! arena storage is allocated here. Allocation uses the existing PagePool
6//! generations with one allocation unit per byte, not sector rounding.
7//! CPU entry calls borrow the registry and backing arena for their full scope.
8//! DMA, renderer and other external users must be quiescent before unload.
9
10use crate::{overlay, Handle, PagePool, Placement};
11
12/// Admission or installation failure; no callable entry is published on failure.
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum Error {
15    /// Invalid package or relocation.
16    Format(overlay::Error),
17    /// The supplied arena has a different range or alignment.
18    Arena,
19    /// No legal fixed-window range is free.
20    Space,
21    /// An allocation was evicted or reused.
22    Stale,
23    /// A dependency has not completed installation.
24    NotReady,
25    /// Immutable package identity or checksum differs.
26    Integrity,
27}
28impl From<overlay::Error> for Error {
29    fn from(error: overlay::Error) -> Self {
30        Self::Format(error)
31    }
32}
33
34/// A view of an existing word-aligned arena, including its MIPS address.
35/// Host tests may supply a model address; executing code requires its actual
36/// physical address, checked on MIPS at construction.
37pub struct CallerArena<'a> {
38    words: &'a mut [u32],
39    address: u32,
40}
41impl<'a> CallerArena<'a> {
42    /// Borrow existing storage. This creates no owned buffer or reservation.
43    pub fn new(words: &'a mut [u32], address: u32) -> Result<Self, Error> {
44        let bytes = u32::try_from(words.len().checked_mul(4).ok_or(Error::Arena)?)
45            .map_err(|_| Error::Arena)?;
46        if address & 3 != 0 || bytes == 0 || address.checked_add(bytes).is_none() {
47            return Err(Error::Arena);
48        }
49        #[cfg(target_arch = "mips")]
50        if words.as_ptr() as usize as u32 != address {
51            return Err(Error::Arena);
52        }
53        Ok(Self { words, address })
54    }
55}
56
57/// Trusted descriptor emitted alongside the same-compilation package.
58#[derive(Clone, Copy)]
59pub struct Descriptor {
60    /// Package identity.
61    pub id: u32,
62    /// Original linked address of its image.
63    pub linked: u32,
64    /// Checksum over all package words, before relocation.
65    pub checksum: u32,
66}
67
68/// Final-link-patched resident metadata; keep initialized storage in `.data`.
69/// This fixed layout avoids a second compilation moving typed callsites.
70#[repr(C)]
71#[derive(Clone, Copy)]
72pub struct PackedDescriptor {
73    /// Complete package word count, excluding CD sector padding.
74    pub words: u32,
75    /// Module identity.
76    pub id: u32,
77    /// Original linked image address.
78    pub linked: u32,
79    /// Complete package checksum before relocation.
80    pub checksum: u32,
81    /// Number of live records in the fixed-capacity resident call table.
82    pub calls: u32,
83}
84
85/// Final-link-patched typed callsite; selector is the declared call-pair index.
86#[repr(C)]
87#[derive(Clone, Copy)]
88pub struct PackedCall {
89    /// Stable caller/export pair index from packaging arguments.
90    pub selector: u32,
91    /// Resident J/JAL instruction address.
92    pub site: u32,
93    /// Cold export byte offset.
94    pub offset: u32,
95}
96/// A resident jump veneer for one typed call site, built by the final-link packer
97/// (`overlay-compose --veneers SYMBOL`). The site's J/JAL always targets the veneer;
98/// the veneer loads its own `target` word and jumps there. A lease writes the
99/// overlay's entry into `target` and the trap back when it ends, so entering and
100/// leaving a lease are two data stores: the instruction cache is flushed only when
101/// an image is installed or replaced ([`Registry::install`]), never per call.
102///
103/// The five code words never change after the final link and are never written at
104/// run time, so the cache can hold them for good. The data load of `target`
105/// is not cached (the console's data cache is the scratchpad).
106#[repr(C)]
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub struct PackedVeneer {
109    /// `lui t0, hi; lw t0, lo(t0); nop; jr t0; nop`, addressing `target` absolutely.
110    pub code: [u32; 5],
111    /// Where the veneer jumps: the resident trap while no lease is live.
112    pub target: u32,
113}
114impl PackedVeneer {
115    /// Size of one veneer, and the stride of a veneer table.
116    pub const BYTES: u32 = 24;
117    /// Initial contents of a veneer table in resident `.data`; the packer overwrites
118    /// every record it uses. Keep the table in `.data` (`link_section`), never `.bss`.
119    pub const PLACEHOLDER: Self = Self {
120        code: [0; 5],
121        target: 0,
122    };
123    /// The code words of the veneer stored at `address`. The pair `lui`/`lw`
124    /// addresses the veneer's own `target` word at `address + 20`; `$t0` is a
125    /// caller-saved temporary that no argument register or return value uses.
126    pub const fn code_for(address: u32) -> [u32; 5] {
127        let slot = address.wrapping_add(20);
128        [
129            0x3c08_0000 | (slot.wrapping_add(0x8000) >> 16),
130            0x8d08_0000 | (slot & 0xffff),
131            0,
132            0x0100_0008,
133            0,
134        ]
135    }
136    /// The veneer the packer publishes at `address`, trapping until a lease binds it.
137    pub const fn published(address: u32, trap: u32) -> Self {
138        Self {
139            code: Self::code_for(address),
140            target: trap,
141        }
142    }
143}
144
145/// One veneered typed call: the resident veneer, the module that owns the export and
146/// the export's byte offset in that module's image.
147pub struct VeneerImport<'a> {
148    veneer: &'a mut PackedVeneer,
149    address: u32,
150    module: Handle,
151    offset: u32,
152}
153impl<'a> VeneerImport<'a> {
154    /// Bind only a veneer the final-link packer published for the packaged Rust
155    /// entry at `offset`; its call site's typed caller and callee must share their
156    /// exact ABI/types, as for [`StaticImport`].
157    ///
158    /// # Safety
159    /// `veneer` must be the actual resident record at `address`, and no other CPU or
160    /// DMA user may write it while the import exists.
161    pub unsafe fn new(
162        veneer: &'a mut PackedVeneer,
163        address: u32,
164        module: Handle,
165        offset: u32,
166    ) -> Self {
167        #[cfg(target_arch = "mips")]
168        debug_assert_eq!(veneer as *mut PackedVeneer as usize as u32, address);
169        Self {
170            veneer,
171            address,
172            module,
173            offset,
174        }
175    }
176}
177
178/// Word checksum matching the existing HK module transport.
179pub fn checksum(words: &[u32]) -> u32 {
180    words.iter().fold(0x811c9dc5, |hash, word| {
181        (hash ^ word).wrapping_mul(16777619)
182    })
183}
184#[derive(Clone, Copy)]
185struct Installed {
186    id: u32,
187    code_end: u32,
188    ready: bool,
189}
190const EMPTY: Installed = Installed {
191    id: 0,
192    code_end: 0,
193    ready: false,
194};
195
196/// Small persistent allocation/publication registry. Keep it across title,
197/// gameplay and title re-admission so old handles cannot become current again.
198pub struct Registry<const SLOTS: usize> {
199    pool: PagePool<SLOTS>,
200    installed: [Installed; SLOTS],
201    address: Option<u32>,
202}
203impl<const SLOTS: usize> Registry<SLOTS> {
204    /// Byte capacity of the existing arena, with at most `SLOTS` allocations.
205    pub const fn new(pool: u8, capacity_bytes: u32) -> Self {
206        Self {
207            pool: PagePool::new(pool, capacity_bytes, Placement::FirstFit),
208            installed: [EMPTY; SLOTS],
209            address: None,
210        }
211    }
212    fn check_arena(&self, arena: &CallerArena<'_>) -> Result<(), Error> {
213        if arena.words.len() * 4 != self.pool.capacity_pages() as usize
214            || self.address.is_some_and(|address| address != arena.address)
215        {
216            return Err(Error::Arena);
217        }
218        Ok(())
219    }
220    fn place(&mut self, arena: &CallerArena<'_>, bytes: u32, code: bool) -> Result<Handle, Error> {
221        if bytes == 0 || bytes & 3 != 0 || (code && bytes > 0x10000) {
222            return Err(Error::Space);
223        }
224        let mut at = 0u32;
225        loop {
226            let end = at
227                .checked_add(bytes)
228                .filter(|end| *end <= self.pool.capacity_pages())
229                .ok_or(Error::Space)?;
230            let address = arena.address.checked_add(at).ok_or(Error::Space)?;
231            if overlay::placement(address, bytes, code).is_err() {
232                if !code {
233                    return Err(Error::Space);
234                }
235                at = overlay::window(address)
236                    .checked_add(0x8000)
237                    .and_then(|next| next.checked_sub(arena.address))
238                    .ok_or(Error::Space)?;
239                continue;
240            }
241            let overlap = self
242                .pool
243                .iter_runs()
244                .find(|(_, run, _)| at < run.end_page() && run.first_page < end);
245            if let Some((_, run, _)) = overlap {
246                at = run.end_page();
247                continue;
248            }
249            return self
250                .pool
251                .allocate_at(at, bytes)
252                .map(|(handle, _)| handle)
253                .ok_or(Error::Space);
254        }
255    }
256    /// Install a completed, checked payload. Copy, relocation and I-cache
257    /// synchronization all finish before the handle becomes admissible.
258    pub fn install(
259        &mut self,
260        arena: &mut CallerArena<'_>,
261        words: &[u32],
262        descriptor: Descriptor,
263    ) -> Result<Handle, Error> {
264        self.check_arena(arena)?;
265        let (package, rest) = overlay::Package::parse(words)?;
266        if !rest.is_empty() || package.id != descriptor.id || checksum(words) != descriptor.checksum
267        {
268            return Err(Error::Integrity);
269        }
270        if package.image.is_empty() {
271            return Err(Error::Space);
272        }
273        let bytes = u32::try_from(package.image.len() * 4).map_err(|_| Error::Space)?;
274        let handle = self.place(arena, bytes, package.code_end != 0)?;
275        let run = self.pool.try_run(handle).ok_or(Error::Stale)?;
276        let start = run.first_page as usize / 4;
277        let image = &mut arena.words[start..start + package.image.len()];
278        image.copy_from_slice(package.image);
279        let address = arena.address + run.first_page;
280        for &fixup in package.fixups {
281            let offset = fixup & 0x0fff_ffff;
282            let index = offset as usize / 4;
283            match overlay::relocate(
284                image[index],
285                fixup >> 28,
286                descriptor.linked,
287                address,
288                offset,
289            ) {
290                Ok(word) => image[index] = word,
291                Err(error) => {
292                    self.pool.free(handle);
293                    return Err(error.into());
294                }
295            }
296        }
297        flush();
298        self.installed[handle.slot() as usize] = Installed {
299            id: descriptor.id,
300            code_end: package.code_end,
301            ready: true,
302        };
303        self.address = Some(arena.address);
304        Ok(handle)
305    }
306    /// Borrow the arena and registry until every CPU call/data view completes.
307    /// All dependencies are checked before any admission is returned.
308    pub fn admit<'a, 'buffer>(
309        &'a mut self,
310        arena: &'a mut CallerArena<'buffer>,
311        dependencies: &'a [Handle],
312    ) -> Result<Admission<'a, 'buffer, SLOTS>, Error> {
313        self.check_arena(arena)?;
314        for &handle in dependencies {
315            if !self.pool.is_current(handle) {
316                return Err(Error::Stale);
317            }
318            if !self.installed[handle.slot() as usize].ready {
319                return Err(Error::NotReady);
320            }
321        }
322        Ok(Admission {
323            registry: self,
324            arena,
325            dependencies,
326        })
327    }
328    /// Remove an allocation after external DMA/render users have completed.
329    /// A live admission prevents this mutable registry access in safe Rust.
330    pub fn unload(&mut self, handle: Handle) -> bool {
331        if !self.pool.free(handle) {
332            return false;
333        }
334        self.installed[handle.slot() as usize] = EMPTY;
335        true
336    }
337    /// Quiescent phase handoff before gameplay overwrites title code storage.
338    /// Persistent PagePool generations survive the next title re-admission.
339    pub fn invalidate_all(&mut self) {
340        for slot in 0..SLOTS {
341            let handle = self
342                .pool
343                .iter_runs()
344                .find(|(candidate, _, _)| *candidate as usize == slot)
345                .and_then(|(_, _, _)| self.pool.handle_for_slot(slot as u16));
346            if let Some(handle) = handle {
347                self.unload(handle);
348            }
349        }
350    }
351}
352
353/// A known resident direct-call instruction, not an escaped function pointer.
354pub struct StaticImport<'a> {
355    word: &'a mut u32,
356    site: u32,
357    module: Handle,
358    offset: u32,
359}
360impl<'a> StaticImport<'a> {
361    /// Bind only a J/JAL emitted by the same compilation as the packaged Rust
362    /// entry. The typed caller and callee must share their exact ABI/types.
363    ///
364    /// # Safety
365    /// `word` must name the actual writable resident instruction at `site`.
366    /// Its typed callee must be the packaged export at `offset`; no other CPU
367    /// or DMA user may read/write the instruction during rebinding.
368    pub unsafe fn new(word: &'a mut u32, site: u32, module: Handle, offset: u32) -> Self {
369        Self {
370            word,
371            site,
372            module,
373            offset,
374        }
375    }
376}
377
378/// Execution/data lease. Its fields deliberately do not expose raw code
379/// addresses or an owned run that could escape the admission borrow.
380pub struct Admission<'a, 'buffer, const SLOTS: usize> {
381    registry: &'a mut Registry<SLOTS>,
382    arena: &'a mut CallerArena<'buffer>,
383    dependencies: &'a [Handle],
384}
385impl<const SLOTS: usize> Admission<'_, '_, SLOTS> {
386    /// Read only through this live admission, never through a cached static view.
387    pub fn words(&self, handle: Handle) -> Result<&[u32], Error> {
388        if !self.dependencies.contains(&handle) {
389            return Err(Error::NotReady);
390        }
391        let run = self.registry.pool.try_run(handle).ok_or(Error::Stale)?;
392        Ok(&self.arena.words[run.first_page as usize / 4..run.end_page() as usize / 4])
393    }
394    /// Installed logical identity, under the same generation-bound lease.
395    pub fn id(&self, handle: Handle) -> Result<u32, Error> {
396        self.words(handle)?;
397        Ok(self.registry.installed[handle.slot() as usize].id)
398    }
399    /// Run a statically typed same-compilation caller while its imports are
400    /// bound. Trap all sites again and flush I-cache on normal/unwind exit.
401    ///
402    /// # Safety
403    /// The closure may call only the exact packaged Rust entries matching the
404    /// supplied sites/offsets. It must not retain module callbacks or pointers,
405    /// nor start asynchronous users of module bytes beyond this scope.
406    pub unsafe fn invoke<R>(
407        &self,
408        imports: &mut [StaticImport<'_>],
409        trap: u32,
410        caller: impl FnOnce() -> R,
411    ) -> Result<R, Error> {
412        for import in imports.iter() {
413            self.words(import.module)?;
414            let info = self.registry.installed[import.module.slot() as usize];
415            if import.site & 3 != 0
416                || import.offset & 3 != 0
417                || import.offset >= info.code_end
418                || !matches!(*import.word >> 26, 2 | 3)
419            {
420                return Err(Error::Integrity);
421            }
422            let run = self
423                .registry
424                .pool
425                .try_run(import.module)
426                .ok_or(Error::Stale)?;
427            overlay::direct(
428                *import.word,
429                1,
430                self.arena.address + run.first_page + import.offset,
431                import.site,
432            )?;
433            overlay::direct(*import.word, 1, trap, import.site)?;
434        }
435        for import in imports.iter_mut() {
436            let run = self
437                .registry
438                .pool
439                .try_run(import.module)
440                .ok_or(Error::Stale)?;
441            *import.word = overlay::direct(
442                *import.word,
443                1,
444                self.arena.address + run.first_page + import.offset,
445                import.site,
446            )?;
447        }
448        flush_sites(imports);
449        let guard = CallScope { imports, trap };
450        let result = caller();
451        drop(guard);
452        Ok(result)
453    }
454
455    /// Like [`Admission::invoke`], for call sites the packer routed through
456    /// resident jump veneers ([`PackedVeneer`]). Entering the lease stores each
457    /// module entry into its veneer's `target` word; leaving it (normal or unwind)
458    /// stores the trap back. Nothing is patched and nothing is flushed: the
459    /// instruction cache sees only the image install, so a lease costs two data
460    /// stores per import instead of a gated cache flush on entry and another on exit.
461    ///
462    /// Every import is validated before any veneer is touched: the module must be
463    /// admitted, the export inside its executable prefix, the veneer exactly the
464    /// published code for its address, and its target the trap (a leaked earlier
465    /// lease is an integrity failure, not a silent rebind).
466    ///
467    /// # Safety
468    /// As [`Admission::invoke`]: the closure may call only the exact packaged
469    /// entries through their typed callers, must not retain module callbacks or
470    /// pointers, and must not start asynchronous users of module bytes beyond the scope.
471    pub unsafe fn invoke_veneered<R>(
472        &self,
473        imports: &mut [VeneerImport<'_>],
474        trap: u32,
475        caller: impl FnOnce() -> R,
476    ) -> Result<R, Error> {
477        if trap & 3 != 0 {
478            return Err(Error::Integrity);
479        }
480        for import in imports.iter() {
481            self.words(import.module)?;
482            let info = self.registry.installed[import.module.slot() as usize];
483            if import.address & 3 != 0
484                || import.offset & 3 != 0
485                || import.offset >= info.code_end
486                || import.veneer.code != PackedVeneer::code_for(import.address)
487                || import.veneer.target != trap
488            {
489                return Err(Error::Integrity);
490            }
491        }
492        for import in imports.iter_mut() {
493            let run = self
494                .registry
495                .pool
496                .try_run(import.module)
497                .ok_or(Error::Stale)?;
498            let entry = self.arena.address + run.first_page + import.offset;
499            // SAFETY: the record is exclusive (`VeneerImport::new`); a volatile store
500            // is the one write the veneer's load must observe.
501            unsafe { core::ptr::write_volatile(&mut import.veneer.target, entry) };
502        }
503        order_stores();
504        let guard = VeneerScope { imports, trap };
505        let result = caller();
506        drop(guard);
507        Ok(result)
508    }
509}
510struct VeneerScope<'a, 'veneer> {
511    imports: &'a mut [VeneerImport<'veneer>],
512    trap: u32,
513}
514impl Drop for VeneerScope<'_, '_> {
515    fn drop(&mut self) {
516        for import in self.imports.iter_mut() {
517            // SAFETY: as in `invoke_veneered`; the trap was validated before binding.
518            unsafe { core::ptr::write_volatile(&mut import.veneer.target, self.trap) };
519        }
520        order_stores();
521    }
522}
523/// Keep the compiler from moving the veneer stores across the lease's calls.
524fn order_stores() {
525    #[cfg(target_arch = "mips")]
526    // SAFETY: empty asm only constrains compiler memory ordering.
527    unsafe {
528        core::arch::asm!("", options(nostack, preserves_flags));
529    }
530    #[cfg(not(target_arch = "mips"))]
531    core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
532}
533struct CallScope<'a, 'instruction> {
534    imports: &'a mut [StaticImport<'instruction>],
535    trap: u32,
536}
537impl Drop for CallScope<'_, '_> {
538    fn drop(&mut self) {
539        for import in self.imports.iter_mut() {
540            // Both target and trap were checked before any site was published.
541            *import.word =
542                overlay::direct(*import.word, 1, self.trap, import.site).expect("validated trap");
543        }
544        flush_sites(self.imports);
545    }
546}
547/// Make the patched call-site words visible to instruction fetch: only the cache lines that hold
548/// them are invalidated (the rest of the cache keeps its working set; a full flush after every
549/// patch and every restore cost a cold cache twice per lease).
550fn flush_sites(imports: &[StaticImport<'_>]) {
551    for import in imports {
552        #[cfg(target_arch = "mips")]
553        psx_rt::cache::flush_instruction_cache_range(import.site, import.site + 4);
554        #[cfg(not(target_arch = "mips"))]
555        let _ = import;
556        #[cfg(test)]
557        count_flush();
558    }
559    #[cfg(target_arch = "mips")]
560    // SAFETY: empty asm only constrains compiler memory ordering.
561    unsafe {
562        core::arch::asm!("", options(nostack, preserves_flags));
563    }
564    #[cfg(not(target_arch = "mips"))]
565    core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
566}
567fn flush() {
568    #[cfg(test)]
569    count_flush();
570    #[cfg(target_arch = "mips")]
571    psx_rt::cache::flush_instruction_cache();
572    // The pinned MIPS-I backend lowers compiler_fence to unsupported SYNC.
573    // Match psx-rt's empty-asm memory barrier instead.
574    #[cfg(target_arch = "mips")]
575    // SAFETY: empty asm only constrains compiler memory ordering.
576    unsafe {
577        core::arch::asm!("", options(nostack, preserves_flags));
578    }
579    #[cfg(not(target_arch = "mips"))]
580    core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
581}
582
583#[cfg(test)]
584std::thread_local! {
585    /// Instruction-cache flushes requested on this thread, for the host tests.
586    static FLUSHES: core::cell::Cell<u32> = const { core::cell::Cell::new(0) };
587}
588#[cfg(test)]
589fn count_flush() {
590    FLUSHES.with(|count| count.set(count.get() + 1));
591}
592#[cfg(test)]
593fn flush_count() -> u32 {
594    FLUSHES.with(core::cell::Cell::get)
595}
596
597#[cfg(test)]
598mod tests {
599    use super::*;
600    #[test]
601    fn final_link_metadata_has_the_fixed_patch_layout() {
602        assert_eq!(core::mem::size_of::<PackedDescriptor>(), 20);
603        assert_eq!(core::mem::offset_of!(PackedDescriptor, checksum), 12);
604        assert_eq!(core::mem::size_of::<PackedCall>(), 12);
605        assert_eq!(core::mem::offset_of!(PackedCall, offset), 8);
606    }
607    fn package(id: u32) -> [u32; 7] {
608        [overlay::MAGIC, id, 2, 0, 8, 0x03e00008, 0]
609    }
610    fn descriptor(words: &[u32]) -> Descriptor {
611        Descriptor {
612            id: words[1],
613            linked: 0x80408000,
614            checksum: checksum(words),
615        }
616    }
617    #[test]
618    fn byte_allocations_do_not_round_to_sectors_and_stale_handles_stay_stale() {
619        let mut backing = [0u32; 8];
620        let mut arena = CallerArena::new(&mut backing, 0x801d8000).unwrap();
621        let mut registry = Registry::<4>::new(0, 32);
622        let words = package(7);
623        let first = registry
624            .install(&mut arena, &words, descriptor(&words))
625            .unwrap();
626        let second = registry
627            .install(&mut arena, &words, descriptor(&words))
628            .unwrap();
629        assert_eq!(registry.pool.used_pages(), 16);
630        assert_eq!(registry.pool.try_run(second).unwrap().first_page, 8);
631        assert!(registry.unload(first));
632        let replacement = registry
633            .install(&mut arena, &words, descriptor(&words))
634            .unwrap();
635        assert_eq!(replacement.slot(), first.slot());
636        assert_ne!(replacement.generation(), first.generation());
637        assert!(matches!(
638            registry.admit(&mut arena, &[first]),
639            Err(Error::Stale)
640        ));
641    }
642    #[test]
643    fn failure_cannot_publish_and_missing_dependency_admission_is_all_or_none() {
644        let mut backing = [0u32; 8];
645        let mut arena = CallerArena::new(&mut backing, 0x801d8000).unwrap();
646        let mut registry = Registry::<4>::new(0, 32);
647        let words = package(7);
648        let mut bad = descriptor(&words);
649        bad.checksum ^= 1;
650        assert_eq!(
651            registry.install(&mut arena, &words, bad),
652            Err(Error::Integrity)
653        );
654        assert_eq!(registry.pool.used_pages(), 0);
655        let good = registry
656            .install(&mut arena, &words, descriptor(&words))
657            .unwrap();
658        assert!(matches!(
659            registry.admit(&mut arena, &[good, Handle::NONE]),
660            Err(Error::Stale)
661        ));
662        assert!(registry.unload(good));
663        let invalid = [overlay::MAGIC, 8, 2, 1, 8, 0, 0x0c000000, 0x10000004];
664        let mut desc = descriptor(&invalid);
665        desc.linked = 0xfffffffc;
666        assert_eq!(
667            registry.install(&mut arena, &invalid, desc),
668            Err(Error::Format(overlay::Error::Bounds))
669        );
670        assert_eq!(registry.pool.used_pages(), 0);
671        assert!(registry.installed.iter().all(|slot| !slot.ready));
672    }
673    #[test]
674    fn fixed_window_placement_and_oversized_code_are_bounded() {
675        let mut backing = [0u32; 16];
676        let mut arena = CallerArena::new(&mut backing, 0x801d7ff0).unwrap();
677        let mut registry = Registry::<2>::new(0, 64);
678        let words = [overlay::MAGIC, 1, 6, 0, 24, 0, 0, 0, 0, 0, 0];
679        let handle = registry
680            .install(&mut arena, &words, descriptor(&words))
681            .unwrap();
682        assert_eq!(registry.pool.try_run(handle).unwrap().first_page, 16);
683        assert_eq!(registry.place(&arena, 0x10004, true), Err(Error::Space));
684        assert_eq!(
685            registry.place(&arena, 0xffff_fffc, false),
686            Err(Error::Space)
687        );
688    }
689    #[test]
690    fn title_gameplay_title_reuse_keeps_generation_invalidation() {
691        let mut backing = [0u32; 8];
692        let mut registry = Registry::<1>::new(0, 32);
693        let words = package(7);
694        let first = {
695            let mut arena = CallerArena::new(&mut backing, 0x801d8000).unwrap();
696            let handle = registry
697                .install(&mut arena, &words, descriptor(&words))
698                .unwrap();
699            registry.invalidate_all();
700            handle
701        };
702        backing.fill(0x12345678); // Normal mutable gameplay arena access.
703        let mut arena = CallerArena::new(&mut backing, 0x801d8000).unwrap();
704        let second = registry
705            .install(&mut arena, &words, descriptor(&words))
706            .unwrap();
707        assert_ne!(first.generation(), second.generation());
708        assert!(matches!(
709            registry.admit(&mut arena, &[first]),
710            Err(Error::Stale)
711        ));
712        let dependencies = [second];
713        let admission = registry.admit(&mut arena, &dependencies).unwrap();
714        assert_eq!(admission.id(second).unwrap(), 7);
715        assert_eq!(admission.words(second).unwrap(), &words[5..]);
716    }
717    #[test]
718    fn callable_scope_traps_on_normal_and_unwind_exit_and_rejects_data_entries() {
719        let mut backing = [0u32; 8];
720        let mut arena = CallerArena::new(&mut backing, 0x801d8000).unwrap();
721        let mut registry = Registry::<2>::new(0, 32);
722        let words = package(7);
723        let handle = registry
724            .install(&mut arena, &words, descriptor(&words))
725            .unwrap();
726        let dependencies = [handle];
727        let admission = registry.admit(&mut arena, &dependencies).unwrap();
728        let mut instruction = 0x0c000000;
729        let trap = 0x80010080;
730        let expected = overlay::direct(instruction, 1, trap, 0x80010000).unwrap();
731        {
732            // SAFETY: model instruction storage is exclusive and is never executed.
733            let mut imports =
734                [unsafe { StaticImport::new(&mut instruction, 0x80010000, handle, 0) }];
735            assert_eq!(
736                // SAFETY: the closure executes no model instruction or async user.
737                unsafe { admission.invoke(&mut imports, trap, || 42) },
738                Ok(42)
739            );
740        }
741        assert_eq!(instruction, expected);
742        {
743            // SAFETY: exclusive model storage; no instruction is executed.
744            let mut imports =
745                [unsafe { StaticImport::new(&mut instruction, 0x80010000, handle, 0) }];
746            // SAFETY: the closure only unwinds, with no asynchronous user.
747            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe {
748                admission.invoke(&mut imports, trap, || panic!("caller unwind"))
749            }));
750            assert!(result.is_err());
751        }
752        assert_eq!(instruction, expected);
753        // SAFETY: invalid entry is tested in exclusive model storage without execution.
754        let mut imports = [unsafe { StaticImport::new(&mut instruction, 0x80010000, handle, 8) }];
755        assert_eq!(
756            // SAFETY: validation rejects this before any instruction is executed.
757            unsafe { admission.invoke(&mut imports, trap, || ()) },
758            Err(Error::Integrity)
759        );
760    }
761
762    const TRAP: u32 = 0x80010080;
763    const VENEER_AT: u32 = 0x80020000;
764
765    #[test]
766    fn veneered_calls_flush_nothing_after_install() {
767        let mut backing = [0u32; 8];
768        let mut arena = CallerArena::new(&mut backing, 0x801d8000).unwrap();
769        let mut registry = Registry::<2>::new(0, 32);
770        let words = package(7);
771        let installs = flush_count();
772        let handle = registry
773            .install(&mut arena, &words, descriptor(&words))
774            .unwrap();
775        assert_eq!(flush_count() - installs, 1, "an install flushes once");
776        let mut veneer = PackedVeneer::published(VENEER_AT, TRAP);
777        let after_install = flush_count();
778        for tick in 0..100u32 {
779            let dependencies = [handle];
780            let admission = registry.admit(&mut arena, &dependencies).unwrap();
781            let mut imports =
782                // SAFETY: model veneer storage is exclusive and never executed.
783                [unsafe { VeneerImport::new(&mut veneer, VENEER_AT, handle, 0) }];
784            // SAFETY: the closure executes no model instruction and starts no async user.
785            let seen = unsafe {
786                admission.invoke_veneered(&mut imports, TRAP, || {
787                    // Not reached through the model; the veneer is bound while we run.
788                    tick
789                })
790            };
791            assert_eq!(seen, Ok(tick));
792        }
793        assert_eq!(
794            flush_count(),
795            after_install,
796            "a lease must not flush the instruction cache"
797        );
798        // The counter sees the patching lease (so the assertion above is not vacuous):
799        // it flushes once to bind and once to trap again.
800        let mut instruction = 0x0c000000;
801        let dependencies = [handle];
802        let admission = registry.admit(&mut arena, &dependencies).unwrap();
803        // SAFETY: model instruction storage is exclusive and never executed.
804        let mut sites = [unsafe { StaticImport::new(&mut instruction, 0x80010000, handle, 0) }];
805        // SAFETY: the closure executes no model instruction or async user.
806        unsafe { admission.invoke(&mut sites, TRAP, || ()) }.unwrap();
807        assert_eq!(flush_count() - after_install, 2);
808    }
809
810    #[test]
811    fn a_veneer_targets_the_overlay_only_while_the_lease_is_live() {
812        let mut backing = [0u32; 8];
813        let mut arena = CallerArena::new(&mut backing, 0x801d8000).unwrap();
814        let mut registry = Registry::<2>::new(0, 32);
815        let words = package(7);
816        let handle = registry
817            .install(&mut arena, &words, descriptor(&words))
818            .unwrap();
819        let mut veneer = PackedVeneer::published(VENEER_AT, TRAP);
820        let dependencies = [handle];
821        let admission = registry.admit(&mut arena, &dependencies).unwrap();
822        let entry = 0x801d8000 + 4; // installed address plus the export offset
823        {
824            let veneer_ptr: *const PackedVeneer = &veneer;
825            let mut imports =
826                // SAFETY: model storage, never executed.
827                [unsafe { VeneerImport::new(&mut veneer, VENEER_AT, handle, 4) }];
828            // SAFETY: the closure only reads the model veneer through a raw pointer.
829            let bound = unsafe {
830                admission.invoke_veneered(&mut imports, TRAP, || {
831                    core::ptr::read_volatile(&(*veneer_ptr).target)
832                })
833            };
834            assert_eq!(bound, Ok(entry));
835        }
836        assert_eq!(veneer.target, TRAP, "the lease's end traps the veneer");
837        assert_eq!(veneer.code, PackedVeneer::code_for(VENEER_AT));
838        // An unwind restores the trap too.
839        {
840            let mut imports =
841                // SAFETY: model storage, never executed.
842                [unsafe { VeneerImport::new(&mut veneer, VENEER_AT, handle, 4) }];
843            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
844                // SAFETY: the closure only unwinds.
845                unsafe { admission.invoke_veneered(&mut imports, TRAP, || panic!("unwind")) }
846            }));
847            assert!(result.is_err());
848        }
849        assert_eq!(veneer.target, TRAP);
850    }
851
852    #[test]
853    fn a_veneer_that_is_not_the_published_one_is_refused_before_anything_binds() {
854        let mut backing = [0u32; 8];
855        let mut arena = CallerArena::new(&mut backing, 0x801d8000).unwrap();
856        let mut registry = Registry::<2>::new(0, 32);
857        let words = package(7);
858        let handle = registry
859            .install(&mut arena, &words, descriptor(&words))
860            .unwrap();
861        let dependencies = [handle];
862        let admission = registry.admit(&mut arena, &dependencies).unwrap();
863        let mut good = PackedVeneer::published(VENEER_AT, TRAP);
864        let mut bad = PackedVeneer::published(VENEER_AT + 32, TRAP);
865        bad.code[3] ^= 1; // not a `jr`
866        {
867            let mut imports = [
868                // SAFETY: model storage, never executed.
869                unsafe { VeneerImport::new(&mut good, VENEER_AT, handle, 0) },
870                // SAFETY: as above.
871                unsafe { VeneerImport::new(&mut bad, VENEER_AT + 32, handle, 0) },
872            ];
873            assert_eq!(
874                // SAFETY: validation rejects this before any lease begins.
875                unsafe { admission.invoke_veneered(&mut imports, TRAP, || ()) },
876                Err(Error::Integrity)
877            );
878        }
879        assert_eq!(good.target, TRAP, "nothing was bound on a refused lease");
880        // A veneer already pointing somewhere else (a lease leaked) is refused as well.
881        good.target = 0x801d8000;
882        let mut imports =
883            // SAFETY: model storage, never executed.
884            [unsafe { VeneerImport::new(&mut good, VENEER_AT, handle, 0) }];
885        assert_eq!(
886            // SAFETY: as above.
887            unsafe { admission.invoke_veneered(&mut imports, TRAP, || ()) },
888            Err(Error::Integrity)
889        );
890        // An export outside the executable prefix is refused like a site import.
891        let mut fresh = PackedVeneer::published(VENEER_AT, TRAP);
892        let mut imports =
893            // SAFETY: model storage, never executed.
894            [unsafe { VeneerImport::new(&mut fresh, VENEER_AT, handle, 8) }];
895        assert_eq!(
896            // SAFETY: as above.
897            unsafe { admission.invoke_veneered(&mut imports, TRAP, || ()) },
898            Err(Error::Integrity)
899        );
900    }
901
902    #[test]
903    fn the_veneer_encoding_loads_its_own_target_word_and_jumps_to_it() {
904        // lui t0, hi; lw t0, lo(t0); nop; jr t0; nop; then the target word.
905        for address in [0x80020000, 0x8002ffec, 0x80017ff8, 0x801fffe8] {
906            let code = PackedVeneer::code_for(address);
907            let slot = address + 20;
908            let hi = code[0] & 0xffff;
909            let lo = code[1] & 0xffff;
910            assert_eq!(code[0] >> 16, 0x3c08, "lui $t0");
911            assert_eq!(code[1] >> 16, 0x8d08, "lw $t0, lo($t0)");
912            assert_eq!(code[2], 0, "the load delay slot is a nop");
913            assert_eq!(code[3], 0x0100_0008, "jr $t0");
914            assert_eq!(code[4], 0, "the jump delay slot is a nop");
915            assert_eq!(
916                (hi << 16).wrapping_add(lo as u16 as i16 as i32 as u32),
917                slot,
918                "the pair addresses the veneer's own target word"
919            );
920        }
921        assert_eq!(core::mem::size_of::<PackedVeneer>(), 24);
922    }
923}