1use crate::{overlay, Handle, PagePool, Placement};
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum Error {
15 Format(overlay::Error),
17 Arena,
19 Space,
21 Stale,
23 NotReady,
25 Integrity,
27}
28impl From<overlay::Error> for Error {
29 fn from(error: overlay::Error) -> Self {
30 Self::Format(error)
31 }
32}
33
34pub struct CallerArena<'a> {
38 words: &'a mut [u32],
39 address: u32,
40}
41impl<'a> CallerArena<'a> {
42 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#[derive(Clone, Copy)]
59pub struct Descriptor {
60 pub id: u32,
62 pub linked: u32,
64 pub checksum: u32,
66}
67
68#[repr(C)]
71#[derive(Clone, Copy)]
72pub struct PackedDescriptor {
73 pub words: u32,
75 pub id: u32,
77 pub linked: u32,
79 pub checksum: u32,
81 pub calls: u32,
83}
84
85#[repr(C)]
87#[derive(Clone, Copy)]
88pub struct PackedCall {
89 pub selector: u32,
91 pub site: u32,
93 pub offset: u32,
95}
96#[repr(C)]
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub struct PackedVeneer {
109 pub code: [u32; 5],
111 pub target: u32,
113}
114impl PackedVeneer {
115 pub const BYTES: u32 = 24;
117 pub const PLACEHOLDER: Self = Self {
120 code: [0; 5],
121 target: 0,
122 };
123 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 pub const fn published(address: u32, trap: u32) -> Self {
138 Self {
139 code: Self::code_for(address),
140 target: trap,
141 }
142 }
143}
144
145pub struct VeneerImport<'a> {
148 veneer: &'a mut PackedVeneer,
149 address: u32,
150 module: Handle,
151 offset: u32,
152}
153impl<'a> VeneerImport<'a> {
154 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
178pub 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
196pub 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 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 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 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 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 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
353pub struct StaticImport<'a> {
355 word: &'a mut u32,
356 site: u32,
357 module: Handle,
358 offset: u32,
359}
360impl<'a> StaticImport<'a> {
361 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
378pub 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 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 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 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 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 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 unsafe { core::ptr::write_volatile(&mut import.veneer.target, self.trap) };
519 }
520 order_stores();
521 }
522}
523fn order_stores() {
525 #[cfg(target_arch = "mips")]
526 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 *import.word =
542 overlay::direct(*import.word, 1, self.trap, import.site).expect("validated trap");
543 }
544 flush_sites(self.imports);
545 }
546}
547fn 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 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 #[cfg(target_arch = "mips")]
575 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 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); 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 let mut imports =
734 [unsafe { StaticImport::new(&mut instruction, 0x80010000, handle, 0) }];
735 assert_eq!(
736 unsafe { admission.invoke(&mut imports, trap, || 42) },
738 Ok(42)
739 );
740 }
741 assert_eq!(instruction, expected);
742 {
743 let mut imports =
745 [unsafe { StaticImport::new(&mut instruction, 0x80010000, handle, 0) }];
746 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 let mut imports = [unsafe { StaticImport::new(&mut instruction, 0x80010000, handle, 8) }];
755 assert_eq!(
756 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 [unsafe { VeneerImport::new(&mut veneer, VENEER_AT, handle, 0) }];
784 let seen = unsafe {
786 admission.invoke_veneered(&mut imports, TRAP, || {
787 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 let mut instruction = 0x0c000000;
801 let dependencies = [handle];
802 let admission = registry.admit(&mut arena, &dependencies).unwrap();
803 let mut sites = [unsafe { StaticImport::new(&mut instruction, 0x80010000, handle, 0) }];
805 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; {
824 let veneer_ptr: *const PackedVeneer = &veneer;
825 let mut imports =
826 [unsafe { VeneerImport::new(&mut veneer, VENEER_AT, handle, 4) }];
828 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 {
840 let mut imports =
841 [unsafe { VeneerImport::new(&mut veneer, VENEER_AT, handle, 4) }];
843 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
844 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; {
867 let mut imports = [
868 unsafe { VeneerImport::new(&mut good, VENEER_AT, handle, 0) },
870 unsafe { VeneerImport::new(&mut bad, VENEER_AT + 32, handle, 0) },
872 ];
873 assert_eq!(
874 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 good.target = 0x801d8000;
882 let mut imports =
883 [unsafe { VeneerImport::new(&mut good, VENEER_AT, handle, 0) }];
885 assert_eq!(
886 unsafe { admission.invoke_veneered(&mut imports, TRAP, || ()) },
888 Err(Error::Integrity)
889 );
890 let mut fresh = PackedVeneer::published(VENEER_AT, TRAP);
892 let mut imports =
893 [unsafe { VeneerImport::new(&mut fresh, VENEER_AT, handle, 8) }];
895 assert_eq!(
896 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 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}