psx_rt/lib.rs
1// SPDX-License-Identifier: GPL-2.0-or-later
2//! PS1 bare-metal runtime.
3//!
4//! Provides the `_start` entry point that the PSX-EXE loader jumps to,
5//! a panic handler, direct i-cache control, a BIOS TTY debug
6//! trampoline, and optional heap initialisation. Homebrew crates
7//! depend on this crate to get a working `main()` environment without
8//! thinking about linker symbols or cache-flushing.
9//!
10//! # Entry sequence
11//!
12//! 1. The loader (our emulator or the real BIOS) copies the EXE
13//! payload to `LOAD_ADDR` and jumps to [`_start`].
14//! 2. [`_start`] zeroes the `.bss` section using the linker-defined
15//! `__bss_start` / `__bss_end` symbols. `.bss` starts where `.data`
16//! ends, so the zero bytes that round the stored image up to whole
17//! sectors (`hazard-patch` appends them) land over its first bytes and
18//! are cleared with it; nothing may read `.bss` before this.
19//! 3. With the `alloc` feature, the bump allocator is seeded from
20//! `__heap_start..__heap_end`.
21//! 4. `main()` is called. When it returns, we halt.
22
23#![no_std]
24#![deny(unsafe_op_in_unsafe_fn)]
25#![warn(missing_docs)]
26// Required for MIPS `global_asm!` blocks (BIOS trampolines). Suppress
27// the "feature is declared but not used" warning that shows on the
28// host target where only the panic handler + heap are live.
29#![cfg_attr(target_arch = "mips", feature(asm_experimental_arch))]
30// The console stop-panel is cold; its functions are size-optimised so a diagnostic build costs
31// as little RAM as possible.
32#![cfg_attr(
33 all(feature = "console-diag", target_arch = "mips"),
34 feature(optimize_attribute)
35)]
36
37// Corrected signed 64-bit divide/mod (compiler-builtins' are broken here).
38#[cfg(target_arch = "mips")]
39mod builtins;
40// Hand-scheduled memcpy/memset/memcmp (compiler-builtins' are generic loops).
41#[cfg(target_arch = "mips")]
42mod mem;
43
44#[cfg(target_arch = "mips")]
45pub mod bios;
46pub mod cache;
47pub mod critical_section;
48#[cfg(all(feature = "console-diag", target_arch = "mips"))]
49pub mod diag;
50pub mod interrupts;
51mod peripherals;
52#[cfg(feature = "present-queue")]
53pub mod present;
54pub mod scratchpad;
55#[cfg(target_arch = "mips")]
56pub mod tty;
57#[allow(
58 dead_code,
59 reason = "used by the MIPS waits and the present queue, which a host build lacks"
60)]
61mod wait;
62
63#[cfg(feature = "alloc")]
64pub mod heap;
65
66pub use peripherals::Peripherals;
67
68/// Registers psx-rt's critical section as the `critical-section` crate's
69/// implementation, so `critical_section::with` anywhere in the program masks
70/// interrupts. Off by default: a program links at most one implementation.
71#[cfg(feature = "critical-section")]
72mod critical_section_impl {
73 struct PsxRt;
74 critical_section::set_impl!(PsxRt);
75
76 // SAFETY: psx-rt's acquire/release pair masks interrupts and restores
77 // the previous state, nesting like brackets, which is the crate's
78 // contract.
79 unsafe impl critical_section::Impl for PsxRt {
80 unsafe fn acquire() -> critical_section::RawRestoreState {
81 // SAFETY: the crate pairs every acquire with one release.
82 let state = unsafe { crate::critical_section::acquire() };
83 crate::critical_section::RestoreState::was_enabled(state)
84 }
85
86 unsafe fn release(restore: critical_section::RawRestoreState) {
87 // SAFETY: `restore` came from the matching acquire.
88 unsafe {
89 crate::critical_section::release(
90 crate::critical_section::RestoreState::from_enabled(restore),
91 )
92 }
93 }
94 }
95}
96
97/// Post-link home for R3000 load-delay hazard trampolines.
98///
99/// LLVM's MIPS delay-slot filler leaves loads in branch delay slots whose
100/// consumer runs one instruction later, inside the load delay, and so reads
101/// the stale register. `hazard-patch` rewrites each such branch to
102/// jump through a short trampoline it writes here after the link (magic,
103/// capacity, then code words), which the staged guest build runs and verifies
104/// instead of disabling the filler's backward search at a cost of tens of
105/// kilobytes of nops. Every guest that links psx-rt therefore carries this
106/// 392-byte array in `.data` (776 bytes with `hazard-trampolines-192`,
107/// 1,032 bytes with `hazard-trampolines-256`); nothing reads it at runtime except the CPU.
108#[cfg(feature = "runtime")]
109#[no_mangle]
110#[used]
111static mut HAZARD_TRAMPOLINES: [u32; 2 + HAZARD_TRAMPOLINE_WORDS] = {
112 let mut words = [0u32; 2 + HAZARD_TRAMPOLINE_WORDS];
113 words[0] = 0x4841_5a54;
114 words[1] = HAZARD_TRAMPOLINE_WORDS as u32;
115 words
116};
117// Code words available to the patcher. A guest whose link reports
118// "trampoline array full" opts into 192 (+384 bytes) or 256 (+640 bytes).
119// Cargo feature unification selects the larger capacity when both are enabled.
120#[cfg(all(feature = "runtime", feature = "hazard-trampolines-256"))]
121const HAZARD_TRAMPOLINE_WORDS: usize = 256;
122#[cfg(all(
123 feature = "runtime",
124 not(feature = "hazard-trampolines-256"),
125 feature = "hazard-trampolines-192"
126))]
127const HAZARD_TRAMPOLINE_WORDS: usize = 192;
128#[cfg(all(
129 feature = "runtime",
130 not(any(feature = "hazard-trampolines-256", feature = "hazard-trampolines-192"))
131))]
132const HAZARD_TRAMPOLINE_WORDS: usize = 96;
133
134// Symbols emitted by `psoxide.ld`.
135extern "C" {
136 static mut __bss_start: u8;
137 static mut __bss_end: u8;
138 #[cfg(feature = "alloc")]
139 static __heap_start: u8;
140 #[cfg(feature = "alloc")]
141 static __heap_end: u8;
142}
143
144#[cfg(all(target_arch = "mips", feature = "runtime"))]
145extern "Rust" {
146 fn main();
147}
148
149#[cfg(all(target_arch = "mips", feature = "runtime"))]
150#[used]
151#[link_section = ".region"]
152static PSX_EXE_REGION: [u8; 55] = *b"PSoXide SDK homebrew executable ";
153
154/// Entry point the PSX-EXE loader jumps to.
155///
156/// The arguments are the MIPS ABI's first three registers as the loader left
157/// them. A BIOS boot leaves garbage there, which is why
158/// [`psx_io::disc_base::install`] gates on a magic value rather than trusting
159/// them; a multi-program loader passes
160/// (`HANDOFF_MAGIC`, disc LBA offset, CD-DA track base) so the SDK can find
161/// this program's data on a disc it does not own.
162///
163/// # Safety
164/// Called exactly once at boot by the loader. The caller must
165/// have set up a valid stack pointer before branching here -- the
166/// PSX-EXE header's `initial_sp_base` + `initial_sp_offset` fields
167/// guarantee this.
168#[cfg(all(target_arch = "mips", feature = "runtime"))]
169#[no_mangle]
170#[link_section = ".text._start"]
171pub unsafe extern "C" fn _start(a0: u32, a1: u32, a2: u32) -> ! {
172 #[cfg(feature = "boot-trace")]
173 tty::println("psx-rt: start");
174
175 // Zero BSS.
176 let bss_start = &raw mut __bss_start;
177 let bss_end = &raw const __bss_end;
178 let bss_len = bss_end as usize - bss_start as usize;
179 if bss_len > 0 {
180 // SAFETY: [__bss_start, __bss_end) is this image's .bss as psoxide.ld lays it out: writable
181 // RAM the program owns. No Rust code has run yet, so nothing reads or references it, and
182 // zero is each .bss static's initial value.
183 unsafe { core::ptr::write_bytes(bss_start, 0, bss_len) };
184 }
185 #[cfg(feature = "boot-trace")]
186 tty::println("psx-rt: bss ok");
187
188 // Before any game code can replace the exception vector: `wait_vblank` installs lazily only
189 // over the word found here.
190 interrupts::record_boot_vector();
191
192 // After the zeroing, not before: the bases live in statics.
193 // SAFETY: once, at boot, before anything can observe them.
194 unsafe { psx_io::disc_base::install(a0, a1, a2) };
195
196 #[cfg(feature = "alloc")]
197 {
198 let heap_start = &raw const __heap_start as usize;
199 let heap_end = &raw const __heap_end as usize;
200 // The RAM region ends 0x100 bytes above __heap_end, so a .bss that ends in that window
201 // puts __heap_start past __heap_end: that leaves no heap, not a wrapped 4 GiB one.
202 let heap_size = heap_end.saturating_sub(heap_start);
203 // SAFETY: runs once, before `main` and any allocation. [heap_start, heap_start +
204 // heap_size) is the range psoxide.ld leaves between .bss and the stack reserve (empty if
205 // they meet), used by nothing else.
206 unsafe { heap::init(heap_start, heap_size) };
207 }
208
209 #[cfg(feature = "boot-trace")]
210 tty::println("psx-rt: main");
211 // SAFETY: the game crate defines `#[no_mangle] fn main()` and the link resolves this
212 // declaration to it. The signature is not checked across that boundary; a `main` with a
213 // different signature would be undefined behaviour.
214 unsafe { main() };
215 #[cfg(feature = "boot-trace")]
216 tty::println("psx-rt: main returned");
217 halt();
218}
219
220/// Current MIPS stack pointer (`$sp`). No memory or stack side effects.
221#[cfg(target_arch = "mips")]
222#[inline(always)]
223fn stack_pointer() -> usize {
224 let sp: usize;
225 // SAFETY: a single register move out of `$sp`.
226 unsafe {
227 // The allocator may pick $at; `.set noat` keeps the assembler quiet.
228 core::arch::asm!(".set noat", "move {}, $sp", ".set at", out(reg) sp, options(nomem, nostack, preserves_flags));
229 }
230 sp
231}
232
233/// Trap (loudly, via TTY) if the live stack pointer has descended into
234/// the static data region.
235///
236/// The linker lays out `.text/.data/.bss` from the load address upward
237/// and runs the stack downward from the top of RAM. The two are only
238/// safe while `$sp` stays above the top of `.bss`. A large
239/// stack-resident object (e.g. a multi-hundred-KB struct held in a
240/// `main` local) or very deep call frames push `$sp` *below* `__bss_end`;
241/// from there a stack write and a write to some `static` alias the same
242/// RAM and silently corrupt each other -- the corruption surfaces far
243/// from the cause and is brutal to debug. Call this once the deepest
244/// expected stack frame is live (e.g. right after constructing the main
245/// scene object) to turn that into an immediate, located halt instead.
246///
247/// Note: this checks against the *actual* top of static data, not the
248/// linker's `__heap_end` stack floor, which currently reserves only a
249/// nominal slice and would false-positive on any real stack.
250#[cfg(target_arch = "mips")]
251pub fn assert_stack_headroom() {
252 /// Bytes of slack required between `$sp` and the top of `.bss`.
253 const GUARD: usize = 0x800;
254 let data_top = &raw const __bss_end as usize;
255 let sp = stack_pointer();
256 if sp <= data_top.saturating_add(GUARD) {
257 tty::print("\nSTACK/DATA COLLISION: $sp=0x");
258 tty::print_hex_u32(sp as u32);
259 tty::print(" is inside static data (top=0x");
260 tty::print_hex_u32(data_top as u32);
261 tty::print(").\n A large stack object or deep call frames overran the stack and\n now alias `static` memory -- this silently corrupts both. Move big\n objects into .bss, shrink static buffers, or enlarge the stack.\n");
262 halt();
263 }
264}
265
266/// Infinite loop with no useful side effects. Used after `main()`
267/// returns or from panic / reset paths.
268#[inline(never)]
269pub fn halt() -> ! {
270 loop {
271 core::hint::spin_loop();
272 }
273}
274
275/// Panic handler. Tries to write the message to TTY so PCSX-Redux
276/// (and our emulator's future console hook) shows it, then halts.
277///
278/// A panic raised on a [`scratchpad::ScratchpadStack`] first moves back to
279/// the RAM stack, so reporting (BIOS `putchar` included) never runs on the
280/// scratchpad. `stack-guard` counts this function's own frame and
281/// nothing below it, which is only sound while the report stays out of line.
282///
283/// Only registered when targeting PS1 hardware. Host builds of the
284/// SDK use `std`'s panic handler -- this avoids the lang-item conflict
285/// that would otherwise fire when something on host transitively
286/// depends on both `psx-rt` and `std`.
287#[cfg(all(target_arch = "mips", feature = "runtime"))]
288#[panic_handler]
289fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
290 let info = (info as *const core::panic::PanicInfo<'_>).cast::<u8>();
291 scratchpad::leave_for_panic(info, report_panic);
292 report_panic(info)
293}
294
295#[cfg(all(target_arch = "mips", feature = "runtime"))]
296#[inline(never)]
297extern "C" fn report_panic(info: *const u8) -> ! {
298 // SAFETY: `panic` passes its `&PanicInfo`, alive for the whole panic.
299 let info = unsafe { &*info.cast::<core::panic::PanicInfo<'_>>() };
300 #[cfg(feature = "console-diag")]
301 diag::panic_panel(info);
302 #[cfg(not(feature = "console-diag"))]
303 {
304 tty::print("PANIC: ");
305 if let Some(msg) = info.message().as_str() {
306 tty::print(msg);
307 }
308 tty::print("\n");
309 if let Some(loc) = info.location() {
310 tty::print(" at ");
311 tty::print(loc.file());
312 tty::print(":");
313 // Print the line number (no fmt machinery in no_std): up to 8 digits.
314 let mut line = loc.line();
315 let mut buf = [0u8; 8];
316 let mut i = buf.len();
317 if line == 0 {
318 i -= 1;
319 buf[i] = b'0';
320 }
321 while line > 0 && i > 0 {
322 i -= 1;
323 buf[i] = b'0' + (line % 10) as u8;
324 line /= 10;
325 }
326 if let Ok(s) = core::str::from_utf8(&buf[i..]) {
327 tty::print(s);
328 }
329 tty::print("\n");
330 }
331 halt()
332 }
333}
334
335#[cfg(all(test, feature = "runtime"))]
336mod trampoline_capacity_tests {
337 #[test]
338 fn selected_header_and_exact_storage_match_feature_precedence() {
339 let expected = if cfg!(feature = "hazard-trampolines-256") {
340 256
341 } else if cfg!(feature = "hazard-trampolines-192") {
342 192
343 } else {
344 96
345 };
346 assert_eq!(super::HAZARD_TRAMPOLINE_WORDS, expected);
347 assert_eq!(
348 core::mem::size_of::<[u32; 2 + super::HAZARD_TRAMPOLINE_WORDS]>(),
349 (expected + 2) * 4
350 );
351 // SAFETY: the host unit test only reads this initialized array; no
352 // runtime post-link patcher or guest CPU mutates it in this process.
353 let header = unsafe {
354 let words = (&raw const super::HAZARD_TRAMPOLINES).cast::<u32>();
355 [words.read(), words.add(1).read()]
356 };
357 assert_eq!(header, [0x4841_5a54, expected as u32]);
358 }
359}